diff --git a/docs/subsystems/gateway-routing.md b/docs/subsystems/gateway-routing.md index 3e29e4dba..94665ea86 100644 --- a/docs/subsystems/gateway-routing.md +++ b/docs/subsystems/gateway-routing.md @@ -259,7 +259,7 @@ recorded as a prediction failure (`noPrediction`). - A reasoning item with its text in it (`content` parts: DeepSeek's Responses API writes `reasoning_text`, relayed to Codex as it came) is another vendor's. OpenAI's API and the ChatGPT backend take a reasoning item's `content` only empty, and refuse the whole request over one with 400 "Invalid 'input[n].content': array too long. Expected an array with maximum length 0" (`array_above_max_length`). Codex hands the item back on every later turn, so it never goes to them: for one of Codex's own models, `codexInput(body, false)` leaves it out (and a reasoning item with nothing sealed in it) on `/backend-api/codex`'s `/responses` and on `/responses/compact`, before Codex's own sign-in, its API key or a magpie Codex account (`compactOn`) is asked. Codex compacts a thread before its first turn back on its own model, and a refused compaction shows as that turn's error (jue on Discord). `passthrough` leaves it out for OpenAI, Azure OpenAI and a Codex account (`withoutReasoningText`), and for any other upstream once it has refused one (`refusesReasoningText`, `reasoningTextRefused`, #1411). OpenAI's own sealed reasoning (`encrypted_content`, no text) stays, and a DeepSeek model (`replaysReasoning`) still gets the text. `TestForeignReasoningNeverReachesOpenAI`, `TestReasoningTextLeftOutWhereRefused`, `TestReasoningTextNotSentToCodexAccount`. - Native compaction (#1099, off by default): a provider with `nativeCompaction` on (`provider.Provider.CompactsOn`; the editor's Compaction row, `magpie provider set compaction=native`) is asked Codex's `compaction_trigger` as Codex sent it, and the compaction item it seals goes back to Codex unchanged, not as a `magpie1:` summary. Only a wire that carries it can be set so (`CarriesCompaction`): a Responses API, a ChatGPT account, GitHub Copilot (its models asked on Responses; its Claude models keep magpie's summary). The decision is made where `handle` and `codexBackend` read the input (`nativeCompactionFor`, `codexInputAs`): a group compacts natively only when every member does. Such a request, and a later one carrying a sealed compaction to a provider set so or to the provider recorded as its writer, is relayed, never translated, which would drop the item (`keepsCompaction` in `attempt`); a provider that can't be asked it on Responses answers a 400 saying so. The trigger is kept only when a key or account the request would go over (the provider's and its fallbacks', or a group's members', held and capped ones too, not one whose own list lacks the model) can be asked it on Responses (`plannedCarrier`, read from `perKeyBarred` without weighing, so a provider routed in turn isn't moved along by the decision). When the vendor lists the model only to keys that speak no Responses there, a key set to Chat say, `codexCompact` gives magpie's summary through the listed key, as with native compaction off; before, the trigger was kept and refused 400 `carrierError` with no upstream asked (#2725, ggbdpq; `TestNativeCompactionTriggerSummarisedWhenNoListedKeyCarriesIt`, `TestNativeCompactionTriggerThroughTheListedKeyThatCarriesIt`, `TestNativeCompactionDecisionLeavesTheTurnsAlone`). The key or account that answered is recorded, whoever it is: a fallback or another member that answered the trigger sealed it whatever its own setting, and only it can read the seal (#2271, JasonBuildAI: a fallback's seal went unrecorded, and the next turn was answered 200 without the compacted history; `TestNativeCompactionFallbackSealStaysWithItsWriter`). It is recorded by the hash of what it sealed (`wroteCheckpoint`, `compactions.json` beside `affinity.json`, 0600, at most 1024 for 30 days). A later request carrying it goes only to that writer (`checkpointReaders`); a writer whose own list has since dropped the model is tried still, as the last resort an account whose list lacks the model is — it sealed the model's compaction, and no other can read it (`planned.unlisted`, `TestNativeCompactionWriterWhoseListLacksTheModel`, #2642: it was refused as "switched off, removed, or no longer serves" though it was on, and switching it on changed nothing). With the writer gone from the candidates, magpie answers 400 `checkpointError` with the reason its settings give (`checkpointGone`: the provider removed, the account signed out, its sign-in lapsed, paused while others are on, switched off, kept from the model in Names & levels, the key off or gone, the model disabled, or the model or group asked for not going to it), what lets the conversation go on, and whether native compaction is on for the writer's provider now, and never sends it to another key, drops it, or summarises it in its place (`TestNativeCompactionWriterGoneSaysWhy`). One of Codex's own models asked on the backend path is decided as a magpie model is when magpie's Codex accounts serve it (`codexAccounts`): the trigger is kept only with the codex provider's native compaction on, else `codexCompact` gives magpie's summary, which any account reads, and no writer is recorded (#2582, ump45nose; before, every such compaction was sealed natively whatever the setting, and the conversation was held to its account; `TestCodexOwnModelCompactionHonoursTheToggle`). Codex's own sign-in alone, relayed as it came, still compacts natively, unrecorded, as does `/responses/compact`; but a request carrying a compaction magpie recorded the writer of goes through routing even then (`codexSealedFor`), so with the writer switched off the one account left isn't sent it. A legacy `/responses/compact` carrying one is judged at its passthrough (`sealedCompact`): the writer on in magpie answers it signed as the writer — its own seal while the sign-in can be asked, a key's seal, a request signing with its own `chatgpt-account-id`, or an unreadable sign-in state relays as it came — and a writer gone is refused with `checkpointError`'s reason, the same words as on `/responses` (`TestNativeCompactionCompactJudgesItsWriter`, #2727). The writer matched is the account user the record holds, so two Team seats of one email read as one and such a compact relays as it came. A gateway key held to some accounts (#905) is asked of the account the compact goes to (`compactSigninHeld`): the writer when it answers it, so a writer the key may not use is refused 403 (`sealedCompactHeldError`) with nothing asked, and one it may use answers though the sign-in isn't the key's (`TestNativeCompactionCompactKeepsTheKeysAccounts`). With the writer held at its usage cap or for credits it may not spend, the answer is 429 `checkpointCappedError` (record `checkpointCappedRecord`, "native compaction's account at its usage cap"), naming that account, that the others serving the model weren't tried for the compaction, and that neither the routing mode nor how conversations stay changes that: wait for the window, raise or lift its cap, or start a new conversation (#2517, lm0711; before, it read "every account at its usage cap" though another had room; `TestNativeCompactionWriterAtItsCap`). `withoutCompaction` (the drop after a refused reasoning item) isn't used for such a request. A route carrying a compaction names its sealer (`Route.Compaction`), and Routing says that is why no other account was asked, not that it is "the only account on" for the model (#2639; `TestNativeCompactionRouteNamesItsWriter`, `routing-compaction.test.cjs`). A refusal of the trigger reaches Codex as the upstream sent it. Not tried against a real upstream; Copilot may refuse a history that holds Codex's `web_search` items. [`native_compaction.go`](../../internal/gateway/native_compaction.go), `TestNativeCompaction*`. - A compaction magpie answers itself (`codexCompact`: a magpie model, Codex's own models through magpie's Codex accounts, a CC Switch table) goes to Codex as a `compaction` item whose `encrypted_content` is `magpie1:` and the summary in base64 (`codexsummary.Encrypted`), and `codexInputAs` sends Codex's own summary message in its place (`codexsummary.Message`: Codex's summary prefix, a newline and the summary, as a user message). Codex keeps the item in its rollout and replays it, and OpenAI refuses it once Codex talks to OpenAI itself (`invalid_encrypted_content`, LukeMa on X). So `sessions.PortCodexRollouts` writes that same message into the rollouts in its place ([`codex_portable.go`](../../internal/sessions/codex_portable.go)). A reasoning item carrying Claude's block (`magpie-claude1:`, above) is written as its summary, as the gateway sends it to OpenAI (`TestPortLineDropsClaudeBlocks`). It changes only magpie's items, keeps every other line's bytes and the file's line count, mode and time, and drops an unreadable item together with its `replacement_history_metadata` entry. Every rewritten line keeps its length (`fitLine`: a shorter one padded with spaces after its JSON, a longer one in a paginated rollout not written), as Codex keeps places in a rollout by byte: a fork's `history_base.end_byte_offset` and the state database's turn and projection offsets. A shorter parent left a fork's place past its end, and Codex refused to open the fork ("cutoff byte offset is past the source rollout", xybio on Discord); once per Codex home a pass sets each such fork's place again from the ordinal it names (`repairLineages`). `MoveCodexProvider` keeps the session_meta line's length the same way and refuses a longer provider id for a paginated rollout. It and `MoveCodexThreads` (Codex stepping off magpie) hold the thread's writer lock as Codex's own archive does, from before a file is copied until the thread's row has moved: a Codex that has the thread open writes on to the file it opened, and what it wrote after a move was lost (#3751). Such a thread is refused as one written to in the last minute is (`ErrActive`), and a Codex home without writer locks moves as before. A pass publishes as Codex publishes a compressed rollout: under `thread-writer-locks/.coordination.lock`, only with the thread's lock free, through a temp file and a rename. A thread a Codex has open is left for a later pass, and a Codex home without writer locks is left alone. It runs 2 minutes after the GUI or `magpie serve` starts and every 10 minutes after, on Codex Disconnect (3s), and as the GUI quits (3s). Each pass reads what changed since the last whole pass, plus what was held (`codex-portable.json`). A ported thread was resumed by Codex 0.162.1 against an upstream that refuses `magpie1:` as OpenAI does. Not tried: a Codex in a WSL distro, whose locks this machine can't take, so it is skipped. `TestPortCodexRollouts*`, `TestPortedCompactionReadsTheSame`. -- 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 shape taken off (`fromLite`): its `additional_tools` item lifted into `tools` (`liftAdditionalTools`, #350), its `reasoning.context` left out, and its `X-OpenAI-Internal-Codex-Responses-Lite` header not sent on (`liteKept`). A subagent a Lite lead (gpt-6.1-sol) spawns on another model comes in that shape, its model name alone changed, and OpenCode Go's DeepSeek answered it 503 "Endpoint is unavailable" (TangForX on X, `TestLiteSubagentLeavesLite`). Also 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`). That holds when Codex offers `web_search` too: the request is relayed with it, not translated for magpie's search (`searchedForIt`), which merged the developer messages into `instructions`, sent `apply_patch` as a function, left `web_search` out and added `max_output_tokens` (`codexAsSent` in `route`; maralica on Discord). `spawn_agent`'s description is still widened with the catalog's models (`spawnAgentModels`). Off is the default, and a subscription account is never sent so. `TestCodexAsSent`, `TestCodexAsSentWebSearch`. +- 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 shape taken off (`fromLite`): its `additional_tools` item lifted into `tools` (`liftAdditionalTools`, #350), its `reasoning.context` left out, its Lite marker removed from `client_metadata` (`withoutLiteMetadata`), and its `X-OpenAI-Internal-Codex-Responses-Lite` header not sent on (`liteKept`). A Codex websocket turn repeats the marker in `client_metadata`; leaving it beside a removed `reasoning.context` made a downstream Responses relay forward an inconsistent Lite request, which its ChatGPT backend refused with "requires `reasoning.context` to be `all_turns`". A subagent a Lite lead (gpt-6.1-sol) spawns on another model comes in that shape, its model name alone changed, and OpenCode Go's DeepSeek answered it 503 "Endpoint is unavailable" (TangForX on X, `TestLiteSubagentLeavesLite`). Also 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`). That holds when Codex offers `web_search` too: the request is relayed with it, not translated for magpie's search (`searchedForIt`), which merged the developer messages into `instructions`, sent `apply_patch` as a function, left `web_search` out and added `max_output_tokens` (`codexAsSent` in `route`; maralica on Discord). `spawn_agent`'s description is still widened with the catalog's models (`spawnAgentModels`). Off is the default, and a subscription account is never sent so. `TestCodexAsSent`, `TestCodexAsSentWebSearch`, `TestFromLiteRemovesOnlyTheWebsocketLiteMarker`, `TestCodexTitleRelayKeepsLiteShapeConsistent`. - A tool a Chat request's message carries joins the request's `tools` (`liftMessageTools` in [`message_tools.go`](../../internal/gateway/message_tools.go), #2322). Pi with `supportsMidConvoToolAdditions` gives a tool it adds mid-conversation as `{"role":"system","tools":[…]}` with no content, and keeps top-level `tools` as they were at the start; no Chat API reads tools there, and `parseChat` read only the top-level ones, so the tool could be called on no route. `handle` lifts them for every Chat body before `serveAgent`, so the Chat relay, the schema fixers, redaction (the tool is a tool definition, not message text), the prompt shown and routing all see them; `parseChat` lifts too, for a body that never came through `handle` (the Claude subscription bridge's direct callers). Each tool joins once by name and the first definition wins: a top-level tool keeps its own, then the earliest message's, as `liftAdditionalTools` and a `tool_addition` (`withoutDeferredTools`) do. A system or developer message that carried only tools is left out, so it is neither relayed as an empty system message nor joined into the system text as an empty part; one with content keeps its place without `tools`. Messages stay where they are: the in-place system message the issue also asks for is not this change. `TestPiAddedToolReachesEveryRoute` sends deephbz's Pi 1.2.0 bytes through the Chat relay, Messages, Responses, Gemini and Codex, and `TestPiAddedToolOfferedToClaudeCode` through the Claude subscription bridge. - A Chat request's tool in another API's shape is put in the Chat shape, `{"type":"function","function":{name, description, parameters, strict}}` (`shapeChatTools` in [`chat_tool_shape.go`](../../internal/gateway/chat_tool_shape.go), #2622, jinyue806): MCP's `{"name","description","inputSchema"}` (ZCode), Anthropic's `input_schema`, a bare `{"name","parameters"}` and Responses' flat `{"type":"function","name",…}`. No Chat API takes those (SenseNova: "field Tools[0].Type invalid, should be set" and "function cannot be empty"), and `parseChat` read no name from them, so a translated request offered a tool named "". It runs right after `liftMessageTools`, in `handle` for every Chat body and in `parseChat`, so it holds for every Chat upstream, not SenseNova's alone. A tool with its `function`, a hosted tool (any other `type`) and one with no name are left as they came, and a request with none to shape is relayed byte for byte. `TestChatToolInAnotherShapeIsShaped` sends the report's request with each of its four tools through the Chat relay, Messages and Responses; `TestShapeChatToolsLeavesChatShape`. - Every request to a key+URL provider goes with magpie's User-Agent (`magpie/`, `userAgentFor` in [`user_agent.go`](../../internal/gateway/user_agent.go)), except a provider set `passUserAgent` (#1851, `magpie provider set user-agent=agent`, the editor's "Send the agent's own User-Agent"): it gets the User-Agent the inbound request carried, unchanged, for a coding plan that serves only the agents it names. One the agent didn't send, and magpie's own (`magpiesOwn`: another magpie's `magpie/…`, `magpie-router/1`, `magpie-vision/1`, `magpie-search/1`, and the image tool's ` magpie-image/1`, built from MCP's clientInfo, or behind the MCP router from the first word of the agent's User-Agent), go as magpie; magpie never makes up another client's. `forwardOnce` sets it for chat, Anthropic, Responses, Gemini and count_tokens; embeddings, images and videos (`retrieveFrom`, `sendWith`, `remoteVideoContent`) set it with `stampUA` from the caller the request came with (`caller.ua`, `withCaller`), and before #1851 went with Go's default. Claude Code's and Codex's own headers are copied after, as before, and the user's `header.User-Agent` is put on when the request is signed, so it wins. `provider.PassesUserAgent` refuses it for a signed-in account, a plugin's, and a vendor whose own client magpie goes as (`OwnClient`: OpenCode, Cline, Kilo, another magpie); their signing sets their own. `TestUserAgentPassedOn`, `TestUserAgentAccountUntouched`, `TestUserAgentFor`, `TestPassesUserAgent`, `provider-user-agent.test.cjs`. diff --git a/internal/gateway/additional_tools.go b/internal/gateway/additional_tools.go index 5022e4daf..bffe8afc0 100644 --- a/internal/gateway/additional_tools.go +++ b/internal/gateway/additional_tools.go @@ -22,23 +22,53 @@ import ( // Lite also asks for reasoning context "all_turns" (the ChatGPT backend // turns a Lite request away without it, #534) and says it is Lite in the // X-OpenAI-Internal-Codex-Responses-Lite header. Neither is in the -// Responses API anyone else serves. A subagent a GPT lead spawns on another -// model is sent in the lead's Lite shape, its model name alone changed -// (codex-rs builds the child's request from the lead's catalog entry), and -// OpenCode Go's DeepSeek answered it with 503 "Endpoint is unavailable" -// while the same subagent under a DeepSeek lead, not Lite, was answered -// (TangForX on X). So a request leaving Lite has both taken off too -// (fromLite, liteHeaderKept). +// Responses API anyone else serves. A Codex websocket turn also repeats the +// header in client_metadata. A subagent a GPT lead spawns on another model +// is sent in the lead's Lite shape, its model name alone changed (codex-rs +// builds the child's request from the lead's catalog entry), and OpenCode +// Go's DeepSeek answered it with 503 "Endpoint is unavailable" while the +// same subagent under a DeepSeek lead, not Lite, was answered (TangForX on +// X). So a request leaving Lite has all three taken off too (fromLite, +// liteHeaderKept). // liteHeader says a Codex request is Responses Lite. const liteHeader = "X-OpenAI-Internal-Codex-Responses-Lite" // fromLite is a Responses request Codex sent as Responses Lite in the shape // it sends a model that isn't Lite: its additional_tools in its tools -// (liftAdditionalTools) and no reasoning context. A request that isn't -// Lite is returned as it was. +// (liftAdditionalTools), no reasoning context, and no Lite marker in +// client_metadata. A request that isn't Lite is returned as it was. func fromLite(body []byte) []byte { - return withoutReasoningContext(liftAdditionalTools(body)) + return withoutLiteMetadata(withoutReasoningContext(liftAdditionalTools(body))) +} + +// withoutLiteMetadata is body without the Lite marker a Codex websocket +// turn repeats in client_metadata, the rest of client_metadata and every +// other member byte for byte as they were. The marker is removed whatever +// its value, as the header is: a request leaving Lite must not still claim +// to be one. +func withoutLiteMetadata(body []byte) []byte { + const marker = "ws_request_header_x_openai_internal_codex_responses_lite" + if !bytes.Contains(body, []byte(marker)) { + return body + } + r, found, ok := topMember(body, "client_metadata") + if !found || !ok || len(r) == 0 || r[0] != '{' { + return body + } + var m map[string]json.RawMessage + if json.Unmarshal(r, &m) != nil || m == nil { + return body + } + if _, has := m[marker]; !has { + return body + } + delete(m, marker) + nb, err := json.Marshal(m) + if err != nil { + return body + } + return withMembers(body, map[string][]byte{"client_metadata": nb}) } // withoutReasoningContext is body without reasoning.context, the rest of diff --git a/internal/gateway/codex_lite_metadata_test.go b/internal/gateway/codex_lite_metadata_test.go new file mode 100644 index 000000000..3fce571a9 --- /dev/null +++ b/internal/gateway/codex_lite_metadata_test.go @@ -0,0 +1,157 @@ +package gateway + +import ( + "encoding/json" + "net/http" + "net/http/httptest" + "strings" + "testing" + + "github.com/tidwall/gjson" + + "github.com/yetone/magpie/internal/provider" +) + +func TestFromLiteRemovesOnlyTheWebsocketLiteMarker(t *testing.T) { + tests := []struct { + name string + body string + want string + }{ + { + name: "metadata with other fields", + body: `{"client_metadata":{"session_id":"s","ws_request_header_x_openai_internal_codex_responses_lite":"true","x-codex-turn-metadata":"{\"thread_source\":\"thread_title\"}"},"reasoning":{"effort":"low","context":"all_turns"},"input":[]}`, + want: `{"client_metadata":{"session_id":"s","x-codex-turn-metadata":"{\"thread_source\":\"thread_title\"}"},"reasoning":{"effort":"low"},"input":[]}`, + }, + { + name: "boolean marker", + body: `{"client_metadata":{"ws_request_header_x_openai_internal_codex_responses_lite":true,"session_id":"s"},"input":[]}`, + want: `{"client_metadata":{"session_id":"s"},"input":[]}`, + }, + { + name: "false marker", + body: `{"client_metadata":{"ws_request_header_x_openai_internal_codex_responses_lite":false},"input":[]}`, + want: `{"client_metadata":{},"input":[]}`, + }, + { + name: "without marker", + body: `{"client_metadata":{"session_id":"s"},"input":[]}`, + want: `{"client_metadata":{"session_id":"s"},"input":[]}`, + }, + { + name: "non object metadata", + body: `{"client_metadata":"opaque","input":[]}`, + want: `{"client_metadata":"opaque","input":[]}`, + }, + { + name: "malformed body", + body: `{"client_metadata":{"ws_request_header_x_openai_internal_codex_responses_lite":true}`, + want: `{"client_metadata":{"ws_request_header_x_openai_internal_codex_responses_lite":true}`, + }, + } + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + if got := string(fromLite([]byte(test.body))); got != test.want { + t.Fatalf("fromLite:\n got %s\nwant %s", got, test.want) + } + }) + } +} + +func TestCodexTitleRelayKeepsLiteShapeConsistent(t *testing.T) { + for _, asSent := range []bool{false, true} { + name := "default" + if asSent { + name = "as sent" + } + t.Run(name, func(t *testing.T) { + upstream := &fake{t: t} + upstream.refuse = func([]byte) (int, string) { + return http.StatusBadRequest, `{"error":{"message":"diagnostic upstream rejection"}}` + } + setup(t, provider.Responses, upstream) + relay, err := provider.Find("fake") + if err != nil { + t.Fatal(err) + } + relay.CodexAsSent = asSent + if err := provider.Save(*relay); err != nil { + t.Fatal(err) + } + + body := strings.Replace(liteRequest, `"model":"fake/m1",`, + `"model":"fake/m1","reasoning":{"effort":"low","context":"all_turns"},"client_metadata":{"session_id":"title-session","ws_request_header_x_openai_internal_codex_responses_lite":"true","x-codex-turn-metadata":"{\"thread_source\":\"thread_title\"}"},`, 1) + req := liteSent(body) + req.URL.Path = CodexPath + "/responses" + req.RequestURI = "" + req.RemoteAddr = "127.0.0.1:51000" + req.Header.Set("session_id", "title-session") + req.Header.Set("x-codex-turn-metadata", `{"thread_source":"thread_title"}`) + recorder := httptest.NewRecorder() + New().Handler().ServeHTTP(recorder, req) + if recorder.Code != http.StatusBadRequest { + t.Fatalf("upstream diagnostic status = %d, want 400: %s", recorder.Code, recorder.Body) + } + + var got struct { + Reasoning map[string]any `json:"reasoning"` + ClientMetadata map[string]any `json:"client_metadata"` + Input []map[string]any `json:"input"` + } + if err := json.Unmarshal(upstream.got, &got); err != nil { + t.Fatalf("decode upstream request: %v", err) + } + if got.ClientMetadata["session_id"] != "title-session" || + got.ClientMetadata["x-codex-turn-metadata"] != `{"thread_source":"thread_title"}` { + t.Fatalf("unrelated client metadata changed: %v", got.ClientMetadata) + } + _, hasContext := got.Reasoning["context"] + _, hasMarker := got.ClientMetadata["ws_request_header_x_openai_internal_codex_responses_lite"] + hasHeader := upstream.head.Get(liteHeader) != "" + hasAdditionalTools := len(got.Input) > 0 && got.Input[0]["type"] == "additional_tools" + if hasContext != asSent || hasMarker != asSent || hasHeader != asSent || hasAdditionalTools != asSent { + t.Fatalf("asSent=%t: context=%t marker=%t header=%t additional_tools=%t; body=%s", + asSent, hasContext, hasMarker, hasHeader, hasAdditionalTools, upstream.got) + } + }) + } +} + +// Codex over its socket says it is Lite in client_metadata, not a header +// (codex-rs build_ws_client_metadata), and the socket's turn carried the +// marker on to a relay after its reasoning context was taken off: a CPA in +// front of the ChatGPT backend read it as Lite and was refused +// "X-OpenAI-Internal-Codex-Responses-Lite requires `reasoning.context` to be +// `all_turns`" (#4853, ChangQiu on Discord). The turn reaches the relay +// with none of the three. +func TestCodexSocketLiteTurnLeavesLiteForARelay(t *testing.T) { + fresh(t) + u := &respUp{} + sockUp(t, u) + _, ts := sockServer(t) + c, _, err := dialSock(t, ts, CodexPath+"/responses", http.Header{"Openai-Beta": {"responses_websockets=2026-02-06"}}) + if err != nil { + t.Fatal(err) + } + got := c.turn(create("", userHi, + `"reasoning":{"effort":"low","context":"all_turns"}`, + `"client_metadata":{"session_id":"s","ws_request_header_x_openai_internal_codex_responses_lite":"true"}`)) + if last(got).Get("type").String() != "response.completed" { + t.Fatalf("%v", got) + } + if u.calls() != 1 { + t.Fatalf("%d calls", u.calls()) + } + body := u.body(0) + u.mu.Lock() + head := u.head[0] + u.mu.Unlock() + if gjson.GetBytes(body, "reasoning.context").Exists() || + gjson.GetBytes(body, "client_metadata.ws_request_header_x_openai_internal_codex_responses_lite").Exists() || + head.Get(liteHeader) != "" { + t.Errorf("still Lite: header %q, body %s", head.Get(liteHeader), body) + } + if gjson.GetBytes(body, "reasoning.effort").String() != "low" || gjson.GetBytes(body, "client_metadata.session_id").String() != "s" { + t.Errorf("the rest changed: %s", body) + } +}