diff --git a/docs/subsystems/gateway-routing.md b/docs/subsystems/gateway-routing.md index da10e2ca2..49bbbb259 100644 --- a/docs/subsystems/gateway-routing.md +++ b/docs/subsystems/gateway-routing.md @@ -287,7 +287,7 @@ recorded as a prediction failure (`noPrediction`). - 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__`), 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/`, named by its hash (`keepSignature` in [`gemini_sigstore.go`](../../internal/gateway/gemini_sigstore.go)), and the id carries only the key (`__tsk16__`), 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. A signature goes back only to the provider that gave it (mimi001234: a group of Vertex AI and AI Studio moved on Vertex AI's 429, and AI Studio answered its signatures "Corrupted thought signature." on every try): the provider is noted beside it (`gemini-signatures/.by`, `noteSigner`) where a reply is decoded (`decoderFor`, `signersNoted`) or relayed (`sigTidy`, a Gemini client's reply in `native` mode), and every request is fitted to its provider (`ownSignatures` in `forwardTranslated`, `chatCallSignatures` and `geminiBodySignatures` in `passthrough`): another provider's signature goes as `skip_thought_signature_validator` on a call and not at all on text. One of no known provider (an id from before, or a note that couldn't be written) goes as before, and the 400 retry above covers it. The provider is the provider id, not the account. `TestSignatureGoesOnlyToItsSigner`, `TestSignatureGoesOnlyToItsSignerTranslated`, `TestCorruptedSignatureTriedWithout`, `TestGeminiBodyKeepsOnlyItsOwn`. Across APIs, only Claude's reasoning is carried to a Responses client, below. - A Responses upstream reads only the reasoning it sealed itself (`encrypted_content`). When one answers that it can't read the sealed reasoning or compaction it was sent (`foreignReasoning` in [`affinity.go`](../../internal/gateway/affinity.go): OpenAI's and Codex's "could not be verified", xAI's "Could not decrypt", Azure's "invalid encrypted summary", a relay's compaction-blob refusal), `serve` asks once more without it and remembers its hashes for that conversation (`stickKey`) and key or account (`candidate.vendor`, `refusedSeals`), so the conversation's later turns there go without it the first time; the try is `fail: foreign`. A Responses client's own items go first (`withoutReasoning`, `withoutRefused`), then OpenAI's compaction (`withoutCompaction`). A Chat, Messages or Gemini client holds a Responses upstream's sealed reasoning in its calls' ids instead (`__rk__`, `carryReasoning` and `unreasonCalls` in [`reasoning_carry.go`](../../internal/gateway/reasoning_carry.go), 9da9bfabd), and every later turn of its history sends it again, so a conversation that moved to another Responses upstream or account (Grok to Codex after a 402, and back) was refused on that turn and every one after it (#4798, zane668, ZanderH-code). Such a refusal is asked again once too: `refuseCarried` remembers what the request's calls carried as refused by that key or account, and `translate` leaves those items out of this and every later request to it (`withoutRefusedCarry`, scoped to the try's provider through `withSealScope`). The calls, their arguments and results and the text go as the client wrote them, under the calls' own ids; the one that sealed an item, and every other key or account, is still given it. As for a Responses client, all the reasoning the request carried goes, the upstream's own earlier items among them; what it seals next goes along. `TestForeignSealAcrossGroupMembers`, `TestForeignCarriedReasoningAskedAgainWithout`. - Claude signs a thinking block for the conversation and the account it was made in. When an Anthropic upstream answers 400 that a block's signature is invalid, "bound to a different conversation" or "not created in this conversation" (`boundRefusal`: a conversation moved between accounts or providers, or a relay that serves Claude from several accounts of its own; ferock on Discord, through Command Code's plugin), `forward` asks once more without the block it names (`messages..content.`) and every thinking block after it, whose signatures cover it, and remembers those signatures for that provider and account (`refuseBoundThinking`, `withoutRefusedThinking` in [`thinking_bound.go`](../../internal/gateway/thinking_bound.go)), so the conversation's later turns go without them the first time. Every route to an Anthropic upstream (relayed, translated, a plugin's fetch, count_tokens) passes there. Blocks before it, other providers and accounts, and every other refusal (DeepSeek's wanting its thinking back among them) are left as they are. magpie doesn't send the `thinking-binding-controls` beta's `drop_block` for an agent. `TestBoundThinkingLeftOut`, `TestPluginBoundThinkingLeftOut`, `TestOtherRefusalKeepsThinking`. -- A thinking block DeepSeek's Anthropic endpoint made is signed with its reply's id, a UUID, which Claude refuses ("Invalid `signature` in `thinking` block"). A routing group whose conversation ran on DeepSeek and goes on to Claude (DeepSeek unticked; GgbondHi6930 on X) holds such blocks, so before any refusal, `forwardOnce` leaves them out of every request to an upstream serving Claude (api.anthropic.com, or a `claude-` model name; `withoutForeignThinking` in [`thinking_bound.go`](../../internal/gateway/thinking_bound.go)), and `refuseBoundThinking` reads a refusal's indices against that same body. Claude's own signatures (base64), unsigned blocks, redacted_thinking and other vendors' signatures go as they were; DeepSeek's endpoint and every other upstream get the body byte for byte. `TestDeepSeekThinkingThenClaude`, `TestDeepSeekThinkingThenClaudeResponses`, `TestWithoutForeignThinking`. +- A thinking block DeepSeek's Anthropic endpoint made is signed with its reply's id, a UUID, which Claude refuses ("Invalid `signature` in `thinking` block"). A routing group whose conversation ran on DeepSeek and goes on to Claude (DeepSeek unticked; GgbondHi6930 on X) holds such blocks, so before any refusal, `forwardOnce` leaves them out of every request to an upstream serving Claude (api.anthropic.com, or a `claude-` model name; `withoutForeignThinking` in [`thinking_bound.go`](../../internal/gateway/thinking_bound.go)), and `refuseBoundThinking` reads a refusal's indices against that same body. A thinking block signed empty (or with no signature) is left out there too: magpie gives every block a Messages client gets a signature, "" for reasoning it has none for (a Chat or Responses vendor's, Grok on Cursor's plugin), Claude Code keeps such blocks through a compaction, and a group that moves on to Claude mid tool loop was turned away on every turn (citricdu on Discord: Kiro's Claude Opus 5.5 answered a bare invalid_request_error, which `refuseBoundThinking` can't read). An assistant message left with nothing goes; its text, tool calls and the results stay. The rule reaches every route to an upstream serving Claude (relayed, translated, a plugin's fetch such as Kiro's, Bedrock's `us.anthropic.claude-…` and Vertex AI's `claude-…@` ids, count_tokens). A model that asked for its tool turns' thinking back (`thinkingBackNeeded`, DeepSeek under another name) keeps the blocks filled in for it. Claude's own signatures (base64), redacted_thinking and other vendors' signatures go as they were; DeepSeek's endpoint and every other upstream get the body byte for byte. `TestDeepSeekThinkingThenClaude`, `TestDeepSeekThinkingThenClaudeResponses`, `TestWithoutForeignThinking`, `TestUnsignedThinkingNotSentToClaude`, `TestGrokThinkingThenClaude`. - Claude's reasoning goes to a Responses client (Codex) in an envelope and comes back as Claude wrote it (mysterious_dove_96933 on Discord). Anthropic wants a tool loop's next request to have the turn's thinking blocks, signed, and its `redacted_thinking` whole, or answers 400; Codex with `store: false` keeps only a reply's items, and of a reasoning item only `encrypted_content` is opaque. So the Anthropic decoders name a signature as Claude's (`KSig` with `sealAnthropic`, `Part.SignedBy`), and the Responses encoder and `renderResponses` give each thinking block a reasoning item whose `encrypted_content` is `magpie-claude1:` and the block's JSON in base64 (`claudeThinking`, [`internal/claudeseal`](../../internal/claudeseal/claudeseal.go)): its summary with it, an empty summary for a block signed with no text, and a `redacted_thinking` block as an item of its own. `parseResponses` reads such an item back into the block (`claudePart`), in order, so `anthropicBody` sends it as it was; an envelope that can't be read is its summary, as before. A Gemini thought's signature isn't named, and isn't sealed. The envelope goes to no Responses API: `passthrough` and `forwardOnce` take it out (`withoutClaudeSeals`: the item keeps its summary, one with none goes), `codexInputAs` leaves such an item out for Codex's own models as it does one with nothing sealed, and `codexUpstreamOn` takes it out before the ChatGPT backend; OpenAI's own `encrypted_content` is untouched. `redact.MaskJSON` keeps it whole (a reasoning item's seal), so the placeholders Claude was sent stay in what its signature covers. Claude's subscription names its signatures too, so Codex gets the same items, though its tool loop goes on inside Claude Code's own run, which keeps the thinking itself. `TestCodexToolLoopGivesClaudeItsThinkingBack`, `TestClaudeBlocksNeverGoToAResponsesAPI`, `TestGeminiSignatureIsNotSealedAsClaudes`, `TestMaskJSONKeepsClaudeBlocks`. - A translated Responses reply gives Codex the reasoning items a Responses upstream sent, as it sent them — one that carries its text in it (content parts, another vendor's shape) made over into one magpie could have, its text a summary and nothing sealed, in a reply translated or relayed as it came, for the client to store and replay where OpenAI's rules hold even with magpie disconnected (#2855, the reporter's rollout: 25 reasoning items a DeepSeek phase had left, each with its text in it and a seal of the vendor's own, stuck every later turn on OpenAI with a 400 `array too long` nothing of magpie's could strip then); 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. The summary request magpie makes offers none either: `codexInputAs` sends `tools: []` and leaves out the `additional_tools` input item, where Codex's Responses Lite (the entry of a ChatGPT account's gpt-6 model, copied from Codex's own) puts every tool; left in, the model may call one in place of the summary (the likely cause of WuSix's codex/gpt-6-astra "the model wrote no summary" on Discord, not confirmed on a real reply), and a reply with no summary says what it held instead (`answeredWith`). A reply that called a tool instead (`calledTool`) is asked once more with the conversation as text (`plainCompact`), and compacted locally when that writes no summary either: a model deep in an exchange of calls goes on with it whatever it is offered (Lucy on Discord: DeepSeek through group/auto-deepseek-v4-1-flash answered reasoning and an `exec_command` call 3 times in a row; `TestCodexCompactToolCallAsksAgainAsText`, `TestCodexCompactToolCallEveryTimeCompactsLocally`, over Chat, Responses and Messages, a group and a single model). When a provider answers its summary request 404, 405 or 501 (`lacksEndpoint`), or 400 for an item it didn't find (`itemNotFound`, a relay in front of either), or a kind of input item it doesn't take (`inputKindRefused`: Command Code's 400 `unsupported_input_item`, which takes messages, function calls, their outputs and reasoning only, and Grok's 422 "unknown item type"; as that status, as another magpie's 400 or 502 in front of it, or as an error in the summary's stream; never a 401, 403 or 429), `codexCompact` asks once more with the conversation as text (`plainCompact`), then compacts locally (#866, #1008, #5181, #5259), so the refusal never counts toward the guard's three. The text, and magpie's own summary, carry a Codex subagent's `agent_message` items (its task, the lead's follow-ups) as the user's (`itemText`). `TestCodexCompactUnsupportedInputItemAsksAgainAsText`, `TestCodexCompactUnsupportedInputItemCompactsLocally`, `TestCodexCompactUnsupportedInputWordsOnAnAccountFailureStay`. So does a summary request refused for its size (`summaryTooLarge`): a 413 byte cap, or an overflow of the model's window. Codex's remote compaction trims only by its own token estimate against the catalog's window and asks nothing smaller after either, so the turn's `context_length_exceeded` led to a compaction refused the same way, every time, and the session could neither compact nor go on (celestial_eagle_99230 on Discord: DeepSeek's own API, 1M window, answered 413 "Failed to buffer the request body: length limit exceeded"). The text ask leaves images out, keeps the ends of a long output and the latest 400K characters. `TestCodexCompactTooLargeAsksSmaller`, `TestCodexCompactTooLargeCompactsLocally`, `TestCodexCompactOtherRefusalStays`. Any other failure goes back with its status, said as the compaction's with who answered it (`compactFailed`: "compaction: (, ) answered the summary request 502 Bad Gateway: …"), the vendor's code, param and Retry-After kept. Not so the compaction Codex runs before a turn on another model, on the model the thread was on: a switch to a smaller window (`compaction.reason` `model_downshift` in the turn metadata) or to another compaction hash (`comp_hash_changed`), the only places Codex names either (`maybe_run_previous_model_inline_compact` in codex-rs `core/src/session/turn.rs`). When it fails, Codex asks the turn's own model instead only under its provider named "OpenAI" (`compact_model_fallback.rs`). Under magpie's provider, the one Codex has while its sign-in is used up (codex.out), the refusal was the turn's, and every turn of that thread asked the used-up account again, restarts or not, while a new thread worked (hiwise_aigc on X). Off `CodexPath`, `codexCompact` compacts such a failure locally (`previousModelCompaction`), whatever the failure, the compaction-failure hold included, and the thread goes on on the model it was switched to. On `CodexPath` the provider is Codex's own "OpenAI", which asks the turn's model itself, so the failure goes back as before. `TestCodexLeavingModelCompactsLocally`; Codex 0.162.1 in a sandbox sent the old model's `compaction_trigger` to `/v1` and failed the turn on a 429, and went on to the new model once the trigger was answered. A compaction relayed to OpenAI (`/responses/compact` on Codex's own model, as a `/responses` turn) that OpenAI answers with an error status and an empty body, which Codex shows as "unexpected status 502 Bad Gateway: Unknown error", or with a web page, is said in words naming the model, the status, and the account it went to (`codexSaidNothing`, outrageous_piglet on Discord); an error OpenAI says in JSON goes as it came. `TestCodexOwnCompactFailureIsSaid`, `TestCodexCompactFailureSaysCompaction`, `TestCodexCompactNoEndpointCompactsLocally`. 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) — but one whose stream merely broke off, with nothing failed or incomplete in it, is followed by magpie's own summary (#3526, Edward4226: Codex told a 502 asked the same huge summary over three times and the guard then held the conversation), as when no model can be asked at all. So is a translated summary serve found cut and answered 502 "the reply ended before it was complete" (`summaryEndedShort`).. 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`. A summary is waited for `compactWithin` (4 minutes) at most: Codex hears nothing while it is made and gives up on a stream silent for 300s, so a later summary, and a local one made after Codex left, reached nobody, and Codex sent the same history again, 300s each time (#5275, hayden4608: a ~3.1MB summary request still going up a ~10KB/s uplink at 299s). Past it the ask ends (`sideTimedOut`, logged as magpie's own limit, not the agent leaving) and magpie's own summary goes to Codex while it still waits. A compaction Codex left before it was answered writes nothing and counts as a failure (499), never clearing the count. `TestCodexCompactLateSummaryCompactsLocallyInTime`, `TestCodexCompactLeftBeforeAnsweredStillCounts`. - An `output_text` annotation without the offsets OpenAI's schema wants of its kind (a `url_citation` or `container_file_citation` with no `start_index`/`end_index`, as Volcengine Ark's Responses endpoint writes its url citations) cannot be replayed where that schema holds: the ChatGPT backend refuses the whole request, every turn of the thread, with "Missing required parameter: 'input[n].content[m].annotations[k].start_index'" (#4921; `withoutOffsetlessCitations` in [`codex_backend.go`](../../internal/gateway/codex_backend.go), the same leaving-out as a reasoning item's text, #1411). A whole reply streamed as the vendor's own events drops such an annotation in every place a client reads one (`dropOffsetlessCitations` beside `responsesWholeEvents` in [`whole_stream.go`](../../internal/gateway/whole_stream.go), the #2855 rule: what magpie hands a client must be something it could send again); a history that carries one goes to the ChatGPT backend, OpenAI's API and a relay that has turned one away without it, and a refusal naming the parameter is asked again without it (`refusesCitationOffsets`). The text, a citation with its offsets, and a `file_citation` or `file_path`, which OpenAI places by a single `index`, go as they came (`TestCitationsWithoutOffsetsAskedAgainWithout`, `TestWholeAsStreamDropsCitationsWithoutOffsets`, `TestCitationsWithOneIndexKept`). @@ -313,7 +313,7 @@ recorded as a prediction failure (`noPrediction`). - 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`. +- 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, but never to an upstream serving Claude (`withoutForeignThinking`, above). `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`. Relayed Messages streams buffer complete SSE events with `tidyEvents` ([`phase.go`](../../internal/gateway/phase.go)), so splitting an event header, data and blank delimiter across reads cannot detach headers or join distinct JSON payloads (#4868). Held text-block starts and stops own their bytes so buffer reuse cannot overwrite them. `TestAnthropicTextCallsSSEChunksKeepFraming` and `TestAnthropicMessagesSSEChunksKeepFraming` cover native and text-written calls, held text, whole/event/line/byte reads, and CRLF. - 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. diff --git a/internal/gateway/gateway.go b/internal/gateway/gateway.go index 1702fac91..43475e9d9 100644 --- a/internal/gateway/gateway.go +++ b/internal/gateway/gateway.go @@ -5744,7 +5744,7 @@ func (s *Server) forwardOnce(ctx context.Context, p provider.Provider, to provid // (thinking_bound.go), every route to it alike body = s.withoutRefusedThinking(p, body) // and those another vendor signed, to Claude (thinking_bound.go) - body = withoutForeignThinking(p, body) + body = s.withoutForeignThinking(p, body) if isKimi(p, to) || isDeepSeekAnthropic(p, to) || p.IsOpenCode() && strings.Contains(strings.ToLower(modelOf(body)), "deepseek") { // Claude Code's deferred-tool blocks, for which Kimi's // Anthropic endpoint turns the whole request away with a 400 diff --git a/internal/gateway/thinking_bound.go b/internal/gateway/thinking_bound.go index c79049d65..c4af2c3aa 100644 --- a/internal/gateway/thinking_bound.go +++ b/internal/gateway/thinking_bound.go @@ -7,6 +7,7 @@ import ( "encoding/json" "regexp" "strconv" + "strings" "github.com/tidwall/gjson" @@ -179,7 +180,7 @@ func (s *Server) refuseBoundThinking(p provider.Provider, errBody, body []byte) if !boundRefusal.Match(errBody) { return false } - sent := withoutForeignThinking(p, s.withoutRefusedThinking(p, body)) + sent := s.withoutForeignThinking(p, s.withoutRefusedThinking(p, body)) msgs := gjson.GetBytes(sent, "messages").Array() // from the block named, or from the start when it names none, or one // that isn't a thinking block in what was sent @@ -218,15 +219,39 @@ func (s *Server) refuseBoundThinking(p provider.Provider, errBody, body []byte) // Claude refuses each one, 400 "messages.1.content.0: Invalid `signature` // in `thinking` block" (checked on 2026-11-03), which forward mends only // where the refusal reaches it as Claude's own 400, and with a request -// spent. withoutForeignThinking leaves those blocks out of a request to an -// upstream serving Claude before it sees them: Claude's own signatures are -// base64 (3,000 of Claude Code's, 800 characters and longer), never a -// UUID. A block with no signature Claude takes (checked the same day), so -// it goes as it was, and so does every other vendor's signature, which -// refuseBoundThinking still mends. Every other upstream, DeepSeek's among -// them, gets the body byte for byte. +// spent. A conversation that ran on a model magpie translates for (Grok +// on Cursor's plugin, a Chat or Responses vendor) holds thinking blocks +// signed empty: magpie gives every block a client gets a signature, and +// one it has none for is "" (thinking_signature.go). Claude Code keeps +// them through a compaction and sends them on to whatever the group +// picks next (citricdu on Discord: Grok 4.7, then Claude Opus 5.5 on +// Kiro, which answered 13 turns in a row with a bare +// invalid_request_error that refuseBoundThinking can't read; the same +// request without the block was answered). A block with no signature +// can't be Claude's own, as Claude signs every block it makes, and where +// it sits in a tool loop Claude checks it. +// +// withoutForeignThinking leaves both out of a request to an upstream +// serving Claude (api.anthropic.com, or a claude- model on any route: +// a relay, Bedrock's and Vertex AI's ids, a plugin such as Kiro's) before +// it sees them, and an assistant message left with nothing goes too. Its +// text, tool calls and the results after them stay. Claude's own +// signatures (base64, 3,000 of Claude Code's 800 characters and longer) +// go as they were, as do redacted_thinking and every other vendor's +// signature, which refuseBoundThinking still mends. Every other upstream, +// DeepSeek's among them (which wants its thinking back and takes an empty +// signature), gets the body byte for byte, and so does a model that asked +// for its tool turns' thinking back (thinking_back.go: DeepSeek behind a +// name that doesn't say so), whose filled-in blocks are signed empty. +func (s *Server) withoutForeignThinking(p provider.Provider, body []byte) []byte { + if !s.fits(p.ID, thinkingBackNeeded(modelOf(body)), provider.Anthropic) { + return body + } + return withoutForeignThinking(p, body) +} + func withoutForeignThinking(p provider.Provider, body []byte) []byte { - if !bytes.Contains(body, []byte(`"signature"`)) { + if !bytes.Contains(body, []byte(`"signature"`)) && !thinkingTyped.Match(body) { return body } model := modelOf(body) @@ -234,10 +259,18 @@ func withoutForeignThinking(p provider.Provider, body []byte) []byte { return body } return withoutThinkingBlocks(body, func(_, _ int, b gjson.Result) bool { - return b.Get("type").String() == "thinking" && deepseekSignature.MatchString(b.Get("signature").String()) + if b.Get("type").String() != "thinking" { + return false + } + sig := b.Get("signature").String() + return strings.TrimSpace(sig) == "" || deepseekSignature.MatchString(sig) }) } +// thinkingTyped is a body with a thinking block in it, for one that says +// no signature at all. +var thinkingTyped = regexp.MustCompile(`"type"\s*:\s*"thinking"`) + // deepseekSignature is the signature DeepSeek's Anthropic endpoint gives // its thinking: the reply's id, a UUID. var deepseekSignature = regexp.MustCompile(`(?i)^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$`) diff --git a/internal/gateway/thinking_switch_test.go b/internal/gateway/thinking_switch_test.go index 004bfeb56..0bc85220d 100644 --- a/internal/gateway/thinking_switch_test.go +++ b/internal/gateway/thinking_switch_test.go @@ -298,7 +298,7 @@ func deepSeekThenClaude(t *testing.T, stream bool) { } // Only an upstream serving Claude is sent the body without DeepSeek's -// blocks; Claude's own, an unsigned one and a redacted one stay, and +// blocks and those signed empty; Claude's own and a redacted one stay, and // DeepSeek's endpoint and another vendor's get it byte for byte. func TestWithoutForeignThinking(t *testing.T) { fresh(t) @@ -329,8 +329,20 @@ func TestWithoutForeignThinking(t *testing.T) { if s := gjson.GetBytes(got, "messages.1.content.#.type").Raw; s != `["text"]` { t.Errorf("Claude's message 1 = %s, want DeepSeek's thinking out", s) } - if s := gjson.GetBytes(got, "messages.3.content").Raw; s != gjson.GetBytes(conv("claude-opus-5-5"), "messages.3.content").Raw { - t.Errorf("Claude's message 3 = %s, want it as it was", s) + // an empty signature is none Claude made (citricdu: Grok's thinking + // after a compaction): out too, Claude's own and redacted ones kept + want3 := `[{"type":"thinking","thinking":"b","signature":"CAQS8gcKEAgTGAI4AUqAAQ=="},{"type":"redacted_thinking","data":"EmwKAhgB"},{"type":"text","text":"Ok"}]` + if s := gjson.GetBytes(got, "messages.3.content").Raw; s != want3 { + t.Errorf("Claude's message 3 = %s, want %s", s, want3) + } + // on Bedrock's and Vertex AI's ids too, and a block with no signature + // field at all; an assistant message of nothing else goes + for _, model := range []string{"us.anthropic.claude-opus-5-5-v1:0", "claude-opus-5-5@20261001"} { + body := []byte(`{"model":"` + model + `","messages":[{"role":"user","content":"go"},{"role":"assistant","content":[{"type":"thinking","thinking":"grok"}]},{"role":"assistant","content":[{"type":"thinking","thinking":"x","signature":" "},{"type":"tool_use","id":"t1","name":"Read","input":{}}]},{"role":"user","content":[{"type":"tool_result","tool_use_id":"t1","content":"ok"}]}]}`) + got := withoutForeignThinking(find("claude-api"), body) + if n, s := len(gjson.GetBytes(got, "messages").Array()), gjson.GetBytes(got, "messages.1.content.#.type").Raw; n != 3 || s != `["tool_use"]` { + t.Errorf("%s: messages = %s", model, gjson.GetBytes(got, "messages").Raw) + } } for _, c := range []struct{ id, model string }{{"deepseek", "deepseek-v4-pro"}, {"kimi", "kimi-k2.6"}} { if got := withoutForeignThinking(find(c.id), conv(c.model)); string(got) != string(conv(c.model)) { diff --git a/internal/gateway/thinking_unsigned_test.go b/internal/gateway/thinking_unsigned_test.go new file mode 100644 index 000000000..b382cd7e8 --- /dev/null +++ b/internal/gateway/thinking_unsigned_test.go @@ -0,0 +1,228 @@ +package gateway + +import ( + "encoding/json" + "fmt" + "io" + "net/http" + "net/http/httptest" + "strings" + "sync" + "testing" + + "github.com/tidwall/gjson" + + "github.com/yetone/magpie/internal/provider" +) + +// citricdu on Discord (magpie 0.1.3356): Claude Code auto-compacted a +// session on a Smart group that had moved to Cursor's Grok 4.7, then the +// group went back to Kiro's Claude Opus 5.5. The compacted history kept a +// thinking block Grok made, which magpie had handed Claude Code signed +// empty, and Kiro turned the session away 13 times in a row with a bare +// invalid_request_error. The same request without the block was answered. + +// grokThought is the shape of the reasoning Grok gave in the report: its +// own words, not Claude's, in a tool turn. +const grokThought = "The user wants the split logic checked. I should read internal/split.go first, then run the tests to see which case fails." + +// unsignedConversation is the reporter's request after the compaction: +// the summary Claude Code continues from, then the tool loop it was in, +// whose assistant turns open with Grok's thinking signed "" before the +// calls, and the results after them. +func unsignedConversation(model string) string { + return `{"model":"` + model + `","max_tokens":32000,"stream":false,"thinking":{"type":"adaptive"},"output_config":{"effort":"high"},` + + `"tools":[{"name":"Read","description":"Read a file","input_schema":{"type":"object","properties":{"file_path":{"type":"string"}}}},{"name":"Bash","description":"Run a command","input_schema":{"type":"object","properties":{"command":{"type":"string"}}}}],` + + `"messages":[` + + `{"role":"user","content":[{"type":"text","text":"This session is being continued from a previous conversation that ran out of context. The summary below covers the earlier portion of the conversation.\n\nSummary: the user asked to fix the split of long requests."}]},` + + `{"role":"assistant","content":[{"type":"thinking","thinking":` + jsonString(grokThought) + `,"signature":""},{"type":"text","text":"Reading the split code."},{"type":"tool_use","id":"toolu_01Grok1","name":"Read","input":{"file_path":"internal/split.go"}}]},` + + `{"role":"user","content":[{"type":"tool_result","tool_use_id":"toolu_01Grok1","content":"package split"}]},` + + `{"role":"assistant","content":[{"type":"thinking","thinking":"Now run the tests.","signature":""},{"type":"tool_use","id":"toolu_01Grok2","name":"Bash","input":{"command":"go test ./internal/split"}}]},` + + `{"role":"user","content":[{"type":"tool_result","tool_use_id":"toolu_01Grok2","content":"ok"}]}]}` +} + +func jsonString(s string) string { + b, _ := json.Marshal(s) + return string(b) +} + +// kiroClaude answers as the reporter's Kiro did: a thinking block with no +// signature is turned away with Anthropic's error type and words that +// name nothing (so refuseBoundThinking can't mend it); anything else is +// answered as boundClaude answers. +type kiroClaude struct{ boundClaude } + +func (c *kiroClaude) ServeHTTP(w http.ResponseWriter, r *http.Request) { + b, _ := io.ReadAll(r.Body) + for _, m := range gjson.GetBytes(b, "messages").Array() { + for _, blk := range m.Get("content").Array() { + if blk.Get("type").String() == "thinking" && blk.Get("signature").String() == "" { + c.mu.Lock() + c.bodies = append(c.bodies, string(b)) + c.mu.Unlock() + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(400) + io.WriteString(w, `{"type":"error","error":{"type":"invalid_request_error","message":"Improperly formed request."}}`) + return + } + } + } + r.Body = io.NopCloser(strings.NewReader(string(b))) + c.boundClaude.ServeHTTP(w, r) +} + +// Every route to Claude leaves the empty-signed thinking out, and keeps +// the turns' text, calls and results: relayed to a Claude API, and +// through Kiro's plugin's fetch. +func TestUnsignedThinkingNotSentToClaude(t *testing.T) { + check := func(t *testing.T, sent []string, code int, said string) { + t.Helper() + if code != 200 { + t.Fatalf("answered %d %s, want 200", code, said) + } + if len(sent) != 1 { + t.Fatalf("Claude asked %d times, want once", len(sent)) + } + b := sent[0] + if strings.Contains(b, "split logic") || strings.Contains(b, "Now run the tests.") || len(signatures(b)) != 0 { + t.Errorf("unsigned thinking went to Claude: %s", gjson.Get(b, "messages").Raw) + } + for _, want := range []string{`"Reading the split code."`, `"toolu_01Grok1"`, `"toolu_01Grok2"`, `"package split"`, `"go test ./internal/split"`} { + if strings.Count(b, want) == 0 { + t.Errorf("%s left out: %s", want, gjson.Get(b, "messages").Raw) + } + } + if n := len(gjson.Get(b, "messages").Array()); n != 5 { + t.Errorf("%d messages sent, want the 5 the agent sent", n) + } + } + t.Run("relayed", func(t *testing.T) { + fresh(t) + up := &kiroClaude{} + srv := httptest.NewServer(up) + t.Cleanup(srv.Close) + if err := provider.Save(provider.Provider{ID: "kiro-relay", Name: "Kiro relay", Key: "k", Anthropic: srv.URL, Models: []string{"claude-opus-5-5"}}); err != nil { + t.Fatal(err) + } + code, said := claudeCodeMessages(t, New(), unsignedConversation("kiro-relay/claude-opus-5-5")) + check(t, up.sent(), code, said) + }) + t.Run("plugin", func(t *testing.T) { + up := &kiroClaude{boundClaude{stream: true}} + t.Setenv("FAKE_KIRO", "1") + pid := besideFake(t, "kiro", up) + code, said := claudeCodeMessages(t, New(), unsignedConversation(pid+"/claude-opus-5.5")) + check(t, up.sent(), code, said) + }) +} + +func claudeCodeMessages(t *testing.T, s *Server, body string) (int, string) { + t.Helper() + rec := httptest.NewRecorder() + req := httptest.NewRequest("POST", "/v1/messages", strings.NewReader(body)) + req.Header.Set("anthropic-version", "2023-06-01") + req.Header.Set("User-Agent", "claude-cli/2.1.120 (external, cli)") + s.Handler().ServeHTTP(rec, req) + return rec.Code, rec.Body.String() +} + +// switchGrok answers as a Chat vendor serving Grok does: its reasoning, +// then a tool call, or text once the call has its result. +type switchGrok struct { + mu sync.Mutex + n int +} + +func (g *switchGrok) ServeHTTP(w http.ResponseWriter, r *http.Request) { + b, _ := io.ReadAll(r.Body) + g.mu.Lock() + g.n++ + n := g.n + g.mu.Unlock() + ms := gjson.GetBytes(b, "messages").Array() + done := len(ms) > 0 && ms[len(ms)-1].Get("role").String() == "tool" + msg := map[string]any{"role": "assistant", "reasoning_content": grokThought} + finish := "tool_calls" + if done { + msg["content"], finish = "Read it.", "stop" + } else { + msg["content"] = "" + msg["tool_calls"] = []any{map[string]any{"id": fmt.Sprintf("call_grok%d", n), "type": "function", "function": map[string]any{"name": "Read", "arguments": fmt.Sprintf(`{"file_path":"f%d.go"}`, n)}}} + } + if !gjson.GetBytes(b, "stream").Bool() { + w.Header().Set("Content-Type", "application/json") + json.NewEncoder(w).Encode(map[string]any{"id": "c1", "object": "chat.completion", "model": "grok-4.7", "choices": []any{map[string]any{"index": 0, "message": msg, "finish_reason": finish}}, "usage": map[string]any{"prompt_tokens": 1, "completion_tokens": 1}}) + return + } + w.Header().Set("Content-Type", "text/event-stream") + chunk := func(delta map[string]any, finish any) { + c, _ := json.Marshal(map[string]any{"id": "c1", "object": "chat.completion.chunk", "model": "grok-4.7", "choices": []any{map[string]any{"index": 0, "delta": delta, "finish_reason": finish}}}) + fmt.Fprintf(w, "data: %s\n\n", c) + } + chunk(map[string]any{"role": "assistant", "reasoning_content": grokThought}, nil) + if done { + chunk(map[string]any{"content": "Read it."}, nil) + } else { + calls := msg["tool_calls"].([]any) + c := calls[0].(map[string]any) + chunk(map[string]any{"tool_calls": []any{map[string]any{"index": 0, "id": c["id"], "type": "function", "function": c["function"]}}}, nil) + } + chunk(map[string]any{}, finish) + io.WriteString(w, "data: [DONE]\n\n") +} + +// The reporter's whole path: a group's turns on Grok (a Chat vendor, +// whose reasoning Claude Code gets as thinking signed empty), then the +// group moves to Claude in the middle of a tool loop. Claude, which +// turns a block it didn't sign away, is never sent Grok's. +func TestGrokThinkingThenClaude(t *testing.T) { + fresh(t) + gk, cl := &switchGrok{}, &switchClaude{} + gku, clu := httptest.NewServer(gk), httptest.NewServer(cl) + t.Cleanup(gku.Close) + t.Cleanup(clu.Close) + for _, p := range []provider.Provider{ + {ID: "grokco", Name: "Grok", Key: "sk-gk", Chat: gku.URL + "/v1", Models: []string{"grok-4.7"}}, + {ID: "claude-api", Name: "Claude API", Key: "sk-ant", Anthropic: clu.URL, Models: []string{"claude-opus-5-5"}}, + } { + if err := provider.Save(p); err != nil { + t.Fatal(err) + } + } + g := provider.Group{ID: "dc", Name: "Smart split", Members: []string{"grokco/grok-4.7", "claude-api/claude-opus-5-5"}} + if err := provider.SaveGroup(g); err != nil { + t.Fatal(err) + } + s := New() + msgs := []json.RawMessage{json.RawMessage(`{"role":"user","content":[{"type":"text","text":"check the split"}]}`)} + var code int + var said string + if msgs, code, said = switchTurn(t, s, false, msgs); code != 200 { + t.Fatalf("Grok's turn: %d %s", code, said) + } + last := msgs[len(msgs)-1] + th := gjson.GetBytes(last, `content.#(type=="thinking")`) + if th.Get("thinking").String() != grokThought || !th.Get("signature").Exists() || th.Get("signature").String() != "" { + t.Fatalf("Grok's reply = %s, want its thinking signed empty", last) + } + id := gjson.GetBytes(last, `content.#(type=="tool_use").id`).String() + msgs = append(msgs, json.RawMessage(`{"role":"user","content":[{"type":"tool_result","tool_use_id":"`+id+`","content":"package f"}]}`)) + // Grok unticked: the tool loop goes on on Claude + g.Off = []string{"grokco/grok-4.7"} + if err := provider.SaveGroup(g); err != nil { + t.Fatal(err) + } + if _, code, said = switchTurn(t, s, false, msgs); code != 200 { + t.Fatalf("Claude's turn: %d %s", code, said) + } + if cl.refused != 0 || len(cl.bodies) != 1 { + t.Fatalf("Claude refused %d of %d requests: %s", cl.refused, len(cl.bodies), cl.bodies[0]) + } + sent := cl.bodies[0] + if strings.Contains(sent, "split logic") { + t.Errorf("Grok's thinking went to Claude: %s", sent) + } + if !strings.Contains(sent, id) || !strings.Contains(sent, `"package f"`) { + t.Errorf("Grok's call or its result left out: %s", sent) + } +} diff --git a/internal/plugin/testdata/fake/index.js b/internal/plugin/testdata/fake/index.js index 916c7da10..a39f11222 100644 --- a/internal/plugin/testdata/fake/index.js +++ b/internal/plugin/testdata/fake/index.js @@ -81,6 +81,9 @@ export const FakePlugin = async ({ client }) => ({ "fake-gemini": { name: "Fake Gemini", provider: { npm: "@ai-sdk/google" }, reasoning: true, modalities: { input: ["text"], output: ["text"] }, limit: { context: 3000, output: 300 } }, }, } + // $FAKE_KIRO: a Claude model named as Kiro's plugin names it, on + // Anthropic's Messages API + if (process.env.FAKE_KIRO) cfg.provider[ID].models["claude-opus-5.5"] = { name: "Claude Opus 5.5", provider: { npm: "@ai-sdk/anthropic" }, reasoning: true, modalities: { input: ["text", "image"], output: ["text"] }, limit: { context: 200000, output: 32000 } } // $FAKE_RESPONSES: one model more, on OpenAI's Responses (Grok's) // $FAKE_FAST=1: fake-1 has a fast one, as Cursor's plugin 0.1.x lists // a model's -fast (=tier: see the models hook)