From f3335dd1b43d362be112a89d6ebeebe38e592827 Mon Sep 17 00:00:00 2001 From: yetone Date: Tue, 3 Nov 2026 12:57:57 +0800 Subject: [PATCH] gateway: DeepSeek's thinking is left out of a request to Claude (GgbondHi6930 on X) GgbondHi6930 on X: a Smart group of DeepSeek and a Claude API key. A conversation ran on DeepSeek at max effort; with DeepSeek unticked its next turn went to Claude and failed "signature in thinking". A new conversation worked. Cause: DeepSeek's Anthropic endpoint signs each thinking block with its reply's id, a UUID (checked against api.deepseek.com/anthropic). The agent keeps those blocks and sends them back, so the first Claude turn carries them, and Claude refuses the request, 400 "messages.1.content.0: Invalid `signature` in `thinking` block" (real reply through OpenRouter's Anthropic route, req_011CgfP4zyRcUhPiTg5sLpoe). Until now magpie mended this only after the refusal, in forward's bound-thinking retry. That needs the refusal to reach forward as a 400/422 with Claude's wording, and it spends a request. With fakes that answer as Claude does, main recovers through it, on Messages (whole and streamed) and on Codex's Responses. So the reporter's failure is where that retry can't read the refusal. A relay's status or wording is the likely case; it is not reproduced exactly. Change: forwardOnce, which every route to an Anthropic upstream passes (relayed, translated Chat/Responses, group fallback and Smart routing, a plugin's fetch, count_tokens), now calls withoutForeignThinking. For an upstream serving Claude (api.anthropic.com, or a claude- model name) and not DeepSeek, it leaves out each thinking block whose signature is a UUID. Those blocks never reach Claude, and refuseBoundThinking reads a refusal's indices against that same body. These go byte for byte: - Claude's own signatures (base64; 3,000 of Claude Code's own were checked, all base64 and 800+ characters); - unsigned blocks (Claude took one in a real request); - redacted_thinking; - other vendors' signatures, which the retry still mends. DeepSeek's endpoint and every other upstream get the body unchanged. Tests (thinking_switch_test.go): - TestDeepSeekThinkingThenClaude: the reporter's case, whole and streamed. 3 DeepSeek tool turns, then DeepSeek unticked and 3 Claude turns. Claude refuses nothing and gets its own blocks back as signed. With DeepSeek ticked again and Claude unticked, DeepSeek is sent every block, its own and Claude's. - TestDeepSeekThinkingThenClaudeResponses: the same through Codex's /v1/responses. - TestWithoutForeignThinking: Claude, DeepSeek and Kimi upstreams. Run on mote (mote-run): - gofmt -l, go vet ./..., GOOS=linux go vet -tags nogui ./... and GOOS=windows go vet ./...: clean, at cfa9a6987 (base 17d2ef10f). - go test -timeout 45m ./internal/gateway/... ./internal/provider/... at cfa9a6987: provider ok. Gateway ok except TestCodexPoolSaysTheClientsVersion, which is #4807 (passes alone 3/3; commented there). It was fixed on main by 17f2387e1, which this commit is rebased onto. - After the rebase onto 17f2387e1, which touched none of these files' code: -run 'Thinking|Bound|TestCodexPoolSaysTheClientsVersion' ok. Broken by hand: with withoutForeignThinking returning the body as it came, all three tests go red ("Claude refused 1 of its 4 requests", "Claude refused 1 of its 3 requests", "message 1 = [thinking,text]"). Not tried: - a real Claude account through magpie; no Anthropic key was usable here, and the relay accounts found (aihubmix, yylx) are out of credit; - the reporter's own relay; - Chat Completions clients, which carry no signatures; - Kimi, GLM and MiniMax signatures, which the refusal path still mends. --- docs/subsystems/gateway-routing.md | 1 + internal/gateway/gateway.go | 2 + internal/gateway/thinking_bound.go | 32 +- internal/gateway/thinking_switch_test.go | 415 +++++++++++++++++++++++ 4 files changed, 449 insertions(+), 1 deletion(-) create mode 100644 internal/gateway/thinking_switch_test.go diff --git a/docs/subsystems/gateway-routing.md b/docs/subsystems/gateway-routing.md index eb122067f..338ec54cf 100644 --- a/docs/subsystems/gateway-routing.md +++ b/docs/subsystems/gateway-routing.md @@ -256,6 +256,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. 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`. - 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), `codexCompact` asks once more with the conversation as text (`plainCompact`), then compacts locally (#866, #1008). 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`. - 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`). diff --git a/internal/gateway/gateway.go b/internal/gateway/gateway.go index deacbe5af..7c6d16ca2 100644 --- a/internal/gateway/gateway.go +++ b/internal/gateway/gateway.go @@ -5076,6 +5076,8 @@ func (s *Server) forwardOnce(ctx context.Context, p provider.Provider, to provid // the thinking blocks it refused as another conversation's // (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) if isKimi(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 0589749b3..c79049d65 100644 --- a/internal/gateway/thinking_bound.go +++ b/internal/gateway/thinking_bound.go @@ -179,7 +179,7 @@ func (s *Server) refuseBoundThinking(p provider.Provider, errBody, body []byte) if !boundRefusal.Match(errBody) { return false } - sent := s.withoutRefusedThinking(p, body) + sent := 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 @@ -211,3 +211,33 @@ func (s *Server) refuseBoundThinking(p provider.Provider, errBody, body []byte) s.refuseThinking(owner, keys) return true } + +// A conversation that ran on DeepSeek's Anthropic endpoint first (a +// routing group with DeepSeek unticked, then Claude: GgbondHi6930 on X) +// holds thinking blocks DeepSeek signed with its reply's id, a UUID. +// 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. +func withoutForeignThinking(p provider.Provider, body []byte) []byte { + if !bytes.Contains(body, []byte(`"signature"`)) { + return body + } + model := modelOf(body) + if anthropicReplaysThinking(p.Host(), model) || p.Host() != "api.anthropic.com" && !anthropicModel.MatchString(model) { + return body + } + return withoutThinkingBlocks(body, func(_, _ int, b gjson.Result) bool { + return b.Get("type").String() == "thinking" && deepseekSignature.MatchString(b.Get("signature").String()) + }) +} + +// 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 new file mode 100644 index 000000000..004bfeb56 --- /dev/null +++ b/internal/gateway/thinking_switch_test.go @@ -0,0 +1,415 @@ +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" +) + +// GgbondHi6930 on X: a Smart group of DeepSeek and a Claude API key. +// The conversation ran on DeepSeek at max effort; with DeepSeek unticked +// its next turn went to Claude, which refused it, "signature in +// thinking". A new conversation worked. Claude is now sent the +// conversation without DeepSeek's thinking, so it never refuses it, and +// DeepSeek, ticked again, still gets every block. + +// switchDeepSeek answers as DeepSeek's Anthropic endpoint does (checked +// against api.deepseek.com/anthropic on 2026-11-03): a thinking block +// signed with the reply's own id, a UUID, then a tool call or text. +type switchDeepSeek struct { + mu sync.Mutex + n int + bodies []string +} + +func (d *switchDeepSeek) ServeHTTP(w http.ResponseWriter, r *http.Request) { + b, _ := io.ReadAll(r.Body) + d.mu.Lock() + d.n++ + n := d.n + d.bodies = append(d.bodies, string(b)) + d.mu.Unlock() + id := fmt.Sprintf("49e144b6-799a-40e9-af71-%012d", n) + var last string + if ms := gjson.GetBytes(b, "messages").Array(); len(ms) > 0 { + last = ms[len(ms)-1].Get("content.0.type").String() + } + act := fmt.Sprintf(`{"type":"tool_use","id":"call_00_ds%d","name":"Read","input":{"file_path":"f%d.go"}}`, n, n) + stop := "tool_use" + if last == "tool_result" { + act, stop = `{"type":"text","text":"Read it."}`, "end_turn" + } + answerMessages(w, b, fmt.Sprintf(`{"id":%q,"type":"message","role":"assistant","model":"deepseek-v4-pro","content":[{"type":"thinking","thinking":"We need to read f%d.go.","signature":%q},%s],"stop_reason":%q,"stop_sequence":null,"usage":{"input_tokens":85,"output_tokens":18}}`, id, n, id, act, stop)) +} + +// answerMessages writes msg whole, or as the Messages stream when body asks for +// one: a thinking block starts with an empty signature, which its +// signature_delta then gives, as DeepSeek's and Claude's streams do. +func answerMessages(w http.ResponseWriter, body []byte, msg string) { + if !gjson.GetBytes(body, "stream").Bool() { + w.Header().Set("Content-Type", "application/json") + io.WriteString(w, msg) + return + } + w.Header().Set("Content-Type", "text/event-stream") + m := gjson.Parse(msg) + ev := func(name string, v any) { + b, _ := json.Marshal(v) + fmt.Fprintf(w, "event: %s\ndata: %s\n\n", name, b) + } + ev("message_start", map[string]any{"type": "message_start", "message": map[string]any{"id": m.Get("id").String(), "type": "message", "role": "assistant", "model": m.Get("model").String(), "content": []any{}, "stop_reason": nil, "usage": map[string]any{"input_tokens": 1, "output_tokens": 0}}}) + for i, b := range m.Get("content").Array() { + switch b.Get("type").String() { + case "thinking": + ev("content_block_start", map[string]any{"type": "content_block_start", "index": i, "content_block": map[string]any{"type": "thinking", "thinking": "", "signature": ""}}) + ev("content_block_delta", map[string]any{"type": "content_block_delta", "index": i, "delta": map[string]any{"type": "thinking_delta", "thinking": b.Get("thinking").String()}}) + ev("content_block_delta", map[string]any{"type": "content_block_delta", "index": i, "delta": map[string]any{"type": "signature_delta", "signature": b.Get("signature").String()}}) + case "text": + ev("content_block_start", map[string]any{"type": "content_block_start", "index": i, "content_block": map[string]any{"type": "text", "text": ""}}) + ev("content_block_delta", map[string]any{"type": "content_block_delta", "index": i, "delta": map[string]any{"type": "text_delta", "text": b.Get("text").String()}}) + case "tool_use": + ev("content_block_start", map[string]any{"type": "content_block_start", "index": i, "content_block": map[string]any{"type": "tool_use", "id": b.Get("id").String(), "name": b.Get("name").String(), "input": map[string]any{}}}) + ev("content_block_delta", map[string]any{"type": "content_block_delta", "index": i, "delta": map[string]any{"type": "input_json_delta", "partial_json": b.Get("input").Raw}}) + } + ev("content_block_stop", map[string]any{"type": "content_block_stop", "index": i}) + } + ev("message_delta", map[string]any{"type": "message_delta", "delta": map[string]any{"stop_reason": m.Get("stop_reason").String()}, "usage": map[string]any{"output_tokens": 1}}) + ev("message_stop", map[string]any{"type": "message_stop"}) +} + +// streamedContent is the content a Messages stream gives, as Claude Code +// puts it together. +func streamedContent(t *testing.T, stream string) string { + t.Helper() + var blocks []map[string]any + inputs := map[int]string{} + for _, line := range strings.Split(stream, "\n") { + data, ok := strings.CutPrefix(line, "data: ") + if !ok { + continue + } + e := gjson.Parse(data) + i := int(e.Get("index").Int()) + switch e.Get("type").String() { + case "content_block_start": + var b map[string]any + json.Unmarshal([]byte(e.Get("content_block").Raw), &b) + for len(blocks) <= i { + blocks = append(blocks, nil) + } + blocks[i] = b + case "content_block_delta": + d := e.Get("delta") + switch d.Get("type").String() { + case "text_delta": + blocks[i]["text"] = blocks[i]["text"].(string) + d.Get("text").String() + case "thinking_delta": + blocks[i]["thinking"] = blocks[i]["thinking"].(string) + d.Get("thinking").String() + case "signature_delta": + blocks[i]["signature"] = d.Get("signature").String() + case "input_json_delta": + inputs[i] += d.Get("partial_json").String() + } + } + } + for i, in := range inputs { + var v any + if json.Unmarshal([]byte(in), &v) != nil { + t.Fatalf("tool input %q isn't JSON", in) + } + blocks[i]["input"] = v + } + out, _ := json.Marshal(blocks) + return string(out) +} + +// switchClaude answers as api.anthropic.com does: a thinking block it +// didn't sign, in any turn, is refused with the first one named (checked +// on 2026-11-03 through OpenRouter's Anthropic route, a UUID-signed +// block in an earlier, finished turn too). +type switchClaude struct { + mu sync.Mutex + bodies []string + signed map[string]bool + n int + // refused is how many requests Claude turned away + refused int +} + +func (c *switchClaude) ServeHTTP(w http.ResponseWriter, r *http.Request) { + b, _ := io.ReadAll(r.Body) + c.mu.Lock() + defer c.mu.Unlock() + c.bodies = append(c.bodies, string(b)) + w.Header().Set("Content-Type", "application/json") + for mi, m := range gjson.GetBytes(b, "messages").Array() { + for bi, blk := range m.Get("content").Array() { + if blk.Get("type").String() == "thinking" && !c.signed[blk.Get("signature").String()] { + c.refused++ + w.WriteHeader(400) + e, _ := json.Marshal(map[string]any{"type": "error", "error": map[string]any{"type": "invalid_request_error", "message": fmt.Sprintf("messages.%d.content.%d: Invalid `signature` in `thinking` block", mi, bi)}, "request_id": "req_011CgfP4zyRcUhPiTg5sLpoe"}) + w.Write(e) + return + } + } + } + c.n++ + sig := fmt.Sprintf("EqQBCkgIBxABGAIiQL%d", c.n) + if c.signed == nil { + c.signed = map[string]bool{} + } + c.signed[sig] = true + answerMessages(w, b, fmt.Sprintf(`{"id":"msg_011Cgf%d","type":"message","role":"assistant","model":"claude-opus-5-5","content":[{"type":"thinking","thinking":"Go on.","signature":%q},{"type":"text","text":"Done."}],"stop_reason":"end_turn","usage":{"input_tokens":1,"output_tokens":1}}`, c.n, sig)) +} + +// switchTurn posts a Claude Code turn to the group and gives back the +// conversation with the reply added, as Claude Code keeps it. +func switchTurn(t *testing.T, s *Server, stream bool, msgs []json.RawMessage) ([]json.RawMessage, int, string) { + t.Helper() + ms, _ := json.Marshal(msgs) + body := `{"model":"group/dc","max_tokens":32000,"stream":` + fmt.Sprint(stream) + `,"thinking":{"type":"adaptive"},"output_config":{"effort":"max"},` + + `"tools":[{"name":"Read","description":"Read a file","input_schema":{"type":"object","properties":{"file_path":{"type":"string"}}}}],` + + `"metadata":{"user_id":"{\"session_id\":\"5c9a2f0e-1b7d-4c43-9a43-6f1e0a8b2d11\"}"},"messages":` + string(ms) + `}` + 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) + if rec.Code != 200 { + return msgs, rec.Code, rec.Body.String() + } + content := gjson.Get(rec.Body.String(), "content").Raw + if stream { + content = streamedContent(t, rec.Body.String()) + } + return append(msgs, json.RawMessage(`{"role":"assistant","content":`+content+`}`)), 200, rec.Body.String() +} + +func TestDeepSeekThinkingThenClaude(t *testing.T) { + for _, stream := range []bool{false, true} { + t.Run(fmt.Sprintf("stream=%v", stream), func(t *testing.T) { deepSeekThenClaude(t, stream) }) + } +} + +func deepSeekThenClaude(t *testing.T, stream bool) { + fresh(t) + ds, cl := &switchDeepSeek{}, &switchClaude{} + dsu, clu := httptest.NewServer(ds), httptest.NewServer(cl) + t.Cleanup(dsu.Close) + t.Cleanup(clu.Close) + for _, p := range []provider.Provider{ + {ID: "deepseek", Name: "DeepSeek", Key: "sk-ds", Anthropic: dsu.URL + "/anthropic", Models: []string{"deepseek-v4-pro"}}, + {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: "DC", Members: []string{"deepseek/deepseek-v4-pro", "claude-api/claude-opus-5-5"}} + if err := provider.SaveGroup(g); err != nil { + t.Fatal(err) + } + s := New() + user := func(text string) json.RawMessage { + b, _ := json.Marshal(map[string]any{"role": "user", "content": []map[string]any{{"type": "text", "text": text}}}) + return b + } + result := func(msgs []json.RawMessage) json.RawMessage { + id := gjson.GetBytes(msgs[len(msgs)-1], `content.#(type=="tool_use").id`).String() + return json.RawMessage(`{"role":"user","content":[{"type":"tool_result","tool_use_id":"` + id + `","content":"package f"}]}`) + } + // a few turns on DeepSeek, each a tool call and its answer + var msgs []json.RawMessage + for i := 0; i < 3; i++ { + var code int + var said string + msgs = append(msgs, user(fmt.Sprintf("read the next file, %d", i))) + if msgs, code, said = switchTurn(t, s, stream, msgs); code != 200 { + t.Fatalf("DeepSeek turn %d: %d %s", i, code, said) + } + msgs = append(msgs, result(msgs)) + if msgs, code, said = switchTurn(t, s, stream, msgs); code != 200 { + t.Fatalf("DeepSeek turn %d's result: %d %s", i, code, said) + } + } + if len(cl.bodies) != 0 { + t.Fatalf("Claude asked %d times while DeepSeek answered", len(cl.bodies)) + } + // DeepSeek unticked: the next turn goes to Claude + g.Off = []string{"deepseek/deepseek-v4-pro"} + if err := provider.SaveGroup(g); err != nil { + t.Fatal(err) + } + for i := 0; i < 3; i++ { + var code int + var said string + msgs = append(msgs, user(fmt.Sprintf("now on Claude, %d", i))) + if msgs, code, said = switchTurn(t, s, stream, msgs); code != 200 { + t.Fatalf("Claude turn %d: %d %s", i, code, said) + } + } + // Claude was never sent a block it didn't sign, so never refused one, + // and was sent its own blocks as it signed them + if cl.refused != 0 { + t.Errorf("Claude refused %d of its %d requests: %s", cl.refused, len(cl.bodies), cl.bodies[0]) + } + last := cl.bodies[len(cl.bodies)-1] + if strings.Contains(last, "49e144b6-") { + t.Errorf("DeepSeek's thinking went to Claude: %s", last) + } + for _, m := range msgs[:len(msgs)-1] { // the last is its answer + for _, b := range gjson.GetBytes(m, "content").Array() { + if b.Get("type").String() == "thinking" && strings.HasPrefix(b.Get("signature").String(), "EqQ") && !strings.Contains(last, b.Get("signature").Raw) { + t.Errorf("Claude's own block %s didn't go back to it", b.Raw) + } + } + } + // DeepSeek ticked again, Claude unticked: DeepSeek is sent every + // thinking block of the conversation, its own and Claude's + g.Off = []string{"claude-api/claude-opus-5-5"} + if err := provider.SaveGroup(g); err != nil { + t.Fatal(err) + } + asked := len(ds.bodies) + msgs = append(msgs, user("back on DeepSeek")) + if _, code, said := switchTurn(t, s, stream, msgs); code != 200 { + t.Fatalf("DeepSeek again: %d %s", code, said) + } + if len(ds.bodies) != asked+1 { + t.Fatalf("DeepSeek asked %d times, want 1", len(ds.bodies)-asked) + } + sent := ds.bodies[asked] + for _, m := range msgs { + for _, b := range gjson.GetBytes(m, "content").Array() { + if b.Get("type").String() == "thinking" && !strings.Contains(sent, b.Get("signature").Raw) { + t.Errorf("DeepSeek wasn't sent %s", b.Raw) + } + } + } +} + +// 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 +// DeepSeek's endpoint and another vendor's get it byte for byte. +func TestWithoutForeignThinking(t *testing.T) { + fresh(t) + for _, p := range []provider.Provider{ + {ID: "claude-api", Name: "Claude API", Key: "k", Anthropic: "https://relay.example/anthropic", Models: []string{"claude-opus-5-5"}}, + {ID: "deepseek", Name: "DeepSeek", Key: "k", Anthropic: "https://api.deepseek.com/anthropic", Models: []string{"deepseek-v4-pro"}}, + {ID: "kimi", Name: "Kimi", Key: "k", Anthropic: "https://api.moonshot.ai/anthropic", Models: []string{"kimi-k2.6"}}, + } { + if err := provider.Save(p); err != nil { + t.Fatal(err) + } + } + find := func(id string) provider.Provider { + p, err := provider.Find(id) + if err != nil { + t.Fatal(err) + } + return *p + } + conv := func(model string) []byte { + return []byte(`{"model":"` + model + `","messages":[{"role":"user","content":"hi"},` + + `{"role":"assistant","content":[{"type":"thinking","thinking":"a","signature":"49e144b6-799a-40e9-af71-4992a62c8076"},{"type":"text","text":"Hi"}]},` + + `{"role":"user","content":"go"},` + + `{"role":"assistant","content":[{"type":"thinking","thinking":"b","signature":"CAQS8gcKEAgTGAI4AUqAAQ=="},{"type":"thinking","thinking":"c","signature":""},{"type":"redacted_thinking","data":"EmwKAhgB"},{"type":"text","text":"Ok"}]},` + + `{"role":"user","content":"more"}]}`) + } + got := withoutForeignThinking(find("claude-api"), conv("claude-opus-5-5")) + 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) + } + 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)) { + t.Errorf("%s's body changed: %s", c.id, got) + } + } + // nothing of DeepSeek's: byte for byte + body := []byte(`{"model":"claude-opus-5-5","messages":[{"role":"assistant","content":[{"type":"thinking","thinking":"b","signature":"CAQS8gcKEAgTGAI4AUqAAQ=="}]}]}`) + if got := withoutForeignThinking(find("claude-api"), body); string(got) != string(body) { + t.Errorf("changed with nothing to leave out: %s", got) + } +} + +// The same through Codex's Responses API: DeepSeek's thinking comes back +// to Codex as reasoning, and with DeepSeek unticked goes to Claude as a +// thinking block with DeepSeek's signature, which Claude is no longer +// sent. +func TestDeepSeekThinkingThenClaudeResponses(t *testing.T) { + fresh(t) + ds, cl := &switchDeepSeek{}, &switchClaude{} + dsu, clu := httptest.NewServer(ds), httptest.NewServer(cl) + t.Cleanup(dsu.Close) + t.Cleanup(clu.Close) + for _, p := range []provider.Provider{ + {ID: "deepseek", Name: "DeepSeek", Key: "sk-ds", Anthropic: dsu.URL + "/anthropic", Models: []string{"deepseek-v4-pro"}}, + {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: "DC", Members: []string{"deepseek/deepseek-v4-pro", "claude-api/claude-opus-5-5"}} + if err := provider.SaveGroup(g); err != nil { + t.Fatal(err) + } + s := New() + var input []json.RawMessage + turn := func(what string) { + t.Helper() + in, _ := json.Marshal(input) + body := `{"model":"group/dc","stream":false,"reasoning":{"effort":"xhigh","summary":"auto"},"include":["reasoning.encrypted_content"],"store":false,` + + `"tools":[{"type":"function","name":"Read","description":"Read a file","parameters":{"type":"object","properties":{"file_path":{"type":"string"}}}}],"input":` + string(in) + `}` + rec := httptest.NewRecorder() + req := httptest.NewRequest("POST", "/v1/responses", strings.NewReader(body)) + s.Handler().ServeHTTP(rec, req) + if rec.Code != 200 { + t.Fatalf("%s: %d %s", what, rec.Code, rec.Body.String()) + } + for _, o := range gjson.Get(rec.Body.String(), "output").Array() { + input = append(input, json.RawMessage(o.Raw)) + if o.Get("type").String() == "function_call" { + input = append(input, json.RawMessage(`{"type":"function_call_output","call_id":"`+o.Get("call_id").String()+`","output":"package f"}`)) + } + } + } + user := func(text string) json.RawMessage { + b, _ := json.Marshal(map[string]any{"type": "message", "role": "user", "content": []map[string]any{{"type": "input_text", "text": text}}}) + return b + } + for i := 0; i < 2; i++ { + input = append(input, user(fmt.Sprintf("read the next file, %d", i))) + turn("DeepSeek's call") + turn("DeepSeek's answer") + } + if !strings.Contains(string(mustJSON(input)), "encrypted_content") { + t.Fatalf("no reasoning came back to Codex: %s", mustJSON(input)) + } + g.Off = []string{"deepseek/deepseek-v4-pro"} + if err := provider.SaveGroup(g); err != nil { + t.Fatal(err) + } + for i := 0; i < 2; i++ { + input = append(input, user(fmt.Sprintf("now on Claude, %d", i))) + turn("Claude") + } + if cl.refused != 0 { + t.Errorf("Claude refused %d of its %d requests: %s", cl.refused, len(cl.bodies), cl.bodies[0]) + } + if last := cl.bodies[len(cl.bodies)-1]; !strings.Contains(last, "EqQBCkgIBxABGAIiQL1") { + t.Errorf("Claude's own thinking didn't go back to it: %s", last) + } +}