What changed: in thinking mode, DeepSeek's Anthropic endpoint (api.deepseek.com/anthropic) refuses a request when an assistant turn has a tool_use and no thinking block: 400 "The `content[].thinking` in the thinking mode must be passed back to the API". It also refuses redacted_thinking anywhere in the request with 422 "unknown variant `redacted_thinking`". A Claude Code routing group whose Claude turns fall over to DeepSeek met both refusals. This is the Anthropic-endpoint sibling of #1592 (Responses) and #1462 (Chat). - anthropicReplaysThinking(host, model): DeepSeek only, by host or model id. It is never api.anthropic.com or a Claude model. - withThinkingOnToolTurns: a tool_use turn with no thinking gets a {"type":"thinking","thinking":" "} block first. Redacted thinking becomes that block, or is dropped when the turn already has thinking. The body is returned byte for byte when nothing changes. - The passthrough and the translated build (a Chat/Responses client to an Anthropic-only DeepSeek) both use it. The translated build also replays the turn's own reasoning text, where it has one. - docs/subsystems/gateway-routing.md describes it. Checked live on 2026-10-11 against api.deepseek.com/anthropic with deepseek-flash and deepseek-v4-pro: - Thinking on (no field, enabled or adaptive) with a bare tool_use: 400. - Thinking disabled with a bare tool_use: 200. - redacted_thinking, even in a text-only turn: 422. - Thinking " ", thinking "", unsigned thinking and thinking after text: all 200. What was run: - New tests in deepseek_anthropic_thinking_test.go: - direct and through group/cc; - glm-5.2 and claude-sonnet-4-6 on the same upstream are sent unchanged; - the translated path; - the body is returned byte for byte when nothing changes. - Breaking each call site by hand turns its test red. - go test ./internal/gateway passed (410s). gofmt -l is clean, and go vet passes for linux, windows and darwin. - End to end, with a built binary on port 3611 and a sandbox HOME holding the owner's real DeepSeek key: - before this change: 422 with redacted thinking, and 400 with thinking adaptive; - after it: 200 with a complete reply in all 8 cases (direct and group/cc, streamed and whole, adaptive and no thinking field).
86 KiB
Gateway routing and fallback
The gateway is magpie's local LLM endpoint (127.0.0.1:3425 by default). It
serves Chat Completions, Responses, Anthropic Messages and Gemini. It finds
the provider, key or account and model for each request. When the upstream
doesn't speak the agent's API, the gateway translates. When an upstream
fails before any of the reply is sent, the gateway moves to the next
candidate.
This page covers how a request is routed. Plugins that change requests and replies are in Gateway middleware. Subscriptions served by a plugin are in Provider and plugin ownership.
Responsibilities and sources of truth
| Part | Responsibility | Source |
|---|---|---|
| Address and caller | DefaultAddr. The local token magpie and the per-agent magpie-<agent> (TokenFor). agentOf tells which agent asked, first by token, then by User-Agent. |
gateway.go |
| HTTP surface | Handler routes /v1/chat/completions, /v1/responses, /v1/messages (each also without /v1), /v1/models, Gemini's /v1beta/models/…, the Codex backend path, /v1/codex/models (Codex's catalog shape for a Codex elsewhere with a gateway key, codexCatalog, kept to the key's models by keyAllowed; #1281), /mcp/{name}, /mcp/magpie/web-search (magpie's own web search as an MCP server, below) and the /v1/magpie/* status endpoints. A GET on /v1/responses (a client opening Responses over a WebSocket) is answered 426, a plain one 405: Responses is relayed over HTTP only. Every route is wrapped in counted, corsGuard, callerGuard, withCaller and keyLimited; /v1/messages, /messages and /v1/messages/count_tokens in keepsSignIn too. corsGuard (#1051) serves CORS only to the origins listed in Settings › Network › Web pages (settings.CORSOrigins, cleaned to scheme://host[:port] by settings.CleanOrigins, which refuses a wildcard). For a listed origin it answers the preflight (204) and adds Access-Control-Allow-Origin, and every other request from it needs an enabled gateway key (access.Authenticate), even on loopback, or gets a 401. It takes the key from the caller lanGuard recorded too, since on the running server lanGuard has already put magpie's own token in the key's place. Any other web page is refused 403 on every route (foreignPage): on loopback a call needs no key and the body's Content-Type isn't checked, so a page the user visits could otherwise send a "simple" text/plain POST and spend their subscriptions blind. Only an http/https Origin is judged, and one on this computer (localhost, *.localhost, 127.0.0.0/8, [::1], any port) or the request's own origin (its host and port equal to Host, such as a page on the gateway's LAN address) passes, as does usemagpie.ai on /v1/magpie/omarchy. null and other schemes (app://, file://, tauri://, vscode-webview://, chrome-extension://) come from desktop apps, webviews and extensions that don't enforce CORS, and pass. A request with no Origin (every agent's) passes through with no CORS headers, as before. A page whose own name resolves to 127.0.0.1 (DNS rebinding) would count as same-origin here, so lanGuard refuses it first (rebound, 403): a loopback request carrying a browser's marks (Origin, Sec-Fetch-Site/Sec-Fetch-Mode, a Mozilla/ user agent) whose Host isn't this computer's (an IP, localhost, *.localhost, a container runtime's name for the host such as host.docker.internal, MAGPIE_PUBLIC_URL's or MAGPIE_ADDR's host, the machine's own name) needs an enabled gateway key. Agents send none of those marks and pass under any name. Before any of that, lanGuard lets in one request without a key from anywhere: POST /_magpie/claude-mcp/<token> with the token of a Claude subscription run now live (ownCallback, see the Claude subscription bridge), the run's MCP helper calling back to a MAGPIE_ADDR that isn't loopback (#1546). |
gateway.go, cors.go, codex_catalog.go, internal/settings/origins.go |
| Model resolution | serve resolves the model the agent asked for: Claude tier stand-ins, a routing group (provider.GroupFor: its id, the model's id however a vendor spells it, else the one group whose name it is, unless a provider serves a model by that id), auto stand-ins, the agent's own stand-in (StandIn: Codex's config.toml model when magpie is its provider, for a name it sends that magpie doesn't serve, such as its auto-review's codex-auto-review), itself taken through GroupFor and auto stand-ins so a config naming a group bare reaches it, then provider.Resolve. A Codex memory call or auto-review (x-openai-subagent: guardian, or codex-auto-review) that still names no served model goes to the model Codex's last turn was answered on (codexMemoryStandIn, per agent and gateway key), so a Codex on magpie through another provider table, a profile or another computer isn't answered 404 (Adam on Discord, TestCodexAutoReviewReachesItsTurnsModel). A bare model id several providers serve (MOMO on Discord: glm-5.3 under opencode-go and a6api) is never refused: with found groups on (the default) GroupFor takes it to the group magpie found for it (auto-<slug>), its members in the Providers order, routed and failed over as any group, a conversation staying with the member that answered it while its cache is worth it (affinity); with them off, Resolve takes the first provider in the Providers order that exposes it, with no fallback. magpie writes only provider/model ids into agents' configs (magpieModels), so a bare id is one the user wrote. Every reply says who answered in X-Magpie-Provider and X-Magpie-Model (noteMember), and the usage log and the Routing page keep it. A model id with ~ and no slash that resolves as nothing else is the one served id (a provider's model or a group) whose slashes it spells as ~ (unflat, provider.Unflat; MiniMax Code's spelling, #1387), taken back in validateModel before key limits, middleware and usage see it; two ids spelled alike are neither. A Claude model id whose version is dashed (relay/claude-opus-4-6-us, with or without :level and [1m]) that is not served as spelled is the one served id it dashes (provider.ClaudeUndashed; the spelling magpie gives Claude Code, which reads a dotted version as Claude Opus 4), taken back in validateModel and unprefixed the same way. An unknown model gets a 404 naming why: a switched-off provider, a disabled group or an empty group. Otherwise it names up to three ids nearest to what was asked (provider.Closest: words of a model's display name count before words of its id, and a provider's id or name only alongside them, so "Zen-Space-Bunny" is told opencode-zen-free/space-bunny-free, MOMO on Discord), then the ways a model can be named, then every id (unknownModel; chat and embeddings). |
gateway.go, internal/provider/group.go, internal/provider/flat.go, internal/provider/claudedash.go |
| Candidates | plan lists one provider's candidates: one per key or account on, then each Fallback model, with resting ones last (restLast). planGroup and planLevel weigh a group's members together. A nested group plans by its own routing (#576). So does a member whose provider routes other than Smart (ownRouting): weighed as one by its first not resting (firstAwake), tried whole in its own order; leastHeld leaves such a group's order alone too. A provider on Smart, or routed as the group is, is pooled with the group's other keys and accounts. group_own_routing_test.go. A member's own fallbacks are not the group's. |
fallback.go |
| Order of keys and accounts | Routing: smart (""), order, rotate, usage (least used, with an usageHalfLife of 1h), pace or weight (weightedFirst). Smart, usage and pace weigh a subscription by its allowance (allowances), and a key by its own usage windows when magpie reads them (keyAllowance: a sub2api key given a 5-hour, day or 7-day limit, or a key bought as a plan, such as Kimi Code's or a GLM Coding Plan's); any other key has none. A lone key or account is weighed against nobody, but what it has left is still read into the trace (weighRouted), so the Routing page shows it as it does for several (#1016); all but used up, it keeps its conversation rather than being said to move (affine). A failure rests a candidate (failure, failureOf). |
routing.go, weighted.go, internal/provider/routing.go |
| Limits | Each key or account (a candidate's who()) has at most MaxConcurrency requests out at once (its own AccountConcurrency over it); one more waits in its lane's queue, bounded by QueueLimit and QueueWait and turned away with a 429 past either (lanes.take). MaxRPM (coeo91 on Discord: OpenRouter's free models take 20 a minute) bounds how many requests it sends the vendor in any rolling 60 seconds (rpms), counting each for a second more (rpmSlack), since the vendor counts a request when it arrives and the first on a new connection arrives later by its dial: one more waits for room in the minute, in the order they came, after it has its slot and right before it is sent. A wait that would be longer than 2 minutes (or the provider's QueueWait, when shorter: rpmWait) is turned away at once with a 429 whose Retry-After is when the minute has room; nothing rests for it. An agent gone while it waits gives its place back. Every request that reaches the vendor counts: each try of the candidate loop (a retry, the next key, a fallback) waits in serve, and the requests a try makes on the way and the gateway's own asks (count_tokens, System One's decisions, embeddings, drawing, Kimi's search) are counted by rpmTransport on s.client (metered, paidFor). count_tokens never waits: a candidate with no room is skipped, and the local estimate answers. A full lane or a minute with no room gives way to a ready key or account of the provider or the group (laneMate, ready); a fallback is never asked for want of either. A plugin's account sends through its own transport, so only its tries are counted, not a plugin's own extra requests. Set in the provider editor (Concurrency, Requests per minute, Queue size, Queue wait) or with magpie provider account-concurrency, queue and rpm; a subscription's are kept with its picks. |
concurrency.go, rpm.go, internal/provider/concurrency.go |
| Sink | With Sink on, a key or account that answers 429 while it still has quota goes to the back, behind every one not rate limited since. Held in memory until restart. |
sink.go |
| Affinity | A conversation stays with the key or account that answered it, so the vendor's prompt cache is read again. Modes: auto (""), session, turn, off. Stored in affinity.json next to providers.json. |
affinity.go |
| 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 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. 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) is remembered in unfit until magpie restarts. 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; 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. |
gateway.go |
| Trace | The Routing view's record of each decision, written where the decision is made: candidates, rests, which try answered. | trace.go |
| 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 masked copy is kept all the same. 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, its text is gone. 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). |
prompt.go |
| Vertex AI | A Google Vertex AI provider speaks Gemini alone. A request goes to <base>/publishers/google/models/<model>: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, gateway.go, codeassist.go, gemini.go, gemini_signature.go, search.go |
Runtime path
handle(proto)reads the body and the model (requestBody,requestModel), then callsserveAgent. Every route that reads an agent's body (each API, count_tokens, Gemini's, embeddings, images, videos, System One, the Codex backend path) reads it throughreadBoundedRequestBodyinrequest_bounds.go. It decodes aContent-Encodingofgziporzstd(decodedBody; Codex sends zstd to a custom provider's/v1/responsestoo, #1223) and drops the header, so the provider is sent plain JSON. The size limit holds for the decoded bytes (413), and any other encoding is refused 415.keyLimitedreads a limited key's compressed body the same way, so its reservation is the decoded size.serveAgentruns the middleware chain, thenserve.serveredacts secrets in the request (redacted;redact.MaskJSONleaves ids alone, and what the vendor sealed with a signature, a thinking block, Gemini's thoughts or Responses' encrypted reasoning, goes back as the vendor wrote it: only the values masked elsewhere in the request, and secrets masked before, are put back as their placeholders; a value masked once, at least 8 characters long, is masked again wherever a request has it, as an exact match whatever words are around it, so what the vendor wrote about a placeholder doesn't go back with the value in it,redact/known.go), resolves the model to a provider or a group, and refuses what can't be served. A request whose provider and fallbacks, or whose group's models, all skip redaction (unredactedRoute,provider.SkipsRedaction: set Send requests unmasked,Unredacted, with every address on this machine or the local network) goes to them as the agent wrote it; the log and recent calls keep the masked body. count_tokens and embeddings follow the same rule.- With Mask personal data on, each kind in
redact.Categories(internal/redact/more.go) is masked unless the user turned it off (redactKindsin settings,Options.Kinds). On by default: US SSNs, passport numbers, IBANs that pass mod 97, birthdays next to a word that says so, MAC addresses, and serial numbers next to S/N or the like. Off by default: the user name in a home folder, user@host in a prompt or ssh command, public IPv4 and IPv6 addresses (never private, loopback, link-local, CGNAT or documentation ranges) and cloud bucket names, since agents send them in nearly every request and the model must copy the placeholder exactly inside a path or URL. Context rules run only near their words (rule.matches). The Settings rows come fromREDACT_KINDSin app.js, whichTestRedactKindsAreRedactsholds to the same ids and defaults. - With Mask secrets on, the user's own masking rules (
redactRules,redact.Rule: a placeholder name and a prefix or an RE2 pattern,internal/redact/rules.go) run before magpie's. Settings → Privacy adds them, removes them, and edits one in place (POST /api/settings/redact-rulewith the rule's index and its current value,editRedactRuleininternal/gui/api.go). Every rule is checked byredact.CheckRuleswhen settings are saved; an edit that doesn't compile, matches the empty string, repeats another rule or names a rule no longer at that index is refused with the rules left as they were. The gateway reads the rules from settings on each request (redactionOptions), so a change applies to the next request. DecidesModelgives a 400.- A gateway key held to some models (
keyHolds, #882) gets a 403 for any other model. - Sealed tasks (#619) are checked here. A Codex subagent's task its lead's
spawn_agentsealed goes only to a ChatGPT account, or back to the Responses provider that answered the lead (leadProvider, a relay of the ChatGPT backend such as Sub2API, #1109), relayed as it came even when web search is offered. A lead's turn carrying its subagent's sealed reply (send_message) goes back to the Responses provider that answered the lead's own conversation (leadProviderof the request'sconversationID, #1237); otherwise it is refused before anyone is asked (sealedReader,sealedTaskError). A sealed message (Message Type: MESSAGE, not a task) that nobody asked can open is left out instead, aninput_textnote naming its sender in its place (withoutSealedMessages, #1613): a lead on a chat provider whose subagent is on one of Codex's own models goes on, as the subagent's final result still reaches it as text. Only a sealed task (NEW_TASK, or an item with neither header) is refused. Who answered is first what affinity remembers; when affinity has let it go (a day since, a restart past the 512 conversationsaffinity.jsonkeeps, or the lead's last reply broken off,unanswered), the usage log's answers to the lead's thread and the request's own conversation in the last 30 days count too (loggedAnswers, #1367), andleadFirstreads the lead's key or account from them. A refused or failed call and a title answer nothing, and Codex's own sign-in is told of as the ChatGPT backend. The refusal names who sealed the task when it is known, and says how to go on with it. - A model set for Codex's subagents (
settings.CodexSubagentModel, the Agents page's Codex "subagent model", willz on Discord) is put on a Codex subagent's request (x-openai-subagentread askind:collab_spawn) before this check, whatever model its lead'sspawn_agentasked for (codexSubagentPickincodex_subagent.go): incodexBackendfor one of Codex's own bare models, which then goes throughserveAgent, and inservefor any other. Any model magpie serves can be set (provider.SetCodexSubagentModel, #1633): a task handed as text (a lead magpie served on a chat provider, or multi-agent V1) is read by any model. A request carrying a task the ChatGPT backend sealed (sealedTaskIn: a sealed agent message that isn't aMESSAGE, whichwithoutSealedMessagesleaves out) is put only on a ChatGPT account's model; set to another, the subagent stays on the model asked for, which the sealed gate below handles as with nothing set. When magpie doesn't serve the model set now, or a gateway key held to some models may not use it, the subagent goes on the model asked for too. The route trace keeps both models and the reason it stayed (Route.Subagent), and the Routing page'skindWhysays it. The lead's turns, titles and every other kind are never moved. - Rules and image inputs are handled here too.
- A rule by folder (
Rule.Folders,folders=~/work/acme,~/oss; Cario0x on X: routing by the project being worked on) matches when the folder the agent works in is one of them or inside one (provider.FolderUnder,rulefolder.go): at a path's boundary, so/a/bis not under/a/bc;~is the home folder; a Windows drive is one with its WSL mount (C:\workis/mnt/c/work) and a\\wsl$\<distro>or\\wsl.localhost\<distro>share is the distro's own path; case doesn't count on macOS and Windows, nor ever for a drive. A rule outside folders (Rule.ExceptFolders,except-folders=~/big-task; #1606, Ti800) matches when the folder is in none of them, and an agent that says none isn't known to be in one, so it matches; a rule may have both (Rule.ByFolder,inFolders). The folder is read from the request only when a rule of the group has folders or except-folders (workDirinworkdir.go), in each agent's own words, taken from captured requests: Claude Code's- Primary working directory: <path>(its</>as entities;(was <old>)after a change dropped), Codex's<environment_context><cwd>, Pi's<cwd>in the system prompt, and OpenCode'sWorking directory:inside its<env>block. Only the system prompt and the user's and system messages' text count, never the model's words or a tool's result, and the last said wins. An agent that says none has no folder, and nofolders=rule matches it (unknown, never empty). The same reading tells a plugin's fetch where its agent works (provider-plugins). A pause rule may hold by folder too (below). The trace'sRuleHit.Folderis the folder read, and the Routing page tells it beside the rule'sfolder …condition.TestFolderUnder,TestRuleMatchesByFolder,TestParseRuleFolders,TestWorkDirOfEachAgent,TestRuleByFolder,TestRuleMatchesExceptFolders,routing-folder.test.cjs. Rules by folder are never in a shared group (ShareGroupdrops everyByFolderrule). - A pause rule (
Rule.Pause,pause=<model>; John on Discord: a model of the group paused in its vendor's peak hours) leaves the model it names out of the group while it holds (provider.PausedOut, onruleClock): the group's own rules and each nested group's on the way down to a member, a group named taking all its models, and a model named taking it wherever a group in the group has it (#625). It runs before planning, on every request rather than once a turn, so the model is not first, not a failover, and not kept by affinity, and comes back as soon as the hours end. It holds by hours, days, agents and folders only (cleanRulesrefuses another condition), and is not a send-to rule:Matches,MatchRule,ThenUses,Ruledand the compaction rules leave it out. A send-to rule naming a paused model finds it unready and the group routes as without it. The trace keeps what was paused (GroupRef.Paused), and the Routing page says so. Every model paused answers 503 (pausedError) naming each rule. Embeddings go by the same pauses; manual groups have no rules (Live), so none pause there. A pause by folder (#1606, Ti800: a subscription's quota kept for the long task in one folder,pause=<model> except-folders=~/big-task) reads the folder only when such a pause is on the way (provider.PausesByFolder, thenworkDir): outside its except-folders, which includes a request that says no folder (a subagent's or a small model's that doesn't), the model is left out; withfolders=, only requests known to be in them. Embeddings and System One's decision calls have no folder.Paused.Folder/ByFoldercarry what was read, and the Routing page says the folder or that none was said.rules_pause_test.go,TestPauseByFolder,TestPauseByFolderRule,TestParsePauseByFolder,routing-pause-folder.test.cjs.
- With Mask personal data on, each kind in
- Candidates come from
planGroupfor a group orplanfor a provider. They are filtered bysealedReadersandallowedCandidates. An account past its share is held out of the candidates (capHeld): a usage cap's share, each window at its own where the account gives it one (AccountWindowCaps, willz on Discord: 50% of the five hours, 40% of the week) and at the account's cap otherwise, or 100% of a window for a Codex account set not to spend its credits (provider.HoldCaps,WindowCaps.Of,CodexNoCredits). A ChatGPT account's call oncodex-auto-review, which OpenAI counts in no window, is held by no usage cap, only by credits it may not spend (freeOnChatGPT, #1593,TestAccountCapLetsAutoReviewThrough). The account is held while any window is past its own share, andcappedErrorand the trace name the fullest such window's share and cap. When every candidate is held and one held for its credits spends its resets by itself,autoResetspends a reset on it and it is tried (planned.held); otherwise a capped or barred set returnscappedErrororbarredError. Thenaffinemoves the conversation's last answerer first, unless it is resting or nearly used up. AnX-Magpie-Accountheader (AccountHeader) pins the request to one account: only that account is tried, and when it can't answer the caller is told why. - The candidate loop calls
attempton each candidate in turn, through aholdWriter. The writer holds the reply until it is clearly passing. A candidate that fails before anything is sent rests (failure): out of credit for 30 minutes, out of quota until reset, rate limited until retry-after, otherwise a minute and longer on repeats. A 400, 403, 404 or 422 that says the model isn't served (unservedWords) and says nothing of quota, credit or a rate limit rests only that key's or account's model (modelRefused, keyed byrestID, its backoff counted apart): its other models are still served first in order (#1235, SenseNova's 403 "model is not available in the current token plan"). A 400, 404, 410 or 422 that says the model is retired (retiredWords: OpenCode Zen's 410ModelDeprecated"Model exo-free has been deprecated.", whose own model list still names it; MOMO on Discord) rests only that model the same way, is retryable so a group's next member or another provider of it is asked, and is remembered (provider.Retire,retired.jsonbesideproviders.json): the model leaves that provider's entries in the catalog (buildEntries), so /v1/models, every agent's model list and the found groups go without it, until a request on it is answered again (UnretireinservedCandidate) or a week has passed. A refresh of the vendor's list doesn't bring it back early, since that list is where it still is. Aprovider/modelrequest for it is still sent. A subscription account that fails any other way with a window full, by magpie's latest reading of its windows, rests until that window renews. Both quota rests and window rests are held tolongestQuota(8 days), so a reset time read wrong (a year off) doesn't bench the account for that long. The next candidate is then tried. A failed provider waitsfallbackCooldown(1 minute) at the back. The vendor's safety filter refusing a reply rests nobody, whether it refuses the turn before any of the reply is said or once some of it has been said (refused,refusedAfter). The ChatGPT backend's 502 "response protection is unavailable" is about the request's content, not the account: the same history fails the same on each of its accounts and models. It rests nobody, isn't tried again after a moment, and isn't asked of the provider's other accounts or models; another provider left in a group is asked once (protectionRefused,elsewhere). One cause is known (#1270): a history that replays the backend's ownweb_search_callin a request that doesn't declare theweb_searchtool is refused so, whatever the account, model or turn (a plain turn, a thread's description, a compaction, Codex's own text compaction for a custom provider withtools: []). Every request to the ChatGPT backend with such a history therefore declares cached-only search ({"type":"web_search","external_web_access":false},provider.DeclareSearch): an account's incodexBody, Codex's own sign-in relayed incodexUpstreamOn. It goes in the tools, or for Responses Lite (its header,reasoning.contextall_turns, or anadditional_toolsitem already there), which refuses a top-levelweb_search, in theadditional_toolsitem. A request that offered no tools getstool_choicenoneso the model can't search; one with a forced choice keeps it. A history without a search, or a request that declares search already, is relayed unchanged. siwc, API-key requests to openai.com and the legacy/responses/compactare left as they were. - The last candidate's error reaches the agent, with one exception for a group (#1418,
patience.go). When every member has failed in a way that passes (busy: 408, 500, 502, 503, 504 or 529 that isn't a proxy, a quota or response protection, or a 429 that is a short rate limit, not a plan or credit), and nothing of the reply has been sent, the members that failed so are asked again in turn after a pause (replan). The pause isretryPausedoubled each round up toreplanLongest(30s), and never shorter than the soonest Retry-After; a member whose Retry-After ends past the pause is asked after the others. This goes on for at mostreplanRounds(6) rounds and only while the group'sPatiencelasts, counted from the first time every member had failed, when the agent would have had the error (waitFrom;Group.Waits: 0 isPatienceDefault, 60s; -1,PatienceOff, turns it off; at mostPatienceLongest, 240s). A pause that would end past the budget isn't taken, and the agent gets the error. While another member is busy too, the last one isn't first tried again alone (passing): the members take turns, and once the budget has begun, the same-one retries aren't taken either. While the budget lasts, the last candidate's failure is held (newHoldWriter), and a streaming agent is kept alive through the pause with SSE comments (pauseAlive). The try is traced withAgain(the pause),Replan(how many are asked again) andPatience(the budget in seconds). The group editor's "Every member busy" row sets it. A plain provider keeps only the same-one retriespassinggives the last one left. A try that answered is recorded (served,answered) for routing, affinity and usage.
Constraints and failure behavior
- A fallback happens only while none of the reply has been sent. An agent never gets half a reply from one upstream and the rest from another.
- A request is one usage record, counted once by how it ended (小一 on Discord: Codex on credits showed "5,482 · 1,094 failed" while rows said "2 tries/3 tries" and had been answered). The final record carries
trieswhen the route took more than one (rec.Tries, from the trace'sTries). A try a vendor refused or turned away (hw.refused,hw.turnedAway) still writes its own record, for what it billed and why it failed, markedhanded_on;usage.Totals.countskips such a record for calls and failures. A request failed only when the agent got an error (LostRequest); one answered after a failed try is counted beside it as answered on a retry (Totals.Retried,RetriedRequest, theretriedfilter). Logs written beforehanded_onare read the same way: the log index marks a failed, non-rejected record followed by another of the same route id as handed on (routeRowsinlog_index.go). Counts by account or route (vias, window holds) still count every try. - A request whose key is a Claude sign-in (
claudeSignIn:Authorization: Bearer sk-ant-oat…, Claude Code signed in to claude.ai with magpie as its base URL) is never told a 401, nor a 403 saying "OAuth token has been revoked". magpie never passes that sign-in on, so such an answer is a provider refusing magpie's credential, or one of magpie's own Claude accounts lapsing; told it, Claude Code renews its own sign-in before each of its retries (ten for one request) and then asks to/login. Any error whose message mentions x-api-key, whatever its status, Claude Code tells as "Not logged in · Please run /login" too. It is told as a 502 in magpie's words, anapi_errorsaying " refused magpie's credential (HTTP 401): …" with x-api-key said as "API key", and any other error such a request is told keeps its status with x-api-key said as "API key", as does a stream's error after its 200 (keepsSignIn,claude_signin.go). Recent calls and the usage log keep the provider's status and message. Any other 403, and a request with magpie's key or an API key, is answered as before. The sign-in's beta (oauth-…inanthropic-beta) isn't passed on either (askedBetas), so a provider gets the request as Claude Code with magpie's key sends it; a provider's ownheader.anthropic-betastill goes. - A 2xx that can't be an API's answer is the 502 it stands for (
notAnAPIReply, #1012): a web page (text/html, or a body that begins as one: a sign-in page, Cloudflare's challenge), a body with nothing in it, or one sent as JSON that doesn't begin as JSON. Every upstream request goes through it (forwardOnce, and the built-in clients' own: the ChatGPT backend's/responses, Kiro, Zed, Qoder, Devin, Cursor, Command Code), so it fails over, rests and is logged as a 502 does, its reason naming the page's title. Only the first bytes are peeked, which a stream waits for anyway, and a compressed body is left as it came. - A streamed request is never left silent while its vendor says nothing.
holdWriter.watchruns beside each try: pastkeepHeldAfter(15s) it sends a held try's agent the stream's 200 and SSE comments (keepAlive), none of the try, so another candidate may still answer in the same stream; once the reply passes, it puts a comment between two of its lines afterkeepaliveEveryof quiet. It stops afterkeepaliveLongest(5 minutes) with nothing from the vendor. A try waiting for its key's or account's slot or for room in its minute (lanes.take,rpms.wait) is kept alive the same way (keepQueued), for as long as it waits; once the 200 is out, the try is held, and its failure or its queue turning it away reaches the agent as the stream's error (failTo), not a status (coeo91 on Discord). A wait shorter thankeepHeldAftersends nothing, so its 429 keeps itsRetry-After. A proxy in front such as Cloudflare (125s) otherwise ends the request (#947). Gemini streams get no comments (#934). A vendor that then ignoresstream:trueand answers 200 with its reply whole has it sent as the agent's stream (wholeAsStream: Chat, Responses, Anthropic), not as the stream's error, while a stream under a type that says neither JSON nor a stream goes through as it comes (sseStartreads its first bytes); a 200 that is no reply of the protocol's fails as a translated reply that didn't stream does (502, "… did not stream"), for the next candidate to answer, and the last one's reaches the agent as the stream's error. A held stream that has sent nothing but the frames before a reply (response.created,response.in_progress,codex.rate_limits, pings, an empty part begun:eventLead) stays held as long as its agent is kept alive, up toholdLead(4 minutes, under the 300s Codex waits for an event;keptQuiet), so aserver_is_overloadedthat comes after it is a failure the next candidate answers (#1418: let through at 15s, the ChatGPT backend's failure 36s in ended Codex's turn with sub2api, next in the group, never asked). A stream whose agent can't be kept alive (Gemini's) is let through afterholdLongest(15s), as before. Codex counts only events toward that 300s, not comments, so the bound is the request's, not each try's: once Codex on Responses has heard no event foragentQuietMost(4 minutes) since the request began or its last event (keptAlive.tooQuiet), the try in hand is let through (scan,keepQuiet), and no group replan or same-one retry is taken whose pause would end past it (fadenoob on Discord: held tries and replan pauses added up past 300s and Codex reconnected on "idle timeout waiting for SSE"). A translated reply whose upstream stream stops before it said its reply had — an Anthropic one with no stop_reason and no message_stop, a Responses one with noresponse.completed, the same two a relayed one is told by (sniff.whole; a Chat stream may end without[DONE]and be whole), a Gemini or Code Assist one whose last chunk has no candidate'sfinishReason(geminiEnds, #1643:usageMetadatais no end, Vertex AI sends it on every chunk; a chunk with no candidate at all is the empty reply's to answer, #667), and a relayed Gemini one told the same way (#1644; it ends in Gemini's own{"error":{"code":502,…,"status":"UNAVAILABLE"}}data line fromstreamFailure,TestGeminiRelayEndedShort) — ends the turn with "the reply ended before it was complete" (errEndedShort,TestResponsesUpstreamEndedShort,TestGeminiUpstreamEndedShort), asked again in place where the upstream goes on from a prefill (continuation.go). A client that asked for no stream is told the same 502 of such a cut (translate,TestNonStreamEndedShort,TestGeminiNonStreamEndedShort), rather than handed what came as its whole reply. - Claude's, GPT's and Gemini's reasoning is held (
refusesAfterThinking, up toholdThinking, 4 minutes) so that a refusal after it goes to the next candidate unseen (#248). It is held only while one could: on the last candidate a refusal isn't asked again, so Claude's and GPT's reasoning streams as it comes there, and a refusal after it reaches the agent as the vendor's own. Held there, a lone relay's Claude or GPT showed Claude Code its thinking all at once with the text, and Codex none until then (iTianbao on X). Gemini's stays held on the last candidate too, for a reply that only reasoned to be asked again (#667). Any other model's reasoning is never held. - A streamed reply stuck in a loop is ended, not let run to its output limit (#1359, Moody-Sin: WorkBuddy's DeepSeek v4.1 flash reasoned round "Now." "Writing." "Go." "Let me write." "OK." until max tokens while dsh and Pi waited).
holdWriter.Writefeeds every streamed try, passed through or translated, a key's, a built-in subscription's or a plugin's (a moved WorkBuddy's fetch in the plugin host,TestLoopEndsWorkBuddysReply), in each of the agent's protocols, to aloopGuard(loop_guard.go). It cuts the reasoning and the text, each apart, into units, its lines and sentences (a list's1.or a decimal is no sentence's end), compared without case or a closing stop. A unit with no word in it (a letter run with no digit: not a brace, a rule,0x00, a hash or a row of numbers) isn't counted. When the lastloopWindow(256) counted units of either are among no more thanloopDistinct(24) different ones, the try is cut (cutLoop): what came with that write goes out, then the protocol's stream error (streamError, 502) naming the loop and quoting its units, and the vendor's request is cancelled. It falls back to nobody and rests nobody (failLoop); its usage record's error type isreply_loop. A reply magpie translates into the agent's protocol (streamTranslated) whose reasoning loops before it has said a text or a call, and isn't a continuation, is asked again once in place instead (loopReasks, throughholdWriter.onLoop; cdredfox on X, WorkBuddy AI's DeepSeek v4 flash): the agent keeps the reasoning it has, the next try's follows it in the same stream, as an empty reply's re-ask does (#667), and only a loop on that try ends the reply with the error (TestReasoningLoopIsAskedAgain). A loop in the text, or after a text or call, is ended at once (TestLoopAfterTextIsNotAskedAgain), and so is a Chat stream passed through as it comes, whose bytes aren't magpie's to splice. A cycle need not be exact. Code, tables, lists, logs, CSV and base64 differ line to line or have no words, and don't trip it (TestLoopGuardLeavesOrdinaryRepliesAlonefeeds magpie's own sources and docs through it). A reply sent whole (no stream, or Gemini withoutalt=sse) isn't read. Settings › Models › Replies › Stop looping replies (noLoopGuard) turns it off. - The order of the steps a request's accounts go through, how much the accounts' own order (Make first) counts under each routing, and how often an allowance is read are described for users in How magpie picks an account. Smart compares renewals window by window, biggest first, each truncated to the hour (
weighRouted), so the order decides only when every window falls in the same hour. A window's renewal is its reset, or, when what it has left runs out sooner or it has no reset, that moment (Limit.RunsOut, fromQuotaWindow.RunsOutAt;Allowance.Renewal): the WorkBuddy plugin (0.1.14) sends it on its Credits window as the soonest end of a package with credits left (cdredfox on X). Only Smart reads it; Weekly pace, the 90%/98% tiers and rests go by the window's share and reset as before. Affinity keeps a conversation on an account at 90–97%: onlySpentShareOf(98%, 100% In order) stops it (affine), while the 90% tier (lowShare) orders only conversations nobody has answered. - A turn's end is told to the app for the "Task done alert" notification (itieniu on X,
turndone.go). The trace follows each agent session's turn (turns, keyed by agent and session): a request is of the turn unless it has aKindor is a Claude Code subagent's (agentTurnOf), and its reply is scanned on the way to the agent for a tool call in any wire format (toolScan, a JSON value such as"type":"tool_use"or"finish_reason":"tool_calls", never a key or text). The turn is done when no request of it is going, the last reply was whole, under 400 and called no tool, and nothing more came forturnQuiet(4s); a session idle pastturnStale(30m) starts over. Only a turn that ran at leastsettings.TurnDoneAlertseconds is told (TurnDone, set by the GUI; nil undermagpie serve, so nothing is followed). The ChatGPT backend path (codexBackend) is followed the same way.TestTurnDoneSaidAtTheTurnsEnd,TestTurnDoneCodexBackend,TestToolScan,turn-done.test.cjs. - A resting candidate is tried last, never dropped (
restLast). A lone candidate is tried even while it rests, because there is no other. - Routing decides who goes first only when nobody has answered the conversation yet. Affinity keeps the answerer while its cache is worth it. Auto mode keeps it across turns while at least
cacheWorth(1024) tokens were read from the cache and the cache isn't cold (cacheCold, 5 minutes). - In turn (
rotate), a conversation nobody has answered yet goes to the key, account or model the fewest other conversations of the provider's model or the group answered in the lastheldFor(30 minutes) are on (leastHeld, #946). Ties, resting ones and a group with a group in it keep routing's order. With session affinity, two sessions of one group so stay on different models. - A ChatGPT account that holds credits answers past its windows on them; the vendor spends them. That is the default. Set not to spend them (Usage card's Use credits,
magpie quota credits <account> off), the account is held at 100% of a window till it renews, by magpie's latest reading of its windows (provider.Allowances, refreshed about every minute), so the other accounts, groups and fallbacks take the request. A cap set on the account (1–99%) takes precedence. Unlike a cap, the hold is at the vendor's own 100%, so an account allowed to spend its resets spends one there, both when every candidate is held and after the last one is refused. A reset made forgets the account's cached allowance (renewedNow), so neither hold outlives the windows it started again. - Different failures are classified separately: out of credit, out of quota, rate limit and other errors rest for different lengths. A fix must not merge them into one bucket (see #873).
- A sub2api key out of its own limit answers 429
api key 7天限额已用完(or日限额,5小时限额) asrate_limit_exceeded. It is out of quota (plannedWords), not rate limited: it rests till the window it filled renews when its windows as last read say so, elsequotaRest, and its windows are read again (staleKeyAllowance). A reading that finds that window full no more (the limit raised in the relay's panel, or the key's usage reset) lifts the rest (renewed, told throughprovider.OnRenewed), as a Codex reset spent does an account's; the key's other rests stay. While it rests out of its windows, they are read again each time it is planned (restingOf, once a minute at most), so this holds where nothing weighs it by them: an ordered group. The relay out of accounts for everyone (503No available accounts, or a later version's 429All available accounts are currently rate-limited) says nothing of the key's windows: it backs off as any failure or rate limit does, never to the window. A key's windows count only its own spend, so other users draining the relay's accounts show up as those errors, not in the windows. - A 5xx is a server error, not quota, unless the vendor's own quota code says so (
quotaCodes:usage_limit_reached,RESOURCE_EXHAUSTED, Claude Code'susage limit reached|<unix>). A relay's 500 "当前模型 gpt-5.5 负载已经达到上限,请稍后重试" names its load, not the key's allowance: it was read as out of quota byusedUpWords(上限), which rested the key till a reset and kept a group's Patience from waiting it out (#1418). The quota words (usedUpWords) still apply to a 4xx. - An account resting out of its window (a Claude account by the time Claude Code's refusal named,
resets, or any bywindow) is back once magpie's reading of its windows (provider.Allowances) finds it full till sooner: the window used belowSpentShareOf, or its reset passed, with no other window over the same models still full. The reading tellsprovider.OnRenewedas the account'sUsageAgentand user, andrenewedlifts that account's rests out of quota or bywindow; its rests for a rate limit, its credit, a verification or a failure stay, as a key's do, and so does every rest of other accounts still out of their windows. Planning reads every account candidate's allowance, ordered groups included, so this needs no step of its own inrestingOf. - Only an account is held at a usage cap (
capHeld) or rested out of one model's pool (pooled); a key's windows order it and rest it, nothing more. - Codex offers its image tool (the
image_gennamespace, #870) to every magpie provider. When a provider other than a ChatGPT sign-in or openai.com answers a bare 400,attemptasks it once more without the tool (image_tool.go). This happens both passed through and translated. If that works, the provider is marked unfit for the tool (tool:image_gen) and isn't offered it again. If it doesn't, the tool is restored and the 400 stands (#949). - A turn the agent stopped with its tool call still out is replayed by the client with the call and no result, and Google's APIs turn a history whose call turn goes unanswered away with 400, every later turn of the conversation with it. The Gemini build (
buildCodeAssistSent, which serves a Google sign-in, Vertex AI and a custom provider's Gemini API alike) answers such a call with the synthetic result the chat build pairs an interrupted turn's call with (pairToolMessages, #1275), right after the calls (pairFunctionTurns, #1560): beside the answers the client sent there, or in a user turn of its own before what the user said, since a turn mixing afunctionResponsewith text is turned away too (#1533); a Claude model on Antigravity gets it in the one tool_result turn. A call with no id counts as answered by a response of its name. - 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'sX-Models-Etagtagged withprovider.CodexListTagso 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 withprovider.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 iscodex-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). - 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 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; eventsKThinkStart,KSealed,KTextSiginir.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'sredacted_thinkinggoes back raw (to DeepSeek as a thinking block, below), and a thinking block signed with no text keeps its signature (aBlockstill writes"thinking": "", #1447), on Claude's subscription too. A Responses reasoning item keeps its id, summary andencrypted_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'sthoughtSignaturestays 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 getsskip_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<n>__), so an id a client shortened carries no signature and the call goes as unsigned (#1536); it gets no one else's seal. Carrying reasoning across APIs (an envelope) isn't done. - 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) unlessstoreis 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:paramisinput, or the error names an item by id), as a relay in front of OpenAI does with a message of its own,passthroughasks 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. When a provider answers its summary request 404, or 400 for an item it didn't find (itemNotFound, a relay in front of either),codexCompactasks once more with the conversation as text (plainCompact), then compacts locally (#866, #1008). 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, acompaction_triggeron/responsesthat wants exactly one compaction item back, on any provider table named "OpenAI", as CC Switch names its relay tables. magpie points those at/v1while a magpie model is on, sohandlemakes the summary there too (codexInput,codexCompact), and magpie's summaries go back to the model as text (#1301). - A Chat upstream that wants a turn's reasoning back (
chatReplaysReasoninginchat.go: a host or a model, as magpie or the provider names it, withdeepseekin it, such as OpenCode Go'sdeepseek-v4.1-flash, or Command Code's plugin) gets every assistant tool call withreasoning_content, relayed (withReasoningOnToolTurnsinpassthrough) or translated (buildChat). DeepSeek turns the whole request away ("Thereasoning_contentin the thinking mode must be passed back to the API") when a tool call made since the user's last message has none, which a client sends for a turn it saw no thinking on: another model's, a translated one (#1462). The turn's own thinking goes back as it came; one sent inreasoningorreasoning_detailsis copied in; otherwise it goes with a space (noReasoning: DeepSeek's Chat API takes an empty one, but a relay that leaves empty fields out would drop it). A reply without tool calls, any other model and Mistral (#494) are sent as before. - A Responses upstream that wants a turn's reasoning back (
replaysReasoninginresponses.go: a model withdeepseekin its name, on any host but OpenAI's, xAI's, Copilot's and Azure's) gets every reasoning item with areasoning_textand every tool call after one, relayed (withReasoningTextinpassthrough) or translated (buildResponses). DeepSeek's/v1/responsesturns the whole request away ("Thereasoning_textin the thinking mode must be passed back to the API") over a reasoning item without text, one with an empty text, and afunction_callwhose step (since the last user message or tool output) has no reasoning item. Codex sends all three in a routing group that falls to DeepSeek after ChatGPT: the backend's sealed items (encrypted_contentonly), magpie's summary-only items, and another member's calls with none (#1104, #1592). An item's own text is kept; one without gets its summary, else a space (noReasoning); a step without one gets a reasoning item holding a space before its first call. A sealed item keeps its id andencrypted_content. - A Messages upstream that wants a turn's thinking back (
anthropicReplaysThinkinginanthropic.go: a host or a model withdeepseekin it, neverapi.anthropic.comor a Claude model) gets a thinking block on every assistant message with atool_use, relayed (withThinkingOnToolTurnsinpassthrough) or translated (build, which also keeps unsigned thinking as its text there). DeepSeek's/anthropic/v1/messages, thinking (its default, or asked for), turns the whole request away with 400 "Thecontent[].thinkingin the thinking mode must be passed back to the API" when such a message has none, and answers anyredacted_thinkingwith 422, a block it can't read. Claude Code sends both in a routing group that falls to DeepSeek after Claude (#1611). A message with no thinking gets one holding a space (noReasoning) first; Claude'sredacted_thinkingbecomes that block, or is left out beside thinking of the message's own. Signed thinking, DeepSeek's own and every other message go as they came. Checked against the real endpoint on 2026-10-11: it takes Claude's signed thinking, unsigned thinking and a space, anywhere in the message. - A Grok model writes a whole number in a call's arguments with a fraction of zeros (
2500.0,17277.0), whoever serves it: the Grok subscription or its plugin, xAI, OpenRouter or a relay. Codex reads its integer fields as u64, usize or i32 even though their schemas saynumber, so serde turns away the whole call (#1431). In a reply to a request whose model, as magpie names it or as it is sent upstream, has a last/segment beginning withgrok(grokModel,grokServed), every number in a call's arguments written with a fraction of zeros and no exponent loses the fraction:2500.0becomes2500,-3.00becomes-3. Strings, keys, other fractions (2.5,2.50) and exponents (1.0e3) stay as written. No tool schema is consulted, since JSON has one number type. The rule runs over the arguments as a stream of text (wholeNums), holding back only a fraction of zeros until the next byte. This gives the same arguments whether they come whole or in deltas cut anywhere, so what a call's deltas add up to is what its done events say. Relayed replies are rewritten inpassthroughbyintTidy: Responses' function_call items, argument deltas and done events and the completed response; Chat'stool_callsdeltas and messages; Messages'tool_useinput andinput_json_delta, streamed or whole. Translated replies are rewritten at the encoder (wholeEncoder, outsideusageEncoder) and atrender(wholeResult) whenRequest.Grokis set. Any other model's reply is relayed byte for byte (grok_integral.go). - Structured output is carried across every translation (
Format,format.go). It is read from Responses'text.format, Chat'sresponse_format, Anthropic'soutput_config.formatand Gemini'sresponseMimeTypewithresponseJsonSchema/responseSchema:json_schemawith its name, description, schema and strict, orjson_object. Each upstream is asked in its own field:text.formaton Responses,response_formaton Chat,output_config.formaton Messages, andgenerationConfig.responseMimeType/responseJsonSchemaon Gemini and Code Assist. An API with no name for it getsresponse. Messages and the Claude subscription's--json-schematake a schema only, sojson_objectis told in the system prompt there (inSystem). The bridges to a vendor's own API (Cursor, Devin, Kiro, Qoder, Command Code, Zed) are always told in the system prompt. A 400 or 422 that names the field (refusesFormat: DeepSeek's "This response_format type is unavailable now", a schema Anthropic can't hold) marks the provider and model (formatRefused), and the request is asked again with the format told in the system prompt, as are later requests to that provider and model. A relayed request keeps its format as sent. A Gemini client's format is also still told in its system prompt, as before. - Group members are
provider/model[:effort]. A member with a fixed effort is asked for that effort, bounded by the group's levels (#671). - An agent whose config can't carry an effort has one picked in magpie (
provider.AgentEffort, settings'agentEfforts; Cursor Private Inference's row, #1003). It is asked for on that agent's requests to a model that reasons (Provider.Thinks), in place of the level the request sent, fitted to the model's levels and bounded by the group's. Order: a member's fixed effort, then a model's:effortsuffix, then the turn's pick (a routing rule's), then the agent's pick, then the request's own. A model that doesn't reason is sent as asked; the default (none picked) leaves every request as it came. The pick beats the request's own because Cursor sends its own default as often as a real choice. Picking Default hands the choice back to Cursor. - Gemini's OpenAI-compatible API (AI Studio's, or a proxy in front of Gemini on this computer or the LAN:
geminiCompat) is asked for the model's thoughts inextra_body.google.thinking_config. A 400 or 422 whose error namesextra_body,include_thoughtsor thinking at all (refusesThinkingConfig) marks the provider unfit for the field (thinking_config), and it is asked again withreasoning_effortalone. Gemini 3 can't stop thinking, so reasoning turned off goes atminimal, its least, or at the model's lowest level where it has nominimal(geminiLevels: those of the model's levels it hasn't turned away, or of Gemini 3's where its own aren't known or none is left). Gemini 3 turns away a level the model hasn't with a 400 that names the level (geminiRefusedLevel): AI Studio's "Thinking level MINIMAL is not supported for this model. Please retry with other thinking level." for gemini-3.8-flash, Vertex AI's "Thinking level is unsupported: THINKING_LEVEL_MINIMAL". It names thinking too, but isn't the field turned away. The level is marked refused for that model (levelRefused), and the model is asked again at the nearest level it has left, still for its thoughts, and at that level from then on. A level turned away again, with none left, is the client's 400. Passed through, a Chat client's ownnoneorminimalthat Gemini turns away this way is asked again at the model's lowest level (onEffort), and that level goes at the lowest from then on (turnedAway); the other still goes as sent, as AI Studio takesnonefrom gemini-3.8-flash. A refusal that names the levels the model takes (effortLevelsNamed, Command Code's for Qoder'snone) marks reasoning off as a whole (offRefused): both go at the lowest from then on; one that lists the other among the levels taken (otherOffNamed, quoted, OpenAI's for gpt-5.1'sminimal) marks only the level turned away. Both routes read and write the same marks. Vertex AI's OpenAI-compatible API marks each streamed chunk of thoughts in the delta'sextra_content.google.thought, and such a chunk is read as thinking. - A Claude that thinks only adaptively (
adaptiveOnlyinanthropic.go: Opus, Sonnet and Haiku from 4.6 on, Fable and Mythos 5 and 5.1, read byclaudeVersionhowever a relay spells them) is never sent a thinking budget, which they answer with 400. magpie's own request from a Chat or Responses client (buildAnthropic) goes asthinking: {type: "adaptive", display: "summarized"}with the effort inoutput_config.effort, so the client sees the reasoning Opus 4.7 and later otherwise leave out (displayomittedby default), and a relay that refusesdisplayis asked again without it (refuseShapes); a client'sthinking: {type: "enabled", budget_tokens}is turned into the same inforwardOnce(adaptiveThinking), the budget as its nearest effort, abovehighasmax, anddisplay: "summarized"unless the client named its own display, so the thinking that enabled shows stays shown (the refused shapes are taken out after it, andrefuseShapesreads the display as it is sent); and Pi, dsh and omp are written to ask it adaptively (AdaptiveThinking:forceAdaptiveThinking, omp'santhropic-adaptive; #1470). A client'sxhighgoes asxhigh, except to Opus and Sonnet 4.6, which have noxhighand are askedmax(noXhigh, #1471). - A request to an Anthropic endpoint that turns thinking off is sent as the model takes it (
thinkingOffAsTaken, inforwardOnce, so relayed requests, count_tokens, magpie's own thinking-off and retries all get it; the model is read as the vendor names it, from the body, or from the path for Bedrock and Vertex). Claude Sonnet 5.5 refusesthinking: {type: "disabled"}and is sent{type: "between_tools"}alone, at efforthighat most. Opus 5.5, Fable 5 and Mythos 5 refuse it at every effort and are sent no thinking, at effortlowunless one was asked, withclassifierRoomadded to a reply limit below it, as Claude Code does. Opus 5 and Haiku 5.5 take it only up tohigh, soxhighandmaxare asked ashigh.between_toolssent to any other Claude goes asdisabled, or as none where that is refused too. Other vendors' models, older Claudes and later lines than these go as they came (#1454). A Sonnet 5.5 by a name these rules can't read, answering 400 that asks forbetween_tools(asksBetweenTools), is asked again with it, once; a refusal ofdisabledat any effort (thinkingOffRefused) is asked again with thinking left to the model, asalwaysThinksis. - A Chat or Responses client's reasoning turned off (
none,ThinkOff), translated to an Anthropic endpoint (buildAnthropic), goes asthinking: {type: "disabled"}; it went as thinking at a 4096-token budget before (#1636). A model that refuses it (alwaysThinks,mandatoryReasoning,thinkingOffRefused) is asked again at its least (thinkingBackOn), andmarkUnfit(offRefused)sends it so at once until magpie restarts. A translated request's level can differ from the one asked:noneandminimalgo aslowwhere the model's levels don't say it stops (effortOf). The route keeps the level asked; the try, the usage log and Routing's "went" say the one built (noteWireEffort,wireEffortinwire_effort.go). Gemini's builders say theirs their own way and are logged as asked. - A request to an Anthropic endpoint with
temperature,top_portop_kreaches a model that refuses them without them (samplingAsTaken, besidethinkingOffAsTakeninforwardOnce): Opus 4.7, 4.8, 5 and 5.5, Fable 5, Mythos 5, Sonnet 5 and 5.5, and Haiku 5.5, whose 400 is "temperatureis deprecated for this model" (Claude Code's auto mode classifier and magpie's own classifiers ask at temperature 0). Older Claudes, Haiku 4.5 among them, other vendors' models and later lines go as they came (#1454). A Claude by a name these rules can't read, answering that a sampling parameter is deprecated (samplingDeprecated), is asked again without them, once — a Chat or Responses client's request translated to Messages (forwardTranslated) as much as a relayed one. - Claude Code's billing line (
x-anthropic-billing-header: cc_version=…; cc_entrypoint=…; cch=…;, its own first system block,cchchanging every turn) goes on only to a Claude model asked on Anthropic's Messages API (keepsBillingLineinbilling_line.go: Anthropic's, a relay's, Bedrock's), as Claude Code sent it. Anywhere else it is left out, the rest of the system as sent (withoutBillingLine): a vendor's model relayed on Messages (passthrough), every translation to Chat, Responses or Gemini (forwardTranslated, Claude models too), and the subscriptions asked through their own clients' APIs (Cursor, Devin, Kiro, Qoder, Zed, Command Code's Go plan, inattempt). Kept, a vendor read it as the prompt's first words and its prefix cache missed from byte 0 every turn (#1600, justrun1983: 4% read from DeepSeek's cache behind Command Code's plan). The Claude subscription's run sends its own (withoutBillingHeader), another magpie decides for the provider it picks, and Code Assist (Antigravity, Gemini CLI) is sent it as before, whichantigravityTurnsAwayreads (#666). - A model that refuses a conversation ending with the assistant's message (
refusesPrefill: OpenCode Go's Claude models over Messages, "This model does not support assistant message prefill"; Volcengine's Agent Plan, "…for a model that does not support prefill"; Gemini's, "Requests ending with a model turn are not supported") is marked for that provider, model and API (prefillRefused, #1447); the provider's other models keep their prefill (prefill.go). A Chat or Responses client's conversation ending with the assistant's message, which those APIs read as a turn already said (Request.LastIsTurn), is asked again with a user turn after it (continueText), translated (forwardTranslated) or relayed (passthrough,userLastBody), and so from then on. An Anthropic client's prefill is its own ask and gets the refusal as sent. magpie's own continuation of a cut reply (continuation.go) isn't asked of that model again; the try the model refused ends the reply with what cut it, not with the refusal. A request magpie builds in Gemini's own shape (buildCodeAssistSent: Vertex AI, Gemini CLI's and Antigravity's Code Assist, Factory) never ends with the model's turn, which all of them turn away: a user turn goes after it,continueText, orcompactLastTextwhen an agent is compacting with its ask in the system prompt (modelLastAsk), as one goes before a history that opens with the model's. Nor does it send a user turn that mixes a tool'sfunctionResponsewith text, which Vertex AI answers with the same "ending with a model turn" (#1533: Codex's compaction prompt after a tool's output): what the user said goes in a user turn of its own after the tools' responses (hasResponse), except for a Claude model on Antigravity, whose tool_result turn holds both. - A model's reply limit is published within the window beside it (#1438,
provider.OutputWithin,Entry.PublishedOutput):/v1/models'max_output_tokens(modelObject), Cursor Private Inference'scapabilities.max_output_tokens(cursorLocalModel), Muse Code'slimit.output(museModels), the GUI's model and group rows (providerInfo,providersState),magpie model output, and every agent's file (agent.maxTokens, #338). The window and the output can come from different sources: Grok's backend lists grok-4.7's 256000 window, and models.dev fills its 500000 output (catalog.DecorateandProvider.replyLimitfill an output only where the vendor gives none). An unknown window or output is published as it is. The catalog keeps the unclampedEntry.Output, and a group's member is still asked for no more than that (outputLimit,withMaxOutput), so a request isn't lowered by the clamp. A limit the user set stays in their settings as they set it (TestModelListsKeepOutputWithinTheWindow).
Remote magpie APIs
A remote provider serves the conversation, token-counting, System One,
embeddings, rerank, image generation/edit and video creation/status/content
APIs. Gemini clients enter through the local Gemini adapter and follow the
same model routing as other conversation clients. Responses uses HTTP/SSE;
its WebSocket route still answers 426. Discovery and older-peer behavior
are described in Providers and accounts.
GET /v1/magpie/limit (keyLimit in
key_limit.go) answers the limit of
the gateway key the request carries (access.Caller) and of no other: it
reads nothing from the request but its key. A local magpie asks it with
each of its remote-magpie keys for that key's card on its Usage page
(#1547).
System One uses RouteDecider and postDecide in
decide.go, taking one provider prefix
off at each hop and preserving the state, questions and vendor errors.
A model naming a group of decision models (provider.Group.Decides: every
member a decision model; cleanDecisionGroup in
decide_group.go refuses a mixed
one, one inside a chat group, and patterns, rules, effort or fast mode on
it) goes to serveDecisionGroup in
decide_group.go instead
(decisionGroupOf: group/<id>, or a group's id or name by GroupFor). It
plans the members' keys and accounts with planGroup (perKeyBarred keeps
a decision-only provider's keys: DecidesModel), applies a gateway key's
model and account limits and pause rules as for a chat, and tries each
candidate in turn: a retryable failure that is not the request's own
(shapeRefused, promptRefused, protectionRefused) rests it
(decideFailed → restAfter) and the next is asked; the last one's answer
is passed on. Every try is a Try of one route; one usage row is written
for the answer. A group classifier of decision models fails over the same
way (askDecisionGroup, decideRefused carrying the vendor's status). A
decision group is kept out of the agents' catalog (groupEntries), and a
conversation asked of it is refused 400 pointing at /v1/systemone.
embeddings.go relays retrieval
bodies and options, draw.go sends images
to the remote's images API, and video.go
wraps remote task ids for later polls and downloads. passOnCaller in
remote_magpie.go supplies
caller/session headers without replacing the outgoing User-Agent.
Conversation forwarding preserves Claude Code and Codex client headers
(including Codex's originator) so relays behind the remote can recognize
them. Decision, retrieval and media requests set magpie's User-Agent at
their own call sites, so the remote accepts their attribution. Vendors
receive no caller labels.
A custom provider (no account, no preset plan's videos) makes videos the
same OpenAI way (#1446, customVideomakers), but only with the models its
own fetched list marks "kind": "video" (catalog.LiveVideomakers); a
name alone never makes a model a video maker. Start, poll and content go to
videoBase (its Chat base, else its Responses base) + /videos, with the
vendor's own User-Agent and no caller headers. Its ids end with the key's
fingerprint (customVideoID, markedKey), so a poll and its download go
on the key that started the video. A gateway key's account and model holds
apply to all three routes (videoAsker, videoModelHeld), and to Grok's
and Volcengine's polls and downloads as well.
Turning provider search off
Settings' searcher: "off" disables magpie's provider-assisted search,
including Kimi Code's search service and Google sign-ins' separate search
requests. Configured Search APIs still run in their saved order; failures
never fall back to a provider while this setting is off. Without a ready
Search API, canSearchFor does not offer magpie's replacement search tool.
searchesOwn is the one check for a provider searching for its own models (Kimi Code, a Google sign-in), so
ownSearcher and the model list another magpie reads (webSearchOf, which then says no search) follow it too.
A provider's native search on the client's protocol remains unchanged.
An empty searcher still selects a provider automatically; an unavailable
named provider still falls back to that selection.
webSearch enforces the API-only path.
Covered by TestSearchProviderOff, TestSearchProviderOffForwarding, TestSearchProviderOffTellsRemoteMagpie,
TestSearcherChosen, TestSettingsSearchProviderOff, and searcher-pick.test.cjs.
A search API's base URL
Each search API (provider.SearchAPI)
has an optional url, its base URL: an endpoint of the user's own that
answers as that API does (#1580). Empty is the vendor's own
(SearchVendor.Base); SearXNG has none, so its URL is required. check
takes only an http:// or https:// URL with a host and no ?query or
#fragment, since askSearchAPI puts the vendor's path after it
(/search, /res/v1/web/search, /v2/search) with the slash at its end
trimmed. The request goes through the gateway's client, so it follows
magpie's proxy settings as the vendor's own address does
(TestSearchFollowsTheSearchersProxy).
The key is sent only to that URL. Go keeps Brave's X-Subscription-Token
and Exa's x-api-key across a redirect to another host, so askSearchAPI
doesn't follow one. The 3xx is the error, and it names where the search
was sent. magpie ships and lists no third-party search endpoint; the URL
is only ever the user's.
A value the user set is never replaced by the vendor's default. In
Settings › Models › Web search the field sits under the key for every API,
with the vendor's own address as its placeholder. Picking an API that is
already added fills in its saved URL, so Add with a new key alone keeps
the URL, and Add with no key changes only the URL. On the CLI,
magpie search add <api> <key> keeps the URL set before, and url= with
nothing after it puts the vendor's own back. Backup and sync carry url
with the rest of the entry.
Covered by TestSearchAPIAtItsOwnBaseURL, TestSearchKeyStaysAtItsBaseURL,
TestSearchAPIBaseURLFromSettings, TestSearchCLI and
search-api.test.cjs.
Web search as an MCP server
SearchMCPPath, /mcp/magpie/web-search, serves the same webSearch a
model that can't search is given (the searcher's model, a Kimi Code plan's
service, the search APIs, as Settings › Models › Web search orders them)
as an MCP server of its own, so Cursor, Claude Desktop or any agent can
mount it as a web_search tool (Kayphoon on Discord). It speaks Streamable
HTTP only: each POST of a JSON-RPC message or batch is answered with JSON
(initialize, ping, tools/list, tools/call), notifications get 202,
and GET and DELETE get 405, since the server has no stream or session of
its own. Legacy SSE isn't served; a client that only speaks stdio mounts it
through mcp-remote. The path has two segments under /mcp/, so it can't
hide a signed-in server's /mcp/{name}.
It is a gateway route like the others. lanGuard takes a gateway key from
another machine (only while magpie is shared) and refuses a rebound browser
host, and the handler checks local/sharedWith again as a backstop when
Handler is served without lanGuard. Unlike other routes, a web page on
this computer (a localhost Origin, which corsGuard lets through) is
refused too: only an origin listed in Settings, which corsGuard already
held to a gateway key, may call it, as the MCP spec has a server check
Origin. keyLimited passes /mcp/ by, so each tools/call reserves the
calling key's limit itself (budget.Reserve), and a spent key's call is a
tool error with no search made. The search is marked CallFor{Agent, MCP: true}, so Routing says the agent called magpie's web_search MCP tool rather
than that magpie searched for one of its models. With nothing that can
search, the tool error says where to add a search API. Settings › Models ›
Web search shows the address (#searchMcpRow, from the Settings page's own
gateway address).
Covered by TestSearchMCPServesWebSearch, TestSearchMCPWithNoSearcher,
TestSearchMCPGuarded, TestSearchMCPHeldToKeyLimit,
TestSearchMCPRoutedAsTheAgentsCall and search-mcp.test.cjs.
Verification
go test -tags nogui ./internal/gateway -run 'TestLoop|TestLongReplyThatDoesNotLoop|TestQuiet|TestSilentHeld|TestRotateSpreadsSessions|TestRouting|TestSmartRouting|TestFallback|TestNoFallbackForOtherErrors|TestLastFallbackErrorReachesTheAgent|TestRateLimitedSinksToTheBack|TestGroupRateLimitedSinks|TestAffinity|TestSeveralKeysOnTakeOverFromEachOther|TestModelNotInPlanRestsTheModelNotTheKey|TestSubscriptionAccountsTakeOver|TestGroup|TestTrace|TestImageTool|TestCodexNoCredits|TestWindowCapsHoldTheAccount|TestAccountCap|TestClaudeGoesOnMessagesWhereTheRelayHasThem|TestAutoRelaysOnTheClientsOwnAPI|TestSearchOfferedStaysOnTheClientsAPI|TestSearchFollowsTheSearchersProxy|TestCodexSearchAnsweredOnResponses|TestAgentEffortOnCursorLocal|TestAzureCompactionWithoutMagpiesReasoning|TestCodexCompact|TestProtection|TestSearchedConversation|TestUnsearchedConversationUnchanged|TestNotAnAPIReply|TestAPIReplyUntouched|TestCodexBackendWebPage|TestSub2APIKeyLimitIsQuota|TestKeysWeighedByTheirWindows|TestGroupWeighsKeyWindows|TestKeyOutOfItsWindowRestsUntilReset|TestKeyPoolErrorDoesNotRestForWindow|TestKeyBackOnceItsWindowIsNotFull|TestRestingKeyReadAgainInAnOrderedGroup|TestClaudeAccountBackOnceItsWindowRenews|TestThinkingStreams|TestHeldThinkingKeepsTheAgentAlive|TestCodexHeardWithinItsIdleTimeout|TestRefusalAfterThinkingFailsOver|TestGeminiEmptyRepliesAskedAgain|TestLocalUnredacted|TestCORS|TestForeignPagesRefused|TestAIStudioThinking|TestGeminiThoughtsThroughLocalProxy|TestGeminiRefusedLevel|TestGeminiThinkingOffAtItsLowest|TestThinkingOff|TestTranslatedEffortLoggedAsSent|TestTranslatedThinkingOffRefused|TestClaudeFiveFiveThinkingOffOnTheWire|TestSamplingAsTheModelTakesIt|TestHaikuFiveFiveSamplingOnTheWire|TestGeminiThoughtsMarkedInExtraContent|TestGeminiThinkingLevelRefused|TestGeminiMinimalRefusedTwiceAtOnce|TestPassthroughGeminiMinimalRefused|TestPassthroughEffortNoneRefused|TestPassthroughMinimalRefusedNoneTaken|TestOtherOffNamed|TestClaudeSignInNotToldItsSignInFailed|TestSignInWriterReleasesA403|TestSignInBetaStaysWithMagpie|TestStructuredOutput|TestResponsesTextKeepsVerbosityBesideFormat|TestRefusedFormatToldInWords|RPM|TestQueued|TestCustomGeminiUpstream|TestWholeNums|TestGrokCalls|TestOnlyGrokCalls|TestGrokModel|TestGrokPluginCalls'
go test -tags nogui ./internal/gateway -run 'TestVertex'
go test -tags nogui ./internal/gateway ./internal/usage -run 'TestRetriedRequestCountsOnce|TestRequestsCountedOnceWithTheirRetries'
go test -tags nogui ./internal/gateway -run 'TestRemoteMagpie|TestRedactedKinds|TestKeyLimitTellsOnlyTheCaller'
go test -tags nogui ./internal/gateway -run 'TestSearchMCP'
go test -tags nogui ./internal/gateway ./internal/gui . -run 'TestSearchAPIAtItsOwnBaseURL|TestSearchKeyStaysAtItsBaseURL|TestSearchAPIBaseURLFromSettings|TestSearchCLI'
go test -tags nogui ./internal/redact ./internal/gui -run 'TestMoreKinds|TestCategoryDefaults|TestRedactKindsAreRedacts|TestRedactRuleEdit'
go test -tags nogui ./internal/gateway -run 'TestCodexModelList|TestCodexModelsEtag'
go test -tags nogui ./internal/provider ./internal/gateway -run 'TestFolderUnder|TestRuleFoldersCleaned|TestRuleMatchesByFolder|TestRuleMatchesExceptFolders|TestParseRuleFolders|TestParsePauseByFolder|TestWorkDir|TestRuleByFolder|TestPauseByFolder'
go test -tags nogui ./internal/provider -run 'TestGroup|TestCodexCreditsSwitch|TestRenewedAccountForgetsItsAllowance|TestDeclareSearch|TestNative|TestKeyAllowance|TestPlanKeyAllowance|TestClaudeAccountToldRenewed|TestPluginAccountToldRenewed|TestSkipsRedaction|TestSetRPM'
The gateway's TestMain gives the package a home of its own, so these tests
never read real providers or accounts.