diff --git a/docs/subsystems/gateway-routing.md b/docs/subsystems/gateway-routing.md index 67e4f3e78..38c6d348c 100644 --- a/docs/subsystems/gateway-routing.md +++ b/docs/subsystems/gateway-routing.md @@ -72,6 +72,7 @@ served by a plugin are in [Provider and plugin ownership](provider-plugins.md). - Codex's model list from the backend path (`codexModels`) is the ChatGPT backend's for its sign-in and then magpie's (`provider.CodexListed`), its ETag and every reply's `X-Models-Etag` tagged with `provider.CodexListTag` so a change has Codex ask again. A Codex there only for account failover, not connected (`CodexOwnOnly`, `agent.CodexOwnOnly`; #1385), gets the backend's alone, tagged with `provider.CodexOwnListTag`; neither tag contains the other, so connecting or disconnecting has Codex fetch the list again. The user's picks on the codex provider (`provider.CodexNativePicked`) narrow the backend's listed models. They keep its hidden ones (`visibility: "hide"`), which no picker shows. One of those is `codex-auto-review`: when the list lacks it and no reviewer is set, Codex's auto-review runs on the conversation's model at low effort (#1460, `TestCodexModelListPicksKeepHidden`). - Reasoning state goes through magpie's translation as the vendor wrote it when the agent and the upstream speak the same API (#1445, XYenon): a non-streaming request to a stream-only account, web search on the agent's own API, a plugin, failover. The IR carries it sealed (`Part.Sealed`, `SealedBy`; events `KThinkStart`, `KSealed`, `KTextSig` in [`ir.go`](../../internal/gateway/ir.go)), so each thinking block or reasoning item stays apart, whole or streamed, and a seal is written only for its own API (`sealedBy`). Anthropic's `redacted_thinking` goes back raw (to DeepSeek as a thinking block, below), and a thinking block signed with no text keeps its signature (`aBlock` still writes `"thinking": ""`, #1447), on Claude's subscription too. A Responses reasoning item keeps its id, summary and `encrypted_content`, and goes back to a Responses upstream as it came when it has no reasoning text (`sealedReasoning`; text, another vendor's, is still left out for OpenAI, #1411). Gemini's `thoughtSignature` stays on the call it signed and on text; a later call of a signed step goes without one, and only an unsigned step or Claude on Antigravity gets `skip_thought_signature_validator`. Another API's agent gets the call's signature in its id, as on chat (#687), with its length in the mark (`__ts__`), so an id a client shortened carries no signature and the call goes as unsigned (#1536); it gets no one else's seal. Carrying reasoning across APIs (an envelope) isn't done. - A translated Responses reply gives Codex the reasoning items a Responses upstream sent, as it sent them; any other upstream's reasoning becomes items magpie made: an `rs_` id and a summary, nothing sealed. Codex hands them back on every turn. A request relayed as is to OpenAI's API or Azure OpenAI goes without them (`withoutBareReasoning`) unless `store` is true, because both look the id up among stored items and answer 400 "Item with id 'rs_…' not found" (#1008). Any other Responses upstream gets them, because a DeepSeek model wants its reasoning back (#388). When one answers 400 naming the input (`refusesInput`: `param` is `input`, or the error names an item by id), as a relay in front of OpenAI does with a message of its own, `passthrough` asks once more without them and, once that works, leaves them out for that provider and model from then on (`bareReasoningRefused`, #1044). Codex's compaction offers no tools, so it is relayed even when its turns were translated. When a provider answers its summary request 404, or 400 for an item it didn't find (`itemNotFound`, a relay in front of either), `codexCompact` asks once more with the conversation as text (`plainCompact`), then compacts locally (#866, #1008). So does the ChatGPT backend's 502 "response protection is unavailable" (`protectionRefused`): a long history refused so was answered as text. Codex also compacts remotely, a `compaction_trigger` on `/responses` that wants exactly one compaction item back, on any provider table named "OpenAI", as CC Switch names its relay tables. magpie points those at `/v1` while a magpie model is on, so `handle` makes the summary there too (`codexInput`, `codexCompact`), and magpie's summaries go back to the model as text (#1301). +- A Responses request Codex sends a Responses provider is fitted for a backend that isn't OpenAI's before it goes (`passthrough`): Responses Lite's `additional_tools` item lifted into `tools` (`liftAdditionalTools`, #350), the tool search as a function, OpenAI-only fields left out. A relay that checks a request is Codex's own turns that shape away (#1758: 400 "Codex 客户端请求特征无效", 10014). A provider set `codexAsSent` (`magpie provider set codex=as-sent`) gets a request from Codex (`fromCodex`) as Codex sent it, its model name alone swapped, with Codex's own headers (`codexClientHeader`). Off is the default, and a subscription account is never sent so. `TestCodexAsSent`. - A Chat upstream that wants a turn's reasoning back (`chatReplaysReasoning` in [`chat.go`](../../internal/gateway/chat.go): a host or a model, as magpie or the provider names it, with `deepseek` in it, such as OpenCode Go's `deepseek-v4.1-flash`, or Command Code's plugin) gets every assistant tool call with `reasoning_content`, relayed (`withReasoningOnToolTurns` in `passthrough`) or translated (`buildChat`). DeepSeek turns the whole request away ("The `reasoning_content` in the thinking mode must be passed back to the API") when a tool call made since the user's last message has none, which a client sends for a turn it saw no thinking on: another model's, a translated one (#1462). The turn's own thinking goes back as it came; one sent in `reasoning` or `reasoning_details` is copied in; otherwise it goes with a space (`noReasoning`: DeepSeek's Chat API takes an empty one, but a relay that leaves empty fields out would drop it). A reply without tool calls, any other model and Mistral (#494) are sent as before. - Kimi's Chat API (`isKimi`: the Kimi platform's and a Kimi Code membership's hosts or presets) turns `reasoning_details` in a message away in any shape: an entry with a stream's `index` ("the reasoning_details at position 1 entry 0 must not contain streaming index") and any other entry ("… has an invalid type"), checked against api.kimi.com/coding on 2026-10-12. pi keeps another vendor's thinking there (MiMo's, through Command Code, with `index: 0`), so a conversation routed on to Kimi was refused on every turn (#1765). `passthrough` sends it to Kimi as `reasoning_content` (`reasoningDetailsAsContent`), which Kimi takes; a message with `reasoning_content` of its own keeps that. Another upstream that refuses a thinking field "at position N", as Kimi words it (a relay in front of it), is asked once more the same way and marked (`refusedInMessages`, `withoutMessageReasoning`). - A Responses upstream that wants a turn's reasoning back (`replaysReasoning` in [`responses.go`](../../internal/gateway/responses.go): a model with `deepseek` in its name, on any host but OpenAI's, xAI's, Copilot's and Azure's) gets every reasoning item with a `reasoning_text` and every tool call after one, relayed (`withReasoningText` in `passthrough`) or translated (`buildResponses`). DeepSeek's `/v1/responses` turns the whole request away ("The `reasoning_text` in the thinking mode must be passed back to the API") over a reasoning item without text, one with an empty text, and a `function_call` whose step (since the last user message or tool output) has no reasoning item. Codex sends all three in a routing group that falls to DeepSeek after ChatGPT: the backend's sealed items (`encrypted_content` only), magpie's summary-only items, and another member's calls with none (#1104, #1592). An item's own text is kept; one without gets its summary, else a space (`noReasoning`); a step without one gets a reasoning item holding a space before its first call. A sealed item keeps its id and `encrypted_content`. diff --git a/internal/cli/providers_cli.go b/internal/cli/providers_cli.go index 606f3c93b..fe37315c3 100644 --- a/internal/cli/providers_cli.go +++ b/internal/cli/providers_cli.go @@ -33,7 +33,9 @@ const providerUsage = `usage: again, it adds another (deepseek-2); k=v pairs too: id, name, header.X-Foo magpie provider add k=v… add a custom vendor k: url, anthropic, responses, gemini, decide, key, models, catalog, icon, header.X-Foo, balance, balance.path, balance.token, models.url, search, access.key, access.secret (a Volcengine access key, or a Tencent Cloud SecretId and SecretKey, for its plan's windows) - magpie provider set k=v… change a provider's settings, with the same k=v pairs as add + magpie provider set k=v… change a provider's settings, with the same k=v pairs as add; + codex=as-sent sends Codex's Responses requests as Codex sent them + (a relay that checks they are Codex's own), codex=default fits them magpie provider key change the API key magpie provider icon give a custom provider a picture (PNG, JPEG, SVG…) or a built-in icon magpie provider fallback … where requests go when it's out of quota or down (none clears) @@ -944,6 +946,17 @@ func applyPairs(p *provider.Provider, pairs []string) error { p.SecretAccessKey = v case "models.url": p.ModelsURL = v + case "codex": + // as-sent: Codex's requests go to it as Codex sent them, for + // a relay that checks they are Codex's own (#1758) + switch strings.ToLower(v) { + case "as-sent", "yes", "on": + p.CodexAsSent = true + case "default", "no", "off": + p.CodexAsSent = false + default: + return fmt.Errorf("codex=as-sent|default, not %q", v) + } case "search": // yes: the vendor searches the web by itself, a web search a // client offers going to it as it was sent (a relay in front of diff --git a/internal/gateway/codex_as_sent_test.go b/internal/gateway/codex_as_sent_test.go new file mode 100644 index 000000000..5fa5d1aad --- /dev/null +++ b/internal/gateway/codex_as_sent_test.go @@ -0,0 +1,74 @@ +package gateway + +import ( + "encoding/json" + "net/http/httptest" + "reflect" + "strings" + "testing" + + "github.com/yetone/magpie/internal/provider" +) + +// asSentRequest is a Responses Lite request with what a relay checking +// Codex's own shape looks at (#1758): the additional_tools item, the +// functions namespace, Codex's stream_options and its turn metadata. +var asSentRequest = strings.Replace(liteRequest, `"stream":true,`, + `"stream":true,"stream_options":{"reasoning_summary_delivery":"inline"},"client_metadata":{"x-codex-turn-metadata":"{\"turn_id\":\"t1\"}"},`, 1) + +// A relay set to take Codex's requests as sent (codex=as-sent) gets the +// request as Codex sent it, its model name alone swapped, and Codex's turn +// metadata header (#1758: lifting additional_tools into tools was answered +// 400 "Codex 客户端请求特征无效", 10014). Off, the default, the request is +// still fitted as before (#350). +func TestCodexAsSent(t *testing.T) { + f := &fake{t: t, reply: sse( + `data: {"type":"response.created","response":{"id":"r1","model":"m1"}}`, + `data: {"type":"response.completed","response":{"id":"r1","output":[],"usage":{"input_tokens":5,"output_tokens":2}}}`)} + setup(t, provider.Responses, f) + ask := func() { + t.Helper() + rec := httptest.NewRecorder() + req := httptest.NewRequest("POST", "/v1/responses", strings.NewReader(asSentRequest)) + req.Header.Set("User-Agent", "codex_cli_rs/0.162.0-alpha.17.2 (Mac OS 26.2.0; arm64)") + req.Header.Set("originator", "codex_cli_rs") + req.Header.Set("X-Codex-Turn-Metadata", `{"turn_id":"t1"}`) + req.Header.Set("X-OpenAI-Internal-Codex-Responses-Lite", "true") + New().Handler().ServeHTTP(rec, req) + if rec.Code != 200 { + t.Fatalf("status %d: %s", rec.Code, rec.Body) + } + } + var sent map[string]any + if err := json.Unmarshal([]byte(asSentRequest), &sent); err != nil { + t.Fatal(err) + } + sent["model"] = "m1" + + ask() + if strings.Contains(string(f.got), `"additional_tools"`) || strings.Contains(string(f.got), "reasoning_summary_delivery") { + t.Fatalf("by default the request is fitted as before: %s", f.got) + } + + p, err := provider.Find("fake") + if err != nil { + t.Fatal(err) + } + p.CodexAsSent = true + if err := provider.Save(*p); err != nil { + t.Fatal(err) + } + ask() + var got map[string]any + if err := json.Unmarshal(f.got, &got); err != nil { + t.Fatal(err) + } + if !reflect.DeepEqual(got, sent) { + t.Fatalf("as sent, the relay got\n%s\nwant Codex's request with model m1", f.got) + } + for _, h := range []string{"X-Codex-Turn-Metadata", "X-Openai-Internal-Codex-Responses-Lite"} { + if f.head.Get(h) == "" { + t.Errorf("%s not sent on: %v", h, f.head) + } + } +} diff --git a/internal/gateway/gateway.go b/internal/gateway/gateway.go index d3b22a9d8..0d1e9e65c 100644 --- a/internal/gateway/gateway.go +++ b/internal/gateway/gateway.go @@ -3380,6 +3380,12 @@ func (s *Server) passthrough(w http.ResponseWriter, r *http.Request, p provider. replay := proto == provider.Responses && (replaysReasoning(model, p.Host()) || replaysReasoning(upstream, p.Host())) switch proto { case provider.Responses: + if p.CodexAsSent && p.Account == nil && fromCodex(r.Header) { + // as Codex sent it, its model name alone swapped: a relay + // that checks it is Codex's own turns away the shape fitted + // for other backends (#1758) + break + } // Responses Lite's tools, as an input item, go as OpenAI takes them // only to OpenAI (#350) if (p.Account == nil || p.Account.Agent != "codex") && !strings.HasSuffix(p.Host(), "openai.com") { diff --git a/internal/gui/providers.go b/internal/gui/providers.go index b9af480a9..28b2d459f 100644 --- a/internal/gui/providers.go +++ b/internal/gui/providers.go @@ -1319,6 +1319,11 @@ func providerRoutes(mux *http.ServeMux, w Windows) { if in.QuotaRest == 0 && old != nil { in.QuotaRest = old.QuotaRest } + // and Codex's requests as sent, set with `magpie provider + // set codex=as-sent` (#1758) + if !in.CodexAsSent && old != nil { + in.CodexAsSent = old.CodexAsSent + } // each account's own proxy likewise: {} clears them if in.AccountProxies == nil && old != nil { in.AccountProxies = old.AccountProxies diff --git a/internal/provider/provider.go b/internal/provider/provider.go index aa2fa2279..4a76245b3 100644 --- a/internal/provider/provider.go +++ b/internal/provider/provider.go @@ -197,6 +197,15 @@ type Provider struct { // it as the client sent it, rather than given magpie's search (#359). Searches bool `json:"searches,omitempty"` + // CodexAsSent has a request Codex sends on the Responses API go to it + // as Codex sent it, its model name alone swapped: a relay that checks + // it is Codex's own (#1758: "Codex 客户端请求特征无效", 10014), which + // the shape magpie fits it to for another backend (Responses Lite's + // additional_tools lifted into tools, the tool search as a function, + // OpenAI-only fields left out) fails. Off, the default, keeps that + // fitting, which a backend that isn't OpenAI's needs (#350). + CodexAsSent bool `json:"codexAsSent,omitempty"` + // PinUpstream, on the Cline API, has its DeepSeek models answered only // by DeepSeek's own API (White Immortal on Discord): Cline routes a // model through an AI gateway that may serve it from any host, and