diff --git a/internal/gateway/codex_backend.go b/internal/gateway/codex_backend.go index 30ed1d965..82c125159 100644 --- a/internal/gateway/codex_backend.go +++ b/internal/gateway/codex_backend.go @@ -107,7 +107,7 @@ func (s *Server) codexBackend(w http.ResponseWriter, r *http.Request) { s.serve(w, r, provider.Responses, body) return } - body = callItemIDs(body) + body = boundCallIDs(callItemIDs(body)) if rest == "/responses/compact" { break // preserve native compaction's existing passthrough } @@ -940,6 +940,55 @@ func callItemIDs(body []byte) []byte { return nb } +// longCallID finds a call_id longer than the ChatGPT backend takes. +var longCallID = regexp.MustCompile(`"call_id"\s*:\s*"[^"]{65,}"`) + +// boundCallIDs is a Responses request with every call_id longer than 64 +// characters as provider.BoundCallID has it, the rest of the request byte +// for byte (#732, congee949): a conversation that had a foreign provider's +// tool calls (two ids joined, 86 or 87 characters) went on Codex's own +// ChatGPT sign-in as it came, and the backend turned it away with 400 +// "input[7].call_id … maximum length 64". A call and its output get the +// same id, on every request. +func boundCallIDs(body []byte) []byte { + if !longCallID.Match(body) { + return body + } + var q map[string]json.RawMessage + if json.Unmarshal(body, &q) != nil { + return body + } + var items []json.RawMessage + if json.Unmarshal(q["input"], &items) != nil { + return body + } + changed := false + for i, raw := range items { + var it map[string]json.RawMessage + var id string + if json.Unmarshal(raw, &it) != nil || json.Unmarshal(it["call_id"], &id) != nil { + continue + } + b := provider.BoundCallID(id) + if b == id { + continue + } + it["call_id"], _ = json.Marshal(b) + if nb, err := marshalPlain(it); err == nil { + items[i], changed = nb, true + } + } + if !changed { + return body + } + q["input"], _ = marshalPlain(items) + nb, err := marshalPlain(q) + if err != nil { + return body + } + return nb +} + // openaiOnly are the parts of a Responses request Codex sends only to a // provider named "OpenAI": its built-in one (signed in, through // openai_base_url), or CC Switch's table so named for remote compaction. diff --git a/internal/gateway/codex_call_id_test.go b/internal/gateway/codex_call_id_test.go new file mode 100644 index 000000000..6a807ffa7 --- /dev/null +++ b/internal/gateway/codex_call_id_test.go @@ -0,0 +1,74 @@ +package gateway + +import ( + "encoding/json" + "io" + "net/http" + "strings" + "testing" + + "github.com/yetone/magpie/internal/provider" +) + +// Codex on its own ChatGPT sign-in, one account, relays a conversation +// that had a foreign provider's tool calls: their ids, two joined (86 and +// 87 characters), go as ids the backend takes, a call and its output +// alike and the same on every request, and ids that fit as they were +// (#732, congee949: thread_description turned away with 400 "input[7]. +// call_id … maximum length 64"). +func TestCodexRelayBoundsLongCallIDs(t *testing.T) { + setup(t, provider.Chat, &fake{t: t}) + var got [][]byte + chatgpt(t, func(w http.ResponseWriter, r *http.Request) { + b, _ := io.ReadAll(r.Body) + got = append(got, b) + w.Header().Set("Content-Type", "text/event-stream") + io.WriteString(w, sse(`data: {"type":"response.completed","response":{"id":"r1","output":[],"usage":{"input_tokens":1,"output_tokens":1}}}`)) + }) + long := "call-" + strings.Repeat("a", 36) + "-46__fc_" + strings.Repeat("b", 36) + "_0" // 86 + other := long + "1" // 87 + short := strings.Repeat("x", 64) + body, _ := json.Marshal(map[string]any{"model": "gpt-6-luna", "stream": true, "input": []any{ + map[string]any{"type": "function_call", "call_id": long, "name": "shell", "arguments": "{}"}, + map[string]any{"type": "function_call_output", "call_id": long, "output": "ok"}, + map[string]any{"type": "tool_search_call", "call_id": other, "arguments": map[string]any{}}, + map[string]any{"type": "tool_search_output", "call_id": other, "tools": []any{}}, + map[string]any{"type": "custom_tool_call", "call_id": short, "name": "apply_patch", "input": "x"}, + map[string]any{"type": "custom_tool_call_output", "call_id": short, "output": "ok"}, + }}) + for range 2 { + if code, b := codexPost(t, string(body)); code != 200 { + t.Fatalf("%d %s", code, b) + } + } + if len(got) != 2 { + t.Fatalf("the backend was asked %d times", len(got)) + } + ids := func(b []byte) []string { + var q struct { + Input []struct { + CallID string `json:"call_id"` + } `json:"input"` + } + if err := json.Unmarshal(b, &q); err != nil { + t.Fatal(err) + } + var out []string + for _, it := range q.Input { + out = append(out, it.CallID) + } + return out + } + a, b := ids(got[0]), ids(got[1]) + if len(a) != 6 || strings.Join(a, ",") != strings.Join(b, ",") { + t.Fatalf("ids %v then %v", a, b) + } + for _, id := range a { + if id == "" || len(id) > 64 { + t.Errorf("an id the backend refuses: %q", id) + } + } + if a[0] != a[1] || a[2] != a[3] || a[0] == a[2] || a[4] != short || a[5] != short { + t.Errorf("ids %v", a) + } +} diff --git a/internal/provider/codex_request.go b/internal/provider/codex_request.go index 7af5b9b7c..48871f24b 100644 --- a/internal/provider/codex_request.go +++ b/internal/provider/codex_request.go @@ -346,6 +346,20 @@ func conversationKey(instructions string, input []any) string { return s[:8] + "-" + s[8:12] + "-" + s[12:16] + "-" + s[16:20] + "-" + s[20:32] } +// BoundCallID is a call's id as the ChatGPT backend takes one: as it is +// when it fits its 64 characters, else the sha256 of it (trimmed, as calls +// and their outputs are paired), 64 hex characters. Foreign providers can +// join two ids into one longer than that (#732, congee949: 86 and 87); the +// same id gives the same hash on every request, so a call and its output +// stay paired, and two ids that differ are never cut down alike. +func BoundCallID(id string) string { + if len(id) <= 64 { + return id + } + sum := sha256.Sum256([]byte(strings.TrimSpace(id))) + return hex.EncodeToString(sum[:]) +} + // codexInput makes input items fit a request that keeps nothing: no // references to stored items, no ids, a tool's output without its call // kept as a message saying what it was, and no system role, which the @@ -356,13 +370,9 @@ func codexInput(input []any) []any { it, _ := item.(map[string]any) id, _ := it["call_id"].(string) switch it["type"] { - case "function_call", "function_call_output", "local_shell_call", "local_shell_call_output", "custom_tool_call", "custom_tool_call_output": - // Foreign providers can join two IDs into one longer than - // Codex's 64-character limit. Keep calls and results paired - // across requests without truncating distinct IDs alike. - if len(id) > 64 { - sum := sha256.Sum256([]byte(id)) - id = hex.EncodeToString(sum[:]) + case "function_call", "function_call_output", "local_shell_call", "local_shell_call_output", "custom_tool_call", "custom_tool_call_output", "tool_search_call", "tool_search_output": + if b := BoundCallID(id); b != id { + id = b it["call_id"] = id } }