gateway: a Chat turn's thinking is read in every spelling the client … (#1075)

* gateway: a Chat turn's thinking is read in every spelling the client sends it back in

A client sends the previous assistant turn's thinking back in reasoning_content (DeepSeek's, which OpenCode and most clients send), reasoning (OpenRouter's) or reasoning_details (OpenRouter's structured one). parseChat read only reasoning_content, so a request translated to a non-Chat upstream lost the thinking of every turn sent another way and the model went on without its own reasoning, which a tool-calling session shows from its second turn on. chattidy's passthrough has read all three since mistralThinking (#494); the parse layer never got the same reader.

The assistant branch now reads the thinking through reasoningText, messageReasoning's own reader, in the order the passthrough keeps it: reasoning_content, else reasoning, else reasoning_details' text.

TestParseChatReadsEveryReasoningSpelling (a tool-calling turn per spelling) and TestParseChatTakesTheFirstReasoningSpellingSent fail without the change ("the assistant turn's parts: [{Kind:tool_call ...}]"). go vet -tags nogui ./internal/gateway/..., builds for windows, darwin and linux, and the package's chat/reasoning/thinking tests pass.

* docs: the Chat parse layer reads the thinking's spellings too

The change reads a Chat turn's thinking through messageReasoning and
reasoningText, so parseChat takes the same three spellings the
passthrough has taken since mistralThinking (#494). AGENTS.md asks for the
owning reference to be updated in the same PR, and gateway-routing.md said
nothing of it: its reasoning bullets are about holding a reply's own
reasoning for a failover and about what a translated Responses reply gives
Codex, not about what a client sends back.

A bullet beside the held-reasoning one now records the spellings, the
order they are read in, and the gap that was there: the parse layer read
reasoning_content alone, so a tool-calling session whose client spelled it
another way went on without the model's own reasoning.

---------

Co-authored-by: TryWorld <TryWorld2026@users.noreply.github.com>
This commit is contained in:
TryWorld
2026-10-13 09:41:46 +08:00
committed by GitHub
co-authored by TryWorld
parent a0c00370f9
commit 184f9184d3
3 changed files with 103 additions and 3 deletions
+1
View File
@@ -59,6 +59,7 @@ served by a plugin are in [Provider and plugin ownership](provider-plugins.md).
- A streamed request is never left silent while its vendor says nothing. `holdWriter.watch` runs beside each try: past `keepHeldAfter` (15s) it sends a held try's agent the stream's 200 and SSE comments (`keepAlive`), none of the try, so another candidate may still answer in the same stream; once the reply passes, it puts a comment between two of its lines after `keepaliveEvery` of quiet. It stops after `keepaliveLongest` (5 minutes) with nothing from the vendor. A try waiting for its key's or account's slot or for room in its minute (`lanes.take`, `rpms.wait`) is kept alive the same way (`keepQueued`), for as long as it waits; once the 200 is out, the try is held, and its failure or its queue turning it away reaches the agent as the stream's error (`failTo`), not a status (coeo91 on Discord). A wait shorter than `keepHeldAfter` sends nothing, so its 429 keeps its `Retry-After`. A proxy in front such as Cloudflare (125s) otherwise ends the request (#947). Gemini streams get no comments (#934). A vendor that then ignores `stream:true` and answers 200 with its reply whole has it sent as the agent's stream (`wholeAsStream`: Chat, Responses, Anthropic), not as the stream's error, while a reply under a type that says neither JSON nor a stream is held as a stream when its first bytes are one (`sseStart`), read event by event like one that says so, so an error among its frames still goes to the next candidate (#1418: it went through at once); a 200 that is no reply of the protocol's fails as a translated reply that didn't stream does (502, "… did not stream"), for the next candidate to answer, and the last one's reaches the agent as the stream's error. A held stream that has sent nothing but the frames before a reply (`response.created`, `response.in_progress`, `codex.rate_limits`, pings, an empty part begun, and any event `streamEvent` doesn't know to carry text, reasoning, a call or a reply's end (`replyEvent`), or an item not known that isn't a call or a tool's (`streamPart.said`): `eventLead`; Aliceonly on #1418: an unknown event was taken for content and let a frames-only 200 through, and its `server_is_overloaded` reached Codex with five candidates left) stays held as long as its agent is kept alive, up to `holdLead` (4 minutes, under the 300s Codex waits for an event; `keptQuiet`), so a `server_is_overloaded` that comes after it is a failure the next candidate answers (#1418: let through at 15s, the ChatGPT backend's failure 36s in ended Codex's turn with sub2api, next in the group, never asked). A stream whose agent can't be kept alive (Gemini's) is let through after `holdLongest` (15s), as before. Codex counts only events toward that 300s, not comments, so the bound is the request's, not each try's: once Codex on Responses has heard no event for `agentQuietMost` (4 minutes) since the request began or its last event (`keptAlive.tooQuiet`), the try in hand is let through (`scan`, `keepQuiet`), and no group replan or same-one retry is taken whose pause would end past it (fadenoob on Discord: held tries and replan pauses added up past 300s and Codex reconnected on "idle timeout waiting for SSE"). A translated reply whose upstream stream stops before it said its reply had — an Anthropic one with no stop_reason and no message_stop, a Responses one with no `response.completed`, the same two a relayed one is told by (`sniff.whole`; a Chat stream may end without `[DONE]` and be whole), a Gemini or Code Assist one whose last chunk has no candidate's `finishReason` (`geminiEnds`, #1643: `usageMetadata` is no end, Vertex AI sends it on every chunk; a chunk with no candidate at all is the empty reply's to answer, #667), and a relayed Gemini one told the same way (#1644; it ends in Gemini's own `{"error":{"code":502,…,"status":"UNAVAILABLE"}}` data line from `streamFailure`, `TestGeminiRelayEndedShort`) — ends the turn with "the reply ended before it was complete" (`errEndedShort`, `TestResponsesUpstreamEndedShort`, `TestGeminiUpstreamEndedShort`), asked again in place where the upstream goes on from a prefill (`continuation.go`). A client that asked for no stream is told the same 502 of such a cut (`translate`, `TestNonStreamEndedShort`, `TestGeminiNonStreamEndedShort`), rather than handed what came as its whole reply.
- Claude's, GPT's and Gemini's reasoning is held (`refusesAfterThinking`, up to `holdThinking`, 4 minutes) so that a refusal after it goes to the next candidate unseen (#248). It is held only while one could: on the last candidate a refusal isn't asked again, so Claude's and GPT's reasoning streams as it comes there, and a refusal after it reaches the agent as the vendor's own. Held there, a lone relay's Claude or GPT showed Claude Code its thinking all at once with the text, and Codex none until then (iTianbao on X). Gemini's stays held on the last candidate too, for a reply that only reasoned to be asked again (#667). Any other model's reasoning is never held.
- A streamed reply stuck in a loop is ended, not let run to its output limit (#1359, Moody-Sin: WorkBuddy's DeepSeek v4.1 flash reasoned round "Now." "Writing." "Go." "Let me write." "OK." until max tokens while dsh and Pi waited). `holdWriter.Write` feeds every streamed try, passed through or translated, a key's, a built-in subscription's or a plugin's (a moved WorkBuddy's fetch in the plugin host, `TestLoopEndsWorkBuddysReply`), in each of the agent's protocols, to a `loopGuard` ([`loop_guard.go`](../../internal/gateway/loop_guard.go)). It cuts the reasoning and the text, each apart, into units, its lines and sentences (a list's `1.` or a decimal is no sentence's end), compared without case or a closing stop. A unit with no word in it (a letter run with no digit: not a brace, a rule, `0x00`, a hash or a row of numbers) isn't counted. When the last `loopWindow` (256) counted units of either are among no more than `loopDistinct` (24) different ones, the try is cut (`cutLoop`): what came with that write goes out, then the protocol's stream error (`streamError`, 502) naming the loop and quoting its units, and the vendor's request is cancelled. It falls back to nobody and rests nobody (`failLoop`); its usage record's error type is `reply_loop` (`usage.LoopErrType`), and Usage counts them per model (`Totals.Loops`), as "{n} looped" beside the model's failures in the Overview's rows and the Requests ranking (#1858, `TestLoopsCountedPerModel`, `usage-loops.test.cjs`). A reply magpie translates into the agent's protocol (`streamTranslated`) whose *reasoning* loops before it has said a text or a call, and isn't a continuation, is asked again once in place instead (`loopReasks`, through `holdWriter.onLoop`; cdredfox on X, WorkBuddy AI's DeepSeek v4 flash): the agent keeps the reasoning it has, the next try's follows it in the same stream, as an empty reply's re-ask does (#667), and only a loop on that try ends the reply with the error (`TestReasoningLoopIsAskedAgain`). A loop in the text, or after a text or call, is ended at once (`TestLoopAfterTextIsNotAskedAgain`), and so is a Chat stream passed through as it comes, whose bytes aren't magpie's to splice. A cycle need not be exact. Code, tables, lists, logs, CSV and base64 differ line to line or have no words, and don't trip it (`TestLoopGuardLeavesOrdinaryRepliesAlone` feeds magpie's own sources and docs through it). A reply sent whole (no stream, or Gemini without `alt=sse`) isn't read. Settings › Models › Replies › *Stop looping replies* (`noLoopGuard`) turns it off.
- A Chat request's earlier turns carry the assistant's thinking back in the spelling its own client used: `reasoning_content` (DeepSeek's, which OpenCode and most clients send), `reasoning` (OpenRouter's) or `reasoning_details` (OpenRouter's structured one). A request translated to a non-Chat upstream reads whichever of the three the turn has, in that order, as the turn's thinking (`messageReasoning`, `reasoningText`, read by `parseChat` in [chat.go](../../internal/gateway/chat.go)); the passthrough has read all three since `mistralThinking` (#494), which was the one place that did. Before that the parse layer read `reasoning_content` alone, so a tool-calling session whose client spelled it another way went on from its second turn without the model's own reasoning.
- The order of the steps a request's accounts go through, how much the accounts' own order (*Make first*) counts under each routing, and how often an allowance is read are described for users in [How magpie picks an account](../reference.md#how-magpie-picks-an-account). Smart compares renewals window by window, biggest first, each truncated to the hour (`weighRouted`), so the order decides only when every window falls in the same hour. A window's renewal is its reset, or, when what it has left runs out sooner or it has no reset, that moment (`Limit.RunsOut`, from `QuotaWindow.RunsOutAt`; `Allowance.Renewal`): the WorkBuddy plugin (0.1.14) sends it on its Credits window as the soonest end of a package with credits left (cdredfox on X). Only Smart reads it; Weekly pace, the 90%/98% tiers and rests go by the window's share and reset as before. A row on the Routing page says the share used (the fullest window's, `Allowance.For`) with when that same window renews (`Allowance.Fullest`, the trace's `usedRenews`), not the biggest window's: a Factory account 32% into its week and 16% into its month reads "32% used · renews in 3 days" while Smart still ranks it by its month (#1778). A route from before `usedRenews` says when only for an account of one window. Affinity keeps a conversation on an account at 90–97%: only `SpentShareOf` (98%, 100% In order) stops it (`affine`), while the 90% tier (`lowShare`) orders only conversations nobody has answered.
- A turn's end is told to the app for the "Task done alert" notification (itieniu on X, `turndone.go`). The trace follows each agent session's turn (`turns`, keyed by agent and session): a request is of the turn unless it has a `Kind` or is a Claude Code subagent's (`agentTurnOf`), and its reply is scanned on the way to the agent for a tool call in any wire format (`toolScan`, a JSON value such as `"type":"tool_use"` or `"finish_reason":"tool_calls"`, never a key or text). The turn is done when no request of it is going, the last reply was whole, under 400 and called no tool, and nothing more came for `turnQuiet` (4s); a session idle past `turnStale` (30m) starts over. Only a turn that ran at least `settings.TurnDoneAlert` seconds is told (`TurnDone`, set by the GUI; nil under `magpie serve`, so nothing is followed). The ChatGPT backend path (`codexBackend`) is followed the same way. `TestTurnDoneSaidAtTheTurnsEnd`, `TestTurnDoneCodexBackend`, `TestToolScan`, `turn-done.test.cjs`.
- A resting candidate is tried last (`restLast`). Of the resting candidates, a request asks only the one whose rest ends soonest, the first in order on a tie (`probeOne`, #1799). The others aren't asked by that request, so a member that is down isn't asked by every request its rest was meant to spare it from, and a group that is down whole takes one upstream request per request, not one per member. Every ready candidate is still asked in its order. A lone candidate is tried even while it rests, because there is no other. The trace still lists every member, the resting ones with their rest. Only rests are read, and a failure about the request's content or its model rests no member (a model refusal rests only `restID`), so neither leaves a member out. The same applies in `count_tokens`, embeddings and rerank, image accounts and a group's System One decision models. A Codex reset (`autoReset`) still looks over every candidate. This is like AxonHub's error-aware load balancing: the rest and its backoff are the penalty that decays, and the member back soonest is the one asked to show it is back. Keys out of their allowance aren't asked even so, not even the one back soonest or a lone one (#1772: four Ollama Cloud keys out for the week, each asked again and refused on every request). When every candidate left is a key (not a subscription account, whose resets `autoReset` may spend) resting out of quota or credit after a 429 or 402, none is asked. The first one's refusal is given again (`quotaHeld`, its words kept in the rest's `said`), saying when it is asked again. The last key left rests too when it is refused so, as the keys before it do. Any 429 that reaches the agent without a vendor `Retry-After`, while every candidate tried is resting, carries one: the seconds until the first of them is back (`soonestBack`). A quota refusal with no word of when it is back rests `quotaRest` (15 minutes), or the provider's own `quotaRest` in minutes (`Provider.QuotaRestFor`, at most `MaxQuotaRest`, 8 days; `magpie provider quota-rest <id> 7d`). A time the vendor names stands over it. A key listed in `keys` as well as in `key` is one candidate (`KeysOn`), not asked twice. `TestAllRestingAnswersFromRest`, `TestOwnQuotaRest`, `TestQuotaHeldOnlyForKeysOutOfAllowance`, `TestFirstKeyListedTwiceAskedOnce`.
+12 -3
View File
@@ -36,7 +36,9 @@ type cRequest struct {
Messages []struct {
Role string `json:"role"`
Content json.RawMessage `json:"content"`
ReasoningContent string `json:"reasoning_content,omitempty"`
ReasoningContent json.RawMessage `json:"reasoning_content,omitempty"`
Reasoning json.RawMessage `json:"reasoning,omitempty"`
ReasoningDetails json.RawMessage `json:"reasoning_details,omitempty"`
ToolCalls []cToolCall `json:"tool_calls,omitempty"`
ToolCallID string `json:"tool_call_id,omitempty"`
} `json:"messages"`
@@ -94,8 +96,15 @@ func parseChat(body []byte) (*Request, error) {
r.Messages = append(r.Messages, Message{Role: "user", Parts: chatParts(m.Content)})
case "assistant":
msg := Message{Role: "assistant"}
if m.ReasoningContent != "" {
msg.Parts = append(msg.Parts, Part{Kind: Thinking, Text: m.ReasoningContent})
// an earlier turn's thinking comes back in any of
// messageReasoning's spellings, and every upstream that
// thinks wants it as the thinking part
if think := reasoningText(map[string]json.RawMessage{
"reasoning_content": m.ReasoningContent,
"reasoning": m.Reasoning,
"reasoning_details": m.ReasoningDetails,
}); think != "" {
msg.Parts = append(msg.Parts, Part{Kind: Thinking, Text: think})
}
msg.Parts = append(msg.Parts, chatParts(m.Content)...)
for _, tc := range m.ToolCalls {
@@ -0,0 +1,90 @@
package gateway
import (
"testing"
)
// A Chat client sends an earlier assistant turn's thinking back in any of
// three spellings: reasoning_content (DeepSeek's, which OpenCode and most
// clients send), reasoning (OpenRouter's) and reasoning_details (OpenRouter's
// structured one). parseChat read only reasoning_content, so a request
// translated to a non-Chat upstream — an Anthropic key, a Codex or
// Antigravity account, a Gemini or DeepSeek key — lost the thinking of every
// turn sent in the other two spellings, and the model went on without its own
// reasoning. A tool-calling session shows it from its second turn on.
func TestParseChatReadsEveryReasoningSpelling(t *testing.T) {
for _, c := range []struct {
name string
body string
want string
}{
{
name: "reasoning_content",
body: `{"model":"deepseek/deepseek-v4.1","messages":[
{"role":"user","content":"Read go.mod and bump the go directive."},
{"role":"assistant","reasoning_content":"go.mod has to be read before it is changed.",
"tool_calls":[{"id":"call_1","type":"function","function":{"name":"read_file","arguments":"{\"path\":\"go.mod\"}"}}]},
{"role":"tool","tool_call_id":"call_1","content":"module github.com/yetone/magpie\n\ngo 1.24\n"}]}`,
want: "go.mod has to be read before it is changed.",
},
{
name: "reasoning",
body: `{"model":"openrouter/qwen3-coder","messages":[
{"role":"user","content":"Read go.mod and bump the go directive."},
{"role":"assistant","reasoning":"The user wants the go directive at 1.25, so read go.mod first.",
"tool_calls":[{"id":"call_2","type":"function","function":{"name":"read_file","arguments":"{\"path\":\"go.mod\"}"}}]},
{"role":"tool","tool_call_id":"call_2","content":"module github.com/yetone/magpie\n\ngo 1.24\n"}]}`,
want: "The user wants the go directive at 1.25, so read go.mod first.",
},
{
name: "reasoning_details",
body: `{"model":"openrouter/qwen3-coder","messages":[
{"role":"user","content":"Read go.mod and bump the go directive."},
{"role":"assistant","reasoning_details":[
{"type":"reasoning.text","text":"A read comes before an edit.","signature":null,"format":"unknown","index":0}],
"tool_calls":[{"id":"call_3","type":"function","function":{"name":"read_file","arguments":"{\"path\":\"go.mod\"}"}}]},
{"role":"tool","tool_call_id":"call_3","content":"module github.com/yetone/magpie\n\ngo 1.24\n"}]}`,
want: "A read comes before an edit.",
},
} {
t.Run(c.name, func(t *testing.T) {
r, err := parseChat([]byte(c.body))
if err != nil {
t.Fatal(err)
}
turn := r.Messages[1]
if len(turn.Parts) != 2 || turn.Parts[0].Kind != Thinking || turn.Parts[1].Kind != ToolCall {
t.Fatalf("the assistant turn's parts: %+v", turn.Parts)
}
if turn.Parts[0].Text != c.want {
t.Errorf("thinking %q, want %q", turn.Parts[0].Text, c.want)
}
if turn.Parts[1].Name != "read_file" || string(turn.Parts[1].Args) != `{"path":"go.mod"}` {
t.Errorf("the tool call went with it: %+v", turn.Parts[1])
}
})
}
}
// The three spellings are the same thinking, so a client that sends more than
// one of them (OpenRouter's reasoning_details with reasoning beside it, say)
// is read once: reasoning_content first, then reasoning, then
// reasoning_details' text — messageReasoning's order, which chattidy's
// passthrough keeps.
func TestParseChatTakesTheFirstReasoningSpellingSent(t *testing.T) {
body := `{"model":"deepseek/deepseek-v4.1","messages":[
{"role":"user","content":"Read go.mod and bump the go directive."},
{"role":"assistant",
"reasoning_content":"the reasoning_content one",
"reasoning":"the reasoning one",
"reasoning_details":[{"type":"reasoning.text","text":"the reasoning_details one","index":1}],
"content":"done"}]}`
r, err := parseChat([]byte(body))
if err != nil {
t.Fatal(err)
}
turn := r.Messages[1]
if len(turn.Parts) != 2 || turn.Parts[0].Kind != Thinking || turn.Parts[0].Text != "the reasoning_content one" || turn.Parts[1].Kind != Text {
t.Fatalf("the assistant turn's parts: %+v", turn.Parts)
}
}