diff --git a/docs/subsystems/gateway-routing.md b/docs/subsystems/gateway-routing.md index f6a9613d6..eb85d502a 100644 --- a/docs/subsystems/gateway-routing.md +++ b/docs/subsystems/gateway-routing.md @@ -237,6 +237,7 @@ recorded as a prediction failure (`noPrediction`). - Codex's model list from the backend path (`codexModels`) is the ChatGPT backend's for its sign-in and then magpie's (`provider.CodexListed`), its ETag and every reply's `X-Models-Etag` tagged with `provider.CodexListTag` so a change has Codex ask again. A Codex there only for account failover, not connected (`CodexOwnOnly`, `agent.CodexOwnOnly`; #1385), gets the backend's alone, tagged with `provider.CodexOwnListTag`; neither tag contains the other, so connecting or disconnecting has Codex fetch the list again. The user's picks on the codex provider (`provider.CodexNativePicked`) narrow the backend's listed models. They keep its hidden ones (`visibility: "hide"`), which no picker shows. One of those is `codex-auto-review`: when the list lacks it and no reviewer is set, Codex's auto-review runs on the conversation's model at low effort (#1460, `TestCodexModelListPicksKeepHidden`). The account's own models stay in it when they are kept out of other agents' lists for routing groups, by the codex provider "Only through routing groups" (`Provider.Unlisted`) or a group that unlists its members (`Group.Unlists`): Codex's own catalog (`catalogOf("codex")`, behind `ListedFor`/`CatalogFor`) keeps `CodexOwn` entries, so the Agents page shows its Codex section, its picker offers them as magpie's, and the desk file and `spawnChoices` list them. #1602 dropped them here, and the picker then still offered them through the own-models switch while the Codex app had none (士奇 on Discord, 10-28). They are hidden from Codex through Codex's list (`provider.CodexNativeHidden`, `TestCodexModelListKeepsOwnForGroups`, `TestCodexOwnModelsListedOnlyThroughGroups`). A backend answer that says the sign-in itself is revoked (`provider.SignInRevoked`, a 401 `token_revoked`; jjt on Discord, #4308) isn't passed through: the list is Codex's cached one (`codexcat.CacheEntries`) and magpie's, so the picker keeps magpie's models; any other refusal, a 401 `token_expired` among them, still is. The desk file does the same while the live list says revoked (`provider.CodexListRevoked`, `codexDesk.revoked`) (`TestCodexModelListRevokedSignIn`, `TestCodexDesktopCatalogRevokedSignIn`). - The Codex app and its VS Code extension read only the first 100 of that list by priority, hidden entries counted: each asks its app-server for `model/list` with `limit: 100` and never for the next page (ChatGPT.app 26.1013, openai.chatgpt 26.51021; the CLI's `/model` lists every one). So `codexcat.FitOwn` ranks the list last of all: hidden entries after every listed one, and, with more than 100 listed (`codexcat.AppList`), Codex's own listed models (the backend's entries in `codexMerged`; a ChatGPT account's `codex/…` ones, `codexcat.ChatGPTOwn`, on the other two routes) and then the models Codex used in the last 30 days (`usage.CodexUsed`, most recent first, at most 100) brought into the first 100 in the order they stood, the rest kept in theirs. The user's own order (`codexcat.Order`, #855) goes first, so an order that names only magpie's models (set while Codex's list had no Codex section, or before OpenAI added a model) no longer puts every GPT model past the 100th (maiya on Discord); the user takes one out of the app by hiding it in Codex's list. The same holds for `/v1/codex/models` (with the models that key's Codex used alone, `usage.CodexUsedBy`, before the 1 MiB cut) and the `model_catalog_json` magpie writes (`codexcat.CatalogUsed`). `codexListTag` carries a tag of the used set (`codexcat.UsedTag`), so the ETag and `X-Models-Etag` change when Codex uses a model it hadn't; `usage.CodexUsed` is read again a minute on, or at once when `Append` writes a Codex call to a model it doesn't hold (`codexUsedNew`). `TestCodexModelListKeepsUsedModelsInTheAppsHundred`, `TestCodexCatalogKeepsTheKeysUsedModelsFirst`, `TestFitKeepsUsedModelsWhereTheCodexAppReads`, `TestCodexUsed`, `TestCodexModelListKeepsOwnModelsInTheAppsHundred`, `TestFitOwnKeepsCodexsOwnInTheAppsHundred` and `TestCatalogUsedKeepsChatGPTOwn` cover it (@ZhenLuoTTAWDTT on X). - 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. +- 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`. - 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; 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). 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). 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 reasoning item with its text in it (`content` parts: DeepSeek's Responses API writes `reasoning_text`, relayed to Codex as it came) is another vendor's. OpenAI's API and the ChatGPT backend take a reasoning item's `content` only empty, and refuse the whole request over one with 400 "Invalid 'input[n].content': array too long. Expected an array with maximum length 0" (`array_above_max_length`). Codex hands the item back on every later turn, so it never goes to them: for one of Codex's own models, `codexInput(body, false)` leaves it out (and a reasoning item with nothing sealed in it) on `/backend-api/codex`'s `/responses` and on `/responses/compact`, before Codex's own sign-in, its API key or a magpie Codex account (`compactOn`) is asked. Codex compacts a thread before its first turn back on its own model, and a refused compaction shows as that turn's error (jue on Discord). `passthrough` leaves it out for OpenAI, Azure OpenAI and a Codex account (`withoutReasoningText`), and for any other upstream once it has refused one (`refusesReasoningText`, `reasoningTextRefused`, #1411). OpenAI's own sealed reasoning (`encrypted_content`, no text) stays, and a DeepSeek model (`replaysReasoning`) still gets the text. `TestForeignReasoningNeverReachesOpenAI`, `TestReasoningTextLeftOutWhereRefused`, `TestReasoningTextNotSentToCodexAccount`. diff --git a/internal/gateway/gateway.go b/internal/gateway/gateway.go index 4b99899b5..5c6e515e6 100644 --- a/internal/gateway/gateway.go +++ b/internal/gateway/gateway.go @@ -423,8 +423,11 @@ type Server struct { calls uint64 // the last Call.ID given // unfit remembers the endpoints each provider's models were turned away // from, so every later turn goes straight to one that takes them. - unfit map[string]bool - subscription *subscriptionBridge + unfit map[string]bool + // refusedThinking is the thinking blocks each provider and account + // refused as signed for another conversation (thinking_bound.go) + refusedThinking map[string]bool + subscription *subscriptionBridge // imageStore is the image MCP server's jobs and images (image_mcp.go) imageStore imageMCPStore debug bool @@ -4379,7 +4382,8 @@ func (s *Server) forward(ctx context.Context, p provider.Provider, to provider.P } // and what of Claude Code's newest asks it turns away (thinking.display // "updates", a turn's output_config in messages: anthropic_shapes.go), - // each learned once + // each learned once, and the thinking blocks Claude says were signed + // for another conversation or account (thinking_bound.go) for range 3 { if err != nil || to != provider.Anthropic || res.StatusCode != http.StatusBadRequest && res.StatusCode != http.StatusUnprocessableEntity { return res, err @@ -4387,8 +4391,10 @@ func (s *Server) forward(ctx context.Context, p provider.Provider, to provider.P b, _ := io.ReadAll(io.LimitReader(res.Body, 1<<20)) res.Body.Close() res.Body = io.NopCloser(bytes.NewReader(b)) + sent := s.withoutRefusedShapes(p, body) betas := len(s.refuseBetas(p, b)) > 0 - if shapes := s.refuseShapes(p, b, body); !betas && !shapes { + shapes := s.refuseShapes(p, b, body) + if bound := s.refuseBoundThinking(p, b, sent); !betas && !shapes && !bound { return res, nil } res, err = s.forwardOnce(ctx, p, to, path, body, in) @@ -4437,6 +4443,9 @@ func (s *Server) forwardOnce(ctx context.Context, p provider.Provider, to provid body = adaptiveThinking(body) } body = s.withoutRefusedShapes(p, body) + // the thinking blocks it refused as another conversation's + // (thinking_bound.go), every route to it alike + body = s.withoutRefusedThinking(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 new file mode 100644 index 000000000..0589749b3 --- /dev/null +++ b/internal/gateway/thinking_bound.go @@ -0,0 +1,213 @@ +package gateway + +import ( + "bytes" + "crypto/sha256" + "encoding/hex" + "encoding/json" + "regexp" + "strconv" + + "github.com/tidwall/gjson" + + "github.com/yetone/magpie/internal/provider" +) + +// Claude's thinking block is signed for the conversation it was made in +// and the account that made it. A block an upstream doesn't take as its +// own is refused with the whole request (ferock on Discord, Command Code's +// plugin): 400 "messages.3.content.20: Invalid signature in thinking +// block. The block is bound to a different conversation. Remove the +// block, or set thinking.block_binding.prefix_mismatch_behavior to +// "drop_block"" (that setting needs a beta magpie doesn't send for an +// agent). Such a block comes from a conversation that moved between +// accounts or providers (a routing group's fallback, an account switch, +// a relay that serves Claude from more than one account of its own) or +// whose earlier turns changed since. +// +// forward does what the refusal asks: it leaves out the block it names +// and every thinking block after it (their signatures cover the turns +// before them, the left-out block among them), asks once more, and +// remembers those signatures for that provider and account +// (thinkingRefused), so the conversation's later turns go without them +// the first time and stay the conversation the model has gone on in. +// Other blocks, and every request to another provider or account, go as +// the agent wrote them. Only Claude's refusal text starts it, so no other +// vendor's request changes. + +// boundRefusal is Claude's refusal of a thinking block it didn't sign for +// this conversation or account: the signature's wording, the newer +// binding's, and a redacted_thinking block's. +var boundRefusal = regexp.MustCompile("(?i)invalid `?signature`? in `?thinking`? block|bound to a different conversation|not created in this conversation|invalid data in `?redacted_thinking`? block") + +// boundAt is where the refusal says the block is: messages..content.. +var boundAt = regexp.MustCompile(`messages\.(\d+)\.content\.(\d+)`) + +// thinkingRefusedMost bounds the signatures remembered; past it the +// memory starts again, and a conversation still going is mended by one +// more refusal. +const thinkingRefusedMost = 1 << 14 + +// thinkingOwner is who a refusal is remembered for: the provider, and the +// account signed in to it. +func thinkingOwner(p provider.Provider) string { + if p.Account != nil { + return p.ID + "\x00" + p.Account.User + } + return p.ID +} + +// thinkingKey names a thinking or redacted_thinking block by its +// signature (a redacted block's data), or its text where it has neither. +func thinkingKey(b gjson.Result) string { + k := b.Get("signature").String() + if k == "" { + k = b.Get("data").String() + } + if k == "" { + k = b.Get("thinking").String() + } + h := sha256.Sum256([]byte(b.Get("type").String() + "\x00" + k)) + return hex.EncodeToString(h[:16]) +} + +func isThinkingBlock(b gjson.Result) bool { + t := b.Get("type").String() + return t == "thinking" || t == "redacted_thinking" +} + +// thinkingRefused tells whether p refused the block with key. +func (s *Server) thinkingRefused(owner, key string) bool { + s.mu.Lock() + defer s.mu.Unlock() + return s.refusedThinking[owner+"\x00"+key] +} + +func (s *Server) refuseThinking(owner string, keys []string) { + s.mu.Lock() + defer s.mu.Unlock() + if s.refusedThinking == nil || len(s.refusedThinking)+len(keys) > thinkingRefusedMost { + s.refusedThinking = make(map[string]bool) + } + for _, k := range keys { + s.refusedThinking[owner+"\x00"+k] = true + } +} + +// withoutRefusedThinking is a Messages body without the thinking blocks p +// refused before; an assistant message left with nothing goes too. A body +// with none of them goes byte for byte. +func (s *Server) withoutRefusedThinking(p provider.Provider, body []byte) []byte { + if !bytes.Contains(body, []byte(`thinking"`)) { + return body + } + owner := thinkingOwner(p) + s.mu.Lock() + none := len(s.refusedThinking) == 0 + s.mu.Unlock() + if none { + return body + } + return withoutThinkingBlocks(body, func(_, _ int, b gjson.Result) bool { + return s.thinkingRefused(owner, thinkingKey(b)) + }) +} + +// withoutThinkingBlocks leaves out of a Messages body each thinking or +// redacted_thinking block drop says to, at message m, block i, and an +// assistant message that had only those. +func withoutThinkingBlocks(body []byte, drop func(m, i int, b gjson.Result) bool) []byte { + var q map[string]json.RawMessage + var msgs []json.RawMessage + if decodeJSON(body, &q) != nil || decodeJSON(q["messages"], &msgs) != nil { + return body + } + out := make([]json.RawMessage, 0, len(msgs)) + changed := false + for mi, raw := range msgs { + content := gjson.GetBytes(raw, "content") + if !content.IsArray() { + out = append(out, raw) + continue + } + var kept []json.RawMessage + gone := false + for bi, b := range content.Array() { + if isThinkingBlock(b) && drop(mi, bi, b) { + gone = true + continue + } + kept = append(kept, json.RawMessage(b.Raw)) + } + if !gone { + out = append(out, raw) + continue + } + changed = true + if len(kept) == 0 { + continue + } + var m map[string]json.RawMessage + if decodeJSON(raw, &m) != nil { + out = append(out, raw) + continue + } + m["content"], _ = json.Marshal(kept) + nb, err := json.Marshal(m) + if err != nil { + return body + } + out = append(out, nb) + } + if !changed { + return body + } + q["messages"], _ = json.Marshal(out) + b, err := json.Marshal(q) + if err != nil { + return body + } + return b +} + +// refuseBoundThinking reads a 400 from an Anthropic upstream: when it is +// Claude refusing a thinking block's signature, the block it names and +// every thinking block after it in body (as forwardOnce sends it, without +// those refused before) are remembered as refused by p. fresh is whether +// any was new, so asking again can go otherwise. +func (s *Server) refuseBoundThinking(p provider.Provider, errBody, body []byte) (fresh bool) { + if !boundRefusal.Match(errBody) { + return false + } + sent := 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 + fromM, fromB := 0, 0 + if at := boundAt.FindSubmatch(errBody); at != nil { + m, _ := strconv.Atoi(string(at[1])) + b, _ := strconv.Atoi(string(at[2])) + if m < len(msgs) { + if blocks := msgs[m].Get("content").Array(); b < len(blocks) && isThinkingBlock(blocks[b]) { + fromM, fromB = m, b + } + } + } + owner := thinkingOwner(p) + var keys []string + for mi := fromM; mi < len(msgs); mi++ { + for bi, b := range msgs[mi].Get("content").Array() { + if mi == fromM && bi < fromB || !isThinkingBlock(b) { + continue + } + if k := thinkingKey(b); !s.thinkingRefused(owner, k) { + keys = append(keys, k) + } + } + } + if len(keys) == 0 { + return false + } + s.refuseThinking(owner, keys) + return true +} diff --git a/internal/gateway/thinking_bound_test.go b/internal/gateway/thinking_bound_test.go new file mode 100644 index 000000000..f390e0b4d --- /dev/null +++ b/internal/gateway/thinking_bound_test.go @@ -0,0 +1,244 @@ +package gateway + +import ( + "encoding/json" + "fmt" + "io" + "net/http" + "net/http/httptest" + "slices" + "strings" + "sync" + "testing" + + "github.com/tidwall/gjson" + + "github.com/yetone/magpie/internal/provider" +) + +// ferock's refusal, as Command Code's plugin passed it on (Discord, +// 2026-10-30), up to where the report was cut. +const boundRefusalText = `messages.3.content.20: Invalid signature in thinking block. The block is bound to a different conversation. Remove the block, or set thinking.block_binding.prefix_mismatch_behavior to "drop_block". That setting requires the thinking-binding-controls-2026-08-01 value in the anthropic-beta header. The system` + +// boundClaude answers as Claude does a conversation it signed only part +// of: the first thinking block whose signature is in foreign is refused, +// named where it is, in Anthropic's error body (magpie's reply puts the +// provider's name before it: "Command Code: {...}"); any other request is +// answered. said is what Claude refuses with (%d %d: message, block). +type boundClaude struct { + mu sync.Mutex + bodies []string + foreign []string + said string + // stream: the reply is Anthropic's stream, as a plugin's account wants + stream bool +} + +func (c *boundClaude) ServeHTTP(w http.ResponseWriter, r *http.Request) { + b, _ := io.ReadAll(r.Body) + c.mu.Lock() + c.bodies = append(c.bodies, string(b)) + c.mu.Unlock() + 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" && slices.Contains(c.foreign, blk.Get("signature").String()) { + w.WriteHeader(400) + msg := fmt.Sprintf(c.said, mi, bi) + e, _ := json.Marshal(map[string]any{"type": "error", "error": map[string]any{"type": "invalid_request_error", "message": msg}}) + w.Write(e) + return + } + } + } + if c.stream { + w.Header().Set("Content-Type", "text/event-stream") + io.WriteString(w, sse( + `event: message_start`+"\n"+`data: {"type":"message_start","message":{"id":"msg_1","type":"message","role":"assistant","model":"claude-opus-5-5","content":[],"stop_reason":null,"usage":{"input_tokens":1,"output_tokens":0}}}`, + `event: content_block_start`+"\n"+`data: {"type":"content_block_start","index":0,"content_block":{"type":"text","text":""}}`, + `event: content_block_delta`+"\n"+`data: {"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"ok"}}`, + `event: content_block_stop`+"\n"+`data: {"type":"content_block_stop","index":0}`, + `event: message_delta`+"\n"+`data: {"type":"message_delta","delta":{"stop_reason":"end_turn"},"usage":{"output_tokens":1}}`, + `event: message_stop`+"\n"+`data: {"type":"message_stop"}`)) + return + } + io.WriteString(w, `{"id":"msg_1","type":"message","role":"assistant","model":"claude-opus-5-5","content":[{"type":"text","text":"ok"}],"stop_reason":"end_turn","usage":{"input_tokens":1,"output_tokens":1}}`) +} + +func (c *boundClaude) sent() []string { + c.mu.Lock() + defer c.mu.Unlock() + return slices.Clone(c.bodies) +} + +// boundConversation is a Claude Code conversation whose message 3 has +// the refused block at 20, as ferock's had: thinking signed ok- before +// it, other-20 there, and a later turn's thinking after it. +func boundConversation(model string) string { + var blocks []string + for i := 0; i < 20; i += 2 { + blocks = append(blocks, + fmt.Sprintf(`{"type":"thinking","thinking":"step %d","signature":"ok-%d"}`, i, i), + fmt.Sprintf(`{"type":"text","text":"note %d"}`, i+1)) + } + blocks = append(blocks, + `{"type":"thinking","thinking":"from elsewhere","signature":"other-20"}`, + `{"type":"tool_use","id":"t1","name":"Read","input":{"file_path":"a.go"}}`) + return `{"model":"` + model + `","max_tokens":4096,"thinking":{"type":"adaptive"},"messages":[` + + `{"role":"user","content":[{"type":"text","text":"hi"}]},` + + `{"role":"assistant","content":[{"type":"thinking","thinking":"first","signature":"ok-a"},{"type":"text","text":"hello"}]},` + + `{"role":"user","content":[{"type":"text","text":"read a.go"}]},` + + `{"role":"assistant","content":[` + strings.Join(blocks, ",") + `]},` + + `{"role":"user","content":[{"type":"tool_result","tool_use_id":"t1","content":"package a"}]},` + + `{"role":"assistant","content":[{"type":"thinking","thinking":"later","signature":"later-5"},{"type":"tool_use","id":"t2","name":"Read","input":{"file_path":"b.go"}}]},` + + `{"role":"user","content":[{"type":"tool_result","tool_use_id":"t2","content":"package b"}]}]}` +} + +// signatures lists a body's thinking signatures, in order. +func signatures(body string) []string { + var out []string + for _, m := range gjson.Get(body, "messages").Array() { + for _, b := range m.Get("content").Array() { + if b.Get("type").String() == "thinking" { + out = append(out, b.Get("signature").String()) + } + } + } + return out +} + +func TestBoundRefusalRead(t *testing.T) { + if !boundRefusal.MatchString(boundRefusalText) { + t.Error("ferock's refusal isn't read as a bound thinking block") + } + for _, s := range []string{ + "messages.1.content.0: Invalid `signature` in `thinking` block", + "messages.1.content.0: thinking block was not created in this conversation", + "messages.1.content.0: Invalid data in redacted_thinking block", + } { + if !boundRefusal.MatchString(s) { + t.Errorf("%q not read as a bound thinking block", s) + } + } + for _, s := range []string{ + // DeepSeek's (#1611) and a plain bad request: nothing to leave out + "The `content[].thinking` in the thinking mode must be passed back to the API", + "messages.1.content.0: Expected `thinking` or `redacted_thinking`, but found `tool_use`", + "prompt is too long", + } { + if boundRefusal.MatchString(s) { + t.Errorf("%q read as a bound thinking block", s) + } + } + if m := boundAt.FindStringSubmatch(boundRefusalText); m == nil || m[1] != "3" || m[2] != "20" { + t.Errorf("boundAt = %v, want message 3 block 20", m) + } +} + +// ferock on Discord: Claude refused message 3's block 20 as bound to +// another conversation. magpie asks again without it and without the +// thinking after it, keeps the blocks before it, and sends the next turn +// so the first time. +func TestBoundThinkingLeftOut(t *testing.T) { + fresh(t) + up := &boundClaude{foreign: []string{"other-20"}, said: "messages.%d.content.%d: Invalid signature in thinking block. The block is bound to a different conversation. Remove the block, or set thinking.block_binding.prefix_mismatch_behavior to \"drop_block\"."} + srv := httptest.NewServer(up) + t.Cleanup(srv.Close) + other := &boundClaude{} + srv2 := httptest.NewServer(other) + t.Cleanup(srv2.Close) + for _, p := range []provider.Provider{ + {ID: "relay", Name: "Relay", Key: "k", Anthropic: srv.URL, Models: []string{"claude-opus-5-5"}}, + {ID: "relay2", Name: "Relay Two", Key: "k", Anthropic: srv2.URL, Models: []string{"claude-opus-5-5"}}, + } { + if err := provider.Save(p); err != nil { + t.Fatal(err) + } + } + s := New() + postProto(t, s, "/v1/messages", boundConversation("relay/claude-opus-5-5")) + sent := up.sent() + if len(sent) != 2 { + t.Fatalf("asked %d times, want once more after the refusal", len(sent)) + } + before := []string{"ok-a", "ok-0", "ok-2", "ok-4", "ok-6", "ok-8", "ok-10", "ok-12", "ok-14", "ok-16", "ok-18"} + if got := signatures(sent[1]); !slices.Equal(got, before) { + t.Errorf("asked again with %v, want the blocks before the refused one: %v", got, before) + } + // the rest of the conversation is as the agent wrote it + if n := len(gjson.Get(sent[1], "messages").Array()); n != 7 { + t.Errorf("%d messages, want 7", n) + } + if c := gjson.Get(sent[1], "messages.3.content"); len(c.Array()) != 21 || c.Get("20.type").String() != "tool_use" { + t.Errorf("message 3 = %s, want its blocks but the refused one", c.Raw) + } + if c := gjson.Get(sent[1], "messages.5.content"); len(c.Array()) != 1 || c.Get("0.id").String() != "t2" { + t.Errorf("message 5 = %s, want its tool call alone", c.Raw) + } + + // the next turn: the provider gets it without them, at once + postProto(t, s, "/v1/messages", boundConversation("relay/claude-opus-5-5")) + if sent = up.sent(); len(sent) != 3 { + t.Fatalf("asked %d times more, want once", len(sent)-2) + } + if got := signatures(sent[2]); !slices.Equal(got, before) { + t.Errorf("next turn sent %v, want %v", got, before) + } + + // another provider never refused them: it gets every block + postProto(t, s, "/v1/messages", boundConversation("relay2/claude-opus-5-5")) + if got := other.sent(); len(got) != 1 || len(signatures(got[0])) != 13 { + t.Errorf("another provider sent %d requests, signatures %v, want all 13 once", len(got), signatures(got[len(got)-1])) + } +} + +// A refusal over something else, DeepSeek's wanting its thinking back +// among them, is passed on as it came: one request, every block kept. +func TestOtherRefusalKeepsThinking(t *testing.T) { + fresh(t) + up := &boundClaude{foreign: []string{"other-20"}, said: "messages.%d.content.%d: The `content[].thinking` in the thinking mode must be passed back to the API"} + srv := httptest.NewServer(up) + t.Cleanup(srv.Close) + if err := provider.Save(provider.Provider{ID: "ds", Name: "DS", Key: "k", Anthropic: srv.URL, Models: []string{"claude-opus-5-5"}}); err != nil { + t.Fatal(err) + } + rec := httptest.NewRecorder() + req := httptest.NewRequest("POST", "/v1/messages", strings.NewReader(boundConversation("ds/claude-opus-5-5"))) + req.Header.Set("anthropic-version", "2023-06-01") + New().Handler().ServeHTTP(rec, req) + if rec.Code == 200 { + t.Fatalf("status 200, want the refusal") + } + if sent := up.sent(); len(sent) != 1 || len(signatures(sent[0])) != 13 { + t.Errorf("asked %d times, want once with every block", len(sent)) + } +} + +// withoutThinkingBlocks leaves a message that had only thinking out, and +// a body with nothing to leave out byte for byte. +func TestWithoutThinkingBlocks(t *testing.T) { + body := []byte(`{"model":"m","messages":[{"role":"user","content":"hi"},{"role":"assistant","content":[{"type":"redacted_thinking","data":"x"}]},{"role":"user","content":"go"}]}`) + got := withoutThinkingBlocks(body, func(int, int, gjson.Result) bool { return true }) + if r := gjson.GetBytes(got, "messages.#.role").Raw; r != `["user","user"]` { + t.Errorf("roles %s, want the empty assistant message gone", r) + } + if got := withoutThinkingBlocks(body, func(int, int, gjson.Result) bool { return false }); string(got) != string(body) { + t.Errorf("changed with nothing to leave out: %s", got) + } +} + +// The same through a plugin's fetch, as Command Code's plugin serves +// Claude: the refusal it passes on is read, and the plugin is asked again +// without the block. +func TestPluginBoundThinkingLeftOut(t *testing.T) { + up := &boundClaude{foreign: []string{"other-20"}, stream: true, said: "messages.%d.content.%d: Invalid signature in thinking block. The block is bound to a different conversation."} + pid := besideFake(t, "commandcode", up) + postProto(t, New(), "/v1/messages", boundConversation(pid+"/fake-claude")) + sent := up.sent() + if len(sent) != 2 { + t.Fatalf("plugin asked %d times, want once more after the refusal", len(sent)) + } + if got := signatures(sent[1]); len(got) != 11 || slices.Contains(got, "other-20") || slices.Contains(got, "later-5") { + t.Errorf("asked again with %v, want the 11 blocks before the refused one", got) + } +}