From 4bd0d6f3893fabbfe488ce99eb027021aadf5bc6 Mon Sep 17 00:00:00 2001 From: yetone Date: Mon, 2 Nov 2026 17:03:27 +0800 Subject: [PATCH] gateway: a provider whose model asks for a tool turn's thinking back, under a name that doesn't say DeepSeek, is asked again with it and sent it from then on (qisishiqi) qisishiqi (Discord #help): a routing group fell from a rate-limited Codex subscription to "My Claude", an Anthropic-format endpoint, and the request failed 400 "My Claude: The `content[].thinking` in the thinking mode must be passed back to the API." That is DeepSeek's model refusing a tool loop continued without the thinking of its tool turn. magpie fills those turns (a space, or the turn's readable reasoning) only when the host or the model names DeepSeek (anthropicReplaysThinking, chatReplaysReasoning, #1462/#1611). A relay serving DeepSeek under another name, or a model the user named otherwise, got nothing, and Codex's sealed reasoning has no text to give. Now forward reads a 400 on Messages or Chat whose words are DeepSeek's (thinkingBackRefusal: `content[].thinking` / `reasoning_content` ... in the thinking mode must be passed back), and when filling the tool turns (withThinkingOnToolTurns / withReasoningOnToolTurns) changes the body, remembers the provider's model (unfit, thinkingBackNeeded) and asks once more; forwardOnce fills them for it from then on, every route alike. A provider that never asked is sent the conversation as before. Scoped to the vendor's refusal, not to every Anthropic endpoint. Checked against api.deepseek.com with the owner's key, 2026-11-02 (deepseek-flash, Messages and Chat): a tool turn of the loop being continued with no thinking is refused with exactly these words (the test fixtures are those bytes); a space thinking block or reasoning_content " " is taken; readable unsigned thinking is taken; finished tool turns and plain replies without thinking are taken, with or without tools; thinking disabled takes it all. So DeepSeek's docs' "even for turns without a tool call" is not enforced today, and the existing tool-turn rule stands. Sibling: the Chat side had the same name-only gate, and gets the same learned fill (TestReasoningBackLearnedBehindAnotherName). Responses (reasoning_text) is filled by model name on any host already. Run at this head on mote: - go test ./internal/gateway -count=1 -timeout 45m: every test ok but TestCodexPoolSaysTheClientsVersion, #4807 (red in a full run, passes alone; passed 5 of 5 alone here). Not touched by this change. - GOOS=linux and GOOS=windows go vet ./internal/gateway: ok. gofmt -l: clean. - New: TestThinkingBackRefusalRead (the live bytes and qisishiqi's literal error read; Responses' reasoning_text and a bound-signature refusal not), TestThinkingBackLearnedBehindAnotherName (Codex request mid loop, group: 429 on the Responses member, then "My Claude" with claude-sonnet-4-6 and relay-model: 200 on the second ask with a space thinking block first, next turn 200 on the first ask, another provider sent no thinking), TestReasoningBackLearnedBehindAnotherName. Broken by hand: with the retry in forward off, all three cases go red with qisishiqi's error ("400 after 1 calls ... My Claude: The `content[].thinking` ..."); with the learned fill in forwardOnce off, the second turn is refused again ("400 after 2 calls"). Not tried: qisishiqi's own provider (its host and model are unknown); a real relay in front of DeepSeek; a plugin provider's fetch path. --- docs/subsystems/gateway-routing.md | 1 + internal/gateway/gateway.go | 10 ++ internal/gateway/thinking_back.go | 67 +++++++++++ internal/gateway/thinking_back_test.go | 147 +++++++++++++++++++++++++ 4 files changed, 225 insertions(+) create mode 100644 internal/gateway/thinking_back.go create mode 100644 internal/gateway/thinking_back_test.go diff --git a/docs/subsystems/gateway-routing.md b/docs/subsystems/gateway-routing.md index 4a9475206..903e74c32 100644 --- a/docs/subsystems/gateway-routing.md +++ b/docs/subsystems/gateway-routing.md @@ -275,6 +275,7 @@ recorded as a prediction failure (`noPrediction`). - A tool Claude Code's ToolSearch loads, translated to a Responses API, used to join the top-level `tools` on the next request, which changed the prompt from its first bytes and missed the cache on every load (#2660). A deferred tool (`defer_loading`, `Tool.Deferred`) that a `tool_result`'s `tool_reference` names (`toolRefs`, `Part.Loads`) now goes, where `Request.LoadedInPlace` is set, in an `{"type":"additional_tools","role":"developer","tools":[…]}` item right after the run of tool outputs that loaded it, once, and not in `tools` (`buildResponses`): tools loaded by parallel results or one result naming several share one item, a tool named again isn't repeated, and the tool output's text is as before. OpenAI's tool search guide documents the item and that its tools load at the end of the context so the cache is kept. A compacted or edited history whose loading result is gone puts the tool back in `tools`, a new prefix, as is expected. `LoadedInPlace` is set (`loadsInPlace`, in `forwardTranslated`) for OpenAI's own API with a key (`api.openai.com`, `*.api.openai.com`), for a ChatGPT (Codex) account, and for a provider set `additionalTools` (`magpie provider set additional-tools=on`); `additional-tools=off` (`additionalToolsOff`) turns it off even where it is the default, and `default` goes back to magpie's. The ChatGPT backend was tried with a real account (#4738, gpt-5.6-terra, gpt-6-luna, gpt-6-sol): it takes the item where it was loaded, the model calls the tool in it, and the next request read 7680–7936 tokens from cache where, with the tool moved into `tools`, it read none. Nothing else is sent it by default, since xAI answers the item 422 (#350), and no relay, other vendor's sign-in (Copilot) or plugin's vendor has been tried. An upstream that refuses a request holding the item with a 400 or 422 naming `additional_tools` is asked again with every tool in `tools`, logged ("turned away additional_tools … loaded tools go in tools from now on") and not sent the item again while magpie runs. Not handled: a tool a `tool_addition` block loads (an MCP server's late tool, the advisor) stays in `tools`. `TestLoadedToolsKeepThePrefix`, `TestLoadedToolsInOneItem`, `TestLoadedToolsWhereNotTaken`, `TestLoadsInPlaceScope`, `TestLoadedToolsThroughTheGateway`, `TestCodexAccountLoadsInPlace`. - A Responses upstream that wants a turn's reasoning back (`replaysReasoning` in [`responses.go`](../../internal/gateway/responses.go): a model with `deepseek` in its name, on any host but OpenAI's, xAI's, Copilot's and Azure's) gets every reasoning item with a `reasoning_text` and every tool call after one, relayed (`withReasoningText` in `passthrough`) or translated (`buildResponses`). DeepSeek's `/v1/responses` turns the whole request away ("The `reasoning_text` in the thinking mode must be passed back to the API") over a reasoning item without text, one with an empty text, and a `function_call` whose step (since the last user message or tool output) has no reasoning item. Codex sends all three in a routing group that falls to DeepSeek after ChatGPT: the backend's sealed items (`encrypted_content` only), magpie's summary-only items, and another member's calls with none (#1104, #1592). DeepSeek reads a step (a run of reasoning, assistant messages and calls) as one assistant message whose thinking is the item it starts with: in the current turn, a step with a call or after a tool output must lead with a reasoning item, so [message, reasoning, call] and [output, message] are refused while [reasoning, message, call] and [output, reasoning, message] are taken (checked against api.deepseek.com on 2026-10-12). Codex sends a step that said something before its call with no reasoning for another model's turn, which magpie used to send [message, reasoning " ", call] and DeepSeek refused intermittently, only while the turn lasted (#1822, through OpenCode Go). An item's own text is kept; one without gets its summary, else a space (`noReasoning`); each such step leads with its reasoning (`reasonFirst`): its own first reasoning item moved ahead, else one holding a space. A sealed item keeps its id and `encrypted_content`; a body already in that shape goes byte for byte. - A Messages upstream that wants a turn's thinking back (`anthropicReplaysThinking` in [`anthropic.go`](../../internal/gateway/anthropic.go): a host or a model with `deepseek` in it, never `api.anthropic.com` or a Claude model) gets a thinking block on every assistant message with a `tool_use` or right after tool results alone (refused the same way, checked 2026-10-12, #1822), relayed (`withThinkingOnToolTurns` in `passthrough`) or translated (`build`, which also keeps unsigned thinking as its text there). DeepSeek's `/anthropic/v1/messages`, thinking (its default, or asked for), turns the whole request away with 400 "The `content[].thinking` in the thinking mode must be passed back to the API" when such a message has none, and answers any `redacted_thinking` with 422, a block it can't read. Claude Code sends both in a routing group that falls to DeepSeek after Claude (#1611). A message with no thinking gets one holding a space (`noReasoning`) first; Claude's `redacted_thinking` becomes that block, or is left out beside thinking of the message's own. Signed thinking, DeepSeek's own and every other message go as they came. Checked against the real endpoint on 2026-10-11: it takes Claude's signed thinking, unsigned thinking and a space, anywhere in the message. A thinking block magpie sends unsigned (the space, or a turn's reasoning kept as its text) says `"signature": ""`, as `aBlock` writes `thinking` even when empty: OpenRouter's `/api/v1/messages` holds a block's signature to a string and turns a DeepSeek request with none away, 400 "Invalid Anthropic Messages API request" (#2883, #3696), and DeepSeek's own endpoint takes the empty one (checked 2026-10-19). `TestOpenRouterDeepSeekThinkingHasASignature`. +- A Messages or Chat upstream whose host and model don't say DeepSeek but whose model answers 400 "The `content[].thinking` (or `reasoning_content`) in the thinking mode must be passed back to the API" (`thinkingBackRefusal` in [`thinking_back.go`](../../internal/gateway/thinking_back.go)) is asked once more with its tool turns filled as above (`withThinkingOnToolTurns`, `withReasoningOnToolTurns`), and that provider's model is sent them at once from then on (`thinkingBackNeeded` in `unfit`, filled in `forwardOnce`), on every route to it. A relay serving DeepSeek under another name, or a provider the user named "My Claude", got a routing group's fall from a rate-limited Codex subscription mid tool loop refused, Codex's sealed reasoning having no text to give (qisishiqi on Discord, 2026-11-02). Checked against api.deepseek.com on 2026-11-02: only the tool loop being continued needs it; finished turns and plain replies are taken without. A provider that never asked is sent the turns as before. `TestThinkingBackLearnedBehindAnotherName`, `TestReasoningBackLearnedBehindAnotherName`. - Every thinking block a Messages client gets says a `signature`, a string, as Anthropic's own do (its stream starts each block with `"signature": ""`): Grok Build reads `ContentBlock::Thinking` as `{thinking, signature}`, both required, and turned a whole reply away, "missing field `signature`" (uk.jent on Discord, on the MiniMax Code plugin). The encoder starts a thinking block signed empty (`anthropicEncoder.thinking`), `renderAnthropic` and `whole_stream.go` write the field too, and a reply relayed from a Messages endpoint that wrote none, streamed or whole, gets an empty one (`sigFieldTidy` in [`thinking_signature.go`](../../internal/gateway/thinking_signature.go), in `passthrough`); a block already signed goes byte for byte, and `redacted_thinking` is untouched. magpie never makes a signature up: an empty one is none to every path that sends history on (`anthropicBody` leaves it out for Anthropic, keeps its text where reasoning is replayed), and a relay sends it back to the vendor that wrote the block. `TestMessagesThinkingIsSigned`, `TestSignedThinkingRelayedAsItCame`. - A model writes a whole number in a call's arguments with a fraction of zeros (`2500.0`, `17277.0`, tool_search's `limit: 8.0`): Grok's on every turn, whoever serves it (#1431), and muse-spark through the gateway (#3152). Codex reads the integer fields it parses as u64, usize or i32 even though their schemas say `number`, so serde turns away the whole call ("invalid number" for tool_search's arguments). In every reply, every number in a call's arguments written with a fraction of zeros and no exponent loses the fraction: `2500.0` becomes `2500`, `-3.00` becomes `-3`. Strings, keys, other fractions (`2.5`, `2.50`) and exponents (`1.0e3`) stay as written. No tool schema is consulted, since JSON has one number type and one that took `2500.0` takes `2500`. The rule runs over the arguments as a stream of text (`wholeNums`), holding back only a fraction of zeros until the next byte. This gives the same arguments whether they come whole or in deltas cut anywhere, so what a call's deltas add up to is what its done events say. Relayed replies are rewritten in `passthrough` by `intTidy`: Responses' function_call items, argument deltas and done events and the completed response; Chat's `tool_calls` deltas and messages; Messages' `tool_use` input and `input_json_delta`, streamed or whole; a whole reply with no call in it is said as it came, undecoded. A glm-5.3-flash* route's stitched CR (`crTidy`, #4256) is dropped before `intTidy` sees the reply, since `intTidy` holds a whole one to its flush (`TestStitchedCRAndWholeFloatsBothGo`). Translated replies are rewritten at the encoder (`wholeEncoder`, outside `usageEncoder`) and at `render` (`wholeResult`). Grok's schema quirks stay `grokModel`'s ([`grok_integral.go`](../../internal/gateway/grok_integral.go)). - A tool call a model writes into its reply's text, when the request offered tools, is made the call it is ([`textcalls.go`](../../internal/gateway/textcalls.go), #823): Hermes' `{…}`, DeepSeek's DSML (`<|DSML|invoke name=…>` with its parameters; its mark found as the parse regexes read it, by `dsmlMark`, not from a list of spellings: any run of pipes, ASCII or full-width or mixed, spaces after `<` and around `/`, `<||DSML||` too, #2623), DeepSeek's half-Hermes `` form (#917), GLM's ``/`` (#906), and the plain `…` of Claude's and MiniMax's calls, bare or in `` or `` (packinggoodsllc_07668 on Discord: Claude Code through a routing group was shown the invokes as text), read by `parseTextCalls`. Text after a call read out, other than tags, ends the calls, and it and all after it go: the model went on as if its call had run ("*Result: Tool loaded.*", then the next call, then "done"), and the agent runs the call and gives it the real result. Each block must name an offered tool and have arguments that can be read; else the text goes on as it came. The text before the first block is kept, what is left of the tags goes, and the reply ends as one that called tools (`finish_reason` `tool_calls`, `stop_reason` `tool_use`). A DSML close with no block before it (``) is held as a block is, and dropped when it is tags and nothing else. A reply whose model made a call itself has no call read out of its text, but tags and nothing else left in it after the call go, with the spaces before them (喜欢一个人 on Discord: a relay made the calls of DeepSeek's invokes and left the wrapper's close as text). Every route reads it the same way: a relayed Chat stream (`textCallTidy`), a relayed Chat reply that came whole, JSON or under `text/plain` or no type (`chatWhole` with `wholeTextCalls`, #1845: a `stream:false` request kept the markup and `finish_reason` `stop`), which also covers a vendor that answered a streamed request whole (`wholeAsStream`), a relayed Messages reply, streamed or whole (`anthropicTextCalls`: the held text's block start and stop are held with it, the calls become `tool_use` blocks after it, or in its place when none of its text went), and every translation, which magpie always asks streamed, a plugin's included, whatever the client asked (`textCallSee`). A relayed Responses reply, streamed or whole, is read too (`responsesTextCalls` in [`textcalls_relay.go`](../../internal/gateway/textcalls_relay.go), #4743, from v0.1.2652): the held text's `output_text.done`, `content_part.done` and `output_item.done` wait with it, and the calls become `function_call` items after it, in the events and in `response.completed`'s output. Before it, Alma (whose provider of type openai speaks Responses) through a group to DeepSeek, whose preset speaks Responses too, had the reply relayed as it came and got DeepSeek's `<||DSML|| calls>` as text with nothing run (wishSeikouudoku on X). A relayed Gemini reply the same (`geminiTextCalls`). Covered by `TestTextWritten*`, `TestInvokeReported*`, `TestDSMLAlma*` (a group of Responses members and a plugin's DeepSeek, from a Responses client, one character to a delta), `TestDSMLClose*`, `TestDSMLBlockClosedWithCalls`, `TestGLMTextCall*`, `TestPluginTextWrittenCall` and `TestQuietWholeReplyStreamed`. diff --git a/internal/gateway/gateway.go b/internal/gateway/gateway.go index 64c9b58f4..65ea4e8f5 100644 --- a/internal/gateway/gateway.go +++ b/internal/gateway/gateway.go @@ -4863,6 +4863,13 @@ func (s *Server) forward(ctx context.Context, p provider.Provider, to provider.P if err == nil { res, err = s.retryTokenField(ctx, p, to, path, body, in, res) } + if err == nil && s.refuseThinkingBack(p, to, body, res) { + // DeepSeek's model behind a name that doesn't say so, asking for + // a tool turn's thinking another model's turn didn't leave + // (thinking_back.go): asked once more with it filled in + res.Body.Close() + res, err = s.forwardOnce(ctx, p, to, path, body, in) + } if err == nil && (res.StatusCode == http.StatusForbidden || res.StatusCode == http.StatusBadRequest) && p.Retries() { // an account that can mend what the refusal names (a Factory org // the server won't take; a model Copilot's Auto picked that the @@ -4923,6 +4930,9 @@ func (s *Server) forwardOnce(ctx context.Context, p provider.Provider, to provid body = kimiLockedSampling(p, to, body) body = clinePin(p, to, body) body = codexImagesFit(p, to, body) + // the tool turns' thinking a provider's model asked for before + // (thinking_back.go) + body = s.withThinkingBack(p, to, body) // under the byte cap the provider refused a larger request over, // its oldest images left out (body_cap.go) body = s.withinCap(p, to, path, body) diff --git a/internal/gateway/thinking_back.go b/internal/gateway/thinking_back.go new file mode 100644 index 000000000..76b740b62 --- /dev/null +++ b/internal/gateway/thinking_back.go @@ -0,0 +1,67 @@ +package gateway + +import ( + "bytes" + "io" + "net/http" + "regexp" + + "github.com/yetone/magpie/internal/provider" +) + +// thinkingBackRefusal is DeepSeek's model asking for an earlier turn's +// thinking, wherever it is served: on its Messages API "The +// `content[].thinking` in the thinking mode must be passed back to the +// API", on its Chat API the same of `reasoning_content` (Kimi's says it +// without the backticks). Checked against api.deepseek.com on 2026-11-02: +// an assistant turn of the tool loop being continued with no thinking is +// refused, one with a space is taken, as are finished turns and plain +// replies without. +var thinkingBackRefusal = regexp.MustCompile("(?i)`?(?:content\\[\\]\\.thinking|reasoning_content)`? in the thinking mode must be passed back") + +// thinkingBackNeeded is how unfit remembers a provider's model asking +// for its thinking back on every tool turn (thinkingBackRefusal). +func thinkingBackNeeded(model string) string { return "thinking back\x00" + model } + +// withThinkingBack is body with each tool turn's thinking filled in +// (withThinkingOnToolTurns, withReasoningOnToolTurns), for a provider's +// model that asked for it before though neither its host nor its name +// says DeepSeek: a relay, or a model the user named otherwise. Those +// two are filled when the body is built (anthropicReplaysThinking, +// chatReplaysReasoning), so this is the learned rest of the class. +func (s *Server) withThinkingBack(p provider.Provider, to provider.Protocol, body []byte) []byte { + if to != provider.Anthropic && to != provider.Chat || s.fits(p.ID, thinkingBackNeeded(modelOf(body)), to) { + return body + } + return fillThinkingBack(to, body) +} + +func fillThinkingBack(to provider.Protocol, body []byte) []byte { + if to == provider.Anthropic { + return withThinkingOnToolTurns(body) + } + return withReasoningOnToolTurns(body) +} + +// refuseThinkingBack reads a 400 from a Messages or Chat upstream: when +// it is thinkingBackRefusal and filling body's tool turns changes it, +// the provider's model is remembered as asking for it, and true says +// to ask once more (forwardOnce fills them from then on). res's body +// is left readable either way. +func (s *Server) refuseThinkingBack(p provider.Provider, to provider.Protocol, body []byte, res *http.Response) bool { + if to != provider.Anthropic && to != provider.Chat || !badRequest(res.StatusCode) { + return false + } + b, _ := io.ReadAll(io.LimitReader(res.Body, 1<<20)) + res.Body.Close() + res.Body = io.NopCloser(bytes.NewReader(b)) + model := modelOf(body) + if !thinkingBackRefusal.Match(wordsOf(b)) || !s.fits(p.ID, thinkingBackNeeded(model), to) { + return false + } + if bytes.Equal(fillThinkingBack(to, body), body) { + return false + } + s.markUnfit(p.ID, thinkingBackNeeded(model), to) + return true +} diff --git a/internal/gateway/thinking_back_test.go b/internal/gateway/thinking_back_test.go new file mode 100644 index 000000000..f41748f0b --- /dev/null +++ b/internal/gateway/thinking_back_test.go @@ -0,0 +1,147 @@ +package gateway + +import ( + "net/http/httptest" + "strings" + "testing" + + "github.com/tidwall/gjson" + + "github.com/yetone/magpie/internal/provider" +) + +// What api.deepseek.com answered on 2026-11-02, byte for byte, to a tool +// loop continued with a tool turn that has no thinking: on its Messages +// API and on its Chat API. +const ( + deepseekThinkingBackLive = `{"error":{"message":"The ` + "`content[].thinking`" + ` in the thinking mode must be passed back to the API. (request_id: cae816b6-d668-4a55-935d-99d1b8ad3686)","type":"invalid_request_error","param":null,"code":"invalid_request_error"}}` + deepseekReasoningBackLive = `{"error":{"message":"The ` + "`reasoning_content`" + ` in the thinking mode must be passed back to the API. (request_id: 6360375a-b044-4a13-b51e-548de94677ea)","type":"invalid_request_error","param":null,"code":"invalid_request_error"}}` + // qisishiqi's error on Discord (#help, 2026-11-02), as magpie passed it on + qisishiqiError = `{"code":null,"message":"My Claude: The ` + "`content[].thinking`" + ` in the thinking mode must be passed back to the API.","param":null,"type":"invalid_request_error"}` +) + +// thinkingBackStream is the Messages stream the fakes answer with. +var thinkingBackStream = sse( + `event: message_start`+"\n"+`data: {"type":"message_start","message":{"id":"msg_1","model":"m1","usage":{"input_tokens":7}}}`, + `data: {"type":"content_block_start","index":0,"content_block":{"type":"text","text":""}}`, + `data: {"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"Done."}}`, + `data: {"type":"content_block_stop","index":0}`, + `data: {"type":"message_delta","delta":{"stop_reason":"end_turn"},"usage":{"output_tokens":2}}`, + `data: {"type":"message_stop"}`) + +// codexMidLoop is Codex continuing a tool loop its own model began: the +// reasoning it has for the call is OpenAI's, sealed, with no text. +const codexMidLoop = `{"model":"%s","stream":false,"reasoning":{"effort":"high"}, + "tools":[{"type":"function","name":"shell","parameters":{"type":"object","properties":{"command":{"type":"string"}}}}], + "input":[ + {"type":"message","role":"user","content":[{"type":"input_text","text":"fix the login bug"}]}, + {"type":"reasoning","id":"rs_1","summary":[],"encrypted_content":"gAAAA-codex-sealed"}, + {"type":"function_call","call_id":"call_1","name":"shell","arguments":"{\"command\":\"ls\"}"}, + {"type":"function_call_output","call_id":"call_1","output":"main.go"}]}` + +func TestThinkingBackRefusalRead(t *testing.T) { + for _, s := range []string{deepseekThinkingBackLive, deepseekReasoningBackLive, qisishiqiError, + `{"error":{"message":"The reasoning_content in the thinking mode must be passed back to the API."}}`} { + if !thinkingBackRefusal.Match(wordsOf([]byte(s))) { + t.Errorf("not read as asking for thinking back: %s", s) + } + } + for _, s := range []string{ + "The `reasoning_text` in the thinking mode must be passed back", // DeepSeek's Responses, its own path + "messages.1.content.0: Invalid signature in thinking block", + "prompt is too long", + } { + if thinkingBackRefusal.MatchString(s) { + t.Errorf("%q read as asking for thinking back", s) + } + } +} + +// qisishiqi (Discord): a routing group fell from a rate-limited Codex +// subscription to "My Claude", an Anthropic endpoint whose host and +// model don't say DeepSeek, mid tool loop. DeepSeek's model behind it +// asked for the call's thinking, which Codex's sealed reasoning can't +// give. magpie asks once more with a space for it, and from then on +// sends it at once; a provider that never asked is sent none. +func TestThinkingBackLearnedBehindAnotherName(t *testing.T) { + for _, model := range []string{"claude-sonnet-4-6", "relay-model"} { + t.Run(model, func(t *testing.T) { + plan := &fake{t: t, ctype: "application/json", code: 429, reply: `{"error":{"message":"rate limited"}}`} + up := setup(t, provider.Responses, plan) + mine := &fake{t: t, reply: thinkingBackStream, refuse: func(b []byte) (int, string) { + if code, _ := deepseekRefuseAnthropic(b); code == 400 { + return 400, deepseekThinkingBackLive + } + return 0, "" + }} + mineSrv := httptest.NewServer(mine) + t.Cleanup(mineSrv.Close) + plain := &fake{t: t, reply: thinkingBackStream} + plainSrv := httptest.NewServer(plain) + t.Cleanup(plainSrv.Close) + for _, p := range []provider.Provider{ + {ID: "plan", Name: "Plan", Key: "k", Models: []string{"gpt-5.5"}, Responses: up.URL + "/v1"}, + {ID: "myclaude", Name: "My Claude", Key: "k", Models: []string{model}, Anthropic: mineSrv.URL}, + {ID: "plain", Name: "Plain", Key: "k", Models: []string{model}, Anthropic: plainSrv.URL}, + } { + if err := provider.Save(p); err != nil { + t.Fatal(err) + } + } + if err := provider.SaveGroup(provider.Group{ID: "cc", Name: "cc", Members: []string{"plan/gpt-5.5", "myclaude/" + model}, Routing: provider.Ordered}); err != nil { + t.Fatal(err) + } + srv := New() + req := strings.Replace(codexMidLoop, "%s", "group/cc", 1) + code, body := postTo(t, srv, "/v1/responses", req) + if code != 200 || mine.calls != 2 { + t.Fatalf("%d after %d calls to My Claude, want 200 on the second: %s", code, mine.calls, body) + } + turn := gjson.GetBytes(mine.got, `messages.#(role=="assistant")`) + if th := turn.Get(`content.#(type=="thinking")`); th.Get("thinking").String() != noReasoning || turn.Get("content.0.type").String() != "thinking" { + t.Errorf("the tool turn went as %s, want a thinking block first", turn.Raw) + } + + // learned: the next request is taken the first time + mine.calls = 0 + if code, body = postTo(t, srv, "/v1/responses", req); code != 200 || mine.calls != 1 { + t.Fatalf("%d after %d calls, want 200 on the first: %s", code, mine.calls, body) + } + + // a provider that never asked gets the turn as before + if code, body = postTo(t, srv, "/v1/responses", strings.Replace(codexMidLoop, "%s", "plain/"+model, 1)); code != 200 { + t.Fatalf("plain: %d %s", code, body) + } + if strings.Contains(string(plain.got), `"thinking":" "`) { + t.Errorf("a provider that never asked was given thinking: %s", plain.got) + } + }) + } +} + +// The sibling on Chat: DeepSeek's model behind a Chat provider whose host +// and model don't say so, given Codex's loop, asks for reasoning_content +// back; magpie asks once more with it, and from then on. +func TestReasoningBackLearnedBehindAnotherName(t *testing.T) { + f := &fake{t: t, reply: chatStreamOK, refuse: func(b []byte) (int, string) { + if code, _ := deepseekRefuseToolTurns(b); code == 400 { + return 400, deepseekReasoningBackLive + } + return 0, "" + }} + up := setup(t, provider.Chat, f) + chatProvider(t, up.URL, provider.Provider{ID: "relay", Models: []string{"relay-model"}}) + srv := New() + req := strings.Replace(codexMidLoop, "%s", "relay/relay-model", 1) + code, body := postTo(t, srv, "/v1/responses", req) + if code != 200 || f.calls != 2 { + t.Fatalf("%d after %d calls, want 200 on the second: %s", code, f.calls, body) + } + if rc := gjson.GetBytes(f.got, `messages.#(role=="assistant").reasoning_content`); !rc.Exists() || rc.String() != noReasoning { + t.Errorf("the tool turn's reasoning_content = %s, want a space: %s", rc.Raw, f.got) + } + f.calls = 0 + if code, body = postTo(t, srv, "/v1/responses", req); code != 200 || f.calls != 1 { + t.Fatalf("%d after %d calls, want 200 on the first: %s", code, f.calls, body) + } +}