Every agent's model. One place. Codex on DeepSeek, Claude Code on Kimi, from the menu bar.
gateway: a relayed Chat reply that made calls and ended "stop" ends "tool_calls", streamed and whole
yetone9a0df964e428
diff --git a/docs/subsystems/gateway-routing.md b/docs/subsystems/gateway-routing.mdindex 601232be5..60f2bdc55 100644--- a/docs/subsystems/gateway-routing.md+++ b/docs/subsystems/gateway-routing.md@@ -142,6 +142,7 @@ recorded as a prediction failure (`noPrediction`).- A request built for a Messages upstream (`buildAnthropic`: a Chat, Responses or Gemini client translated) has its tool exchanges mended after its messages are built (`pairToolBlocks`, #1558, ggbdpq), since Anthropic answers 400 for a `tool_use` the next message doesn't answer and for a `tool_result` naming no call of the message before it. A call left unanswered gets the synthetic interrupted result, `is_error` set, first in the user message after it or in one of its own; a result that answers no call goes as a text block with what it said (its images as they came); a second answer to one call is dropped. A well-formed exchange goes as it was built. An Anthropic client relayed to a Messages upstream isn't mended. [`anthropic_tool_pairing_test.go`](../../internal/gateway/anthropic_tool_pairing_test.go).- A Responses request bound for anything but a ChatGPT sign-in has its tool exchanges mended in `attempt`, before it is relayed or translated, plugins included ([`responses.go`](../../internal/gateway/responses.go)). An item inside a run of calls and results (after one of the run's results and before the last, or before any result when the model didn't write it) moves to the end of that run (`joinToolRuns`, #1752, Edward4226): Codex writes its `<image_resize_notice>` right after each result whose image it resized, so a batch of two calls had it between their results, and a strict upstream answered 400 (OpenCode Go/DeepSeek "No tool output found for tool call …", Volcengine's "must be followed by tool messages", #1822); a Chat translation answered the second call with a synthetic result. An item carrying a `call_id` never moves, the model's own reasoning between its calls stays, and its text between them (an assistant message, with the reasoning right before it) goes ahead of the run's first call, so the step's calls stand together: OpenCode Go opens a new assistant message at such text and answered the call before it "No tool output found for tool call …" (#2100). A call opens a run only when a result after it answers it. A result with no call id becomes a user message after its run (`orphanedToolOutputs`), and a call nothing answers gets a synthetic result at the end of its run (`pairToolItems`, #1341). `TestRelayedCodexImageBatchKeepsItsResultsTogether`, `TestJoinToolRunsOnlyMovesWhatBreaksARun`, `TestRelayedTextBetweenABatchsCallsIsAnswered`.- A Chat request has every tool call that came with no id (`""`, null or none) given one in `attempt`, before it is relayed or translated, plugins included (`chatCallIDs` in [`chat_call_ids.go`](../../internal/gateway/chat_call_ids.go), #2611, RunMintOn). An upstream that sometimes streams a call without an id (OpenCode Zen's free DeepSeek) has the agent keep it as `""`, which that upstream takes back, while WorkBuddy AI turns a streamed request carrying one away (400, code 11133) and Anthropic takes no empty `tool_use` id. The id is made from the call's place in the request, its name and its arguments, never at random, so the next turn's history goes byte for byte and the upstream's prompt cache holds; the tool messages after the call that answer with no `tool_call_id` take the made ids in the calls' order. A body whose calls all have ids goes as it came. On the reply side, a relayed Chat stream's call whose first fragment has no id is given one, and a later fragment's empty id is left out (`chatTidy`); a whole reply's call is given one too (`chatWhole`). `TestEmptyCallIDRelayedWithOne`, `TestEmptyCallIDReachesPluginWithOne`, `TestEmptyCallIDTranslatedWithOne`, `TestStreamedCallGivenAnID` in [`chat_call_ids_test.go`](../../internal/gateway/chat_call_ids_test.go).+- A relayed Chat reply whose choice made calls and ended `stop` ends `tool_calls`, streamed (`chatTidy`) and whole (`chatWhole`), as the translations' collector already ends it (`collector.finish`): told it stopped, a client that reads `finish_reason` ends its turn with the calls not run (喜欢一个人 on Discord, a relay in front of deepseek-v4.1-flash). Any other reason stays as it came. `TestChatCallsEndToolCalls` in [`chattidy_finish_test.go`](../../internal/gateway/chattidy_finish_test.go).- 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`). The account's own models kept out of agents' lists for routing groups (`provider.CodexNativeUnlisted`) are dropped from it too, hidden ones kept: every one when the codex provider is "Only through routing groups" (`Provider.Unlisted`), and those a group that unlists its members names (`Group.Unlists`). A Codex there only for failover keeps them, as it is handed no groups; `spawnChoices` drops the same ones (#1602, `TestCodexModelListUnlistedForGroups`).- 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 Messages 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. The signature itself is kept in magpie's folder, `gemini-signatures/<key>`, named by its hash (`keepSignature` in [`gemini_sigstore.go`](../../internal/gateway/gemini_sigstore.go)), and the id carries only the key (`__tsk16__<key>`), so an id stays under 64 characters however long the step's signature (#2411: LobeHub's PostgreSQL index turned away a 3KB id). A key magpie no longer has, or whose file doesn't hash to it, reads as no signature; one not read for 90 days is removed. Where the folder can't be written, the id carries the signature as before. 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 summary is wanted only whole (`askWhole`, `holdWriter.wantWhole`): its stream is held to its end, not let through at its first words, so a reply cut short (`errEndedShort`), failed halfway (a 429 "Individual quota reached" after some of it) or ended `incomplete` (`endedIncomplete`, `incompleteReply`) fails over to the next candidate like a failure before any of it, and rests the account as that failure would; one that reached its output limit rests nobody. With nobody left, `codexCompact` answers 502 and never hands Codex the words before the cut as the summary (#2274, huangzuomin: Antigravity cutting each summary short). Codex with context_management's experimental mode compacts in the background at every step while the conversation is over its threshold and drops a failed compaction without a word, so a conversation whose summaries keep failing is asked again every few seconds, each paying for the whole history (1169 compactions in 6 hours there). After `compactFailsMost` (3) failed summaries in a row of one conversation (`prompt_cache_key`) on one model, each within `compactHeldFor` (5 minutes) of the last, the next is answered at once with a 400 naming the last failure, which Codex doesn't ask again, and no model is asked until 5 minutes have passed (`compactFails` in [`codex_compact_guard.go`](../../internal/gateway/codex_compact_guard.go)); a summary that comes clears the count, and a sign-in's 401 or 403 isn't counted. `TestCodexCompactCutSummaryFailsOver`, `TestCodexCompactCutSummaryIsNoSummary`, `TestCodexCompactKeepsFailingIsHeld`.diff --git a/internal/gateway/chattidy.go b/internal/gateway/chattidy.goindex c872e7b31..684320165 100644--- a/internal/gateway/chattidy.go+++ b/internal/gateway/chattidy.go@@ -47,10 +47,16 @@ import (// which a strict upstream it is sent to later turns away (#2611): such a// fragment is given an id, and a later fragment's empty one is left out.//+// And a choice that made calls and ended "stop" ends "tool_calls": told+// it stopped, a client that reads finish_reason ends its turn there with+// the calls not run (喜欢一个人 on Discord, a relay in front of+// deepseek-v4.1-flash), as the translations' collector already has it.+//// Lines pass whole, as they came, unless one has any of them.type chatTidy struct {- buf []byte- ids streamCallIDs+ buf []byte+ ids streamCallIDs+ called map[int]bool // the choices that made a call}var (@@ -84,7 +90,7 @@ func (t *chatTidy) flush() []byte {}func (t *chatTidy) lines(b []byte) []byte {- if !needsTidy(b) {+ if !t.needs(b) {return append([]byte(nil), b...)}var out []byte@@ -112,11 +118,18 @@ func needsTidy(line []byte) bool {bytes.Contains(line, toolCallsField)}+// needs is needsTidy, and a finish_reason once a choice made a call.+func (t *chatTidy) needs(b []byte) bool {+ return needsTidy(b) || len(t.called) > 0 && bytes.Contains(b, finishReasonField)+}++var finishReasonField = []byte(`"finish_reason"`)+// tidyLine mends one line as the first of a stream.func tidyLine(line []byte) []byte { return (&chatTidy{}).line(line) }func (t *chatTidy) line(line []byte) []byte {- if !needsTidy(line) {+ if !t.needs(line) {return line}body := bytes.TrimRight(line, "\r\n")@@ -139,6 +152,8 @@ func (t *chatTidy) line(line []byte) []byte {c["finish_reason"] = json.RawMessage("null")changed = true}+ choice := k+ decodeJSON(c["index"], &choice)var delta map[string]json.RawMessageif decodeJSON(c["delta"], &delta) != nil {continue@@ -155,8 +170,10 @@ func (t *chatTidy) line(line []byte) []byte {if t.ids == nil {t.ids = streamCallIDs{}}- choice := k- decodeJSON(c["index"], &choice)+ if t.called == nil {+ t.called = map[int]bool{}+ }+ t.called[choice] = trueif mended, chg := t.ids.mend(choice, calls); chg {calls, delta["tool_calls"] = mended, mendedinDelta = true@@ -170,6 +187,10 @@ func (t *chatTidy) line(line []byte) []byte {c["delta"], _ = json.Marshal(delta)changed = true}+ if t.called[choice] && string(bytes.TrimSpace(c["finish_reason"])) == `"stop"` {+ c["finish_reason"] = json.RawMessage(`"tool_calls"`)+ changed = true+ }}if !changed {return line@@ -324,6 +345,12 @@ func (t *chatWhole) flush() []byte {}mended = true}+ // calls the upstream made, ended "stop" (chatTidy)+ var native []json.RawMessage+ if string(bytes.TrimSpace(c["finish_reason"])) == `"stop"` && decodeJSON(msg["tool_calls"], &native) == nil && len(native) > 0 {+ c["finish_reason"] = json.RawMessage(`"tool_calls"`)+ changed = true+ }if !mended {continue}diff --git a/internal/gateway/chattidy_finish_test.go b/internal/gateway/chattidy_finish_test.gonew file mode 100644index 000000000..4087353af--- /dev/null+++ b/internal/gateway/chattidy_finish_test.go@@ -0,0 +1,55 @@+package gateway++import (+ "strings"+ "testing"+)++// 喜欢一个人 on Discord: a relay in front of deepseek-v4.1-flash made the+// calls and ended the reply "stop", and a Chat client that reads+// finish_reason ended its turn with them not run. A relayed Chat reply+// that made calls ends "tool_calls", streamed and whole; one that made+// none keeps its "stop", and the other reasons stay as they came.+func TestChatCallsEndToolCalls(t *testing.T) {+ stream := `{"model":"a/m","stream":true,"messages":[{"role":"user","content":"go"}],` + execChatTool + `}`+ _, calls, finish, raw := relayedChat(t, stream, chunkOf("Running it."), nativeExec, stopChunk)+ if calls["exec_command"] != `{"cmd":"ls -la"}` || finish != "tool_calls" || !strings.Contains(raw, `"total_tokens":5`) {+ t.Fatalf("stream: calls %v finish %q\n%s", calls, finish, raw)+ }+ // with no tools offered, the same+ _, _, finish, raw = relayedChat(t, `{"model":"a/m","stream":true,"messages":[{"role":"user","content":"go"}]}`, nativeExec, stopChunk)+ if finish != "tool_calls" {+ t.Fatalf("stream, no tools offered: finish %q\n%s", finish, raw)+ }+ _, _, finish, raw = relayedChat(t, stream, chunkOf("Hi."), stopChunk)+ if finish != "stop" {+ t.Fatalf("stream, no call: finish %q\n%s", finish, raw)+ }+ _, _, finish, raw = relayedChat(t, stream, nativeExec, strings.Replace(stopChunk, `"stop"`, `"length"`, 1))+ if finish != "length" {+ t.Fatalf("stream cut short: finish %q\n%s", finish, raw)+ }++ whole := func(content, reason string) string {+ return `{"id":"c1","object":"chat.completion","created":1791370000,"model":"m","choices":[{"index":0,"message":{"role":"assistant","content":` + content + `,"tool_calls":[{"id":"call_up","type":"function","function":{"name":"exec_command","arguments":"{\"cmd\":\"ls -la\"}"}}]},"finish_reason":"` + reason + `"}]}`+ }+ for _, body := range []string{+ `{"model":"a/m","messages":[{"role":"user","content":"go"}],` + execChatTool + `}`,+ `{"model":"a/m","messages":[{"role":"user","content":"go"}]}`,+ } {+ for _, c := range []struct{ content, reason, want string }{+ {`"Running it."`, "stop", "tool_calls"},+ {`null`, "stop", "tool_calls"},+ {`null`, "length", "length"},+ } {+ _, wcalls, finish, raw := wholeChat(t, body, "application/json", whole(c.content, c.reason))+ if len(wcalls) != 1 || finish != c.want {+ t.Fatalf("whole %s %s: calls %+v finish %q\n%s", c.content, c.reason, wcalls, finish, raw)+ }+ }+ }+ _, _, finish, raw = wholeChat(t, `{"model":"a/m","messages":[{"role":"user","content":"go"}],`+execChatTool+`}`, "application/json", wholeChatUp("Hi."))+ if finish != "stop" {+ t.Fatalf("whole, no call: finish %q\n%s", finish, raw)+ }+}diff --git a/internal/gateway/gemini_compat_cut_test.go b/internal/gateway/gemini_compat_cut_test.goindex 9a785fc45..be7a25e47 100644--- a/internal/gateway/gemini_compat_cut_test.go+++ b/internal/gateway/gemini_compat_cut_test.go@@ -76,13 +76,15 @@ func TestGeminiCompatRelayEndedShort(t *testing.T) {t.Errorf("a cut reply given a finish_reason: %s", body)}- // whole, with [DONE] or without it, it goes as it came+ // whole, with [DONE] or without it, it goes as it came, its one+ // finish_reason "tool_calls" as it made a call (chatTidy, 喜欢一个人+ // on Discord), never a second one addedfor what, reply := range map[string]string{"whole": compatCall + compatStop + compatDone,"whole, no [DONE]": compatCall + compatStop,} {code, body := compatServer(t, "gemini-4-argon", reply, "/v1/chat/completions", ask)- if code != 200 || strings.Contains(body, "ended before") || strings.Count(body, `"finish_reason":"`) != 1 || !strings.Contains(body, `"finish_reason":"stop"`) {+ if code != 200 || strings.Contains(body, "ended before") || strings.Count(body, `"finish_reason":"`) != 1 || !strings.Contains(body, `"finish_reason":"tool_calls"`) {t.Errorf("%s: %d %s", what, code, body)}}