diff --git a/docs/subsystems/gateway-routing.md b/docs/subsystems/gateway-routing.md
index eeaf1b554..0154145e8 100644
--- a/docs/subsystems/gateway-routing.md
+++ b/docs/subsystems/gateway-routing.md
@@ -43,7 +43,7 @@ backfilled; see [Gateway Session Aggregation](gateway-sessions.md).
| One try | `attempt` sends one candidate the request. It goes through the proxy of the account or key it uses, else the provider's (`p.Via`, `ProxyChoice`: `AccountProxies` holds an account's by its name, a key's by its `KeyID`). A request magpie makes for one provider while serving another's (a web search, an image description, a classifier call) takes its own provider's proxy or the global one, never the outer one: `netproxy.With` replaces a choice the context already names, "" too, and `webSearch` starts from none, so the search APIs follow the global proxy (#1522). A provider of the user's set not to check its certificate (`InsecureTLS`, #2383) has it skipped for its own base URLs' hosts alone, through `p.Via` ([Providers and accounts](providers-accounts.md)). Every request to one vendor's host shares one HTTP/2 connection (`upstreamTransport`); one with no frame for 20s is pinged, and dropped when no answer comes within 10s (`netproxy.HTTP2Health`, on `http.DefaultTransport` too), so a connection gone silent without closing (a proxy's way out died, a NAT forgot the flow) fails the requests on it, which move on as a 502 does, and the next request dials a new one. A live vendor answers a ping whatever its streams are doing, so a long wait for a first byte is not cut by it (#2843: a group's requests hung with no first byte until a restart; `TestGroupMovesOnFromSilentHTTP2Connection`). A large body (64KB or more, or of no stated length) is pinged too, as a silent connection takes a body that fits its send buffer, but its ping's answer is queued behind the body's own DATA, so on a slow uplink a working connection loses it (#3909: a ~680KB turn on a 2-10KB/s uplink failed every try). Such a body whose connection was dropped for a lost ping is sent once more, through `GetBody`, on a new connection that is not pinged and is given up on when a write moves no bytes for a minute (`uploadTransport`); for 30 minutes after, large bodies go there at once (`drawsApart.slow`; `TestUploadStillUnderwayIsNotCutByHealthPing`, `TestSlowUplinkSkipsTheLostTry`, `TestLargeBodyOnSilentConnectionIsSentAgain`). A subscription with its own client is served specially, such as Claude through the genuine Claude Code. The request is relayed as is (`passthrough`) when the model is usable on the agent's API, except that a Claude model where the provider has an Anthropic URL is translated to Messages from Chat or Responses too (`OnMessages`: OpenCode speaks Chat for every model, and a relay drops cache_control there), unless the user set the model's API or the vendor's list names its APIs. An account that only streams (`Account.Stream`: a plugin's, and most subscriptions magpie signs in to) has a request that asked for one body translated, which magpie always asks streamed, except a plugin's on Responses (`gathers`): that is relayed all the same, asked with `stream:true`, and the client given the `response` of the stream's `response.completed` (or `response.incomplete`) as one JSON body (`gathered` in [`gathered.go`](../../internal/gateway/gathered.go); its `output` filled from the stream's `response.output_item.done` items, or else its text, when that event's is empty). So the tools the vendor runs itself, and its response's `tools` and usage details, reach the client (plugins#112: a translation dropped Grok's `x_search`, and Grok answered without searching; `TestGrokPluginNonStreamKeepsHostedTools`). A stream that fails or ends before that event is a 502 (`TestGrokPluginNonStreamEndedShort`), never an empty 200. A Messages request is still translated, its stream having no event that holds the whole reply, and so is a subscription magpie signs in to itself (the ChatGPT backend's, Qoder's): its own code fits its requests. A request offering web search to a provider that doesn't search by itself is translated too, so magpie can search for it (`search.go`; a provider that searches for some of its models only, Command Code's Provider API, lists them in `searchModels` by API, and none count under its `x-cmd-zdr` header, #1590), but on the agent's own API where the provider serves it and no `ResponsesFirst`/`MessagesFirst` rule prefers another: Codex offers web_search on every turn, and each went out as Chat (#997). Otherwise it is translated (`translate`) to the first API `usable` gives: Chat, except Responses for OpenAI's models where their maker serves them (`ResponsesFirst`), Responses for every model at ModelScope, whose Chat API reports neither the tokens its cache answered nor reasoning while its Responses API reports both (`ResponsesTellsCache`, #1578; a 404 there sends the model to Chat, and only there), and Anthropic's Messages for a Claude model where the provider has an Anthropic URL (`MessagesFirst`, which keeps its cache breakpoints, #997). An API that answers the model is not served there (`wrongEndpoint`, `catalog.WrongEndpoint`: the English wordings and AgentRouter's Chinese one, #3766, read escaped too; a model's test reads them as well, see [Providers and accounts](providers-accounts.md)) is remembered in `unfit` until magpie restarts. A Chat API that refuses function tools with reasoning, with no other API to take them to, is asked once more with `reasoning_effort` `none` (#176), unless `none` is known refused (`turnedAway`); `none` refused naming the levels, the tools refusal is the answer, not a retry at the lowest level (#2670). When every API has turned the model away, the API the user picked for it (`ModelAPI`) is asked again, and without a pick each API the provider has a URL for (`Speaks`), Chat first. `Provider.Native`, the API agents with a per-model API (Pi, omp, droid) are wired to ask on, follows the same order. A custom provider with a Gemini URL (#1346) has Gemini last among the APIs it speaks: a Gemini client's request is relayed there, and any other is translated to it when it has no other, or when the user set Gemini as the model's API (`SetModelAPI` takes chat, responses, anthropic or gemini, each only where the provider has its URL, from the editor's Save or `magpie model api`; a model set to Gemini has no `Native`, so those agents ask it on their own API and it is translated). Upstream it is always asked `models/{model}:streamGenerateContent?alt=sse` under the base (`upstreamPath`), the model only in the path (`forwardOnce` drops the body's), so a Gemini client that asked for one JSON body is translated, as for Factory's generate route. It goes to the first API `usable` gives, Chat where the provider has a Chat URL too, except one that asks an image's size or shape (`generationConfig.imageConfig`), which only a Gemini API takes: that one is translated on the Gemini URL (#3820, `TestGeminiImageConfigGoesToTheGeminiAPIBesideChat`). | [`gateway.go`](../../internal/gateway/gateway.go) |
| Trace | The Routing view's record of each decision, written where the decision is made: candidates, rests, which try answered. `Route.Folder` is the folder the agent says it works in (`workDir`), its last two levels only (`shortFolder`, e.g. `workspace/magpie`), never the full path; a request that says none (a title, a topic check) takes its session's as said last (`trace.sessionFolder`), one without a session id has none (#1068). It is kept in the routing history on disk for as long as the route is (`history.go`: 30 days, 200 MB). The GUI shows it in By session's headings, a request row's tooltip, the stage's agent working in more than one folder, and the tray panel's agent tooltip. | [`trace.go`](../../internal/gateway/trace.go) A request outside the chat path gets a route of its own too ([`media_route.go`](../../internal/gateway/media_route.go), `sideRoute`): an image (`images`, each account `drawOnAccounts` asks a try), a video's start (`videosCreate`; its polls and download are the same video and add none) and an embedding, rerank, transcription or speech (`retrieve`). Each try's key or account is put in `Order` so the page finds its seat, the route's `Kind` stays empty, and the one usage row names it in `RouteID` (zzzkl3994 on Discord: a video the magpie-image MCP made was in Usage's requests and not on Routing; `TestVideoIsOnRoutingOnce`, `TestImageIsOnRouting`, `TestEmbeddingAndRerankAreOnRouting`). |
| Prompt | What each request's prompt held, part by part: the agent's system prompt, tool definitions (an MCP server's tools as one item), instruction files and skills, files its tools read, their other output, and the conversation. `inspectPrompt` reads it from the body as the agent sent it, before translation; `calibrated` scales the estimate to the prompt the vendor counted and sets the window of the model that answered. The route keeps names and sizes only, never the text, so the routing history on disk holds none. For the card's text (masaka on Discord), the trace keeps the last `promptBodies` (10) request bodies in memory only (at most 32 MiB each, 64 MiB together), masked as the vendor got them; for a model let have it unmasked, the body is kept as it went and masked when `PromptText` first reads it, so the request itself never waits on masking (#3973). `PromptText` reads a part's items and their text from that body again (`prompt_text.go`), served to the GUI as `/api/context/text`. Once a body is dropped, or magpie quits, the GUI reads the request archive's copy when the route names one (`Route.Archive`; wangbinyq on Discord): `ArchivedPromptText` parses it the same way and masks it as the body in memory is (`maskedCopy`), and the reply beside it comes from `ReplyBody` (the Recent calls' reply) or the archive's, read into pieces by `ReplyPieces` and masked alike (`prompt_reply.go`, served as `/api/context/reply`). A body or reply that can't be masked shows nothing, and one the archive cut short isn't parsed (`TestArchivedPromptTextIsMasked`, `TestReplyPiecesAreMasked`, `TestContextTextFromTheArchive`). It goes on the trace as `Route.Prompt`, with `Route.Conv` naming a conversation that has no session id. The GUI's `/api/context` scores each agent from it (`internal/gui/context.go`). A session's line and its compactions are its own turns': a call with a `Kind`, a Claude Code subagent's (`Route.Sub`, from `x-claude-code-agent-id`), and, in a session whose turns carry tool definitions, a request without any (auto mode's classifier, the title, the quota check) are left out, so a classifier's 40K after a 100K turn is no compaction (`toolSessions`, `TestContextSideCallsAreNoCompaction`). | [`prompt.go`](../../internal/gateway/prompt.go) |
-| Vertex AI | A [Google Vertex AI provider](providers-accounts.md#responsibilities-and-sources-of-truth) speaks Gemini for its Gemini models, chat completions for its partner models, and Anthropic's Messages API for Claude. Claude (`provider.VertexClaude`: `claude-opus-5-5`, `claude-sonnet-4-5@20250929`) is relayed or translated as at any Anthropic vendor, and `forwardOnce`, after every other change to the body, moves the request to where Anthropic's Vertex SDK sends it (`provider.VertexClaudeRequest`): `/publishers/anthropic/models/:streamRawPredict` when the body streams, `:rawPredict` when it doesn't, the model out of the body; count_tokens to `count-tokens:rawPredict` with the model kept (`countTokens` counts at a provider whose `Base(Anthropic)` is set); `anthropic_version` `vertex-2023-10-16` added unless the body has one; Claude Code's `?beta=true` never sent. `thinkingOffAsTaken` and `samplingAsTaken` run before, so they read the model from the body. Tool search's beta goes as `tool-search-tool-2025-10-19`, the name Claude Code gives it for Vertex as for Bedrock (`bedrockBetas`); Bedrock's left-out betas aren't left out for it. Gemini's effort rules (`vertexEffort`) don't touch it (`TestVertexClaudeModel`). A partner model (`provider.VertexPartner`: a `publisher/model` id such as `deepseek-ai/deepseek-v4.1-flash-maas`) goes to Google's OpenAI-compatible `/endpoints/openapi/chat/completions` (`Base(Chat)`, `ListedAPIs`), signed with the same token, its full id in the body. It is relayed or translated there as any chat completions vendor is, and none of the Gemini rules below (`vertexEffort`, `vertexThinking`, signatures) touch it (`TestVertexPartnerModel`). A Gemini model's request goes to `/publishers/google/models/:streamGenerateContent?alt=sse` (`provider.VertexPath`, `upstreamPath`), the model named as the user's upstream name for it says (`UpstreamNameIn`, which the usage log's endpoint names too), with no `model` or `stream` field in its body (`passthrough`, `forwardOnce`, `geminiRequest`). A Gemini client's request is relayed as it came, its own `thinkingConfig`, `safetySettings` and the rest kept: streamed there, asked whole to `:generateContent` (`provider.VertexWholePath`), which answers one JSON body (Factory's rule of translating a whole request, as its route only streams, isn't Vertex AI's). Every other API's is translated (`buildFor`, `buildVertex`) and its stream read by `codeAssistDecoder`, which gives thought parts as reasoning, never as the answer's text. Effort: `vertexEffort` fits it to the model's levels, reasoning turned off going as `minimal` fitted the same way, and holds a model whose levels aren't known to `low`…`high`. `vertexThinking` sends Gemini 3 a `thinkingLevel` (`includeThoughts` false with reasoning off) and 2.5 a `thinkingBudget` in the model's range (`vertexBudgets`): turned off, the budget that stops its thinking, or Pro's least, as Pro can't stop. Thought signatures are every Gemini path's (#1445): a call's signature reaches the client in its id (`signedID`) and goes back on the call it came on, while a call with none in a step Vertex AI signed goes without; a step with nothing to give back has every call sent `skip_thought_signature_validator`. A 400 `Invalid thought signature.` is asked again with every call sent so (`withoutSignatures`), for that request only. A 400 refusing `minimal` (`geminiRefusedLevel`) is asked again at the model's lowest other level (`onEffort`), and `markUnfit(offRefused)` keeps that level until magpie restarts. Both retries are the translated path's. Vertex AI's own Google Search grounding isn't used: `searchHosts` names only `generativelanguage.googleapis.com` for Gemini, so magpie searches for it (`search.go`). | [`vertex.go`](../../internal/gateway/vertex.go), [`gateway.go`](../../internal/gateway/gateway.go), [`codeassist.go`](../../internal/gateway/codeassist.go), [`gemini.go`](../../internal/gateway/gemini.go), [`gemini_signature.go`](../../internal/gateway/gemini_signature.go), [`search.go`](../../internal/gateway/search.go) |
+| Vertex AI | A [Google Vertex AI provider](providers-accounts.md#responsibilities-and-sources-of-truth) speaks Gemini for its Gemini models, chat completions for its partner models, and Anthropic's Messages API for Claude. Claude (`provider.VertexClaude`: `claude-opus-5-5`, `claude-sonnet-4-5@20250929`) is relayed or translated as at any Anthropic vendor, and `forwardOnce`, after every other change to the body, moves the request to where Anthropic's Vertex SDK sends it (`provider.VertexClaudeRequest`): `/publishers/anthropic/models/:streamRawPredict` when the body streams, `:rawPredict` when it doesn't, the model out of the body; count_tokens to `count-tokens:rawPredict` with the model kept (`countTokens` counts at a provider whose `Base(Anthropic)` is set); `anthropic_version` `vertex-2023-10-16` added unless the body has one; Claude Code's `?beta=true` never sent. `thinkingOffAsTaken` and `samplingAsTaken` run before, so they read the model from the body. Tool search's beta goes as `tool-search-tool-2025-10-19`, the name Claude Code gives it for Vertex as for Bedrock (`bedrockBetas`); Bedrock's left-out betas aren't left out for it. Gemini's effort rules (`vertexEffort`) don't touch it (`TestVertexClaudeModel`). A partner model (`provider.VertexPartner`: a `publisher/model` id such as `deepseek-ai/deepseek-v4.1-flash-maas`) goes to Google's OpenAI-compatible `/endpoints/openapi/chat/completions` (`Base(Chat)`, `ListedAPIs`), signed with the same token, its full id in the body. It is relayed or translated there as any chat completions vendor is, and none of the Gemini rules below (`vertexEffort`, `vertexThinking`, signatures) touch it (`TestVertexPartnerModel`). A Gemini model's request goes to `/publishers/google/models/:streamGenerateContent?alt=sse` (`provider.VertexPath`, `upstreamPath`), the model named as the user's upstream name for it says (`UpstreamNameIn`, which the usage log's endpoint names too), with no `model` or `stream` field in its body (`passthrough`, `forwardOnce`, `geminiRequest`). A Gemini client's request is relayed as it came, its own `thinkingConfig`, `safetySettings` and the rest kept: streamed there, asked whole to `:generateContent` (`provider.VertexWholePath`), which answers one JSON body (Factory's rule of translating a whole request, as its route only streams, isn't Vertex AI's). Every other API's is translated (`buildFor`, `buildVertex`) and its stream read by `codeAssistDecoder`, which gives thought parts as reasoning, never as the answer's text. Effort: `vertexEffort` fits it to the model's levels, reasoning turned off going as `minimal` fitted the same way, and holds a model whose levels aren't known to `low`…`high`. `vertexThinking` sends Gemini 3 a `thinkingLevel` (`includeThoughts` false with reasoning off) and 2.5 a `thinkingBudget` in the model's range (`vertexBudgets`): turned off, the budget that stops its thinking, or Pro's least, as Pro can't stop. Thought signatures are every Gemini path's (#1445): a call's signature reaches the client in its id (`signedID`) and goes back on the call it came on, while a call with none in a step Vertex AI signed goes without; a step with nothing to give back has every call sent `skip_thought_signature_validator`. A 400 `Invalid thought signature.` (or AI Studio's `Corrupted thought signature.`, `signatureRefused`) is asked again with every call sent so (`withoutSignatures`), for that request only, at any upstream Gemini's signatures reach (`signaturesReach`), relayed too; it rests no account and lets a group go on (`restAfterMarked`, `shapeRefused`). A 400 refusing `minimal` (`geminiRefusedLevel`) is asked again at the model's lowest other level (`onEffort`), and `markUnfit(offRefused)` keeps that level until magpie restarts; that retry is the translated path's. Vertex AI's own Google Search grounding isn't used: `searchHosts` names only `generativelanguage.googleapis.com` for Gemini, so magpie searches for it (`search.go`). | [`vertex.go`](../../internal/gateway/vertex.go), [`gateway.go`](../../internal/gateway/gateway.go), [`codeassist.go`](../../internal/gateway/codeassist.go), [`gemini.go`](../../internal/gateway/gemini.go), [`gemini_signature.go`](../../internal/gateway/gemini_signature.go), [`search.go`](../../internal/gateway/search.go) |
| Bedrock Mantle | A request on chat completions or Responses to an [Amazon Bedrock Mantle provider](providers-accounts.md#responsibilities-and-sources-of-truth) goes to the prefix that serves its model (`mantleRoutes`, `provider.MantleBase` in `forwardOnce`): `/openai/v1` for OpenAI's closed GPTs and xAI's Grok, `/v1` for the rest. A model Mantle refuses there with "model `x` isn't supported on this route" (a maker the rule doesn't know yet) is asked once more at the other prefix, and when it is taken there that prefix is remembered for the model in `unfit` (`mantleRouteKey`) until the gateway restarts. A model refused at both gets the first refusal and nothing is remembered (`mantleReroute`). Messages go to `/anthropic` alone. | [`mantle.go`](../../internal/gateway/mantle.go), [`gateway.go`](../../internal/gateway/gateway.go) |
## Codex titles, descriptions, summaries and predictions
@@ -259,7 +259,7 @@ recorded as a prediction failure (`noPrediction`).
- A Chat reply's call whose function names nothing in a JSON string — no name, null, another kind — is dropped, its later fragments with it, and a finish of `tool_calls` with no call left after the drop ends `stop` (a reply that came with no calls keeps its finish), and a whole reply given as a stream numbers the calls it keeps with no gap: streamed (`chatTidy`), whole (`chatWhole`) and a whole reply given to the agent as the stream it asked for (`chatWholeEvents`), since a client that checks the shape of every frame refuses the whole reply for one — the turn not retryable, the call already in the history, the session dead, while the gateway's own log says the reply went (AricRedemption, #1475). A nameless call runs nowhere, so it is no call, as a written block naming no offered tool is; a name the client reads as a string, empty included, goes as it came. `TestNamelessCallStreamDropped`, `TestNameAbsentStreamDropped`, `TestNamelessCallBesideAGoodOne`, `TestNamelessCallWholeDropped`, `TestNamelessCallWholeAsStreamDropped`, `TestNamelessCallWithoutAnIDStaysDropped`, `TestNamelessCallBesideAGoodOneWholeAsStream`, `TestToolCallsFinishWithNoCallsStaysWhole` in [`chat_call_name_test.go`](../../internal/gateway/chat_call_name_test.go).
- Codex's model list from the backend path (`codexModels`) is the ChatGPT backend's for its sign-in and then magpie's (`provider.CodexListedBeside`): every model but a ChatGPT account's own the sign-in's list has already, so a model only another account on in magpie has (a Team or Pro one beside a Free sign-in) is listed by magpie's id, `codex/`, and routed to that account (bigfisheatsmall on X: Codex kept signed in to a Free account, the Team account's models in dsh and not in Codex; `TestCodexListHasAnotherAccountsModels`, `TestCodexListOneAccountNoneTwice`). 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`). Every other agent, and every client of `/v1/models` (one that names no agent is `other` or its User-Agent's name, never `""`), is given `Catalog()`: a group listing alone keeps a signed-in subscription's models out of its list too. 88e6fb9cf had kept them for every agent (`SubscriptionKept`), so for a group of subscription models the option changed no list fetched over HTTP (shaoyang. on Discord, 11-03; `TestGroupAloneKeepsSubscriptionModelsOutOfEveryAgentsList`, `TestGroupAloneKeepsSubscriptionModelsOffAgentsModelList`). 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.
+- 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`.
diff --git a/internal/gateway/fallback.go b/internal/gateway/fallback.go
index 093f17a6b..cc1c24495 100644
--- a/internal/gateway/fallback.go
+++ b/internal/gateway/fallback.go
@@ -1680,12 +1680,15 @@ var unsaidWords = regexp.MustCompile(`(?i)(^|"|\\"|: )invalid request error trac
// 'messages[1].reasoning_content'", EDwinpzy) is one too: the client's
// request is whole, and a group of Beam then another model stopped at
// Beam before.
+// Google's word for a thought signature it didn't give (signatureRefused:
+// "Corrupted thought signature.", one Vertex AI gave replayed to AI Studio,
+// mimi001234) is one: the member that gave it may take it.
// One that also says the account is out of quota or credit (quotaWords,
// creditWords: "请充值") is that, and rests it (#4095).
func shapeRefused(status int, body []byte) bool {
// the words are matched decoded, too (#1669)
body = wordsOf(body)
- return (status == 400 || status == 422) && (shapeWords.Match(body) || unsaidWords.Match(body) || customToolRefusal.Match(body) || zhipuImageRefusal.Match(body) || wrongEndpoint(status, body) || upstreamFailedWords.Match(body) || reasoningBackRefused(body)) &&
+ return (status == 400 || status == 422) && (shapeWords.Match(body) || unsaidWords.Match(body) || customToolRefusal.Match(body) || zhipuImageRefusal.Match(body) || wrongEndpoint(status, body) || upstreamFailedWords.Match(body) || reasoningBackRefused(body) || signatureRefused.Match(body)) &&
!quotaWords.Match(body) && !creditWords.Match(body) && !unservedWords.Match(body) && !refusedWords.Match(body)
}
diff --git a/internal/gateway/gateway.go b/internal/gateway/gateway.go
index ca4dc28cc..e08c5041f 100644
--- a/internal/gateway/gateway.go
+++ b/internal/gateway/gateway.go
@@ -5901,7 +5901,7 @@ func (s *Server) passthrough(w http.ResponseWriter, r *http.Request, p provider.
// Gemini's thought signatures, which came to the client in its
// calls' ids, go back where Gemini wants them; another upstream
// gets the calls' own ids (#687)
- body = chatCallSignatures(body, compat)
+ body = chatCallSignatures(body, compat, p.ID, true)
if p.Preset == "mistral" || p.Host() == "api.mistral.ai" {
// an earlier turn's reasoning_content, which Mistral turns
// away, as the thinking part it takes (#494)
@@ -5930,6 +5930,8 @@ func (s *Server) passthrough(w http.ResponseWriter, r *http.Request, p provider.
// body has no such field, and Factory ignores it.
geminiWhole = !streamOf(body)
body = withoutFields(body, "stream")
+ // a signature another provider gave goes to none (ownSignatures)
+ body = geminiBodySignatures(body, p.ID, true)
case provider.Anthropic:
// what the client holds, taken before the upstream gets its own
// call ids back below, and those given back to it (tool_use_ids.go,
@@ -6084,6 +6086,25 @@ func (s *Server) passthrough(w http.ResponseWriter, r *http.Request, p provider.
if err != nil {
return writeError(w, proto, 502, p.Name+": "+err.Error()), err.Error(), true
}
+ if res.StatusCode == http.StatusBadRequest && (proto == provider.Chat || proto == provider.Gemini) && signaturesReach(p, proto, upstream) {
+ // a signature Google won't take (signatureRefused), one given
+ // before magpie noted whose it was: asked again once without
+ b, _ := io.ReadAll(io.LimitReader(res.Body, 1<<20))
+ res.Body.Close()
+ res.Body = io.NopCloser(bytes.NewReader(b))
+ if signatureRefused.Match(b) {
+ bare := geminiBodySignatures(body, p.ID, false)
+ if proto == provider.Chat {
+ bare = chatCallSignatures(body, true, p.ID, false)
+ }
+ if !bytes.Equal(bare, body) {
+ body = bare
+ if res, err = s.forward(r.Context(), p, proto, path, p.Prepare(body), r.Header); err != nil {
+ return writeError(w, proto, 502, p.Name+": "+err.Error()), err.Error(), true
+ }
+ }
+ }
+ }
if delta && badRequest(res.StatusCode) || delta && res.StatusCode == http.StatusNotFound {
// one it no longer holds: the conversation whole
b, _ := io.ReadAll(io.LimitReader(res.Body, 1<<20))
@@ -6509,7 +6530,10 @@ func (s *Server) passthrough(w http.ResponseWriter, r *http.Request, p provider.
}
var sigs *sigTidy
if proto == provider.Chat && geminiCompat(p.Host(), model) {
- sigs = &sigTidy{sse: sse}
+ sigs = &sigTidy{sse: sse, by: p.ID}
+ } else if proto == provider.Gemini {
+ // a Gemini client keeps the signatures itself: noted as p's
+ sigs = &sigTidy{sse: sse, by: p.ID, native: true}
}
var search *searchTidy
if searchFn && sse {
@@ -7032,6 +7056,8 @@ func (s *Server) forwardTranslated(ctx context.Context, p provider.Provider, to
r.Effort, req = e, &r
}
}
+ // Gemini's signatures another provider gave go to none (ownSignatures)
+ req = ownSignatures(req, p.ID)
if p.IsVertex() && !provider.VertexPartner(model) && !provider.VertexClaude(model) {
// Gemini's levels; a partner model on chat completions, and
// Claude on Anthropic's Messages API, are sent their effort as
@@ -7495,9 +7521,9 @@ func (s *Server) forwardTranslated(ctx context.Context, p provider.Provider, to
continue
}
}
- if p.IsVertex() && res.StatusCode == http.StatusBadRequest && vertexSignatureRefused.Match(b) {
- // a call's signature Vertex AI won't take (a client changed
- // it, or another API gave it, the conversation having moved):
+ if res.StatusCode == http.StatusBadRequest && signaturesReach(p, to, model) && signatureRefused.Match(b) {
+ // a signature Google won't take (a client changed it, or
+ // another provider gave it before magpie noted whose it was):
// the calls waved through instead, for this request
if r, had := withoutSignatures(req); had {
req = r
@@ -8444,7 +8470,14 @@ func build(proto provider.Protocol, r *Request, model, host string, rejectTemp b
// A ChatGPT account is given a declared tool whose name its backend
// refuses under another (provider.CodexToolName); the model's call to it
// comes back by the name the agent declared, from tools, the request's.
+//
+// Each Gemini thought signature the reply gives is noted as p's
+// (signersNoted), so it goes back to p alone (ownSignatures).
func decoderFor(p provider.Provider, proto provider.Protocol, tools []Tool) func(data string, emit func(Event)) error {
+ return signersNoted(decoderOf(p, proto, tools), p.ID)
+}
+
+func decoderOf(p provider.Provider, proto provider.Protocol, tools []Tool) func(data string, emit func(Event)) error {
if proto == provider.Chat && p.IsPlugin() {
d := &chatDecoder{past: true}
return d.decode
diff --git a/internal/gateway/gemini_signature.go b/internal/gateway/gemini_signature.go
index 64606eb9a..41ccaeed4 100644
--- a/internal/gateway/gemini_signature.go
+++ b/internal/gateway/gemini_signature.go
@@ -4,9 +4,13 @@ import (
"bytes"
"encoding/base64"
"encoding/json"
+ "regexp"
"slices"
"strconv"
"strings"
+
+ "github.com/tidwall/gjson"
+ "github.com/yetone/magpie/internal/provider"
)
// Gemini's thought signatures on tool calls (#687). Gemini 3 signs the
@@ -179,11 +183,13 @@ func googleExtra(sig string) map[string]any {
return map[string]any{"google": map[string]any{"thought_signature": sig}}
}
-// chatCallSignatures is a Chat request relayed as it is with the
-// signatures off its call ids: for Gemini (gemini) each call has its own
-// in extra_content, or skip_thought_signature_validator in a turn with
-// none; for another upstream the ids are only the calls' own again.
-func chatCallSignatures(body []byte, gemini bool) []byte {
+// chatCallSignatures is a Chat request relayed as it is to provider by
+// with the signatures off its call ids: for Gemini (gemini) each call has
+// its own in extra_content, or skip_thought_signature_validator in a turn
+// with none; for another upstream the ids are only the calls' own again.
+// A signature another provider gave (foreignSignature) goes to none, nor
+// does any when keep is false (signatureRefused: asked again without).
+func chatCallSignatures(body []byte, gemini bool, by string, keep bool) []byte {
signed := bytes.Contains(body, []byte(sigMark))
if !signed && !(gemini && bytes.Contains(body, []byte(`"tool_calls"`))) {
return body
@@ -216,6 +222,15 @@ func chatCallSignatures(body []byte, gemini bool) []byte {
if s := googleSignature(c["extra_content"]); s != "" {
sig = s
}
+ if sig != "" && (!keep || foreignSignature(sig, by)) {
+ // another provider's, or one turned away: the call goes
+ // as one this provider didn't sign
+ sig = ""
+ if googleSignature(c["extra_content"]) != "" {
+ delete(c, "extra_content")
+ changed = true
+ }
+ }
sigs[i] = sig
signedStep = signedStep || sig != ""
}
@@ -245,14 +260,43 @@ func chatCallSignatures(body []byte, gemini bool) []byte {
// sigTidy gives, in a Chat reply from Gemini relayed as it is, each tool
// call that came with a thought signature an id carrying it (signedID).
// Lines, or a whole reply, pass as they came unless one has a signature.
+//
+// Each signature is noted as provider by's (noteSigner). For a Gemini
+// client's reply (native), which carries its signatures where Gemini
+// gives them, the signatures are only noted, and the reply goes as it
+// came.
type sigTidy struct {
- sse bool
- buf []byte
+ sse bool
+ by string
+ native bool
+ buf []byte
}
var thoughtSignatureField = []byte(`"thought_signature"`)
+// nativeNoteBytes bounds the copy of a whole Gemini reply kept to note
+// its signatures: one past it has none noted, and its signatures go back
+// as before signers were kept.
+const nativeNoteBytes = 8 << 20
+
func (t *sigTidy) write(b []byte) []byte {
+ if t.native {
+ // the reply goes on as it comes; what it signed is read off a
+ // copy, by its lines on a stream, whole at the end otherwise
+ if !t.sse && len(t.buf)+len(b) > nativeNoteBytes {
+ t.buf, t.by = nil, ""
+ }
+ if t.by != "" {
+ t.buf = append(t.buf, b...)
+ }
+ if t.sse {
+ if i := bytes.LastIndexByte(t.buf, '\n'); i >= 0 {
+ noteGeminiSigners(t.buf[:i+1], t.by)
+ t.buf = append(t.buf[:0], t.buf[i+1:]...)
+ }
+ }
+ return b
+ }
t.buf = append(t.buf, b...)
if !t.sse {
return nil
@@ -269,8 +313,12 @@ func (t *sigTidy) write(b []byte) []byte {
func (t *sigTidy) flush() []byte {
b := t.buf
t.buf = nil
+ if t.native {
+ noteGeminiSigners(b, t.by)
+ return nil
+ }
if !t.sse {
- if out, ok := signReply(b); ok {
+ if out, ok := signReply(b, t.by); ok {
return out
}
return b
@@ -296,7 +344,7 @@ func (t *sigTidy) lines(b []byte) []byte {
out = append(out, line...)
continue
}
- nb, ok := signReply(data)
+ nb, ok := signReply(data, t.by)
if !ok {
out = append(out, line...)
continue
@@ -307,8 +355,9 @@ func (t *sigTidy) lines(b []byte) []byte {
}
// signReply is a chunk, or a whole reply, with the signed calls' ids
-// carrying their signatures, and whether there was one.
-func signReply(data []byte) ([]byte, bool) {
+// carrying their signatures, noted as provider by's, and whether there
+// was one.
+func signReply(data []byte, by string) ([]byte, bool) {
if !bytes.Contains(data, thoughtSignatureField) {
return nil, false
}
@@ -337,6 +386,7 @@ func signReply(data []byte) ([]byte, bool) {
if sig == "" {
continue
}
+ noteSigner(sig, by)
var id string
json.Unmarshal(call["id"], &id)
if _, had := unsignedID(id); had != "" {
@@ -362,3 +412,185 @@ func signReply(data []byte) ([]byte, bool) {
}
return out, true
}
+
+// A signature goes back only to the provider that gave it (mimi001234 on
+// Discord: Pi on a group of Vertex AI and AI Studio; Vertex cooled down
+// on turn 15 and AI Studio was sent Vertex's signatures, and answered
+// every turn with 400 "Corrupted thought signature"). Google documents
+// skip_thought_signature_validator for a function call it didn't sign
+// ("when transferring history from a model that does not include thought
+// signatures"), which a step's first call is given in place of another
+// provider's signature; a text part's signature only helps, and goes.
+
+// signersNoted is dec with each signature in its events noted as provider
+// by's: a tool call's, which rides in its id (signedID), and a text's.
+func signersNoted(dec func(string, func(Event)) error, by string) func(string, func(Event)) error {
+ return func(data string, emit func(Event)) error {
+ return dec(data, func(ev Event) {
+ switch ev.Kind {
+ case KToolStart:
+ if _, sig := unsignedID(ev.ID); sig != "" {
+ noteSigner(sig, by)
+ }
+ case KTextSig:
+ noteSigner(ev.Text, by)
+ }
+ emit(ev)
+ })
+ }
+}
+
+// ownSignatures is req for provider by with no signature another provider
+// gave on its calls and texts (foreignSignature). Messages are copied
+// before they change.
+func ownSignatures(req *Request, by string) *Request {
+ return dropSignatures(req, func(sig string) bool { return foreignSignature(sig, by) })
+}
+
+// dropSignatures is req with the Gemini signatures drop says on its calls
+// and texts taken off. Claude's signed thinking is no Gemini signature,
+// and stays.
+func dropSignatures(req *Request, drop func(sig string) bool) *Request {
+ var msgs []Message
+ for i, m := range req.Messages {
+ var parts []Part
+ for j, p := range m.Parts {
+ if (p.Kind != ToolCall && p.Kind != Text) || p.Signature == "" || !drop(p.Signature) {
+ continue
+ }
+ if parts == nil {
+ parts = slices.Clone(m.Parts)
+ }
+ parts[j].Signature = ""
+ }
+ if parts == nil {
+ continue
+ }
+ if msgs == nil {
+ msgs = slices.Clone(req.Messages)
+ }
+ msgs[i].Parts = parts
+ }
+ if msgs == nil {
+ return req
+ }
+ r := *req
+ r.Messages = msgs
+ return &r
+}
+
+// signatureRefused is Google turning a signature away as one it didn't
+// give: Vertex AI's 400 "Invalid thought signature.", AI Studio's 400
+// "Corrupted thought signature.". It is about the request's history, not
+// the account: the request is asked again without signatures, and no
+// account rests for it.
+var signatureRefused = regexp.MustCompile(`(?i)\b(invalid|corrupted) thought signature`)
+
+// signaturesReach says a request built for provider p on API to carries
+// Gemini's signatures there: Gemini's own API (Vertex AI, AI Studio, Code
+// Assist) or its OpenAI-compatible one.
+func signaturesReach(p provider.Provider, to provider.Protocol, model string) bool {
+ return to == provider.Gemini || to == provider.CodeAssist || p.IsVertex() || to == provider.Chat && geminiCompat(p.Host(), model)
+}
+
+var geminiSignatureField = []byte(`"thoughtSignature"`)
+
+// noteGeminiSigners notes each thoughtSignature in a Gemini reply, a chunk
+// or a whole one (an object, or streamGenerateContent's array of them),
+// as provider by's.
+func noteGeminiSigners(b []byte, by string) {
+ if !bytes.Contains(b, geminiSignatureField) {
+ return
+ }
+ note := func(r gjson.Result) {
+ for _, c := range r.Get("candidates").Array() {
+ for _, p := range c.Get("content.parts").Array() {
+ noteSigner(p.Get("thoughtSignature").String(), by)
+ }
+ }
+ for _, c := range r.Get("response.candidates").Array() {
+ for _, p := range c.Get("content.parts").Array() {
+ noteSigner(p.Get("thoughtSignature").String(), by)
+ }
+ }
+ }
+ all := func(r gjson.Result) {
+ if r.IsArray() {
+ r.ForEach(func(_, v gjson.Result) bool { note(v); return true })
+ } else {
+ note(r)
+ }
+ }
+ if gjson.ValidBytes(b) {
+ // a whole reply, however it is laid out
+ all(gjson.ParseBytes(b))
+ return
+ }
+ for len(b) > 0 {
+ line := b
+ if i := bytes.IndexByte(b, '\n'); i >= 0 {
+ line, b = b[:i], b[i+1:]
+ } else {
+ b = nil
+ }
+ line = bytes.TrimSpace(line)
+ if d, ok := bytes.CutPrefix(line, []byte("data:")); ok {
+ line = bytes.TrimSpace(d)
+ }
+ if !bytes.Contains(line, geminiSignatureField) {
+ continue
+ }
+ all(gjson.ParseBytes(line))
+ }
+}
+
+// geminiBodySignatures is a Gemini client's request relayed as it is to
+// provider by with no signature another provider gave (foreignSignature),
+// nor any when keep is false: a function call that had one goes waved
+// through (skipSignature), a text without.
+func geminiBodySignatures(body []byte, by string, keep bool) []byte {
+ if !bytes.Contains(body, geminiSignatureField) {
+ return body
+ }
+ var q map[string]json.RawMessage
+ var contents []map[string]json.RawMessage
+ if json.Unmarshal(body, &q) != nil || json.Unmarshal(q["contents"], &contents) != nil {
+ return body
+ }
+ changed := false
+ for _, c := range contents {
+ var parts []map[string]json.RawMessage
+ if json.Unmarshal(c["parts"], &parts) != nil {
+ continue
+ }
+ edited := false
+ for _, p := range parts {
+ var sig string
+ if json.Unmarshal(p["thoughtSignature"], &sig) != nil || sig == "" || sig == skipSignature {
+ continue
+ }
+ if keep && !foreignSignature(sig, by) {
+ continue
+ }
+ if _, call := p["functionCall"]; call {
+ p["thoughtSignature"], _ = marshalPlain(skipSignature)
+ } else {
+ delete(p, "thoughtSignature")
+ }
+ edited = true
+ }
+ if edited {
+ c["parts"], _ = marshalPlain(parts)
+ changed = true
+ }
+ }
+ if !changed {
+ return body
+ }
+ q["contents"], _ = marshalPlain(contents)
+ out, err := marshalPlain(q)
+ if err != nil {
+ return body
+ }
+ return out
+}
diff --git a/internal/gateway/gemini_signature_test.go b/internal/gateway/gemini_signature_test.go
index ac1257205..83db894ca 100644
--- a/internal/gateway/gemini_signature_test.go
+++ b/internal/gateway/gemini_signature_test.go
@@ -221,7 +221,7 @@ func TestGeminiCallsWithoutSignature(t *testing.T) {
} `json:"tool_calls"`
} `json:"messages"`
}
- if err := json.Unmarshal(chatCallSignatures(body, true), &q); err != nil {
+ if err := json.Unmarshal(chatCallSignatures(body, true, "google", true), &q); err != nil {
t.Fatal(err)
}
sigOf := func(m, c int) string {
@@ -236,7 +236,7 @@ func TestGeminiCallsWithoutSignature(t *testing.T) {
if sigOf(3, 0) != "c2ln" || sigOf(3, 1) != "" || q.Messages[3].ToolCalls[0].ID != "call_a" || q.Messages[4].ToolCallID != "call_a" {
t.Errorf("a signed turn went as %+v", q.Messages[3:5])
}
- other := string(chatCallSignatures(body, false))
+ other := string(chatCallSignatures(body, false, "google", true))
if strings.Contains(other, sigMark) || strings.Contains(other, "extra_content") || !strings.Contains(other, `"id":"call_a"`) {
t.Errorf("another upstream was sent %s", other)
}
@@ -357,7 +357,7 @@ func TestShortenedIDGoesUnsigned(t *testing.T) {
body := []byte(`{"messages":[{"role":"user","content":"list files"},
{"role":"assistant","tool_calls":[{"id":"` + cut + `","type":"function","function":{"name":"bash","arguments":"{}"}}]},
{"role":"tool","tool_call_id":"` + cut + `","content":"a.txt"}]}`)
- if relayed := string(chatCallSignatures(body, true)); !strings.Contains(relayed, `"thought_signature":"`+skipSignature+`"`) {
+ if relayed := string(chatCallSignatures(body, true, "google", true)); !strings.Contains(relayed, `"thought_signature":"`+skipSignature+`"`) {
t.Fatalf("%q cut to %d: relayed as %s", c.id, n, relayed)
}
r := &Request{Messages: []Message{
@@ -469,7 +469,7 @@ func TestKeptSignatureGoneOrChanged(t *testing.T) {
t.Fatalf("a gone file read as %q, %d bytes", got, len(back))
}
body := []byte(`{"messages":[{"role":"assistant","tool_calls":[{"id":"` + id + `","type":"function","function":{"name":"bash","arguments":"{}"}}]}]}`)
- if out := string(chatCallSignatures(body, true)); !strings.Contains(out, `"thought_signature":"`+skipSignature+`"`) {
+ if out := string(chatCallSignatures(body, true, "google", true)); !strings.Contains(out, `"thought_signature":"`+skipSignature+`"`) {
t.Fatalf("relayed as %s", out)
}
// written again, it is read again
diff --git a/internal/gateway/gemini_signer_test.go b/internal/gateway/gemini_signer_test.go
new file mode 100644
index 000000000..f785bc84c
--- /dev/null
+++ b/internal/gateway/gemini_signer_test.go
@@ -0,0 +1,340 @@
+package gateway
+
+import (
+ "encoding/json"
+ "io"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "sync"
+ "testing"
+ "time"
+
+ "github.com/yetone/magpie/internal/provider"
+)
+
+// studioCorrupted is how Gemini's OpenAI-compatible endpoint turns away a
+// thought signature it didn't give (mimi001234, 2026-11-05).
+const studioCorrupted = `[{"error":{"code":400,"message":"Corrupted thought signature.","status":"INVALID_ARGUMENT"}}]`
+
+// studioSig is the signature studioUp gives its own calls.
+const studioSig = "c3R1ZGlvLW1pbnRlZC1zaWduYXR1cmU="
+
+// studioUp is Gemini on Google AI Studio's OpenAI-compatible chat
+// completions: a call's signature has to be one it gave, or the value
+// Google documents for calls it didn't make.
+type studioUp struct {
+ mu sync.Mutex
+ sent [][]string // per request, the signature on each call, in order
+ reply string
+}
+
+func (u *studioUp) ServeHTTP(w http.ResponseWriter, r *http.Request) {
+ b, _ := io.ReadAll(r.Body)
+ var req struct {
+ Stream bool `json:"stream"`
+ Messages []struct {
+ ToolCalls []struct {
+ Extra json.RawMessage `json:"extra_content"`
+ } `json:"tool_calls"`
+ } `json:"messages"`
+ }
+ json.Unmarshal(b, &req)
+ var sigs []string
+ refused := false
+ for _, m := range req.Messages {
+ for _, c := range m.ToolCalls {
+ sig := googleSignature(c.Extra)
+ sigs = append(sigs, sig)
+ if sig != "" && sig != skipSignature && sig != studioSig {
+ refused = true
+ }
+ }
+ }
+ u.mu.Lock()
+ u.sent = append(u.sent, sigs)
+ reply := u.reply
+ u.mu.Unlock()
+ w.Header().Set("Content-Type", "application/json")
+ if refused {
+ w.WriteHeader(http.StatusBadRequest)
+ io.WriteString(w, studioCorrupted)
+ return
+ }
+ if reply == "" {
+ reply = chatOK
+ }
+ if req.Stream && reply == chatOK {
+ w.Header().Set("Content-Type", "text/event-stream")
+ io.WriteString(w, `data: {"id":"ok","choices":[{"index":0,"delta":{"role":"assistant","content":"hello"}}]}`+"\n\n"+
+ `data: {"id":"ok","choices":[{"index":0,"delta":{},"finish_reason":"stop"}]}`+"\n\ndata: [DONE]\n\n")
+ return
+ }
+ io.WriteString(w, reply)
+}
+
+func (u *studioUp) last(t *testing.T) []string {
+ t.Helper()
+ u.mu.Lock()
+ defer u.mu.Unlock()
+ if len(u.sent) == 0 {
+ t.Fatal("AI Studio was asked nothing")
+ }
+ return u.sent[len(u.sent)-1]
+}
+
+func (u *studioUp) count() int {
+ u.mu.Lock()
+ defer u.mu.Unlock()
+ return len(u.sent)
+}
+
+func studioServe(t *testing.T, u *studioUp) {
+ t.Helper()
+ up := httptest.NewServer(u)
+ t.Cleanup(up.Close)
+ if err := provider.Save(provider.Provider{ID: "google-aistudio-paid", Name: "AI Studio", Key: "k",
+ Chat: up.URL + "/v1beta/openai", Models: []string{"gemini-3.8-flash"}}); err != nil {
+ t.Fatal(err)
+ }
+}
+
+func nobodyResting(t *testing.T) {
+ t.Helper()
+ restingUntil.Lock()
+ defer restingUntil.Unlock()
+ for id := range restingUntil.m {
+ if strings.Contains(id, "aistudio") {
+ t.Errorf("%s was rested", id)
+ }
+ }
+}
+
+// piTurn is Pi's next request on the group after the calls with ids
+// (openai-completions).
+func piTurn(ids []string) string {
+ return `{"model":"group/g","stream":false,"tools":[{"type":"function","function":{"name":"get_weather","parameters":{"type":"object","properties":{"city":{"type":"string"}}}}}],"messages":[
+ {"role":"user","content":"Weather in Paris and in Tokyo?"},
+ {"role":"assistant","content":null,"tool_calls":[
+ {"id":"` + ids[0] + `","type":"function","function":{"name":"get_weather","arguments":"{\"city\":\"Paris\"}"}},
+ {"id":"` + ids[1] + `","type":"function","function":{"name":"get_weather","arguments":"{\"city\":\"Tokyo\"}"}}]},
+ {"role":"tool","tool_call_id":"` + ids[0] + `","content":"18C, clear"},
+ {"role":"tool","tool_call_id":"` + ids[1] + `","content":"21C, rain"}]}`
+}
+
+// mimi001234 (2026-11-05): Pi on a group of Vertex AI and AI Studio.
+// Vertex AI served the turns and signed its calls; when it answered 429,
+// the group moved to AI Studio with Vertex AI's signatures, and AI Studio
+// answered every try with 400 "Corrupted thought signature.". A signature
+// goes back only to the provider that gave it: AI Studio is sent its
+// calls as ones it didn't make, and Vertex AI, and AI Studio, each still
+// get their own.
+func TestSignatureGoesOnlyToItsSigner(t *testing.T) {
+ limited := false
+ v := &vertexUp{reply: func(n int, body map[string]any) (int, string) {
+ if limited {
+ return http.StatusTooManyRequests, `{"error":{"code":429,"message":"Resource exhausted. Please try again later.","status":"RESOURCE_EXHAUSTED"}}`
+ }
+ return http.StatusOK, vertexCalls
+ }}
+ s := vertexServe(t, v, vertexLevels)
+ u := &studioUp{}
+ studioServe(t, u)
+ if err := provider.SaveGroup(provider.Group{Name: "G", Routing: provider.Ordered,
+ Members: []string{"google-vertex/gemini-3.8-flash", "google-aistudio-paid/gemini-3.8-flash"}}); err != nil {
+ t.Fatal(err)
+ }
+ s = New()
+
+ code, out := postAs(t, s, "", `{"model":"group/g","stream":false,"tools":[{"type":"function","function":{"name":"get_weather","parameters":{"type":"object"}}}],
+ "messages":[{"role":"user","content":"Weather in Paris and in Tokyo?"}]}`)
+ if code != http.StatusOK {
+ t.Fatalf("turn 1: %d %s", code, out)
+ }
+ ids := vertexCallIDs.FindAllString(out, -1)
+ if len(ids) < 2 || !strings.Contains(ids[0], sigMark) {
+ t.Fatalf("turn 1: Vertex AI's calls came back as %v", ids)
+ }
+ ids = []string{ids[0], ids[len(ids)-1]}
+
+ // Vertex AI is sent its own signature, as before
+ if code, out := postAs(t, s, "", piTurn(ids)); code != http.StatusOK {
+ t.Fatalf("turn 2 on Vertex AI: %d %s", code, out)
+ }
+ parts := v.last(t).body["contents"].([]any)[1].(map[string]any)["parts"].([]any)
+ if sig := parts[0].(map[string]any)["thoughtSignature"]; sig != vertexCallSig {
+ t.Errorf("Vertex AI was sent %v for its own call, want its signature", sig)
+ }
+
+ // Vertex AI out of quota: AI Studio takes the turn, Vertex AI's
+ // signature not sent to it
+ limited = true
+ if code, out := postAs(t, s, "", piTurn(ids)); code != http.StatusOK || !strings.Contains(out, "hello") {
+ t.Fatalf("turn 3 on AI Studio: %d %s", code, out)
+ }
+ if u.count() != 1 {
+ t.Errorf("AI Studio was asked %d times, want once", u.count())
+ }
+ if got := u.last(t); len(got) == 0 || got[0] != skipSignature {
+ t.Errorf("AI Studio was sent %q, want %s on the first call", got, skipSignature)
+ }
+ nobodyResting(t)
+
+ // AI Studio's own signature goes back to it
+ u.mu.Lock()
+ u.reply = `{"id":"s1","choices":[{"index":0,"finish_reason":"tool_calls","message":{"role":"assistant","content":null,"tool_calls":[
+ {"id":"call_s1","type":"function","function":{"name":"get_weather","arguments":"{\"city\":\"Paris\"}"},"extra_content":{"google":{"thought_signature":"` + studioSig + `"}}},
+ {"id":"call_s2","type":"function","function":{"name":"get_weather","arguments":"{\"city\":\"Tokyo\"}"}}]}}]}`
+ u.mu.Unlock()
+ code, out = postAs(t, s, "", piTurn(ids))
+ if code != http.StatusOK {
+ t.Fatalf("turn 4 on AI Studio: %d %s", code, out)
+ }
+ var reply struct {
+ Choices []struct {
+ Message struct {
+ ToolCalls []struct {
+ ID string `json:"id"`
+ } `json:"tool_calls"`
+ } `json:"message"`
+ } `json:"choices"`
+ }
+ if json.Unmarshal([]byte(out), &reply) != nil || len(reply.Choices) == 0 || len(reply.Choices[0].Message.ToolCalls) != 2 {
+ t.Fatalf("turn 4: %s", out)
+ }
+ studioIDs := []string{reply.Choices[0].Message.ToolCalls[0].ID, reply.Choices[0].Message.ToolCalls[1].ID}
+ u.mu.Lock()
+ u.reply = ""
+ u.mu.Unlock()
+ if code, out := postAs(t, s, "", piTurn(studioIDs)); code != http.StatusOK {
+ t.Fatalf("turn 5 on AI Studio: %d %s", code, out)
+ }
+ if got := u.last(t); len(got) == 0 || got[0] != studioSig {
+ t.Errorf("AI Studio was sent %q for its own call, want its signature", got)
+ }
+ nobodyResting(t)
+}
+
+// A signature whose giver isn't known (an id from before signers were
+// noted) that AI Studio turns away as corrupted is tried once more with
+// the calls as ones it didn't make, and rests nobody.
+func TestCorruptedSignatureTriedWithout(t *testing.T) {
+ fresh(t)
+ u := &studioUp{}
+ studioServe(t, u)
+ s := New()
+ ids := []string{signedID("call_1", "c2lnbmF0dXJlLW9uZQ=="), "call_2"}
+ body := strings.Replace(piTurn(ids), "group/g", "google-aistudio-paid/gemini-3.8-flash", 1)
+ if code, out := postAs(t, s, "", body); code != http.StatusOK {
+ t.Fatalf("%d %s", code, out)
+ }
+ if u.count() != 2 {
+ t.Fatalf("AI Studio was asked %d times, want the one turned away and the one after", u.count())
+ }
+ if got := u.last(t); len(got) == 0 || got[0] != skipSignature {
+ t.Errorf("tried again with %q, want %s", got, skipSignature)
+ }
+ nobodyResting(t)
+}
+
+// A 400 for a signature is about the request's history, not the account:
+// it rests nobody and the group goes on to its next member.
+func TestCorruptedSignatureNotTheAccount(t *testing.T) {
+ if !shapeRefused(http.StatusBadRequest, []byte(studioCorrupted)) {
+ t.Error("a corrupted signature isn't taken as the request's shape")
+ }
+ if !shapeRefused(http.StatusBadRequest, []byte(vertexBadSig)) {
+ t.Error("an invalid signature isn't taken as the request's shape")
+ }
+ fresh(t)
+ s := New()
+ c := candidate{p: provider.Provider{ID: "google-aistudio-paid", Key: "k"}, model: "gemini-3.8-flash", rest: "google-aistudio-paid"}
+ if r := s.restAfter(c, http.StatusBadRequest, http.Header{}, []byte(studioCorrupted)); r.By != "off" || r.Until.After(time.Now()) {
+ t.Errorf("a corrupted signature rests the account by %q until %v", r.By, r.Until)
+ }
+}
+
+// The same on every client's protocol the gateway translates: Claude
+// Code's calls Vertex AI signed reach AI Studio as calls it didn't make.
+func TestSignatureGoesOnlyToItsSignerTranslated(t *testing.T) {
+ limited := false
+ v := &vertexUp{reply: func(n int, body map[string]any) (int, string) {
+ if limited {
+ return http.StatusTooManyRequests, `{"error":{"code":429,"message":"Resource exhausted. Please try again later.","status":"RESOURCE_EXHAUSTED"}}`
+ }
+ return http.StatusOK, vertexCalls
+ }}
+ s := vertexServe(t, v, vertexLevels)
+ u := &studioUp{}
+ studioServe(t, u)
+ if err := provider.SaveGroup(provider.Group{Name: "G", Routing: provider.Ordered,
+ Members: []string{"google-vertex/gemini-3.8-flash", "google-aistudio-paid/gemini-3.8-flash"}}); err != nil {
+ t.Fatal(err)
+ }
+ s = New()
+ const tools = `"tools":[{"name":"get_weather","input_schema":{"type":"object","properties":{"city":{"type":"string"}}}}]`
+ out := vertexAsk(t, s, "/v1/messages", `{"model":"group/g","max_tokens":4000,`+tools+`,"messages":[{"role":"user","content":"Weather in Paris and in Tokyo?"}]}`)
+ ids := vertexCallIDs.FindAllString(out, -1)
+ if len(ids) < 2 || !strings.Contains(ids[0], sigMark) {
+ t.Fatalf("Vertex AI's calls came back as %v", ids)
+ }
+ ids = []string{ids[0], ids[len(ids)-1]}
+ limited = true
+ vertexAsk(t, s, "/v1/messages", `{"model":"group/g","max_tokens":4000,`+tools+`,"messages":[
+ {"role":"user","content":"Weather in Paris and in Tokyo?"},
+ {"role":"assistant","content":[
+ {"type":"tool_use","id":"`+ids[0]+`","name":"get_weather","input":{"city":"Paris"}},
+ {"type":"tool_use","id":"`+ids[1]+`","name":"get_weather","input":{"city":"Tokyo"}}]},
+ {"role":"user","content":[
+ {"type":"tool_result","tool_use_id":"`+ids[0]+`","content":"18C, clear"},
+ {"type":"tool_result","tool_use_id":"`+ids[1]+`","content":"21C, rain"}]}]}`)
+ if u.count() != 1 {
+ t.Errorf("AI Studio was asked %d times, want once", u.count())
+ }
+ if got := u.last(t); len(got) == 0 || got[0] != skipSignature {
+ t.Errorf("AI Studio was sent %q, want %s on the first call", got, skipSignature)
+ }
+ nobodyResting(t)
+}
+
+// A Gemini client's own history, relayed as it is: a signature another
+// provider gave goes as Google's value for calls it didn't make on a call,
+// and not at all on text; the provider that gave it gets it as it was.
+func TestGeminiBodyKeepsOnlyItsOwn(t *testing.T) {
+ fresh(t)
+ const vsig, other = "dmVydGV4LXNpZ25lZA==", "dW5rbm93bi1zaWduZWQ="
+ noteGeminiSigners([]byte("data: {\"candidates\":[{\"content\":{\"role\":\"model\",\"parts\":[{\"text\":\"hm\",\"thoughtSignature\":\""+vsig+"\"}]}}]}\r\n\r\n"), "google-vertex")
+ if got := signerOf(vsig); got != "google-vertex" {
+ t.Fatalf("signer noted as %q", got)
+ }
+ body := []byte(`{"contents":[{"role":"user","parts":[{"text":"hi"}]},{"role":"model","parts":[
+ {"functionCall":{"name":"f","args":{}},"thoughtSignature":"` + vsig + `"},
+ {"text":"ok","thoughtSignature":"` + vsig + `"},
+ {"functionCall":{"name":"g","args":{}},"thoughtSignature":"` + other + `"}]}]}`)
+ if got := geminiBodySignatures(body, "google-vertex", true); string(got) != string(body) {
+ t.Errorf("the signer's own body changed:\n%s", got)
+ }
+ got := geminiBodySignatures(body, "google", true)
+ var b struct {
+ Contents []struct {
+ Parts []map[string]any `json:"parts"`
+ } `json:"contents"`
+ }
+ if err := json.Unmarshal(got, &b); err != nil || len(b.Contents) != 2 || len(b.Contents[1].Parts) != 3 {
+ t.Fatalf("%v: %s", err, got)
+ }
+ parts := b.Contents[1].Parts
+ if parts[0]["thoughtSignature"] != skipSignature {
+ t.Errorf("the call went with %v", parts[0]["thoughtSignature"])
+ }
+ if _, ok := parts[1]["thoughtSignature"]; ok {
+ t.Errorf("the text went with %v", parts[1]["thoughtSignature"])
+ }
+ if parts[2]["thoughtSignature"] != other {
+ t.Errorf("a signature of no known giver went as %v, want as it was", parts[2]["thoughtSignature"])
+ }
+ bare := geminiBodySignatures(body, "google-vertex", false)
+ if strings.Contains(string(bare), vsig) || strings.Contains(string(bare), other) {
+ t.Errorf("asked again without signatures, still sent some: %s", bare)
+ }
+}
diff --git a/internal/gateway/gemini_sigstore.go b/internal/gateway/gemini_sigstore.go
index f2d9a87a6..c4e824842 100644
--- a/internal/gateway/gemini_sigstore.go
+++ b/internal/gateway/gemini_sigstore.go
@@ -107,3 +107,71 @@ func pruneSignatures(dir string) {
}
}
}
+
+// Which provider gave a signature (a reply's tool call or text): a
+// signature goes back only to the provider that gave it (ownSignatures).
+// Vertex AI and AI Studio serve the same Gemini models, and a routing
+// group of both falls over from one to the other mid-conversation; the
+// other answers a signature it didn't give with 400 "Corrupted thought
+// signature" (mimi001234 on Discord). It is kept beside the signature,
+// .by, the provider's id in it, keyed by the signature's hash, so
+// it reads the same whichever way the signature came back: in a call's
+// id, in extra_content, or in a Gemini client's own thoughtSignature.
+const signerExt = ".by"
+
+// noteSigner records that provider by gave sig. A record that couldn't
+// be written leaves the signature's giver unknown (signerOf).
+func noteSigner(sig, by string) {
+ if sig == "" || by == "" || sig == skipSignature {
+ return
+ }
+ dir := sigDir()
+ path := filepath.Join(dir, sigKey(sig)+signerExt)
+ if b, err := os.ReadFile(path); err == nil && string(b) == by {
+ now := time.Now()
+ os.Chtimes(path, now, now)
+ return
+ }
+ if err := os.MkdirAll(dir, 0o700); err != nil {
+ return
+ }
+ tmp, err := os.CreateTemp(dir, ".tmp-*")
+ if err != nil {
+ return
+ }
+ _, werr := tmp.WriteString(by)
+ cerr := tmp.Close()
+ if werr != nil || cerr != nil || os.Rename(tmp.Name(), path) != nil {
+ os.Remove(tmp.Name())
+ return
+ }
+ pruneSignatures(dir)
+}
+
+// signerOf is the id of the provider that gave sig, or "" when magpie
+// doesn't know: a signature from before signers were kept, one whose
+// record couldn't be written or read, or one a client made up.
+func signerOf(sig string) string {
+ if sig == "" || sig == skipSignature {
+ return ""
+ }
+ path := filepath.Join(sigDir(), sigKey(sig)+signerExt)
+ b, err := os.ReadFile(path)
+ if err != nil {
+ return ""
+ }
+ now := time.Now()
+ os.Chtimes(path, now, now)
+ return string(b)
+}
+
+// foreignSignature says sig is known to come from a provider other than
+// by. A signature whose giver isn't known goes as it did before signers
+// were kept: dropping it would cost every conversation from before the
+// upgrade its signatures on the very provider that gave them, and the
+// one that can't read it says so (signatureRefused), which is answered
+// by asking again without.
+func foreignSignature(sig, by string) bool {
+ from := signerOf(sig)
+ return from != "" && from != by
+}
diff --git a/internal/gateway/routing.go b/internal/gateway/routing.go
index ac03a663a..8b530429d 100644
--- a/internal/gateway/routing.go
+++ b/internal/gateway/routing.go
@@ -1328,6 +1328,13 @@ func (s *Server) restAfterMarked(c candidate, status int, header http.Header, bo
// connection (regionFresh)
return Rest{Why: why, Status: status, By: "off", Until: now}
}
+ if status == http.StatusBadRequest && signatureRefused.Match(wordsOf(body)) {
+ // Google turned a thought signature away as one it didn't give
+ // (signatureRefused): the history's doing, not the account's. A
+ // group that moved from Vertex AI to AI Studio was refused on every
+ // account alike (mimi001234); none is set aside
+ return Rest{Why: why, Status: status, By: "off", Until: now}
+ }
if status == http.StatusBadGateway && bytes.Contains(body, []byte(openCodeBare)) {
// OpenCode's bare 400 (openCodeBareRefusal, #3740) is about the
// request, not the key: the key's other requests go through, so
diff --git a/internal/gateway/vertex.go b/internal/gateway/vertex.go
index 1586d0494..1636a15df 100644
--- a/internal/gateway/vertex.go
+++ b/internal/gateway/vertex.go
@@ -2,7 +2,6 @@ package gateway
import (
"encoding/json"
- "regexp"
"slices"
"strings"
)
@@ -123,32 +122,10 @@ func vertexEffort(req *Request, levels []string) *Request {
return &r
}
-// vertexSignatureRefused is Vertex AI turning a call's thought signature
-// away as one it didn't give: "Invalid thought signature.".
-var vertexSignatureRefused = regexp.MustCompile(`(?i)invalid thought signature`)
-
-// withoutSignatures is req with no thought signature on its calls, each of
-// which then goes to Vertex AI waved through (skipSignature); false when it
-// had none.
+// withoutSignatures is req with no Gemini signature on its calls and
+// texts, each call then going waved through (skipSignature); false when
+// it had none.
func withoutSignatures(req *Request) (*Request, bool) {
- had := false
- msgs := slices.Clone(req.Messages)
- for i, m := range msgs {
- if !slices.ContainsFunc(m.Parts, func(p Part) bool { return p.Kind == ToolCall && p.Signature != "" }) {
- continue
- }
- parts := slices.Clone(m.Parts)
- for j := range parts {
- if parts[j].Kind == ToolCall {
- parts[j].Signature = ""
- }
- }
- msgs[i].Parts, had = parts, true
- }
- if !had {
- return req, false
- }
- r := *req
- r.Messages = msgs
- return &r, true
+ r := dropSignatures(req, func(string) bool { return true })
+ return r, r != req
}