Every agent's model. One place. Codex on DeepSeek, Claude Code on Kimi, from the menu bar.
gateway: OpenRouter takes a DeepSeek tool turn (signature "") and a turn's effort is asked again without (#3696, #2883)
JoeyWu-tech5f3146be0955
diff --git a/docs/subsystems/gateway-routing.md b/docs/subsystems/gateway-routing.mdindex 8f41350af..692fb072a 100644--- a/docs/subsystems/gateway-routing.md+++ b/docs/subsystems/gateway-routing.md@@ -246,7 +246,7 @@ recorded as a prediction failure (`noPrediction`).- ToolSearch's answer is a `tool_result` whose content is `tool_reference` blocks alone. OpenDesign's Anthropic endpoint can't read one: 422 "Failed to deserialize the JSON body into the target type: messages[4]: missing field `content`" (#2124, the reporter's direct request without magpie fails the same way; the same result with a text block beside the references is taken). A provider that refuses in those words while the request holds such a result is asked again at once with a text block first in each, "Tool <name> is loaded and can be called now." (`toolLoadedText`, the words a translated route already gives a model in `stringOrText`), the references and the `tool_use`/`tool_result` pairing kept, and is sent it that way while magpie runs (`refuseShapes`, `shapeRefsOnly`, `withRefsSaid`). This is in `forward`, so `/v1/messages`, `count_tokens` and a group's member all get it; a request translated to another API already carries the references as that text. Any other provider is sent the bare references (`TestRefsOnlyToolResultRefusedGetsText`, `TestRefsSaidLeavesOtherResults`).- 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`) and for a provider set `additionalTools` (`magpie provider set <id> additional-tools=on`); nothing else, since xAI answers the item 422 (#350), the ChatGPT backend has been seen to take it only for Codex's Responses Lite, and no relay 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`.- 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 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 Grok model writes a whole number in a call's arguments with a fraction of zeros (`2500.0`, `17277.0`), whoever serves it: the Grok subscription or its plugin, xAI, OpenRouter or a relay. Codex reads its integer fields as u64, usize or i32 even though their schemas say `number`, so serde turns away the whole call (#1431). In a reply to a request whose model, as magpie names it or as it is sent upstream, has a last `/` segment beginning with `grok` (`grokModel`, `grokServed`), 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. 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. Translated replies are rewritten at the encoder (`wholeEncoder`, outside `usageEncoder`) and at `render` (`wholeResult`) when `Request.Grok` is set. Any other model's reply is relayed byte for byte ([`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' `<tool_call>{…}</tool_call>`, 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 `<parameter>` form (#917) and GLM's `<arg_key>`/`<arg_value>` (#906), read by `parseTextCalls`. 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 (`</||DSML|| calls>`) 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`), and every translation, which magpie always asks streamed, a plugin's included, whatever the client asked (`textCallSee`). A relayed Responses or Messages upstream's text is not read for calls. Covered by `TestTextWritten*`, `TestDSMLClose*`, `TestDSMLBlockClosedWithCalls`, `TestGLMTextCall*`, `TestPluginTextWrittenCall` and `TestQuietWholeReplyStreamed`.- Structured output is carried across every translation (`Format`, [`format.go`](../../internal/gateway/format.go)). It is read from Responses' `text.format`, Chat's `response_format`, Anthropic's `output_config.format` and Gemini's `responseMimeType` with `responseJsonSchema`/`responseSchema`: `json_schema` with its name, description, schema and strict, or `json_object`. Each upstream is asked in its own field: `text.format` on Responses, `response_format` on Chat, `output_config.format` on Messages, and `generationConfig.responseMimeType`/`responseJsonSchema` on Gemini and Code Assist. An API with no name for it gets `response`. Messages and the Claude subscription's `--json-schema` take a schema only, so `json_object` is told in the system prompt there (`inSystem`). A 400 or 422 that names the field (`refusesFormat`: DeepSeek's "This response_format type is unavailable now", a schema Anthropic can't hold) marks the provider and model (`formatRefused`), and the request is asked again with the format told in the system prompt, as are later requests to that provider and model. A relayed request keeps its format as sent. A Gemini client's format is also still told in its system prompt, as before. A model may still wrap its JSON answer in a Markdown code fence; a client that asked for structured output, in a field or told in the system prompt (`wantsJSON`), gets the JSON inside a single unlabelled or json-labelled fence when that content is a complete valid JSON value, streamed (`fenceEncoder`) or whole (`unfencedResult`), in [`format_fence.go`](../../internal/gateway/format_fence.go). Invalid or truncated JSON, other fence languages, text outside the fence, and answers to plain-text clients reach the client as they came. This normalization applies to translated replies; native protocol passthrough stays byte-preserving.@@ -257,7 +257,7 @@ recorded as a prediction failure (`noPrediction`).- An agent whose config can't carry an effort has one picked in magpie (`provider.AgentEffort`, settings' `agentEfforts`; Cursor Private Inference's row, #1003). It is asked for on that agent's requests to a model that reasons (`Provider.Thinks`), in place of the level the request sent, fitted to the model's levels and bounded by the group's. Order: a member's fixed effort, then the effort the rule that put the member first sets (`Rule.UseEffort`), then a model's `:effort` suffix, then the turn's pick (a routing rule's), then the agent's pick, then the request's own. A model that doesn't reason is sent as asked; the default (none picked) leaves every request as it came. The pick beats the request's own because Cursor sends its own default as often as a real choice. Picking Default hands the choice back to Cursor.- In models.dev, entries from `deepseek`, `kimi-code-plan-cn` and `kimi-code-plan-global` gain `none` only when they have both a `toggle` and effort levels; the DeepSeek and Kimi APIs accepted that value in [#1098](https://github.com/yetone/magpie/issues/1098). Other providers keep their listed levels because their APIs may reject `none`; toggle-only entries remain level-less ([`mdModel.efforts`](../../internal/catalog/catalog.go)).- Gemini's OpenAI-compatible API (AI Studio's, or a proxy in front of Gemini on this computer or the LAN: `geminiCompat`) is asked for the model's thoughts in `extra_body.google.thinking_config`. A 400 or 422 whose error names `extra_body`, `include_thoughts` or thinking at all (`refusesThinkingConfig`) marks the provider unfit for the field (`thinking_config`), and it is asked again with `reasoning_effort` alone. Gemini 3 can't stop thinking, so reasoning turned off goes at `minimal`, its least, or at the model's lowest level where it has no `minimal` (`geminiLevels`: those of the model's levels it hasn't turned away, or of Gemini 3's where its own aren't known or none is left). Gemini 3 turns away a level the model hasn't with a 400 that names the level (`geminiRefusedLevel`): AI Studio's "Thinking level MINIMAL is not supported for this model. Please retry with other thinking level." for gemini-3.8-flash, Vertex AI's "Thinking level is unsupported: THINKING_LEVEL_MINIMAL". It names thinking too, but isn't the field turned away. The level is marked refused for that model (`levelRefused`), and the model is asked again at the nearest level it has left, still for its thoughts, and at that level from then on. A level turned away again, with none left, is the client's 400. Passed through, a Chat client's own `none` or `minimal` that Gemini turns away this way is asked again at the model's lowest level (`onEffort`), and that level goes at the lowest from then on (`turnedAway`); the other still goes as sent, as AI Studio takes `none` from gemini-3.8-flash. A refusal that names the levels the model takes (`effortLevelsNamed`, Command Code's for Qoder's `none`) marks reasoning off as a whole (`offRefused`): both go at the lowest from then on; one that lists the other among the levels taken (`otherOffNamed`, quoted, OpenAI's for gpt-5.1's `minimal`) marks only the level turned away. Both routes read and write the same marks. Vertex AI's OpenAI-compatible API marks each streamed chunk of thoughts in the delta's `extra_content.google.thought`, and such a chunk is read as thinking.-- A Claude that thinks only adaptively (`adaptiveOnly` in [`anthropic.go`](../../internal/gateway/anthropic.go): Opus, Sonnet and Haiku from 4.6 on, Fable and Mythos 5 and 5.1, read by `claudeVersion` however a relay spells them) is never sent a thinking budget, which they answer with 400. magpie's own request from a Chat or Responses client (`buildAnthropic`) goes as `thinking: {type: "adaptive", display: "summarized"}` with the effort in `output_config.effort`, so the client sees the reasoning Opus 4.7 and later otherwise leave out (display `omitted` by default), and a relay that refuses `display` is asked again without it (`refuseShapes`), as is one that refuses auto mode's `safeguards` (Copilot's Messages API: 400 "safeguards: Extra inputs are not permitted" on claude-opus-5.5, #1756; `shapeSafeguards`, `TestSafeguardsRefusedLeftOut`), and neither is sent it again while magpie runs; a client's `thinking: {type: "enabled", budget_tokens}` is turned into the same in `forwardOnce` (`adaptiveThinking`), the budget as its nearest effort, above `high` as `max`, and `display: "summarized"` unless the client named its own display, so the thinking that enabled shows stays shown (the refused shapes are taken out after it, and `refuseShapes` reads the display as it is sent); and Pi, dsh and omp are written to ask it adaptively (`AdaptiveThinking`: `forceAdaptiveThinking`, omp's `anthropic-adaptive`; #1470). A client's `xhigh` goes as `xhigh`, except to Opus and Sonnet 4.6, which have no `xhigh` and are asked `max` (`noXhigh`, #1471).+- A Claude that thinks only adaptively (`adaptiveOnly` in [`anthropic.go`](../../internal/gateway/anthropic.go): Opus, Sonnet and Haiku from 4.6 on, Fable and Mythos 5 and 5.1, read by `claudeVersion` however a relay spells them) is never sent a thinking budget, which they answer with 400. magpie's own request from a Chat or Responses client (`buildAnthropic`) goes as `thinking: {type: "adaptive", display: "summarized"}` with the effort in `output_config.effort`, so the client sees the reasoning Opus 4.7 and later otherwise leave out (display `omitted` by default), and a relay that refuses `display` is asked again without it (`refuseShapes`), as is one that refuses a turn's effort on a `{role: "system"}` message (`withoutTurnEffort`: a relay's "messages.1.output_config: Extra inputs are not permitted", or OpenRouter's "Mid-conversation reasoning effort (configuration_update) is not supported on <model>" on DeepSeek and GLM, #3696; `TestOpenRouterTurnEffortLeftOut`), as is one that refuses auto mode's `safeguards` (Copilot's Messages API: 400 "safeguards: Extra inputs are not permitted" on claude-opus-5.5, #1756; `shapeSafeguards`, `TestSafeguardsRefusedLeftOut`), and neither is sent it again while magpie runs; a client's `thinking: {type: "enabled", budget_tokens}` is turned into the same in `forwardOnce` (`adaptiveThinking`), the budget as its nearest effort, above `high` as `max`, and `display: "summarized"` unless the client named its own display, so the thinking that enabled shows stays shown (the refused shapes are taken out after it, and `refuseShapes` reads the display as it is sent); and Pi, dsh and omp are written to ask it adaptively (`AdaptiveThinking`: `forceAdaptiveThinking`, omp's `anthropic-adaptive`; #1470). A client's `xhigh` goes as `xhigh`, except to Opus and Sonnet 4.6, which have no `xhigh` and are asked `max` (`noXhigh`, #1471).- A vendor's model that takes its level in `output_config.effort` beside thinking on (`effortInOutputConfig` in [`anthropic.go`](../../internal/gateway/anthropic.go): Z.ai's GLM-5.2 and GLM-5.3, and MiniMax's MiniMax-M3.1-Flash and its -Preview) is sent the effort there next to the budget: built from a Chat or Responses client's effort (`buildAnthropic`, when it sends a budget), or added to an Anthropic client's request from its budget's nearest level, fitted to the model's levels (`withOutputEffort`, in `passthrough`). A budget alone left GLM at its default, and under an 8192 cap gave MiniMax's medium to max one budget, 7168 (shin4 on plugins#316). A client that asks such a model adaptively, with its level in `output_config.effort`, has both kept (Z.ai takes adaptive with the level, tried live on GLM-5.3); dsh is written to ask them so (GLM-5.2 and GLM-5.3: `AdaptiveWithEffort`, `forceAdaptiveThinking` in `dshKindConfig`; MiniMax not yet, #3496), since pi-ai's budget path clamps Max to high's 16384 and its Max reached GLM-5.3 as high (01huadalang on Discord, 10-24). Every other model, Claude and MiniMax-M3 included, gets the budget alone. `TestGLMEffortInOutputConfig`, `TestMiniMaxPluginGetsTheNativeEffort`, `TestNativeEffortLeavesOthersAlone`, `TestAdaptiveOnOutputEffortModelAsksItsLevel`, `TestDshMaxReachesOutputEffortModels`.- A request to an Anthropic endpoint that turns thinking off is sent as the model takes it (`thinkingOffAsTaken`, in `forwardOnce`, so relayed requests, count_tokens, magpie's own thinking-off and retries all get it; the model is read as the vendor names it, from the body, or from the path for Bedrock and Vertex). Claude Sonnet 5.5 refuses `thinking: {type: "disabled"}` and is sent `{type: "between_tools"}` alone, at effort `high` at most. Opus 5.5, Fable 5 and Mythos 5 refuse it at every effort and are sent no thinking, at effort `low` unless one was asked, with `classifierRoom` added to a reply limit below it, as Claude Code does. Opus 5 and Haiku 5.5 take it only up to `high`, so `xhigh` and `max` are asked as `high`. `between_tools` sent to any other Claude goes as `disabled`, or as none where that is refused too. Other vendors' models, older Claudes and later lines than these go as they came (#1454). A Sonnet 5.5 by a name these rules can't read, answering 400 that asks for `between_tools` (`asksBetweenTools`), is asked again with it, once; a refusal of `disabled` at any effort (`thinkingOffRefused`) is asked again with thinking left to the model, as `alwaysThinks` is. So is a relay that reads `disabled` as reasoning effort `none` and turns that level away naming the ones it takes (Sub2API's gpt-6.1-sol, "does not support reasoning effort \"none\"; use low, medium, high, xhigh or max", #1465); `refusesThinkingOff` is the one list of these refusals for both routes. A relayed request refused so marks the model (`markUnfit(offRefused)`), and its later requests go with thinking left to the model at once until magpie restarts, as auto mode's classifier asks on every action.- A Chat or Responses client's reasoning turned off (`none`, `ThinkOff`), translated to an Anthropic endpoint (`buildAnthropic`), goes as `thinking: {type: "disabled"}`; it went as thinking at a 4096-token budget before (#1636). A model that refuses it (`refusesThinkingOff`: `alwaysThinks`, `mandatoryReasoning`, `thinkingOffRefused`, or `none` turned away naming the levels taken) is asked again at its least (`thinkingBackOn`), and `markUnfit(offRefused)` sends it so at once until magpie restarts. A translated request's level can differ from the one asked: `none` and `minimal` go as `low` where the model's levels don't say it stops (`effortOf`). The route keeps the level asked; the try, the usage log and Routing's "went" say the one built (`noteWireEffort`, `wireEffort` in [`wire_effort.go`](../../internal/gateway/wire_effort.go)). Gemini's builders say theirs their own way and are logged as asked.diff --git a/internal/gateway/anthropic.go b/internal/gateway/anthropic.goindex e953e520a..96d136a0d 100644--- a/internal/gateway/anthropic.go+++ b/internal/gateway/anthropic.go@@ -63,10 +63,15 @@ func (b aBlock) MarshalJSON() ([]byte, error) {if b.Type != "thinking" {return json.Marshal(plain(b))}+ // a thinking block always says its signature, empty for one magpie+ // sends unsigned (noReasoning, or a turn's thinking replayed): the+ // Messages API schema has it as a string, and OpenRouter's endpoint+ // turns a block without one away (#2883)return json.Marshal(struct {plain- Thinking string `json:"thinking"`- }{plain(b), b.Thinking})+ Thinking string `json:"thinking"`+ Signature string `json:"signature"`+ }{plain(b), b.Thinking, b.Signature})}// ephemeral marks a prompt-cache breakpoint.diff --git a/internal/gateway/anthropic_shapes.go b/internal/gateway/anthropic_shapes.goindex 4d55ba0d8..7e3b20e57 100644--- a/internal/gateway/anthropic_shapes.go+++ b/internal/gateway/anthropic_shapes.go@@ -20,7 +20,10 @@ import (// adaptive.display: Input should be 'summarized', 'omitted'";// - the effort of each turn, as output_config on a {role: "system"}// message inside messages: "messages.1.output_config: Extra inputs are-// not permitted".+// not permitted". OpenRouter's Anthropic endpoint takes it as a+// configuration_update and refuses that on DeepSeek and GLM:+// "Mid-conversation reasoning effort (configuration_update) is not+// supported on z-ai/glm-5.3-flash-20260826" (#3696).//// Claude Code mends either after the 400, once per conversation, sending// the request again without it; every new conversation asks again, and a@@ -75,7 +78,7 @@ const (var (displayValueRefused = regexp.MustCompile(`thinking\.(?:adaptive|enabled)\.display:? Input should be`)displayRefused = regexp.MustCompile(`thinking\.(?:adaptive|enabled)\.display:? Extra inputs are not permitted`)- turnEffortRefused = regexp.MustCompile(`messages\.\d+\.output_config:? Extra inputs are not permitted`)+ turnEffortRefused = regexp.MustCompile(`messages\.\d+\.output_config:? Extra inputs are not permitted|Mid-conversation reasoning effort \(configuration_update\) is not supported`)turnRoleRefused = regexp.MustCompile(`messages\.(\d+)\.role\b`)safeguardsRefused = regexp.MustCompile(`\bsafeguards:? Extra inputs are not permitted`)deferredRefused = regexp.MustCompile("messages\\[\\d+\\]\\.content: unknown variant `(?:tool_addition|tool_removal|tool_definition|tool_reference)`")diff --git a/internal/gateway/deepseek_anthropic_thinking_test.go b/internal/gateway/deepseek_anthropic_thinking_test.goindex 49227494a..b8a64a3e7 100644--- a/internal/gateway/deepseek_anthropic_thinking_test.go+++ b/internal/gateway/deepseek_anthropic_thinking_test.go@@ -2,9 +2,12 @@ package gatewayimport ("encoding/json"+ "fmt""strings""testing"+ "github.com/tidwall/gjson"+"github.com/yetone/magpie/internal/provider")@@ -107,10 +110,10 @@ func TestDeepSeekAnthropicToolTurnsGetThinking(t *testing.T) {}ms := sentAnthropicMessages(t, f.got)sameJSON(t, ms[0], `{"role":"user","content":"fix the login bug"}`)- sameJSON(t, ms[1], `{"role":"assistant","content":[{"type":"thinking","thinking":" "},{"type":"tool_use","id":"toolu_1","name":"Bash","input":{"command":"ls"}}]}`)+ sameJSON(t, ms[1], `{"role":"assistant","content":[{"type":"thinking","thinking":" ","signature":""},{"type":"tool_use","id":"toolu_1","name":"Bash","input":{"command":"ls"}}]}`)sameJSON(t, ms[3], `{"role":"assistant","content":[{"type":"thinking","thinking":"Read main.go.","signature":"EqQBCkgIBxABGAIiQL"},{"type":"tool_use","id":"toolu_2","name":"Bash","input":{"command":"cat main.go"}}]}`)- sameJSON(t, ms[5], `{"role":"assistant","content":[{"type":"thinking","thinking":" "},{"type":"text","text":"Checking the test."},{"type":"tool_use","id":"toolu_3","name":"Bash","input":{"command":"go test"}}]}`)- sameJSON(t, ms[7], `{"role":"assistant","content":[{"type":"thinking","thinking":" "},{"type":"thinking","thinking":"Fine.","signature":"EqQBCkgIBxAB"},{"type":"text","text":"It passes."}]}`)+ sameJSON(t, ms[5], `{"role":"assistant","content":[{"type":"thinking","thinking":" ","signature":""},{"type":"text","text":"Checking the test."},{"type":"tool_use","id":"toolu_3","name":"Bash","input":{"command":"go test"}}]}`)+ sameJSON(t, ms[7], `{"role":"assistant","content":[{"type":"thinking","thinking":" ","signature":""},{"type":"thinking","thinking":"Fine.","signature":"EqQBCkgIBxAB"},{"type":"text","text":"It passes."}]}`)}// another vendor's model, and a Claude model, on the same upstream are@@ -140,11 +143,89 @@ func TestDeepSeekAnthropicNoThinkingField(t *testing.T) {if code, b := postTo(t, New(), "/v1/messages", body); code != 200 {t.Fatalf("%d: %s", code, b)}- if ms := sentAnthropicMessages(t, f.got); !strings.HasPrefix(string(ms[1]), `{"content":[{"type":"thinking","thinking":" "}`) {+ if ms := sentAnthropicMessages(t, f.got); !strings.HasPrefix(string(ms[1]), `{"content":[{"type":"thinking","thinking":" ","signature":""}`) {t.Errorf("first tool turn sent as %s", ms[1])}}+// openRouterRefuseAnthropic answers as OpenRouter's /api/v1/messages did+// for a DeepSeek model in #2883: its request schema wants a thinking+// block's signature as a string, so one with no signature is "Invalid+// Anthropic Messages API request" (400), its metadata naming the block's+// missing signature. The fields are the ones the report quotes. Behind+// it, the model still wants a thinking block on each tool turn+// (deepseekRefuseAnthropic).+func openRouterRefuseAnthropic(body []byte) (int, string) {+ if code, msg := deepseekRefuseAnthropic(body); code != 0 {+ return code, msg+ }+ var q struct {+ Messages []struct {+ Content json.RawMessage `json:"content"`+ } `json:"messages"`+ }+ json.Unmarshal(body, &q)+ for i, m := range q.Messages {+ var blocks []map[string]json.RawMessage+ json.Unmarshal(m.Content, &blocks)+ for j, b := range blocks {+ var kind, sig string+ json.Unmarshal(b["type"], &kind)+ if kind != "thinking" {+ continue+ }+ if raw, ok := b["signature"]; ok && json.Unmarshal(raw, &sig) == nil {+ continue+ }+ return 400, fmt.Sprintf(`{"error":{"message":"Invalid Anthropic Messages API request","code":400,"metadata":{"raw":[{"path":["messages",%d,"content"],"errors":[[],[{"path":[%d,"signature"],"expected":"string","code":"invalid_type","message":"Invalid input: expected string, received undefined"}]]}]}}}`, i, j)+ }+ }+ return 0, ""+}++// A DeepSeek model on OpenRouter's Anthropic endpoint (#2883): the+// thinking block a tool turn is given (a space, or the client's unsigned+// reasoning) goes with an empty signature, which OpenRouter's schema+// takes where it turns a missing one away. Both ways in are held to it:+// Claude Desktop's Messages request relayed as it came, and a Chat+// client's translated.+func TestOpenRouterDeepSeekThinkingHasASignature(t *testing.T) {+ f := &fake{t: t, ctype: "application/json", reply: anthropicWholeOK, refuse: openRouterRefuseAnthropic}+ up := setup(t, provider.Anthropic, f)+ if err := provider.Save(provider.Provider{ID: "openrouter", Name: "OpenRouter", Key: "k", Models: []string{"deepseek/deepseek-v4.1-flash-1017"}, Anthropic: up.URL}); err != nil {+ t.Fatal(err)+ }+ srv := New()+ code, body := postTo(t, srv, "/v1/messages", strings.Replace(claudeTurnsForDeepSeek, "%s", "openrouter/deepseek/deepseek-v4.1-flash-1017", 1))+ if code != 200 || f.calls != 1 {+ t.Fatalf("messages: %d after %d calls: %s", code, f.calls, body)+ }+ ms := sentAnthropicMessages(t, f.got)+ sameJSON(t, ms[1], `{"role":"assistant","content":[{"type":"thinking","thinking":" ","signature":""},{"type":"tool_use","id":"toolu_1","name":"Bash","input":{"command":"ls"}}]}`)+ sameJSON(t, ms[3], `{"role":"assistant","content":[{"type":"thinking","thinking":"Read main.go.","signature":"EqQBCkgIBxABGAIiQL"},{"type":"tool_use","id":"toolu_2","name":"Bash","input":{"command":"cat main.go"}}]}`)++ // a Chat client's request goes on as a stream+ f.calls, f.ctype, f.reply = 0, "", 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":"12:01"}}`,+ `data: {"type":"content_block_stop","index":0}`,+ `data: {"type":"message_delta","delta":{"stop_reason":"end_turn"},"usage":{"output_tokens":2}}`,+ `data: {"type":"message_stop"}`)+ chat := `{"model":"openrouter/deepseek/deepseek-v4.1-flash-1017","stream":false,"tools":[{"type":"function","function":{"name":"get_time","parameters":{"type":"object","properties":{}}}}],"messages":[+ {"role":"user","content":"what time is it? twice"},+ {"role":"assistant","content":null,"tool_calls":[` + timeCall + `]},+ {"role":"tool","tool_call_id":"call_1","content":"12:00"},+ {"role":"assistant","content":null,"tool_calls":[{"id":"call_2","type":"function","function":{"name":"get_time","arguments":"{}"}}],"reasoning_content":"Once more."},+ {"role":"tool","tool_call_id":"call_2","content":"12:01"}]}`+ if code, body := postTo(t, srv, "/v1/chat/completions", chat); code != 200 || f.calls != 1 {+ t.Fatalf("chat: %d after %d calls: %s", code, f.calls, body)+ }+ if !strings.Contains(string(f.got), `{"type":"thinking","thinking":"Once more.","signature":""}`) {+ t.Errorf("the client's reasoning went without a signature: %s", f.got)+ }+}+// Translated onto DeepSeek's Anthropic endpoint (a Chat client, the// provider giving only a Messages URL), a tool call with no thinking goes// after a thinking block holding a space, and one with DeepSeek's own@@ -217,3 +298,64 @@ func TestWithThinkingOnToolTurnsUnchanged(t *testing.T) {t.Error("DeepSeek not replayed")}}++// OpenRouter's Anthropic endpoint takes a turn's effort, the output_config+// Claude Code 2.1.302 puts on a {role: "system"} message, as a reasoning+// configuration_update, and turns it away on DeepSeek and GLM with the+// 400 #3696 quotes. magpie asks again without it (withoutTurnEffort), and+// from then on sends OpenRouter none; the request's own effort and the+// system message's text stay. On DeepSeek the tool turn's thinking says+// its signature too (#2883), or the second try is refused for that.+func TestOpenRouterTurnEffortLeftOut(t *testing.T) {+ for _, model := range []string{"deepseek/deepseek-v4.1-flash-1017", "z-ai/glm-5.3-flash"} {+ t.Run(model, func(t *testing.T) {+ f := &fake{t: t, ctype: "application/json", reply: anthropicWholeOK, refuse: func(body []byte) (int, string) {+ var q struct {+ Messages []map[string]json.RawMessage `json:"messages"`+ }+ json.Unmarshal(body, &q)+ for _, m := range q.Messages {+ if _, ok := m["output_config"]; ok {+ return 400, `{"error":{"type":"invalid_request_error","message":"Mid-conversation reasoning effort (configuration_update) is not supported on ` + model + `"}}`+ }+ }+ return openRouterRefuseAnthropic(body)+ }}+ up := setup(t, provider.Anthropic, f)+ if err := provider.Save(provider.Provider{ID: "openrouter", Name: "OpenRouter", Key: "k", Models: []string{model}, Anthropic: up.URL}); err != nil {+ t.Fatal(err)+ }+ srv := New()+ body := `{"model":"openrouter/` + model + `","max_tokens":64,"stream":false,"output_config":{"effort":"high"},+ "tools":[{"name":"Bash","input_schema":{"type":"object","properties":{}}}],+ "messages":[+ {"role":"user","content":"hi"},+ {"role":"assistant","content":[{"type":"tool_use","id":"t1","name":"Bash","input":{}}]},+ {"role":"user","content":[{"type":"tool_result","tool_use_id":"t1","content":"ok"}]},+ {"role":"system","output_config":{"effort":"medium"},"content":[{"type":"text","text":"# Environment <cwd>"}]},+ {"role":"user","content":"ok"}]}`+ code, out := postTo(t, srv, "/v1/messages", body)+ if code != 200 || f.calls != 2 {+ t.Fatalf("%d after %d calls, want 200 on the second: %s", code, f.calls, out)+ }+ check := func() {+ t.Helper()+ if oc := gjson.GetBytes(f.got, "output_config.effort").String(); oc != "high" {+ t.Errorf("output_config.effort = %q, want the request's own", oc)+ }+ ms := sentAnthropicMessages(t, f.got)+ if len(ms) != 5 {+ t.Fatalf("%d messages sent, want the system message kept: %s", len(ms), f.got)+ }+ sameJSON(t, ms[3], `{"role":"system","content":[{"type":"text","text":"# Environment <cwd>"}]}`)+ }+ check()+ // learned: the next request goes as OpenRouter takes it at once+ f.calls = 0+ if code, out = postTo(t, srv, "/v1/messages", body); code != 200 || f.calls != 1 {+ t.Fatalf("%d after %d calls, want 200 on the first: %s", code, f.calls, out)+ }+ check()+ })+ }+}diff --git a/internal/gateway/deepseek_step_lead_test.go b/internal/gateway/deepseek_step_lead_test.goindex b8cd6c34f..10ac68152 100644--- a/internal/gateway/deepseek_step_lead_test.go+++ b/internal/gateway/deepseek_step_lead_test.go@@ -193,6 +193,6 @@ func TestAnthropicReplyAfterToolGetsThinking(t *testing.T) {t.Fatalf("%d %s", code, msg)}ms := sentAnthropicMessages(t, withThinkingOnToolTurns([]byte(b)))- sameJSON(t, ms[3], `{"role":"assistant","content":[{"type":"thinking","thinking":" "},{"type":"text","text":"Done."}]}`)+ sameJSON(t, ms[3], `{"role":"assistant","content":[{"type":"thinking","thinking":" ","signature":""},{"type":"text","text":"Done."}]}`)sameJSON(t, ms[5], `{"role":"assistant","content":[{"type":"text","text":"You're welcome."}]}`)}