diff --git a/docs/subsystems/gateway-routing.md b/docs/subsystems/gateway-routing.md index 6cf313f1f..b7332b2c1 100644 --- a/docs/subsystems/gateway-routing.md +++ b/docs/subsystems/gateway-routing.md @@ -355,6 +355,7 @@ recorded as a prediction failure (`noPrediction`). - xAI's own API (api.x.ai, wherever a Grok model is served — the Grok subscription's plugin shapes its own bodies, provider's `grokShaped`) takes none of three things a client's wire puts in wrong (`xaiBody` in [`xai_body.go`](../../internal/gateway/xai_body.go), shaped in `passthrough` and on the built body in `forwardTranslated` alike, for a custom-tool refusal puts a Codex request on the translated path from the next turn on; there is nothing to learn, xAI takes none of them at all, #3392's follow-up): Codex hands a sealed reasoning item back with `"content": null` beside its `encrypted_content`, which the backend answers "Could not decode the compaction blob. Ensure it is unmodified from the compact response." (the first turn goes through, every one after it 400s) — the null goes, the item otherwise as it came; and Claude Code, its messages carrying a system turn mid-conversation since Anthropic made them GA, sends one that xAI's Messages answers "Invalid request content: Invalid message role." — each folds into the top-level `system`, its text and blocks (a `cache_control` kept) as they came, the only place that API takes the role; and a tool's schema can say `"required": null` where none are (Claude Code's own tools, an MCP server's among them — Anthropic's API takes the null), which xAI's validation of each schema answers "Invalid request content: Schema validation failed: [standard_violation] /required: null is not of type \"array\"" (the claude calls 400ed once the system turns folded) — the key goes from every shape a body leaves magpie in, `input_schema`, `parameters` and `function`'s, at the schema's root or nested, a real array of names kept as it came. `TestXAITakesCodexsSealedReasoningBack`, `TestXAILearnsCustomToolsThenTakesTheReplay`, `TestXAIFoldsClaudesSystemTurn`, `TestXAITakesANullRequiredToolSchema`, `TestXaiBodyDropsNullRequiredInEveryShape`. - A tool call's arguments reach the client as the vendor writes them, translated too (echo_ts on Discord: Codex on Copilot about 10x slower, an apply_patch shown only once whole). The Responses decoder hands each `function_call_arguments.delta` and `custom_tool_call_input.delta` on as a `KToolArgs` delta (`argsDelta`), holding back only the one that would make the JSON whole until `.done`, which `endCall` checks against the final arguments; the Responses encoder streams a custom tool's input as `custom_tool_call_input.delta` (`customStream` in [`custom_tool.go`](../../internal/gateway/custom_tool.go)) before its `.done`. A Copilot account's Responses request is relayed with a `web_search` tool in it (`searchesItself`; checked on a real account 2026-10-17), and Copilot is never picked to search for another provider's model (`searchRank`). It is translated instead when a tool marks a parameter `"encrypted": true` (`asksSealing`, MultiAgentV2's `spawn_agent`): Copilot seals such an argument and can't read its own seal on the subagent's turn. `TestCallArgsStreamWhenTranslated`, `TestCustomInputStreams`, `TestResponsesCallArgsStream`, `TestCopilotRelayedUnlessAskedToSeal`, `TestCopilotUltraSubagentWithWebSearch`. - A relayed Responses stream gives each output item the one id its `response.output_item.added` gave it, in every event after that carries an `item_id` or an `item`, and in the `output` of `response.completed`, `response.incomplete` or `response.failed` (`idTidy` in [`itemids.go`](../../internal/gateway/itemids.go), applied in `passthrough` before `phaseTidy`). GitHub Copilot's `/responses` gives an item another id in every event (checked 2026-10-19 on a real account, gpt-5.5 with web_search), and Codex starts an item by the added's id and ends one by the done's, so a commentary message was shown twice and a web search never ended (echo_ts on Discord, `TestCopilotItemKeepsItsID`). An upstream whose ids agree goes through byte for byte (`TestItemIDsThatAgreeGoAsTheyCame`); a translated reply's ids are magpie's own. +- A relayed Responses stream to a client that isn't Codex carries only the OpenAI Responses event enum (`responsesEnumTidy` in [`responses_enum.go`](../../internal/gateway/responses_enum.go), last in `passthrough`'s chain, after `sniff` and `codexLimitsTap` have read the upstream bytes). The ChatGPT backend speaks part of the Codex protocol: `codex.rate_limits`, `codex.response.metadata`, `response.metadata` and a `keepalive` event, and a typed client (Grok Build through async-openai's `ResponseStreamEvent`) read one as an unknown variant and lost the whole turn (#4482, crayonlu). Every event whose `event:` name, or data `type` where it names none, is outside the enum goes; a `keepalive` goes on as an SSE comment, so a quiet upstream still keeps the client's idle timer from running out. Codex itself, by `User-Agent`/`originator` or a key of its own (`fromCodex`, `agentOf`, as `codex_own_v1.go` tells it), gets every event as it came. The same applies to a plugin's Responses reply, which takes the same path. `TestResponsesEventsOutsideTheEnumStayWithCodex`, `TestResponsesEnumAllowed`. - A model's reply limit is published within the window beside it (#1438, `provider.OutputWithin`, `Entry.PublishedOutput`): `/v1/models`' `max_output_tokens` (`modelObject`), Cursor Private Inference's `capabilities.max_output_tokens` (`cursorLocalModel`), Muse Code's `limit.output` (`museModels`), the GUI's model and group rows (`providerInfo`, `providersState`), `magpie model output`, and every agent's file (`agent.maxTokens`, #338). The window and the output can come from different sources: Grok's backend lists grok-4.7's 256000 window, and models.dev fills its 500000 output (`catalog.Decorate` and `Provider.replyLimit` fill an output only where the vendor gives none). An unknown window or output is published as it is. The catalog keeps the unclamped `Entry.Output`, and a group's member is still asked for no more than that (`outputLimit`, `withMaxOutput`), so a request isn't lowered by the clamp. A limit the user set stays in their settings as they set it (`TestModelListsKeepOutputWithinTheWindow`). Outside a group, only a Max output the user set for the model (`Entry.OutputSet`) lowers a request (`userOutput`): Claude Code asks a claude-* model for its own full limit (128000 on Opus 5.5) and is told no figure of magpie's for it (`claudeOutput`), and a key whose quota is held per request as max_tokens times the price turned every turn away (YaCo on Discord, `TestUserMaxOutputLowersAPlainProvidersRequest`). A vendor's or models.dev's figure doesn't lower it, since it may be stale. - `/v1/models` and `/v1/models/{id}` give each model magpie knows a price of its `pricing` in OpenRouter's shape, USD a token as decimal strings: `prompt` and `completion` always (a price set at 0 included), `input_cache_read` and `input_cache_write` only when that part has a price (`catalog.OpenRouterPricing`, `catalog.PerToken` in [`openrouter.go`](../../internal/catalog/openrouter.go), which an agent plugin's `connect` is given too; cleary5779 on Discord, an agent showing what a call costs). The price is the one the Usage page counts the model at (`provider.EntryPricer`, as `EntryPriceIn`: the user's own, else the provider's list price or its maker's at its price rate; a subscription's model at its list price; a group only when every member costs the same), the base price only (no `Tiers`, no 1-hour write). A model no price is known for has no `pricing` key, never a 0. It is told to the callers `magpie_price` is (`local` or `sharedWith`), whether they ask or not. The list reads the settings, groups and providers once (`EntryPricer`), and `catalog.PricedBy` and `AtEndpoint` look a model up in indexes built once a catalog load (`priceIndexOf`, `endpoints`), not by walking every models.dev model a look-up: a 755-model list went from about 38ms to 18ms with pricing on, against about 10ms without, at load 65 (`TestModelsListPricing`, `TestPerToken`). Claude Desktop's, Claude Science's, Muse Code's, Codex's and Ollama's lists, the decision, image and video models carry no `pricing`: their clients read a shape of their own, and an image's price isn't a token's. - `/v1/models` and `/v1/models/{id}` say each chat model takes tools, a routing group included (`toolsTold`): models.dev's `tool_call: true`, beside its `reasoning`, and OpenRouter's `supported_parameters` (`tools`, `tool_choice`, and `reasoning` when it thinks), which Kilo's and Cline's lists are read by. A client that judges a model by what its list says found nothing for a group, whose id is the user's own name (psikent on Discord: an SSH client), and gave it no tools. magpie has no model that takes none (a call written as text is read back as one, `textcalls.go`), so every member of a group takes them and the group says so. No `capabilities` key is added: Cursor Private Inference reads it as an object (`cursorLocalModel`), Ollama and LM Studio as arrays of their own words, and no reader of an OpenAI-shaped list agrees on one (`TestGroupListedTakesTools`). A group's window and output stay its largest member's, its images any member's (#712, #756): the gateway sends a longer conversation, a longer reply or an image only to the members that hold it (`roomy`, `withRoom`, `withMaxOutput`), and the editor's Context hint names the member a longer conversation skips when the windows differ (windy on Discord). @@ -2561,7 +2562,9 @@ serves it on `/v1/responses`, `/responses` and the Codex backend's `x-codex-turn-state`, `openai-model` and `x-reasoning-included`; `codex.response.metadata` with `x-models-etag`, the backend's own event given magpie's tag as `modelsEtag` gives it; `codex.rate_limits` from the - `x-codex-*` windows). A whole JSON reply is told as its stream would be. A + `x-codex-*` windows), to Codex alone: a client that isn't Codex gets none + of them, as on the HTTP route (`TestSocketHeaderFramesOnlyForCodex`, + #4482). A whole JSON reply is told as its stream would be. A refused turn is an `error` frame with the status, the error object and the headers Codex acts on (`Retry-After`, `x-codex-*`, `x-ratelimit-*`). - The conversation a turn continues is the socket's own: each completed diff --git a/internal/gateway/gateway.go b/internal/gateway/gateway.go index a4921a640..ff916f961 100644 --- a/internal/gateway/gateway.go +++ b/internal/gateway/gateway.go @@ -6969,6 +6969,14 @@ func (s *Server) passthrough(w http.ResponseWriter, r *http.Request, p provider. if proto == provider.Anthropic { toolIDs = &toolUseIDs{seen: toolSeen, sse: sse} } + // anything the backend says outside the Responses event enum (the + // account's codex.* events, response.metadata, keepalive), which only + // Codex has a name for (responses_enum.go); any other client gets the + // reply without it + var enumTidy *responsesEnumTidy + if proto == provider.Responses && sse && !fromCodex(r.Header) && agentOf(r) != "codex" { + enumTidy = &responsesEnumTidy{} + } // out is what a filter let through, through ids, phases, toolIDs and // thinkSigs out := func(b []byte) []byte { @@ -7136,6 +7144,9 @@ func (s *Server) passthrough(w http.ResponseWriter, r *http.Request, p provider. if thinkSigs != nil { out = thinkSigs.write(out) } + if enumTidy != nil { + out = enumTidy.write(out) + } if _, werr := write(out); werr != nil { return res.StatusCode, "", true } @@ -7252,6 +7263,9 @@ func (s *Server) passthrough(w http.ResponseWriter, r *http.Request, p provider. if thinkSigs != nil { write(thinkSigs.flush()) } + if enumTidy != nil { + write(enumTidy.flush()) + } if sse { sniff.drain() } else { diff --git a/internal/gateway/gateway_test.go b/internal/gateway/gateway_test.go index aceee3b8f..3ff4c8a8e 100644 --- a/internal/gateway/gateway_test.go +++ b/internal/gateway/gateway_test.go @@ -612,6 +612,40 @@ func TestResponsesClientChatUpstream(t *testing.T) { } } +// Every event magpie writes for a Responses client is shaped as the typed +// client reads it: a sequence_number on each, and a whole Response wherever +// one is carried. A missing field is a turn the client drops whole +// ("serialization error: missing field ..."), which is what let this filter +// after one field at a time fail repeatedly. +func TestResponsesEventsAreClientShaped(t *testing.T) { + f := &fake{t: t, reply: sse( + `data: {"id":"c1","model":"m1","choices":[{"delta":{"content":"ok"}}]}`, + `data: {"id":"c1","choices":[{"delta":{},"finish_reason":"stop"}]}`)} + setup(t, provider.Chat, f) + code, body := post(t, "/v1/responses", `{"model":"m1","stream":true,"input":"hi"}`) + if code != 200 { + t.Fatalf("status %d: %s", code, body) + } + seen := 0 + for _, e := range events(body) { + seen++ + typ, _ := e["type"].(string) + if _, ok := e["sequence_number"]; !ok { + t.Errorf("%s carries no sequence_number: %v", typ, e) + } + if r, ok := e["response"].(map[string]any); ok { + for _, k := range []string{"id", "object", "created_at", "status", "model", "output"} { + if _, ok := r[k]; !ok { + t.Errorf("%s's response lacks %s: %v", typ, k, r) + } + } + } + } + if seen == 0 { + t.Fatal("no events in a translated reply") + } +} + func TestPassthroughRewritesModel(t *testing.T) { f := &fake{t: t, ctype: "application/json", reply: `{"id":"msg","type":"message","content":[]}`} setup(t, provider.Anthropic, f) diff --git a/internal/gateway/passthrough_severed_test.go b/internal/gateway/passthrough_severed_test.go index 920843082..9ad7f551f 100644 --- a/internal/gateway/passthrough_severed_test.go +++ b/internal/gateway/passthrough_severed_test.go @@ -1,6 +1,7 @@ package gateway import ( + "bytes" "encoding/json" "fmt" "io" @@ -9,6 +10,8 @@ import ( "strings" "testing" + "github.com/tidwall/gjson" + "github.com/yetone/magpie/internal/provider" ) @@ -224,13 +227,58 @@ func TestPassthroughStreamWhole(t *testing.T) { // A Responses stream cut short fails as Codex reads a failed turn. func TestPassthroughResponsesEndsShort(t *testing.T) { fresh(t) - f := &fake{reply: sse(`event: response.created`+"\n"+`data: {"type":"response.created","response":{"id":"r1","model":"m1"}}`, - `event: response.output_text.delta`+"\n"+`data: {"type":"response.output_text.delta","delta":"hel"}`)} + f := &fake{reply: sse(`event: response.created`+"\n"+`data: {"type":"response.created","sequence_number":0,"response":{"id":"r1","model":"m1","created_at":1700000000}}`, + `event: response.output_text.delta`+"\n"+`data: {"type":"response.output_text.delta","sequence_number":4,"delta":"hel"}`)} setup(t, "responses", f) code, body := post(t, "/v1/responses", `{"model":"fake/m1","stream":true,"input":"hi"}`) if code != 200 || !strings.Contains(body, `"type":"response.failed"`) || !strings.Contains(body, "Fake:") { t.Fatalf("a Responses stream cut short did not fail: %d %s", code, body) } + // The failed turn's response is a whole Response, as a typed client reads + // it, and the event continues the stream's numbering: the last event the + // client got was numbered 4, so this is 5. + failed := "" + for _, line := range strings.Split(body, "\n") { + if d, ok := strings.CutPrefix(line, "data: "); ok && gjson.Get(d, "type").String() == "response.failed" { + failed = d + } + } + if failed == "" { + t.Fatalf("no response.failed data line: %s", body) + } + for _, field := range []string{"sequence_number", "response.id", "response.object", "response.created_at", "response.status", "response.model", "response.output", "response.error"} { + if !gjson.Get(failed, field).Exists() { + t.Errorf("response.failed lacks %s: %s", field, failed) + } + } + if got := gjson.Get(failed, "sequence_number").Int(); got != 5 { + t.Errorf("response.failed sequence_number = %d, want 5: %s", got, failed) + } + if got := gjson.Get(failed, "response.created_at").Int(); got != 1700000000 { + t.Errorf("response.failed created_at = %d, want the stream's 1700000000: %s", got, failed) + } +} + +// The socket route synthesizes the reply headers' events for Codex alone: a +// typed client on the socket reads codex.response.metadata or codex.rate_limits +// as an unknown variant, as on the HTTP route. +func TestSocketHeaderFramesOnlyForCodex(t *testing.T) { + h := http.Header{} + h.Set("X-Models-Etag", `W/"9e0"`) + h.Set("x-codex-primary-used-percent", "3") + h.Set("x-codex-primary-window-minutes", "300") + h.Set("openai-model", "gpt-5.5") + w := &socketTurnWriter{h: h} + if got := w.headerFrames(); len(got) != 0 { + t.Fatalf("a client that isn't Codex was sent the backend's frames: %q", got) + } + w.codex = true + got := string(bytes.Join(w.headerFrames(), nil)) + for _, want := range []string{"response.metadata", "codex.response.metadata", "codex.rate_limits"} { + if !strings.Contains(got, want) { + t.Errorf("Codex's own request lost %s: %s", want, got) + } + } } // A whole stream whose last event is too big for the sniffer to read (an diff --git a/internal/gateway/responses_enum.go b/internal/gateway/responses_enum.go new file mode 100644 index 000000000..21348ac42 --- /dev/null +++ b/internal/gateway/responses_enum.go @@ -0,0 +1,138 @@ +package gateway + +import ( + "bytes" + "strings" + + "github.com/tidwall/gjson" +) + +// responsesEnum is the OpenAI Responses stream event enum: the names a typed +// Responses client knows. Everything the ChatGPT backend says of its own +// that is not here — codex.rate_limits and codex.response.metadata (the +// account's windows, the model list's tag), response.metadata (the turn's +// headers on a socket, its moderation word on the HTTP route), keepalive (a +// quiet upstream's heartbeat) — is read as an unknown variant by such a +// client, which gives up on the whole turn. The list is the one the client +// names in "expected one of ...", with the audio events OpenAI's own SDK +// also names. +var responsesEnum = map[string]struct{}{ + "response.created": {}, + "response.in_progress": {}, + "response.completed": {}, + "response.failed": {}, + "response.incomplete": {}, + "response.output_item.added": {}, + "response.output_item.done": {}, + "response.content_part.added": {}, + "response.content_part.done": {}, + "response.output_text.delta": {}, + "response.output_text.done": {}, + "response.audio.delta": {}, + "response.audio.done": {}, + "response.audio.transcript.delta": {}, + "response.audio.transcript.done": {}, + "response.refusal.delta": {}, + "response.refusal.done": {}, + "response.function_call_arguments.delta": {}, + "response.function_call_arguments.done": {}, + "response.file_search_call.in_progress": {}, + "response.file_search_call.searching": {}, + "response.file_search_call.completed": {}, + "response.web_search_call.in_progress": {}, + "response.web_search_call.searching": {}, + "response.web_search_call.completed": {}, + "response.reasoning_summary_part.added": {}, + "response.reasoning_summary_part.done": {}, + "response.reasoning_summary_text.delta": {}, + "response.reasoning_summary_text.done": {}, + "response.reasoning_text.delta": {}, + "response.reasoning_text.done": {}, + "response.image_generation_call.completed": {}, + "response.image_generation_call.generating": {}, + "response.image_generation_call.in_progress": {}, + "response.image_generation_call.partial_image": {}, + "response.mcp_call_arguments.delta": {}, + "response.mcp_call_arguments.done": {}, + "response.mcp_call.completed": {}, + "response.mcp_call.failed": {}, + "response.mcp_call.in_progress": {}, + "response.mcp_list_tools.completed": {}, + "response.mcp_list_tools.failed": {}, + "response.mcp_list_tools.in_progress": {}, + "response.code_interpreter_call.in_progress": {}, + "response.code_interpreter_call.interpreting": {}, + "response.code_interpreter_call.completed": {}, + "response.code_interpreter_call_code.delta": {}, + "response.code_interpreter_call_code.done": {}, + "response.output_text.annotation.added": {}, + "response.queued": {}, + "response.custom_tool_call_input.delta": {}, + "response.custom_tool_call_input.done": {}, + "error": {}, +} + +// responsesEnumTidy keeps events outside the Responses enum out of a reply +// to a client that isn't Codex. A client with a closed event enum reads one +// and gives up on the whole turn; Codex has names for the backend's own +// events and reads its limits from them, so its own request still gets every +// event as it came. +type responsesEnumTidy struct { + buf []byte +} + +func (t *responsesEnumTidy) write(b []byte) []byte { + t.buf = append(t.buf, b...) + out, rest := tidyEvents(t.buf, t.event) + t.buf = rest + return out +} + +func (t *responsesEnumTidy) flush() []byte { + b := t.buf + t.buf = nil + return b +} + +// event is one whole SSE event, dropped when it is outside the enum. A +// keepalive goes on as an SSE comment, which every client skips, so a quiet +// upstream's heartbeat still keeps the client's idle timer from running out. +func (t *responsesEnumTidy) event(ev []byte) []byte { + if responsesEnumAllowed(ev) { + return ev + } + if sseEventName(ev) == "keepalive" { + return []byte(": keepalive\n\n") + } + return nil +} + +// responsesEnumAllowed says an event may go to a Responses client: its SSE +// name, or the type its data carries where the stream names none, is in the +// enum. A frame with neither is a comment or a blank separator, not an +// event, and goes as it is. +func responsesEnumAllowed(ev []byte) bool { + name := sseEventName(ev) + if name == "" { + return true + } + _, ok := responsesEnum[name] + return ok +} + +// sseEventName is a frame's `event:` name, else the `type` its data carries, +// else "". +func sseEventName(ev []byte) string { + for _, line := range bytes.Split(ev, []byte("\n")) { + v, ok := bytes.CutPrefix(bytes.TrimRight(line, "\r"), []byte("event:")) + if !ok { + continue + } + return strings.TrimSpace(string(v)) + } + data := eventData(ev) + if len(data) == 0 { + return "" + } + return gjson.GetBytes(data, "type").String() +} diff --git a/internal/gateway/responses_enum_test.go b/internal/gateway/responses_enum_test.go new file mode 100644 index 000000000..6dfd61ec6 --- /dev/null +++ b/internal/gateway/responses_enum_test.go @@ -0,0 +1,146 @@ +package gateway + +import ( + "encoding/base64" + "encoding/json" + "fmt" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "strings" + "testing" + "time" + + "github.com/yetone/magpie/internal/provider" +) + +// backendLeads is a turn as the ChatGPT backend answers it: it says what it +// knows of the account first, in the two events only Codex has a name for +// (codex.rate_limits with its windows, codex.response.metadata with the +// model list's tag), then the reply, with keepalive (a quiet upstream's +// heartbeat) and response.metadata (the moderation word) between its deltas. +var backendLeads = sse( + `event: codex.rate_limits`+"\n"+`data: {"type":"codex.rate_limits","plan_type":"plus","rate_limits":{"allowed":true,"limit_reached":false,"primary":{"used_percent":3,"window_minutes":300,"reset_after_seconds":100}}}`, + `event: codex.response.metadata`+"\n"+`data: {"type":"codex.response.metadata","headers":{"x-models-etag":"W\"9e0\""}}`, + `event: response.created`+"\n"+`data: {"type":"response.created","response":{"id":"r1","model":"gpt-5.5"}}`, + `event: response.output_text.delta`+"\n"+`data: {"type":"response.output_text.delta","delta":"a cat"}`, + `event: keepalive`+"\n"+`data: {"type":"keepalive"}`, + `event: response.metadata`+"\n"+`data: {"type":"response.metadata","sequence_number":5,"response_id":"r1","metadata":{"openai_chatgpt_moderation_metadata":{"generation":{},"tool_call":{},"tool_response":{}}}}`, + `event: response.completed`+"\n"+`data: {"type":"response.completed","response":{"id":"r1","status":"completed","usage":{"input_tokens":9,"output_tokens":2}}}`) + +// leadSignIn puts one ChatGPT sign-in in a temp home and points the +// backend at f, as the ChatGPT answers come from there. +func leadSignIn(t *testing.T, f http.Handler) { + t.Helper() + home := t.TempDir() + t.Setenv("HOME", home) + t.Setenv("USERPROFILE", home) + t.Setenv("XDG_CONFIG_HOME", filepath.Join(home, ".config")) + t.Setenv("XDG_CACHE_HOME", filepath.Join(home, ".cache")) + claims := func(m map[string]any) string { + b, _ := json.Marshal(m) + return "h." + base64.RawURLEncoding.EncodeToString(b) + ".s" + } + os.MkdirAll(filepath.Join(home, ".codex"), 0o755) + auth := fmt.Sprintf(`{"auth_mode":"chatgpt","tokens":{"id_token":%q,"access_token":%q,"refresh_token":"r","account_id":"acct-1"}}`, + claims(map[string]any{"email": "me@example.com"}), + claims(map[string]any{"exp": time.Now().Add(time.Hour).Unix()})) + if err := os.WriteFile(filepath.Join(home, ".codex", "auth.json"), []byte(auth), 0o600); err != nil { + t.Fatal(err) + } + up := httptest.NewServer(f) + t.Cleanup(up.Close) + old := provider.CodexBase + provider.CodexBase = up.URL + "/backend-api/codex" + t.Cleanup(func() { provider.CodexBase = old }) +} + +// leadTurn posts a Responses turn with some client's User-Agent and key. +func leadTurn(t *testing.T, body, ua, key string) (int, string) { + t.Helper() + rec := httptest.NewRecorder() + req := httptest.NewRequest("POST", "/v1/responses", strings.NewReader(body)) + req.Header.Set("Content-Type", "application/json") + req.Header.Set("Authorization", "Bearer "+key) + if ua != "" { + req.Header.Set("User-Agent", ua) + } + New().Handler().ServeHTTP(rec, req) + return rec.Code, rec.Body.String() +} + +// A client that isn't Codex gets a ChatGPT account's reply with every event +// outside the OpenAI Responses enum gone: Grok Build reads the stream +// through a typed event enum, and an event type it has no name for ends the +// turn with "unknown variant " before any of the reply is seen. Codex's +// own request — by User-Agent or by a key of its own — still gets them, +// which is where it reads its windows. +func TestResponsesEventsOutsideTheEnumStayWithCodex(t *testing.T) { + const body = `{"model":"codex/gpt-5.5","stream":true,"input":"what is this?"}` + for _, who := range []struct { + ua string + key string + want bool // the backend's own events are for this client + says string + }{ + {"", "magpie", false, "a client with no User-Agent"}, + {"xai-grok-shell/1.0.45", "magpie", false, "Grok Build"}, + {"codex_cli_rs/0.166.0", "magpie", true, "Codex CLI"}, + {"xai-grok-shell/1.0.45", "magpie-codex", true, "a key owned by the codex agent"}, + } { + f := &fake{t: t, ctype: "none", reply: backendLeads} + leadSignIn(t, f) + code, got := leadTurn(t, body, who.ua, who.key) + if code != 200 || !strings.Contains(got, `"delta":"a cat"`) || !strings.Contains(got, "response.completed") { + t.Fatalf("%s: %d %s", who.says, code, got) + } + var seen []string + for _, line := range strings.Split(got, "\n") { + if name, ok := strings.CutPrefix(line, "event: "); ok { + seen = append(seen, name) + } + } + t.Logf("%s received: %v", who.says, seen) + for _, ev := range []string{"codex.rate_limits", "codex.response.metadata", "response.metadata", "keepalive"} { + if has := strings.Contains(got, "event: "+ev+"\n"); has != who.want { + t.Errorf("%s: event %s there=%v, want %v: %s", who.says, ev, has, who.want, got) + } + } + // the heartbeat a foreign client loses as an event still reaches it, + // as a comment its SSE reader skips + if !who.want && !strings.Contains(got, "\n: keepalive\n\n") { + t.Errorf("%s: the keepalive did not go on as a comment: %s", who.says, got) + } + if f.path != "/backend-api/codex/responses" { + t.Errorf("%s: asked %s", who.says, f.path) + } + } +} + +// The enum predicate on its own: the backend's own names are out, the +// enum's are in, and a frame that names no event (a comment) is not an +// event and goes. +func TestResponsesEnumAllowed(t *testing.T) { + for _, c := range []struct { + ev string + want bool + }{ + {"event: codex.rate_limits\ndata: {\"type\":\"codex.rate_limits\"}\n\n", false}, + {"event: response.metadata\ndata: {\"type\":\"response.metadata\"}\n\n", false}, + {"event: keepalive\ndata: {\"type\":\"keepalive\"}\n\n", false}, + // no event line: the data's type decides + {"data: {\"type\":\"keepalive\"}\n\n", false}, + {"data: {\"type\":\"codex.response.metadata\"}\n\n", false}, + {"event: response.created\ndata: {\"type\":\"response.created\"}\n\n", true}, + {"event: response.output_text.delta\ndata: {\"type\":\"response.output_text.delta\"}\n\n", true}, + {"data: {\"type\":\"response.completed\"}\n\n", true}, + {"event: error\ndata: {\"type\":\"error\"}\n\n", true}, + // a comment, not an event + {": keepalive\n\n", true}, + } { + if got := responsesEnumAllowed([]byte(c.ev)); got != c.want { + t.Errorf("%q: allowed=%v, want %v", c.ev, got, c.want) + } + } +} diff --git a/internal/gateway/responses_ws.go b/internal/gateway/responses_ws.go index b912228d0..336dce131 100644 --- a/internal/gateway/responses_ws.go +++ b/internal/gateway/responses_ws.go @@ -502,7 +502,8 @@ func (rs *responsesSocket) turn(ctx context.Context, t *socketTurnRun, frame []b socketTurnBody(body) } req := rs.request(ctx, body) - out := &socketTurnWriter{rs: rs, ctx: ctx, run: t, h: http.Header{}} + out := &socketTurnWriter{rs: rs, ctx: ctx, run: t, h: http.Header{}, + codex: fromCodex(req.Header) || agentOf(req) == "codex"} rs.o.via.ServeHTTP(out, req) out.finish() if ctx.Err() != nil { @@ -645,10 +646,11 @@ func (rs *responsesSocket) request(ctx context.Context, body []byte) *http.Reque // as the socket's frames: each event of a stream as one, an error as an // error frame. type socketTurnWriter struct { - rs *responsesSocket - ctx context.Context - run *socketTurnRun - h http.Header + rs *responsesSocket + ctx context.Context + run *socketTurnRun + h http.Header + codex bool // the client is Codex's own: the backend's events are for it status int stream bool @@ -722,6 +724,12 @@ func (w *socketTurnWriter) startStream() { // response.metadata, the model list's tag in codex.response.metadata, // and the account's windows in codex.rate_limits. func (w *socketTurnWriter) headerFrames() [][]byte { + // Codex's own events, which a typed client on the socket reads as + // unknown variants and gives up on (as on the HTTP route, the same + // guard in passthrough) + if !w.codex { + return nil + } var out [][]byte meta := map[string]string{} for _, k := range []string{"x-codex-turn-state", "openai-model", "x-reasoning-included"} { diff --git a/internal/gateway/responses_ws_test.go b/internal/gateway/responses_ws_test.go index 74c8001a6..869b2c38f 100644 --- a/internal/gateway/responses_ws_test.go +++ b/internal/gateway/responses_ws_test.go @@ -600,7 +600,7 @@ func TestCodexSocketServed(t *testing.T) { }) _, ts := sockServer(t) h := http.Header{"Authorization": {"Bearer chatgpt-token"}, "Chatgpt-Account-Id": {"acct-1"}, - "Openai-Beta": {"responses_websockets=2026-02-06"}} + "Openai-Beta": {"responses_websockets=2026-02-06"}, "User-Agent": {"codex_cli_rs/0.166.0"}} c, resp, err := dialSock(t, ts, CodexPath+"/responses", h) if err != nil { code := 0