gateway: a Responses provider set codex=as-sent gets Codex's requests as Codex sent them, for a relay that checks they are Codex's own (#1758)

A relay that checks a request is Codex's own answered magpie 400
"Codex 客户端请求特征无效" (10014). magpie fits every Codex request
for a Responses backend that isn't OpenAI's: Responses Lite's
additional_tools item is lifted into tools (#350), the tool search
goes as a function, and OpenAI-only fields such as
stream_options.reasoning_summary_delivery are left out. The reporter
found that the relay takes the request when additional_tools is left
as an input item, and that the lifted shape is what it refuses.

The lifting stays the default, because backends that aren't OpenAI's
refuse additional_tools or silently drop it (#350). A provider can now
opt out: `magpie provider set <id> codex=as-sent` (`codexAsSent` in
providers.json; `codex=default` turns it back off). With it on, a
request from Codex (fromCodex: Codex's User-Agent or originator) goes
as Codex sent it, with only its model name swapped. Codex's own
headers go with it as before. A subscription account is never sent
this way, and the GUI's provider save keeps the setting.

What was run:
- TestCodexAsSent: by default the request is still fitted; with
  codexAsSent the upstream gets exactly what Codex sent, with model
  m1, X-Codex-Turn-Metadata and the Responses Lite header. It fails
  on the old gateway.go and passes now. TestAdditionalTools and the
  gateway's Codex tests pass.

Not verified: not tried against the reporter's relay. Their check
was made by hand outside magpie, so which other fields that relay
looks at is not known. There is no GUI control for the setting
(CLI or providers.json only).
This commit is contained in:
yetone
2026-10-12 22:42:47 +08:00
parent cb40e26ec2
commit af7d97fa2f
6 changed files with 109 additions and 1 deletions
+1
View File
@@ -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<n>__`), 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 <id> 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`.
+14 -1
View File
@@ -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 <name> 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 <id> k=v… change a provider's settings, with the same k=v pairs as add
magpie provider set <id> 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 <id> <key> change the API key
magpie provider icon <id> <file|name> give a custom provider a picture (PNG, JPEG, SVG…) or a built-in icon
magpie provider fallback <id> <provider/model>… 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
+74
View File
@@ -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)
}
}
}
+6
View File
@@ -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") {
+5
View File
@@ -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 <id> 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
+9
View File
@@ -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