Files
magpie/docs/subsystems/gateway-routing.md
T
yetone 69453574d7 docs: a key's usage cap (@wanggenjidev on X)
gateway-routing.md and providers-accounts.md: a key whose usage windows magpie reads takes the same usage cap an account does.

Record for the three commits (@wanggenjidev on X: Codex-style percent cap for OpenCode Go keys, generically for every key with windows magpie reads):
- Run at the pushed head (rebased on 08a852a36): TestKeyTakesUsageCap and TestKeyUsageCapPassesTheKeyOver ok; gofmt clean; key-usage-cap, key-spend-cap, account-cap, window-cap, i18n-keys: 180 pass, 0 fail on WSL, chromium and webkit. window-cap in webkit alone: 60/0 on this head and on origin/main a3d2a85dd.
- Earlier on mote at the previous base: provider/gateway/cli targeted tests ok; ./internal/gui ok 188s with -timeout 45m; vet darwin, linux nogui, windows clean.
- Broken by hand: the gateway hold removed, TestKeyUsageCapPassesTheKeyOver goes red.
- mote's disk filled during checking (52 webkit window-cap fails there, 60/0 on WSL on both main and this head); not a window-cap bug found on this change.
- Not tried: a real OpenCode Go key with live windows, Windows/Linux GUI runs, WebKitGTK. The whole GUI suite and the Go suite run after the tag.
2026-11-11 14:21:06 +08:00

679 KiB
Raw Blame History

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.

WorkBuddy and CodeBuddy Code's X-Conversation-ID is a native session header in sessionHeaders (sessionOf, nativeSessionOf, conversationID in gateway.go). It keeps their requests apart even when two chats have the same first message. The same identity is used for affinity, usage and the Routing page, and is preserved when passed to a remote magpie, not copied to an ordinary vendor. Existing header precedence is unchanged. Affinity previously kept under an inferred first message digest is not migrated to a newly recognised native id, so the first request after upgrading can choose an account anew. Historical usage is not backfilled; see Gateway Session Aggregation.

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 an agent named in the path, then by token, then by User-Agent. An agent that can be given neither a key nor a User-Agent of its own is given an address with its id in it, /agent/<id>/v1 (AgentPath, AgentURL in agentpath.go): lanGuard takes /agent/<id> off the path when <id> is an agent magpie knows (takeAgentPath), and the request is served at the rest as that agent's; startedByAgent never takes it for a script. OpenBot is one: it seals an endpoint's key and headers where magpie can't write, and hands the endpoint to the OpenCode it runs, whose User-Agent is OpenCode's, so its requests were counted as OpenCode's (SSNQT on X; TestAgentInPath). A Codex turn that names itself Claude Code is Codex's: OpenAI's Codex plugin for Claude Code (/codex:rescue, /codex:review) runs codex app-server with clientInfo "Claude Code", which Codex sends as its originator and User-Agent, and only Codex's turn headers (x-codex-window-id, x-codex-turn-metadata) tell it apart from Claude Code's own requests (codexForClaudeCode); an app that runs Codex as its own engine under its own name (Lody) stays that app. VS Code's Agents window runs codex app-server as vscode_agent_host, its originator and User-Agent: its calls are counted under VS Code (vscodeAgentHostUA in vscode.go), and its turns are Codex's for every Codex rule (fromCodex, hostedCodex), so one of Codex's own models asked there goes on Codex's sign-in (codexOwnOffMagpie) rather than 404; only Codex's own names (codexNamed) are kept as Codex's shape for a test asked as Codex (TestVSCodeAgentHostIsCodex, TestVSCodeAgentHostOwnModelGoesOnSignIn, TestVSCodeAgentHostNotCodexTestShape). Claude Science, whose User-Agent is the Anthropic SDK's, is told by its client's X-Anthropic-Surface: operon (isClaudeScience). It is listed every model as claude-magpie-<number> (scienceModels; its picker keeps only a claude- id whose name isn't a lower-case slug), and a Claude id magpie doesn't serve (its default before a pick, its haiku side tasks) goes to the model its last turn with tools was on, else the first it is listed (scienceTurn, kept in claude-science.model). gateway.go
WSL under NAT On Windows, while the gateway listens on loopback alone, serveWSL also serves it, in plain HTTP, at each address Windows has on a WSL network (WSLNets: the vEthernet (WSL…) adapters, looked for every 10s, since WSL's VM brings its adapter up and down). That is where a distro in NAT networking reaches Windows, and what place writes into its agents (zaidu259434 on X: Codex in WSL failed with sharing off). A distro in bridged networking is a peer on the LAN, and its default route is the LAN's router, not Windows: wslrun.HostAt takes Windows' address on the bridge's adapter (vEthernet (WSL_Bridge_Switch)), the one whose network holds that route (ecalpal_ on Discord). lanGuard takes a request there as this computer's (fromWSL) only when it arrives at that address, from inside that network, with the WSL key: WSLKey, a wsl- secret in magpie's folder (wsl-key, 0600), optionally followed by -<agent>. It becomes a loopback request carrying magpie or magpie-<agent> (asFromLoopback). A client that can only send its own key (Claude Science in WSL, which sends its Claude sign-in) puts the WSL key first in the path instead, /<WSL key>/v1/…: takeWSLPathKey takes it off before fromWSL judges the request, and the request goes on without it. Anything else there, a Docker Desktop container on the same network included, is judged as another machine's. Windows' firewall still decides whether WSL gets in: WSL's network is a Public one. wsl.go
TLS --tls-cert/--tls-key (MAGPIE_TLS_CERT, MAGPIE_TLS_KEY) make ListenAndServe, Relisten (both through Server.listen) and magpie web's page (ServeTLS) wrap the listener in tlsListener. A connection from another computer is tls.Server at once, so its plain HTTP gets net/http's 400. One from this computer (fromThisComputer: loopback, or a peer address equal to the local one) is sniffed on its own goroutine, 10s at most (sniffWait), and 0x16 makes it TLS, so URL(), the agents, MCP servers, ServedBy and the healthcheck keep http://127.0.0.1. certFiles.get reloads the pair when either file's mtime or size changes; a pair that doesn't load keeps the one served (logged once per change). tlsConfig refuses half a pair or files that don't load before binding. HTTP/1.1 only over TLS (hijack, Codex's websocket). Scheme() gives the scheme of LANURLs, a scheme-less MAGPIE_PUBLIC_URL and the page's network links. Host and Origin checks (foreignPage, rebound) don't depend on the scheme. tls.go, lan.go
HTTPS With Settings → Network and sharing → HTTPS on (settings HTTPS, magpie https on; zhangly1 on X) TLSOn is true, so the listener serves other computers TLS as with mTLS, without a client certificate asked. Without --tls-cert, settingsCert serves the pair imported to <settings>/https (ImportCert: PEM in any split, the leaf the key matches first; refuses an encrypted key, a mismatch, an expired leaf; read again through certFiles), else ownServerCert from magpie's CA (made when HTTPS is turned on). A WSL distro's connection is sniffed, so its plain HTTP still works. GET /magpie-ca.crt (caFile) serves the CA to any address lanGuard lets in without a key (caFileOpen), 404 before one exists. The Settings routes (internal/gui/https.go) refuse a page from another computer that would flip the switch under itself (errFarPage). TestHTTPSOtherComputer, TestHTTPSThisComputerPlain, TestHTTPSImportedCert, TestHTTPSCAFile, TestSettingsHTTPSFarPage, https-settings.test.cjs. https.go, tls.go
mTLS With Settings → Network and sharing → Require a client certificate on (settings MTLS, magpie mtls on; hhdaxia on X, #5596), other computers reach the gateway and magpie web's page only over TLS with a client certificate magpie's own CA (internal/mtls, MTLSStore: ca.pem, ca-key.pem, clients.json under the settings folder) issued and hasn't revoked. tlsServer.config(strict) is asked per connection, so the switch needs no relisten: without --tls-cert it serves a certificate the CA signs in memory for this computer's names, addresses and the SNI name (ownServerCert, made again when they or the CA change, or after a day), and with mTLS on even without --tls-cert the listener serves TLS. A peer that isn't this computer or a WSL distro (fromWSLNet) is asked RequireAndVerifyClientCert and its handshake ended when VerifyConnection's Admits fails. The guards (lanGuard, and ClientCertGuard on the page) then refuse 403 every request NeedsClientCert names: plain HTTP, a proxy's or tunnel's on loopback (proxied, unless MAGPIE_TRUST_PROXY=1 says the proxy checks certificates itself), the page port (viaPagePort), a connection made before the switch, a certificate revoked since its handshake. This computer (local, ownAddress) and a WSL agent with the WSL key (fromWSL) are answered as before. The Settings routes (internal/gui/mtls.go) never let a page from another computer shut itself out: without a certificate it can't turn mTLS on, and it can't revoke or issue again the certificate it came with (pageCert, errOwnCert). Not handled: a .p12 for browsers, and a proxy that can't check certificates itself. TestMTLSOtherComputerHandshake, TestMTLSGuardEveryRoute, TestMTLSThisComputerAndProxies, TestMTLSToggleWithoutRelisten, TestMTLSRevokeMidConnection, TestClientCertGuardPage, TestSettingsMTLSPageLockout. mtls.go, tls.go, internal/mtls
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), Ollama's GET /api/version, GET /api/tags and POST /api/show (ollama.go, for a client that takes a custom endpoint only as an Ollama server: Visual Studio's and VS Code's Copilot, wani on Discord; the list is catalogFor's, so a key's models alone, /api/show tells capabilities (completion, tools, vision from Images, thinking from Thinks) and model_info with general.architecture magpie, general.basename, magpie.context_length (32768, VS Code's own default, when the window isn't known, since VS Code would take a 0) and the general.parameter_count and magpie.embedding_length the ollama CLI before 0.7 reads unchecked; a name ending :latest, as the ollama CLI asks, is the bare id unless a model is really called that (ollamaName); the client then chats on /v1/chat/completions, or on Ollama's own POST /api/chat and POST /api/generate (ollama_chat.go, Zed's Ollama provider, super_lalalalala on Discord), which ollamaChatBody turns into a /v1/chat/completions body handed to the same handle(provider.Chat) on a clone of the request, so they are routed, held to a key's models and counted as it is: messages with images (base64, its type sniffed, as data-URL parts; a tool message's in a user message after it), an assistant's thinking as reasoning_content and its tool_calls given ids where Ollama sent none, a tool result matched to its call by tool_call_id, else tool_name, else in order (one with no call is a 400), tools, format (json or a schema), think (a level is reasoning_effort), and options' temperature, top_p, seed, stop, the two penalties and a positive num_predict as max_tokens (num_ctx, top_k and the rest of Ollama's own are dropped); ollamaWriter turns the reply into Ollama's NDJSON lines (streamed unless stream:false, then one object), tool calls with their arguments as an object and an id, and a last done line with done_reason and the token counts, and an error into {"error":"…"} with the status /v1 would give; a request with no messages or prompt is answered done_reason:"load", as Ollama does to warm a model), /mcp/{name}, /mcp/magpie/web-search, /mcp/magpie/vision and /mcp/magpie/image with its /mcp/magpie/image/files/{name} (magpie's own web search, image recognition and image generation as MCP servers, below) and the /v1/magpie/* status endpoints. /v1/magpie/heap (heapProfile, heap.go, for magpie heap) is held tighter than the rest by heapRefused in the handler itself, so it holds where Handler is served without lanGuard too: only a loopback caller that isn't proxied (local), carries no browser mark (fromBrowser) and names a loopback Host (loopbackHost) gets the profile; a gateway key never lets anything else in. /v1/magpie/cpu (cpuProfile, cpu.go, for magpie cpu) records a CPU profile for ?seconds= (30, from 5 to 120) and is held to the same callers by cpuRefused, which shares profileRefused with heapRefused; one profile records at a time (cpuRecording), a second is answered 409, and a caller that hangs up stops it. /v1/magpie/goroutines (goroutineDump, goroutines.go, for magpie goroutines, #3362) answers every goroutine's stack and wait as text (runtime/pprof's goroutine profile at debug 2) to the same callers, through goroutinesRefused, and is answered ahead of everything below (dumpFirst, around Handler's wrappers and around lanGuard in Front), since it is asked for while magpie hangs: the allow list reads settings.json under its lock, and holdCatalog takes provider.Hold's and filememo's, so a stuck holder of any of them would hold the dump too; a caller goroutinesRefused lets in is one those let in anyway, and any other goes through them as before (TestGoroutineDumpAnswersWhileRequestsWait). /v1/alpha/search (also without /v1, and on the Codex backend path for a magpie model) is Codex's web.run search (alphaSearch, codex_search.go): a ChatGPT account's model goes to the ChatGPT backend's /alpha/search on the account's sign-in, the next account asked on 401, 403, 429 or 5xx; any other model's search_query is searched by webSearch, in the mode its settings.external_web_access says (#5018; a ChatGPT account then searches by the same backend search, see Which providers search for another model), and when nothing answers the reason is a 200 with output, since Codex ends the turn on any failed web.run (anton on Discord). A WebSocket upgrade on /v1/responses, /responses or the Codex backend's /responses is Responses over a WebSocket, as Codex speaks it (below, A Responses WebSocket); one on another Codex backend path is answered 426, and a plain GET on /v1/responses 405. 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). A browser extension's own pages, popup and service worker are listed the same way by their origin, which is the browser's scheme and the extension's id: chrome-extension://<id> (Chromium, the id 32 letters a–p), moz-extension://<uuid> (Firefox, the Internal UUID about:debugging shows, not the add-on id) and safari-web-extension://<uuid> (Safari, which picks a new UUID on each launch, so a listing lasts until Safari restarts); the id must have that browser's shape, cased any way, and nothing else is taken — no bare scheme, no wildcard, no path (SkyAerope on Discord: an extension without host permissions is held to CORS like a page). A content script's fetch carries the page's origin, not the extension's. A listed extension is treated exactly as a listed page, below; one not listed passes as before (other schemes, below) with no CORS headers. 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. A browser sends a preflight without credentials, so a listed origin's preflight from another computer is let past lanGuard's key check to be answered here (#4931, ggbdpq: a page on another machine got 401 to its preflight and never sent the keyed request); lanGuard hands on only an OPTIONS with Access-Control-Request-Method whose origin is listed (corsAllowed). Any other origin's preflight still meets the key check: corsGuard passes some unlisted origins on (loopback names, the request's own origin, other schemes), and Codex's backend relay would serve their OPTIONS on the user's sign-in (TestCORSPreflightFromLANReachesNothing). 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. Other schemes (app://, file://, tauri://, vscode-webview://, chrome-extension://) come from desktop apps, webviews and extensions that don't enforce CORS, and pass keyless as before. Obsidian's app://obsidian.md (appOrigin) is also answered with CORS headers, keyless: Copilot for Obsidian streams through its window's fetch, which reads no reply without them, and the origin is one only Obsidian's own window sends, so it gets no more than its calls without an Origin get, and from the network it still needs a key (TestCORSObsidian, shirotokiren on X); null is not one of them, since any web page sends it from a sandboxed frame and an opened file sends it too, so a call with it needs an enabled gateway key as a listed origin's does, and is answered 403 without one (no CORS headers either way, so a frame or a local page still reads no reply). A page at a subdomain of localhost (localhostSubdomain, #2256) needs a key the same way: Chrome and Firefox resolve *.localhost to loopback themselves, but Safari and other WebKit views ask the system resolver, which before macOS 26 asks the network's DNS (WebKit bug 160504), so a resolver that answers serves such a page from anywhere. tauri.localhost and wails.localhost stay keyless on Windows only, where Tauri's and Wails' webviews serve themselves at those names; on macOS and Linux those apps use tauri:// and wails://. 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 but not a subdomain of it, which WebKit asks the DNS for (#2256), 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). Next, before the key or rebound is looked at, the allow list (lc on Discord, magpie in Docker on a public host): with MAGPIE_ALLOW_IPS or Settings › Network › Allowed addresses (settings.AllowIPs, this computer's own, never brought by a sync or restore: see sync and backup; the variable wins and the page then only shows it) naming IPs and CIDR ranges, a request whose connection (RemoteAddr, IPv4-mapped IPv6 unmapped, zone dropped) is outside them is refused 403 naming its address, even with an enabled gateway key (refuseNotAllowed). Loopback and this computer's own interface addresses always pass. A forwarding header is never taken for the address, so a proxy or tunnel on this computer passes (it arrives from loopback) and its clients are limited at the proxy. An entry that doesn't parse lets nothing in and is logged once; the list stays on. Settings' list is read with settings.LoadChecked: a settings.json that can't be read, or doesn't parse with no last good generation, is unknown, never "no list", so the list read last in this process stays in force (lastAllow), and with none read yet only this computer passes, the 403 saying settings.json couldn't be read; logged once. No file, or an empty one, is no list. The Settings page's saves read with LoadChecked too and refuse such a file, as settings.Save does. magpie web's server is wrapped in the same check (AllowGuard), and its port hands the gateway's client routes (ClientPath) to Server.Front, the same lanGuard-over-Handler the gateway's listener serves, each marked by FromPagePort so local is false for it (viaPagePort; lanGuard refuses it 403 while magpie isn't shared, saying to call the gateway's own address, and asks a gateway key otherwise): a raw TCP forward or a proxy with no forwarding header reaches that port from loopback, so no request there counts as an agent here (TestClientPathCoversHandler fails when a route Handler adds is in neither ClientPath nor its list of routes that stay on the gateway's port). Settings refuses a list that would leave out the address the page saving it is open from (KeepsOut); the page names that address, which behind Docker or a proxy is the proxy's, and offers to add it to the refused list (allowSays, Mathresearcher on Discord). gateway.go, allow.go, internal/settings/allowips.go, cors.go, codex_catalog.go, ollama.go, ollama_chat.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; the user's own groups only while the groups plugin is on, the plugin runtime), auto stand-ins, the agent's own stand-in (StandIn: Codex's config.toml model when magpie is its provider — in a WSL distro, the distro's own, of the ones running now — 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; a memory call first waits beside the turn it was started with, through codexLeads, see the side turns below), 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 the asking agent's own subscription in magpie serves (a provider whose Account.Agent is the agent: Codex's ChatGPT accounts for Codex, Claude's for Claude Code) goes to that subscription first, found groups on or off (ownFirst, provider.OwnRoute; freefcw on X: Codex's bare gpt-6-astra went to Devin through auto-gpt-6-astra, whose soonest-renewing member came first, and with found groups off to the first provider in the order). Not for a group the user made or changed by that name, a found group magpie set one of the agent's fields to (SetToGroup, agent.SetToGroup over the agent's applied record, #750's bare spelling included), a gateway key held to some models, or a client magpie doesn't know as an agent; an auto stand-in and agent.Reseat prefer the agent's own subscription the same way (AutoStandInFor, sameModel). Otherwise a bare model id several providers serve (MOMO on Discord: glm-5.3 under opencode-go and a6api): 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, an agent with a subscription of its own in magpie is refused it with a 400 naming the providers' ids and magpie group auto on (provider.OffSpread, offSpreadRefused): off, magpie picks no vendor for it. Any other client still gets the first provider in the Providers order that exposes it (Resolve), with no fallback. A provider the user keeps out of found groups (Routing's "Leave out a provider", provider.SetAutoGroupSkip, autoGroupSkip in providers.json; chenxiang0010 on Discord) is in none of them, so a model one other provider serves is no group; the groups the user made or changed keep it. A request still naming a found group that took away goes to its model from a provider not kept out (AutoStandIn), and an agent set to it is moved there (agent.Reseat). magpie writes only provider/model ids into agents' configs (magpieModels), so a bare id is one the user wrote. /v1/models lists bare ids only when the user asks for them (Model ids without the provider). 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
A found group's two ids A group magpie found is listed (/v1/models, the catalog, the lists written into agents, the pickers, the CLI and TUI) as auto/<model>: the model's id as a vendor spells it, dots kept and with no vendor prefix (auto/claude-opus-5.5; provider.Group.Ref, spelledIn), so a client that looks the part after the slash up on models.dev finds it (ZeroClover on X). The spelling is the one models.dev gives the model most (catalog.Spelling, its normal index: glm-5.3-flash whether the members serve glm-5-3-flash, Ark's dated id or glm-5.3-flash), so it no longer follows the order the providers were added in; for a model models.dev doesn't know, the first member's spelling it lists, else the first member's. The group's name comes from the same choice (autoGroups): the name models.dev gives that spelling (catalog.NameOf), else a vendor's own name for it, else the spelling itself; they were picked apart, a name of glm-5-3-flash beside auto/glm-5.3-flash (XYenon on Discord, TestFoundGroupIDAndNameAreOneSpelling). A found group the user changed keeps the name they saved. Every spelling it was listed by before is still the group (CanonicalRef), and PublicRef takes one to the spelling now. Its old id group/auto-<slug> is served forever. Inside magpie the group keeps that one id: validateModel takes auto/<model> (with :level or [1m]) back to it with provider.CanonicalRef before key limits, routing, affinity and the usage log see the request, and the request body is rewritten to it, so both ids count as one group. A gateway key naming either id, group/* or auto/* passes for both (allows in key_models.go). SaveGroup stores a member, rule or classifier picked as auto/<model> by the old id. An agent field magpie set to group/auto-<slug>, or to an auto/<model> spelt otherwise than the group is listed now, moves to auto/<model> on the next SyncCatalog (agent.renameFoundGroups, TestFoundGroupMovedOffAnOldSpelling), but only while its value is still what applied.json says magpie wrote; a value the user set or changed stays, and is still served. A pick of the group by its old id written now (Agent.Apply) is written as auto/<model>. An agent's hidden, picked and ordered models saved by the old id hold for the new one (PublicRef in visible.go), and a bare model id still reaches its found group (bareTarget). Claude Code is given a dotted Claude version dashed, so it may send auto/claude-sonnet-4-5: that is the same group, and Reseat still moves an agent off it once the group is gone (samePick). auto is no provider id: Save and Rename refuse it for a new provider, and a plugin's auto is auto-plugin (PluginID). A provider of the user's saved as auto before keeps its models: while it exists, auto/<x> is its model and found groups list as group/auto-<slug> (autoRefsOn). Hand-made groups stay group/<id>. internal/provider/autoref.go, key_models.go, internal/agent/autoref.go
A model's own id at a provider A model the user lists by an id of theirs at a provider (a signed-in account's and a plugin's too; settings' ModelIDs, magpie model id <provider/model> <id>, the editor's "Listed as"; Providers and accounts) is that id everywhere the gateway names it: /v1/models and the lists written into agents (Available), Resolve, the routing groups and the group magpie finds for it (auto/<id>, with every other provider serving that id), a gateway key's models, X-Magpie-Model and the usage log's model. Only the upstream request differs: every place that sends a wire name reads settings.Wires(), which is ModelWires with each ModelIDs entry turned round ("<pid>/<id>" → the vendor's own id, wrapped by a <pid>/* wire), so the body, a Vertex path and the usage log's endpoint carry the vendor's id; an explicit ModelWires entry for that id wins. The vendor's reply names its own id, which the usage log, recent calls and the Routing page keep as served; the agent gets the id it asked for back in the reply, in every protocol, streamed or whole (memberWriter in member.go, replyNamingOf: the reply's model, Responses' response.model, Anthropic's message.model, Gemini's modelVersion; issennknight on Discord, whose agent warned that deepseek-v4.1-flash came back as deepseek-v4.1-flash-1017). The same holds for a group or a provider/model id the vendor knows by another name. A reply whose vendor sent the wire name as asked keeps the vendor's name (a dated -20261017 included). Settings' replyModel (Settings › Models › Replies › Model name in replies) picks for every request: "" the model asked for, member the group's member, vendor the vendor's own name, as before the asked-for name, each for every agent, Claude Code, Claude Desktop and Codex included (ZoeCats on Discord: in v0.1.2760 member still gave those three the model asked for; TestPluginReplyNamesMember holds it on a plugin too). A file from before it with memberModel on reads as member, and memberModel is written beside replyModel for an older magpie (normal in settings.go; Merge in settingsapi takes an older page's memberModel only when its switch moved). A request's X-Magpie-Response-Model (asked, member or vendor) overrides the setting for that request, for every agent (TestReplyNamesAskedModel, TestGeminiReplyNamesAskedModel, TestReplyNamesMember, TestReplyModelFoldsMemberModel, TestReplyModelSaves). A request still naming provider/<own id> (an agent's file magpie didn't rewrite) resolves and goes out as it is. A key held to either id passes for both (modelAllowed checks the ref, then OwnModelID, then ListedModelID); a group member passes the same way. An id is given to a model of the provider's chat list or its picks; the image, video and embeddings routes send no wire name, so they are not served under one (TestLocalModelIDOnEveryRoute). At an account or a plugin the account's own say of the model is read by the vendor's id: a plugin's API and fetch, Claude Code's --model, Antigravity's variant, and which accounts list it and at what levels (TestLocalModelIDAtAPlugin, TestLocalModelIDAtAClaudeAccount, TestLocalModelIDAtAnAntigravityAccount). internal/provider/localid.go, internal/settings/settings.go, key_models.go
Candidates plan lists one provider's candidates: one per key or account on, then each Fallback model, with resting ones last (restLast). A fallback the user unchecked in its own provider's model list is skipped, as a group's member is (provider.ResolveRoute, #3911; fallback_unpicked_test.go), and so is it where fallbacks are read for careful accounts, native compaction, redaction and Codex's own turns. A fallback can be a routing group (group/<id>, 01huadalang on Discord): planPaused hands its members to planLevel as a request to the group would (planFallbackGroup), in the group's own routing and sink, its pause rules applied in serve, and its trace rows marked Fallback with the group in Via. Its turn rules (ruleFor, which may ask a classifier) are not applied: the plan is made before the primary is tried, and a classifier call on every request the primary answers costs too much. Each provider/model is tried once a round: a member that is the primary, an earlier fallback or another fallback group's is left out where it came second, so a group holding this provider is no loop (groups have no fallbacks of their own, and a member's are not followed). A group that is gone is passed over. Every place that reads fallbacks (careful accounts, native compaction, redaction, Codex's own turns, Claude's review) reads a group's members through provider.FallbackModels. fallback_group_test.go. planGroup and planLevel weigh a group's members together. A nested group plans by its own routing (#576); one left on the default (Smart) in a group that pools (Smart, In turn, Least used, Use before expiry, Free first, Speed first, a plugin's) takes the outer group's, as a provider left on the default does (provider.Group.Within, set on Member.Via, so the trace's Subs and the Routing page read the routing that applies, #3847). In a group In order, By weight or Manual it stays Smart. TestFreeFirstReachesAGroupInItLeftOnTheDefault. 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, weight, free (free first), fast (speed first), drain (until used up) or, a group's only, cheap (cheapest first) or expiring (free quota by expiry). weighRouted reads each candidate into a routes.Seat and asks the strategy serving its routing (routes.Find, the router strategy point of the plugin runtime) for the order: Smart is routes.Smart, the core's; the others are routes.Builtin, registered by the built-in plugin rotation. With it off a routing no strategy serves is tried in its listed order, and routingOf treats it as order wherever the core asks about a routing (a turn's mark, goesRound, sinks, a rotate group's sessions, a group's heads). 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. Among accounts a plugin reads as prepaid wallets (a window's balance, #3950), Smart, usage and pace put the one with more left first where they would otherwise tie, only within one provider and unit (routes.Seat.Left/LeftIn, see provider plugins): each kind is ordered in the places its own seats take, so a group weighing several providers' accounts as one pool orders each provider's wallets too (#4095, TestGroupWalletsGoByWhatTheyHaveLeft). free weighs by what a model costs there and nothing else: only a strategy with routes.Strategy.ByFree set (routes.FreeFirst is the one) has weighRouted fill routes.Seat.Free, from provider.FreeModel — the user's word that the whole provider costs them nothing (Provider.CountFree: the editor's Free for me, magpie provider set <id> free=yes; jiabubu on Discord, ModelScope's free daily quota), else the vendor's own catalog.Model.Free word, else a list price of $0 on every count — so a pool routed any other way never reads a model list for it, and one routed free spends the members whose model costs nothing before those that spend the allowance or credits, each tier in its listed order (nothing free is left behind a paid one, and a pool with no free model behaves as order). A group routed free weighs its members whole, each over its own accounts or keys as its provider routes them. Whatever a group's routing, the Routing groups page tags a member provider.FreeModel counts free "free", on the group's card and beside its provider in the editor (groupsState's memberInfo[].free, jiabubu on Discord, TestGroupMemberSaysFree, group-member-free.test.cjs). fast weighs by speed lately and nothing else: only a strategy with routes.Strategy.BySpeed set (routes.Fastest) has weighRouted fill routes.Seat.TTFT and TPS, from speedOf (speed.go): per restID (account or key, and model), a decayed average (half-life 20m) of a streamed answer's ms to its first content and of its output tokens a second as usage.DecodeOf counts them, written once as an answer ends (noteTrySpeed, beside servedCandidate) and read with one map lookup per candidate, never from the usage history; past an hour since its last answer a seat counts as not measured, the records are capped at 4096, and a restart forgets them. routes.Fastest ranks the awake by their first token plus 200 tokens at their pace (a seat with no pace at the measured seats' middle pace), keeps seats within a tenth of their band's fastest in listed order, and of a pool's requests with seats both measured and not, gives every fifth to one not measured (round the unmeasured, probes, so one is never starved); resting seats go after the awake, used-up ones (UsedShare) after those, and rests and failover are as for any routing. The trace's rows carry lateTtft/lateTps for the Routing page's story ("answered fastest lately — first token in 0.8s"). A non-streamed reply tells nothing (no first token), so a pool that never streams stays in listed order bar the probes. cheap (a group's only: provider.normalize drops it from a provider, whose keys and accounts all bill one price, and the CLI refuses it there) weighs by price now and nothing else: only a strategy with routes.Strategy.ByPrice set (routes.Cheapest) has weighRouted fill routes.Seat.Priced, Cost and CacheCost, from provider.Provider.PriceAt at priceClock() — the price Usage would count a call made then (the user's ModelPrices, else list or maker price, at the price rate and RateAt's window, a FreeModel at 0), doubled in its vendor's peak hours by catalog.Price.In (PeakOf: DeepSeek's API, Command Code's and OpenCode Go's DeepSeek models, each at DeepSeek's hours; Ollama Cloud's deepseek-v4.1-flash and deepseek-v4-pro, dated tags too, at its own 12:00–18:00 UTC weekdays, catalog.PeakOllama). routes.Cheapest sorts stably by a million in plus a million out, a tie (within a millionth) by cache read, and unpriced seats after every priced one in listed order; rests and failover are as for any routing. The trace's rows carry price (input, output, cacheRead, peak) for the Routing page's story ("costs least on Ollama now — $0.150 in, $0.600 out a million tokens"). TestCheapestFirstGroupFollowsPeakHours holds the clock at a peak and an off-peak hour, and TestCheapestFirstGroupFollowsOllamaOffPeak at each edge of Ollama Cloud's hours, a Saturday, and in far zones. A group routed expiring (provider.FreeExpiring, routes.FreeExpiring; wowbbs on Discord, five check-in accounts of WorkBuddy, MiniMax, Trae and Qoder in one group) spends free quota before paid, the soonest lost first. Its strategy sets ByFree and ByPlan, so weighRouted fills Seat.Free (the model is free there, as for free) and Seat.FreePlan (provider.FreePlan of the account's Plan: free, trial, 免费, 试用, 体验, 體驗). It orders three tiers: the free ones with quota left, by routes.Expires (the earliest of a window's renewal and a credit's RunsOut, Lapse included) truncated to the hour, a stable tie in listed order and an unknown expiry after every known one; then the paid ones as Smart orders them among themselves; then the used up and resting, by when they come back. A paid account takes a request only when no free one has quota left, and failover walks the same tiers. The trace's rows carry free and expires for the Routing page's story ("its free quota is lost soonest, in 1d 2h"). It is a group's only: provider.normalize keeps it off a provider, and magpie provider set … routing=expiring is refused like cheap. Nothing changes for a group not routed expiring. TestGroupSpendsFreeQuotaSoonestToExpireFirst (gateway), TestFreeExpiringSpendsSoonestFreeFirst (routes) and routing-free-expiring.test.cjs hold it. A plugin whose usage doesn't say when free credits lapse (Trae, Qoder's add-on pools) is ordered after the ones that do. A group routed weight (#1910) takes its members, not their keys, by smooth weighted round robin: planLevel makes each model member (its keys ordered by its own provider's routing) and each nested group one unit, and weightedUnits puts the round's pick (routes.Round over group/<id>, keyed by the member's spelling, Group.Weights, 1 if unset) first and the rest in member order for failover; a unit whose head rests leaves the round, while one whose accounts are only near their limit (Smart's 90% band, not resting) keeps its share, the band ordering only its own accounts (TestWeightedGroupGivesALowGroupItsShare; Creat.wu on Discord read the Routing page's "kept for when the others can't" as the member passed over, so the page now tells a member behind another by a group's weights or order as such, memberSplit in the routing plugin's client.js), and a kept conversation moves the round's charge to the member that kept it (wrrSeat, routes.MoveRound). weight on a provider spreads its keys by each key's Weight and a subscription's accounts by each account's (AccountWeights, rubbzha on X): keyWeight gives a seat its Weight, 1 when none is set, and routes.Weighted takes them by smooth weighted round robin, a resting one leaving the round and a kept conversation staying as Stays says (TestWeightedKeys, TestAccountWeightSharesRequests). 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). drain (dzxx0496 on Discord: free accounts one after another, the first not taking the requests back once it renews) stays on one seat per pool (routes.Drain, which remembers the seat's Key per pool) until it is used up — a known window at 100% (provider.SpentShareOf, as In order) or resting out of quota or credit (routes.Seat.Spent, filled by spentRest from restingOf's failQuota/failCredit) — then goes on to the next not used up in listed order and stays there, wrapping round; the others follow it in listed order for failover. A rate limit or a failure only rests the seat, tried last meanwhile, and the pool comes back to it; with every seat used up it stays put, and a seat that leaves the pool leaves it on the first not used up. A group routed drain pools its members' accounts and keys under group/<id>, as Smart does. A restart forgets where each pool was, and it starts again at the first not used up (TestDrainKeepsTheOneThatTookOver). A failure rests a candidate (failure, failureOf). routing.go, weighted.go, internal/routes/, 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). One with no limit still counts its requests out in a lane of Limit 0, which never waits, so Lanes (/v1/magpie/concurrency, the GUI's /api/lanes) says how many run there too and the Providers page's pill shows it (chentuoyan on Discord, TestLanesCountWithNoLimit); a limit set while they are out counts them. 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) that isn't resting: its lane is free only because nothing is sent there. A request already waiting in a lane doesn't stay bound to it: whenever a slot is given back in any lane or a rest is lifted (lanes.freed, signalled by the releaser, Unrest and UnrestAll), and when the soonest rest among the others runs out (at most every laneRecheck), it goes to the first key or account after it in the planned order that has a free slot with no queue, minute room, isn't resting and isn't a reserve now (waitMate, keepAtOnce re-derived over the provider's candidates, errMoved). So one that took a seat while those before it rested, then became a reserve once they were back, doesn't keep requests waiting behind its own long turns (01huadalang on Discord: three ZCode accounts at three at once, the first two back from a 405 while the waiting ones stayed on the third until its requests were cut by hand; TestWaitingRequestGoesToAccountBackFromRest under Smart and In turn, with Stays on and off, TestWaitingRequestTakesSlotGivenBackElsewhere under every routing). Strict stays leaves no other candidate, so the request waits for its own. A fallback is never asked for want of a slot or a minute (TestFullMemberGivesWay). 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, and every account of it keeps them, those on beside the first as well (withPicks, called by All and AlsoOn; #1899: a second WorkBuddy AI account had none, and queued 62s with the wait set to 1s). concurrency.go, rpm.go, internal/provider/concurrency.go
Accounts at once A provider's MaxAccounts (01huadalang on Discord: three ZCode accounts used at once got the exit address refused with a 405, two didn't) is how many of its keys or accounts take requests at the same time: provider.AtOnce() is the user's own value, else what its plugin declares (maxAccounts on the auth hook or in package.json's magpie, read by host.js atOnceOf; zcode says 2), else no limit; the user's 0 is no limit over the plugin's. perKeyBarred keeps the first N in the user's own order (rank, so a dragged list counts), preferring ones not resting, and hands the rest to keepAtOnce's reserves: they go after everything else as asides with candidate.reserve set (Weighed.Reserve), so whatever the routing mode, a reserve is asked only once the kept ones failed or rest, and a kept one that rests gives its seat to the first reserve on the next request. Three guards keep a reserve from being reached for anything else: laneMate never spills a full lane onto one, a full queue (laneErr) drops the provider's reserves before passing on (dropReserves), so the request is turned away with the 429 instead, and session affinity keeps no conversation on a reserve once the kept ones can take it (affine's "reserve"; Strict still holds). Leak known: a failure that rests nobody (a 5xx on one try) still passes that one request to the reserve, as it does to any next candidate. Set in the provider editor's Advanced (Accounts at once, beside Concurrency) or with magpie provider at-once; Routing's row says "in reserve · {n} at once" (TestAtOnceKeepsFirstInUserOrder, TestAtOnceFullLaneWaitsForTheKept, TestAtOnceReserveTakesOverAndGivesBack, provider-at-once.test.cjs). fallback.go, concurrency.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, or until its rest is lifted by hand (Try now, Unrest calls unsink, UnrestAll unsinkAll for the key and each of its models), which puts it back in its place (TestTryNowPutsASunkAccountBack, TestUnrestAllUnsinksTheModels). Another magpie's model rate limited there, whose rest is the model's alone (remoteModelRest), sinks alone too (restID), and sunkAt reads a candidate's model before its key, so the remote's other models keep their place (#2167, ggbdpq; TestRemoteMagpieRateLimitSinksTheModel, TestMagpieAddedByHandRateLimitSinksTheModel). A group in a group sinks by its own Sink, within its own order (sinkOwn, #2255), and the group asked for then sinks the whole by its own; TestNestedGroupSinksItsOwnOrder. sink.go
Group defaults What a group does when a member is rate limited (Sink), slow to start (FirstToken) or every member is busy (Patience) is set once for every group in settings (groupSink, groupFirstToken, groupPatience; settings.SetGroupDefaults, POST /api/groups/defaults, the Routing groups page's Settings card; jiezhengj on Discord). A group follows the default for each it leaves unset, and its own value wins: Sinks() is Sink, or the default unless NoSink (Keeps its place); FirstTokenOr() is its own FirstToken (FirstTokenWait, -1, is its own Wait), else the default; Waits() reads the default when Patience is 0 (60 is its own 1 min). The group editor's rows open on Default for a group that sets none, the hint naming the value it follows. Groups saved before kept 0 and no NoSink, so they follow the default, which starts at magpie's own (keep its place, wait, 60s). TestGroupDefaultsUnlessItsOwn, TestGroupFirstTokenFollowsTheDefault, TestGroupSinkFollowsTheDefault, TestGroupDefaultsSaved, group-defaults.test.cjs. group.go, groups.go
Image generation /v1/images/generations and /v1/images/edits are translated to the selected model's image API. OpenRouter image-only models use its /images endpoint and send reference images as input_references; OpenRouter models that return images through chat stay on Chat Completions. Volcengine Ark (isArk: an ark.*.volces.com base, the preset's plans or one added by hand) is asked at /images/generations only, as its doc (https://www.volcengine.com/docs/82379/1541523) takes it (drawArk): watermark: false, since it marks every image otherwise; reference images as JSON image (a URL or data URL, an array for several), never a multipart edit; no n, so one request per image (eachDrawing); no ratio as size, so a ratio its doc lists is sent as that ratio's 2K size and any other is a 400 that says to put it in the prompt; no mask, no quality (JL on Discord, TestArkDrawsWithoutWatermarkOncePerImage). DashScope (dashScope: Qwen's, Bailian's and Qwen Cloud's presets, or one of their hosts) draws its Qwen-Image and Wan 2.7 image models (dashScopeDraws) on its own API, <host>/api/v1/services/aigc/multimodal-generation/generation (drawDashScope), as docs.qwencloud.com gives it: the prompt as the user message's text part after an edit's images as image parts (a URL or data URL), n, size as W*H (a ratio is a 400 that says to give WxH), watermark: false, no mask; the images are read from every output.choices[].message.content[].image (readDashScopeAnswer), and a refusal says its message and code. A Token Plan's host serves no OpenAI images API, so the drawing went on to chat completions and "drew nothing" (judi0713 on Discord, TestDashScopeDrawsOnItsOwnAPI). A MiniMax API key (filmsMiniMax: the minimax and minimax-cn presets, or any provider at api.minimax.io, api.minimaxi.com or api.minimax.cn) lists image-01 and image-01-live among its drawers (minimaxDrawers) and draws them on MiniMax's own <host>/v1/image_generation (drawMiniMax), as platform.minimax.io gives it: aspect_ratio from size (one MiniMax lists, or the size it draws for one; else for image-01 a width/height in 512 to 2048 by 8; else the nearest ratio), n, response_format: base64, an edit's images as subject_reference (type: character), and the caller's seed, prompt_optimizer, aigc_watermark and style; no mask. The images are read from data.image_base64 (or image_urls), and a base_resp failure in a 200 is told by its code (1004/2049 key, 1008 balance, 1026 content, 1002 rate) with its status (readMiniMaxDrawing). It went to chat completions before and was answered "unknown model 'image-01' (2013)" (rocbomb123 on X, TestMiniMaxDrawsOnImageGeneration). A routing group named for a drawing or a video (drawingGroup: group/<id>, or a bare id the group goes by that resolved to one of its members) is tried member by member in the order its routing plans for a chat (drawingTries over planGroup), each member over its own keys or accounts (drawOnAccounts, startVideo); the next member is asked while one fails as a chat's would move on (retryable: its vendor 5xx, out of quota, the model not served), never for a refusal of the request itself, and the call's Fallback names those tried first (#2005, tianxia3111: a group of two relays answered the first one's 502). A group with chat models beside its image or video ones is tried on those alone (drawingTries' makes: drawsModel, or servesKind for video), so a drawing never goes to a chat member, on its provider's images API or as a chat asked for an image (changqiu4890 on Discord: a group of three relay chat models, a DeepSeek one and the relay's gpt-image-2.5 drew on its first chat model; TestMixedGroupDrawsOnItsImageMemberOnly, TestMixedGroupMakesVideoOnItsVideoMemberOnly). Codex's image tool draws on the routing group its turn asked for when that group has an image member (codexDrawingProvider gives the turn's group, GroupDraws, then resolveDrawing), and only otherwise on the provider that served the turn or Settings' pick (TestCodexDrawingTakesItsGroupsImageMember). Pause rules and a gateway key's group hold apply as for a chat. A failed drawing rests no member and no key. An account out of quota for the image model (failure reads failQuota) rests that model on it alone (restDrawer, keyed by restID), until the reset its refusal names (resetsAt: Antigravity's "Your quota will reset after 3h19m30s.") or quotaRest, so the next drawing asks the accounts that still have it first (restLast), and the account's text models stay in. Antigravity also tells a model's quota used up as a 200 whose stream is the error; drawCodeAssist gives such an error the status its words stand for (saidStatus: quota or rate 429, credit 402, else 502), as the images API's 200 with no image does, so a spent account hands the drawing to the next one as its 429 does (01huadalang on Discord: a 502 ended the drawing on the spent account; TestAntigravityDrawingOutOfQuotaInsideTheReplyGoesOn, TestAntigravityDrawingQuotaRestsTheImageModel). TestImageGroupMovesOnToTheNextMember, TestVideoGroupMovesOnToTheNextMember. Such a group may be Settings → Models → Images → Image generation's pick (7up6666 on X): the list offers each routing group with a member among its provider's Drawers (GroupDraws), so a request naming no model, the Magpie Image MCP's included, draws on the group; a picked group none of whose members draws any more is DrawerMissing (drawerMissing), the row says so and Automatic draws in its place. TestImageGroupPickedInSettingsDraws, TestImageGenOffersDrawingGroups. A group's Add a model picker offers each provider's image models, /api/groups' drawers (gateway.Drawers less hidden ones, apart from the chat models), said as such and with no reasoning level (jzw690 on X); such a member draws whether or not its provider's picks name it, as picks are of chat models (provider.FindDrawingGroup, used by GroupDraws, resolveDrawing and the image group's turns), and the group is no model agents are offered. A group named on /v1/embeddings, /v1/rerank, /v1/audio/speech, /v1/audio/transcriptions (and translations) or /v1/videos keeps the same way a member its provider's chat list doesn't have (mediaMembers: provider.FindGroupAlso with offChatList), and is tried from its first such member (mediaGroupFirst), so a hand-made group of embedding or speech models of providers with picks is served, not a 404 (XYenon on Discord); a chat model the user unticked stays out. TestMediaGroupOfProvidersWithChatPicks, TestVideoGroupOfProvidersWithChatPicks. The same models need no group made by hand (#5339): a fetched list keeps its models made for another API, each marked with it (catalog.Model.Serves, from the id: catalog.ServesOf; LiveServing), out of the chat models (catalog.Chat), so agents' lists, gateway keys and Routing's chat pickers never offer them, and a moderation model is still dropped. A model of one kind that more than one provider serves under exactly the same id (no other case, no other version) is a group of that kind made per request on its route (provider.KindGroup, mediaMembers and servesKind in media_group.go): asked by the bare id there, or by group/auto-<kind>:<id> (KindGroupID; a chat model's found group's id has no :), never on another kind's route, its members in the Providers order, none switched off and none the model is disabled on. It is in no list of groups (Groups), so no agent, key or picker offers it. Video is the kind video (Videomakers); images keep their own groups. A list saved before this is fetched again once a run, schedule or none (refreshDueLists, catalog.LiveKinded). Another magpie's list (X-Magpie-Drawers) is not marked; its models are found by their id (ServesOf). TestKindGroupsServeEachAPIByRoute, TestVideoKindGroupByTheModelsID, TestKindGroupHoldsTheExactModel, TestKindlessListFetchedOnce, TestFetchKeepsModelsOfOtherAPIs. TestImageGroupOfUnpickedImageModelsDraws, TestGroupEditorOffersImageModels, group-pick-drawers.test.cjs. An account's own list of models (#474) never bars a ChatGPT account's GPT Image, a Grok subscription's Grok Imagine or a WorkBuddy plan's image models (listsCantName): the list is picked from the editor's chat models, which they are never among, so a list kept for some chat models had every drawing refused as "set not to be served by any account" (heyiwei5 on X). A key's list, picked from models that include its image ones, still bars them. TestCodexDrawsPastAccountModelLists. A drawing is given Settings → Models → Images → Image generation timeout (imageTimeout, 1 to 60 minutes, 5 when unset; neighbads on X: a slow image endpoint needed more) as its context's deadline (drawTimeout, drawWithin), and so is downloading an image answered as a link (imageLongest, never under ImageLongest). A drawing's request goes through a transport with no ResponseHeaderTimeout (drawsApart), since an images API sends its headers only once it has drawn, and every other request keeps upstreamHeaderWait (10 minutes). A video's submit, status and download calls keep 5 minutes each (videoTimeout). The magpie mcp image process, which may not read these settings (WSL), waits on a call up to callLongest (two hours and a minute), so it never cuts one the gateway still waits on. TestLongImageTimeoutLetsASlowVendorFinish, TestImageTimeoutSettingReachesTheVendor, TestOnlyDrawingsWaitPastTheHeaderWait. draw.go, draw_volcengine.go, draw_dashscope.go, video.go, catalog.go
Decisions POST /v1/decisions (and /decisions) is OpenAI's Decisions API, checked against openai-python's decisions.create (DecisionCreateParams, Decision): model (gpt-6-luna), input (a string, or messages and items whose parts are input_text, input_image with a data or http(s) URL, JSON), questions (1 to 400 predicate, choice or score questions), and prompt_cache_key, prompt_cache_options, safety_identifier. The answer is {answers, model, usage}, never streamed. decide passes the body through serveRetrieval as embeddings' is, with only model changed, so model resolution, a disabled model, a key's models, accounts and spent limits, pause rules, the provider's keys or accounts, masking (a data URL's image is left as it is) and the Routing page hold as on every route. It goes only to a provider canDecide takes: an OpenAI API key on api.openai.com, Azure OpenAI (IsAzure, at its v1 API's /openai/v1/decisions, the model in the body as the deployment's name), or another magpie, which routes it on. Any other, a relay, a plugin or a ChatGPT sign-in whatever its list says, is never sent it: the try is refused 400 with who serves it (decisionRequest.refuses, next to the no-OpenAI-API check), and a group moves on to its next member. A bare gpt-6-luna is the kind group decision (servesDecision: a provider canDecide takes that lists the model, or an OpenAI key, as the API takes it without it on the key's chat list), so a relay listing the same id is never its member. Usage is recorded as decisions from the answer's usage (decisionRequest.counted): input_tokens less input_tokens_details' cached_tokens and cache_write_tokens as input, those two as cache read and write, and no output, as OpenAI bills none, so gpt-6-luna's own rates price it. native_endpoints is about the chat APIs a model is relayed on, and stays chat/completions and responses. A model that answers System One (systemOneTargets: a decision group's members, else provider.RouteDecider's, none of them a provider canDecide takes, so another magpie still gets the Decisions body) is asked there instead (wudi_boy on Discord: Qwen's decision-model-preview on Decisions was refused): decisionsAsSystemOne turns predicate into noul, choice into a criteria map (a boolean value as "true"/"false"), score into a criteria list of label: description least first, an unnamed question into question_N answered with a null name, and input into the state (a string, or {"messages":[{role, content, refusal}]} with input_json as its JSON text); serveSystemOneBody serves it, and systemOneAsDecision gives the Decisions answer (a choice's value typed back, a score's probabilities by index or label, a missing answer a refusal, usage input and output with no cache split). The prompt-cache hints and safety_identifier change no answer and are left out; anything else with no counterpart is a 400 naming it before a vendor is asked (untranslated: an image unless every target is a Clef or another magpie, an http image, a function or custom tool call or its output, an image or refusal in a question, any other field or question type). The reverse: /v1/systemone whose RouteDecider finds no System One provider (its 404) but resolveRetrievalModel resolves the model is systemOneByDecisions, sent through serveRetrieval as above (systemOneAsDecisions, decisionAsSystemOne). A vendor's error passes through as it was said. TestDecisionsAskSystemOne, TestDecisionsMessagesAsSystemOneState, TestDecisionsUntranslatableRefused, TestDecisionsImagesToClef, TestSystemOneAsksDecisions. TestDecisionsReachOpenAIAndAzure, TestDecisionsRefusedWhereNotServed, TestCanDecide, TestDecisionsThroughAnotherMagpie, TestDecisionsHeldByKeysAndRules. decisions.go, decisions_systemone.go, embeddings.go, media_group.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, strict. Stored in affinity.json next to providers.json. A conversation is kept by its id (affinityID, in stickKey and ruleKey): the agent's session header, else the caller's X-Magpie-Session (#5242: requests that each named a session of their own, and opened alike, were taken for one conversation and kept together; TestMagpieSessionIsTheConversation), else (conversationID, which is what Kilo and a plugin are sent as the conversation, so X-Magpie-Session never goes upstream) a hash of how the conversation opens, which every later turn repeats: its first user message, or, when the agent wrote that one alone (userWords: an <environment_context> block, Reasonix's <session-context …>, an instruction file), the user messages from it through the first that holds the user's own words, an image, a file or a recording (conversationOpening, userOpens). A system or developer message between them is passed over; a reply, a call or a tool's result ends the opening, and with none of the user's before it the first message is hashed alone. One message is hashed as the request has it; several are hashed without their cache marks and with a content of one text part read as that text (writeOpening), since an agent moves its mark on to each turn's newest message, some spelling a marked message as one part and an unmarked one as a string (TestCacheMarkMovingOnKeepsTheID). Before, the first message was always hashed alone, and every conversation an agent opened on the same message in one folder was one: kept under session on the account that answered the first, and never moved on by rotate (keeyangyy, #3938, TestConversationsOnOneEnvironmentMessageAreApart, TestReasonixConversationsInOneWorkspaceAreApart, TestNewConversationsInOneFolderAreRoutedApart). A conversation whose first user message is the user's own keeps the id it had, which the Context page and the Routing page's requests find dsh's sessions by (dshConvs, routeOwners, routeSessions): dsh's pi-ai routes send no session header. A dsh fork repeats its source's opening, so a finished request is named by the id of the reply its client was given (Route.ResponseID, set from clientResponseID as the route is marked done), which dsh writes down on that reply (replayState.response.responseId, read into Session.ResponseIDs: a fork's own replies after its session/end-seed only). Vendors' reply ids can repeat, so a reply's id names a session over the opening only when the opening is that session's own or that of a session it was forked from (ForkOf, from the fork's parentSession; ownerOf), and Routing reads the sessions again for a reply id it has not found only up to a minute after the request ended (looseKeys): a title call's id is never written down (#5491, Flandern1211). A request still running or failed, and one logged before Route had the id, keeps the opening's session. A Claude Code subagent's is kept apart from its lead's by x-claude-code-agent-id (stickKey): Claude Code sends the session's id with its subagents' requests too, and a subagent's answer took the lead's stick over, so the lead's next turn was judged by the subagent's cache and moved to another account, where its whole conversation was written again (slkassinthehood on X, TestClaudeConversationKeepsItsAccountsCache). Behind a remote magpie, the key or account is the remote's key and the provider there that serves the model, its id's first part (remoteUpstream, candidate.vendor, sameVendor): the remote is one key here, but each of its providers keeps its own cache and seals, so a conversation is kept, held strictly, told its seals were refused and given its native compaction's reader by that pair, as the same group on the remote does (fremontdango on Discord: a group of one model from two of the remote's providers kept a conversation on the second as the same account when the first was gone, and a strict one failed over to it; TestRemoteMagpieStrictKeepsTheRemotesProvider, TestRemoteMagpieOtherProviderIsNotTheSameAccount). A remote's group is one vendor by its whole id, its own routing deciding inside it; a model named without a provider is the key alone. Lanes and requests a minute still go by the key here, the limits the user set on it. 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 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), and one held to HTTP/1.1 (HTTP1) is spoken it at those hosts alone. A TLS record error read on an HTTP/2 connection ("bad record MAC", "received record with version …": the bytes under the TLS were mangled, by the far side or a box between) drops that connection, as Go's transport does, and netproxy.Dispatch sends the requests to that host:port over HTTP/1.1 for 6 hours after (markH2Broken, h2BrokenFor; kepner_53726: a company gateway failed 124 turns in 3 days so, each a 200 with no output, until a restart; TestH2RecordErrorMovesHostToHTTP1). Every request to one vendor's host shares one HTTP/2 connection (upstreamTransport); one silent for 10s (no HEADERS or DATA from the vendor since the last request) is pinged, and dropped when no answer comes within 10s, 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 silence answered is pinged again only 5 minutes on (netproxy.CalmHTTP2, PingAgain): Go's own health check pings it every 10s, its ping's answer restarting its clock, and Google's front end, holding clients to gRPC's ping policy (a ping within 5 minutes of the last with nothing sent between is a strike, and the third ends the connection), ended a turn of gemini thinking through Antigravity at ~235s with GOAWAY ENHANCE_YOUR_CALM "too_many_pings" (zdevoz on Discord; TestLongSilenceIsNotPingedIntoGoaway, TestCalmFindsAPathDeadLaterInTheSilence). The try after a GOAWAY goes on a new connection (TestTryAfterGoawayDialsAnew). http.DefaultTransport, whose requests are short, keeps Go's (netproxy.HTTP2Health). 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; 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) 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
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, and 200 MB for the days that are over: today's plain file, however big, takes none of it, TestHistoryTodayTakesNoRoomFromPastDays). 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 A request outside the chat path gets a route of its own too (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, each inline picture's base64 swapped for a ref into keptImages (in memory, 128 MiB at most, least recently used first; image_keep.go), so a conversation of pictures, which DeepSeek's file ids let grow past 64 MiB (#5407), keeps its text and pictures (matrix0487 on Discord; the archive's copy is read the same way, TestFileIDConversationStillShows); 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
Vertex AI A Google Vertex AI provider 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): <base>/publishers/anthropic/models/<model>: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 <base>/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 <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. (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, gateway.go, codeassist.go, gemini.go, gemini_signature.go, search.go
Bedrock Mantle A request on chat completions or Responses to an Amazon Bedrock Mantle provider 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, gateway.go

Codex titles, descriptions, summaries and predictions

Codex's title and description requests are independent hidden turns. The settings CodexTitles and CodexDescriptions select their models separately; an empty setting preserves the requested model. On a Magpie model, both paths wrap plain model text in the object Codex requested. Titles use {"title": ...}; descriptions use {"description": ...} with nonempty text and no invented maximum length. Each has its own Off (off): magpie answers the request itself with a finished reply holding no message, sends nothing upstream and records it as answered here (sentNowhere); the Codex app reads that as no title or no description (its side-turn helper's "empty" result, not an error) and keeps the thread's as it was. Title Off does not turn descriptions off, nor the other way round (cybercaius on Discord asked for the description's).

The Codex app asks for titles, descriptions and one-line thread summaries (thread_summary, after each message) on a model of its own (gpt-6-luna), whatever the conversation is on, and composer predictions (composer_predictions) on the thread's model. An unset setting ("Same as the session" in the picker) sends these on the session's model when it is one of magpie's (codexSideTo with Server.codexSideSession): the model the conversation's own turns last went on (codexLeads: its parent's, the thread it was forked from for a prediction, its own), else the last turn by the gateway key, else, before any turn has come through magpie, agent.CodexSideModel (Codex's config model, when it is magpie's and magpie is not Codex's provider). So a conversation on a third-party model spends none of the ChatGPT account's allowance (atom_Ray on X), whether the model was picked in Codex's config or in the app (cybercaius on Discord, TestCodexAppSideTurnsFollowTheSession). Codex writes a new conversation's title on a temporary thread with no link to it, started as the first message is sent, so it can arrive before that conversation's first turn, when the key's last turn is the previous conversation's, on the model the user just switched from. A call tied to no seen thread whose key's last turn is older than 3s (codexSideFresh) waits, up to 5s (codexSideWait) or its cancellation, for the next turn and takes its model (codexLeads.sideOf, TestCodexTitleBeforeTheFirstTurnFollowsTheSwitch); a later rename suggestion with no turn beside it waits the 5s. One that comes before the key has had any turn at all (the first new conversation after magpie starts) waits the same way, and takes the config's model only when no turn comes: read at once, it went on the config's model, another provider's than the one picked in the app (tenacious_eagle_96548 on Discord, TestCodexFirstTitleFollowsThePickNotTheConfig). A memory call before any turn is Codex consolidating as it starts, and takes the config's model at once. Codex starts its memories with each turn of a conversation that has the user's input (codex-rs start_memories_startup_task; extraction under that conversation's thread, consolidation on a thread of its own), so a memory call waits the same way even when tied to a seen thread (sideOf's beside): one that beats the first turn after a switch, in a new conversation or one under way, goes on the model switched to, through the ChatGPT backend (codexMemorySession) and with magpie as Codex's provider (codexMemoryStandIn, which reads codexLeads before its last-turn record), cybercaius on Discord (TestCodexSideCallsBeforeTheFirstTurnFollowTheSwitch, TestCodexMemoryOfASwitchedConversationFollowsTheSwitch, TestCodexMemoryStandInFollowsTheSwitch). A call tied to a seen thread and not started with a turn (a prediction, a known thread's title) takes that thread's last model at once. With magpie as Codex's provider (/v1/responses) the model in such a request is not the user's pick either: the Codex app asks a new conversation's title on its provider list's default or first model that takes low effort (app.asar's oX), never the thread's, so a title, description, summary or prediction there goes on the session's model (codexSideSession, through codexSideTo), and on the model asked only when no session's is known (tenacious_eagle_96548 on Discord: titles on another provider's qwen while the conversation was on dsf4.1, TestCodexOwnTitleFollowsThePickNotTheAppsChoice). settings.CodexTitles, when set, still writes every title. Codex asks a title with no reasoning effort on any model but its own title model, and its auto-review at a model's default, which it has none of for magpie's models; a model that needs an effort answered those with 400 (cybercaius on Discord). A title, description, summary, prediction, auto-review or memory call on one of magpie's models whose levels are known, asking no effort or an off one the model hasn't, is asked at its lowest on level (codexSideEffort, TestCodexSideCallAskedAtAnEffortTheModelTakes). Wherever the levels aren't known, serve asks any request again once at its lowest (low) when the upstream turns no effort or none away as needing one, matched on the error body (effortRequired, on Chat and Responses, forwarded or translated; TestEffortRequiredRefusalAskedAgainAtLow), or turns none or minimal away in alwaysThinks' words, which name no levels (needsReasoning: Kimi Code's K3.1 Pro on Chat, #3739, TestKimiChatThinkingOffRefused), then at the model's lowest from the start; any other 400 goes back as it came (TestOtherBadRequestNotAskedAgainAtLow). A session on Codex's own model sends them to ChatGPT as Codex sent them, whatever the config says (TestCodexAppSideTurnsStayWithAnOwnModelSession); so does a session model magpie can't serve now (turned off, gone, held from the caller's key). Summaries use {"summary": ...}, with any other string the schema requires (compactSummary) filled and cut to its length (summaryJSON).

codexTitlesTo, codexDescriptionsTo, codexSummariesTo, codexTitle, codexDescription and codexSummary in codex_titles.go own this selection and response wrapping. Both the Responses API and Codex backend entrypoints use it. Usage and Routing retain the original purpose; unusable description answers are recorded as description failures. These helpers do not decrypt foreign sealed history or repair ChatGPT's response protection.

Codex's composer predictions (#1970), its guess at the user's next message, are another hidden turn on a fork of the thread, sent only through the ChatGPT sign-in, with thread_source composer_predictions. Each one reads the whole conversation again. CodexPredictions selects where they go: empty sends them as Codex asked, off answers {"suggestion":null} from magpie and sends nothing (sentNowhere, as title Off mode), and a model id sends them to that model. codexPredictionsTo and codexPrediction own this, at the same two entrypoints. A model's answer reaches Codex only as the {"suggestion": string|null} object it asked for (predictionJSON): plain text is never taken as a suggestion, as Codex would put it in the user's composer as their next message, so it gives no prediction and the call is recorded as a prediction failure (noPrediction).

Runtime path

  1. handle(proto) reads the body and the model (requestBody, requestModel), then calls serveAgent. 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 through readBoundedRequestBody in request_bounds.go. It decodes a Content-Encoding of gzip or zstd (decodedBody; Codex sends zstd to a custom provider's /v1/responses too, #1223) and drops the header, so the provider is sent plain JSON, with one exception: a ChatGPT account's turn (POST CodexBase/responses, from the accounts loop in forwardOnce or relayed by codexUpstreamOn) is compressed again with zstd and a window of at most 2 MiB, as Codex's own client sends it (provider.CodexCompressed; openai/codex responses_request_compression and http-client/src/request.rs). It is compressed once the body is final, and again on each try. /responses/compact, an API key's requests and every other provider stay plain. Sent plain, a 1.1 MB text-only turn was answered 503 (ylorn on X). The plain body is what magpie keeps and shows, and codexDropped judges a reset by the bytes that went on the wire. codexDropped also reads Envoy's 507 "exceeded request buffer limit while retrying upstream" (the backend failed and the front couldn't retry a body that large) as that reset, at any size, told as a 503 so magpie, Codex and pi ask again and nobody rests (#2034). The size limit (defaultBodyLimit, 512 MB) holds for the decoded bytes (413), and any other encoding is refused 415. It was 128 MB until a long Codex session that had read many images went past it decoded, its inline screenshots resent each turn, and got the 413 on all five of Codex's retries (#1422, TestImageHeavyCodexTurnIsRead). Codex's own path (codexBackend, the relay, its WebSocket, and keyLimited on it) reads to codexBodyLimit instead: a sixteenth of the machine's memory (memLimit, else proc.MemTotal), 512 MB at least and 2 GB at most, since Codex keeps every image it generated in the conversation as base64 and over HTTP resends it whole each turn; a session that generated and revised images went past 512 MB while Codex signed in to OpenAI went on (dallascao on Discord). One of Codex's own models is relayed at about 2 to 5 times the body in Go heap at its peak (1000 MB took ~12s and ~2 GB of heap past the body); a turn for a magpie model is translated at several times that and is still held to 512 MB once its model is read, its 413 saying Codex's own models take more (TestCodexGeneratedImagesPastOldLimit). magpie's own 413 says it is magpie's gateway limit, with the size, and that the provider was not asked (overLimit); writeError adds to any 413 it isn't holding that this is a byte limit, not the model's context, and to /compact or start a new conversation (TestOverLimitSaysWhoseAndWhatToDo). Every shape but Gemini's types a 413 request_too_large, Anthropic's own type, which pi's overflow table knows: pi compacts and tries once more rather than stopping on an OpenAI-shaped api_error (@wilsonxuuuu on X, TestPayloadTooLargeSaysRequestTooLargeToPi). keyLimited reads a limited key's compressed body the same way, so its reservation is the decoded size. A JSON body's text that isn't text, bytes that aren't UTF-8 (a GBK file, a surrogate written as UTF-8) and a lone surrogate's escape ("\ud800"), becomes U+FFFD there, one per bad byte, as Go's decoder reads it (textBody in body_text.go); a surrogate pair's escapes, an escaped backslash and a multipart or audio body are left as they came. magpie sent such bytes on as they were, and DeepSeek and OpenAI answered 400 while MiniMax answered 200 with nothing, so a group's request worked or failed by its member (laincatx on X). A turn isn't refused for them: a tool result holds a file's bytes, and every later turn of the session resends it (TestBadTextReachesVendorsAsReplacement, TestBadTextOnSocketAndGemini). serveAgent runs the middleware chain, then serve.
  2. serve redacts secrets in the request (redacted; redact.MaskJSON leaves ids alone, and in any text a backend's id (a UUID, 32 hex digits or more, or a digest of 16 to 31 hex digits in one case with letters and digits both, a cache key or a short commit, which went as a key before: _kaichen on X, 10-28; digestShaped), or an element token cua-driver hands the model for computer use (s0000002a:14, #3782), goes as written: no rule, model label or value known from before masks a piece of one (a phone number at the end of …-a13800138000, a card number across a UUID's groups), and a whole one is masked only by the user's own words and rules or as a credential, by the password, API key and token rules or a secret rule whose field is named for one (api_key=, refresh_token), never one named for an id, a cursor, a request or a digest (secret_id, next_page_token, Idempotency-Key, secret_hash), nor cua-driver's own element_token (any other name with element in it, element_api_key, is a credential's as before), a bare key (not after api, access, secret, private, signing or license: keyPhrase), a field named for a cache, commit, object, blob, file, content, revision, partition, shard, bucket, dedup, lookup, row or sort key, a serial number, or what the model takes a UUID or an element token for, nor an element token known from before (one the model labelled in prose a turn earlier) (noIDs, internal/redact/ids.go); and a tool's name and its MCP server's (namespace, server_label, server_name, #3143); the request's tool definitions and output schemas, found by their place in each protocol (top-level tools, tool_choice, response_format, text, generationConfig, stream_options, the client's ids in client_metadata and the like, and the tools of a Responses additional_tools or tool_search_output item), go as written save their descriptions, so a word the user masks can't break a grammar or an enum (#1911); 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; a text masked for a vendor before, such as a system prompt or a turn already sent, is masked as it was then on the same route (the providers the request can reach: its model's, its fallbacks', or a group's members'; maskedFor, masking.WithRoute, redact.Options.Route), so neither a value a rule first finds later in a conversation nor a name the local model reads in a tool's output only after its first send (the default model's 2s wait, pii.Partial; vvrfxyz on X, dsh's cache hits) changes the prompt the vendor has cached and rewrites all of it to the cache; such a late find is masked in new text (learnLate), and another route, never sent the text, gets it masked with what is known and found now, sentSpans, TestModelReadingLateKeepsTheSentPrefix, TestMaskedPrefixKeptOnlyOnItsRoute), resolves the model to a provider or a group, and refuses what can't be served. The reply has the values put back on its way to the agent (redact.Writer, a stream event by event, a whole body at its end, before the writer outside it that names the member, memberWriter, writes what it holds: the other way round a whole reply with a value masked in its request went out a 200 with an empty body, #4129, TestMaskedWholeReplyNamesMember): a placeholder the model wrote as it was given, or as models rewrite one (spaces inside the braces, a brace or both dropped, another case), is the value again when what is left names one magpie made, and one split across events is held until it is whole (redact.Restore, partialTail, internal/redact/redact.go). Every reply is read so, a request that masked nothing too: a vendor holding the conversation (Codex's compacted history, a server-side session) answers with placeholders sent turns before, and those came back as written (yapechan123 on Discord, a table of {{PERSON_…}}、{{PERSON_…}}; TestReplyToAnUnmaskedTurnIsRestored). Every string of an event is read, a tool call's name, type or data inside its arguments too, but for signatures, data: URLs and opaque blobs (sealedText); a held tail is kept per string, so a Responses event's random obfuscation never takes the hold from its delta; a whole body with a placeholder in no braces or one is restored as with two (heldIn); an audio, image or other binary reply goes through as it comes (binaryType). Past 200,000 values the half used longest ago is let go (makeRoom, touch; before, a random half, so a value just masked could be gone when its reply came). Values are held in memory only, so a placeholder from before a restart that only the vendor still holds comes back as written. A request whose provider and fallbacks, or whose group's models, all skip redaction (unredactedRoute, provider.SkipsRedaction: set Send requests unmasked, Unredacted, and has an address: the user's switch for each provider whatever its address, AcMilan on Discord, http://llm.corp.lan:8000; nothing is looked up to decide, TestSkipsRedaction, TestLANNameUnredactedProvider. A signed-in subscription and a plugin's provider take it too, kept with the account's model picks (withPicks; isee1_1 on Discord: a translation plugin as a provider); and so does another magpie (CrazyMouse_TT on X, his own model behind it): it is sent the request as written with no X-Magpie-Masked-As (withMaskedAs is never called), so it masks by its own Settings › Privacy and its own providers' switches (TestUnredactedRemoteMagpieMasksOnItsOwnSide); left off, it is sent the request masked here, as before. The editor shows it for every provider, another magpie with no caution, and, while it is on, a caution under it naming an address not on this computer or the local network, or, for a subscription or a plugin's provider, its name (unmaskRow, awayHost in app.js; a name of the user's own DNS is asked about, only while it is on, through POST /api/local-hosts, provider.LocalHost, which takes a name every address of which, looked up in 400ms and kept a minute, is loopback, private or link-local, netproxy.LocalName; no request asks it)) goes to them as the agent wrote it and isn't masked on its way, since a request is masked only once its route is known (#3973: masking a body whose masked copy was thrown away took up to minutes of magpie's own time). The log, recent calls and the request archive keep it as it went (the archive's bodies have their secrets taken out, redact.ScrubJSON, as every call's do), whether the archive is on or off; an observer that wants the bodies (the OTLP export, a JS plugin's) is handed it masked, masked once when it is first handed it after a try (Call.maskIn, laterMasked), never before the request is sent. A request turned away before it is routed is logged masked (maskedCopy). count_tokens, embeddings, speech, transcription, pictures and videos (unmaskedMembers over the models the picture or video may be made on: a group with one member left on is masked) and Ark's own API (nativeArk, as nativeAny) follow the same rule (TestUnredactedProviderDrawsWhole, TestUnredactedProviderMakesVideosWhole, TestUnredactedProviderArkNativeWhole); Settings › Privacy lists the providers set so, each opening its editor (Sent unmasked, unmaskedRow in plugins/redact/settings.js, unmaskedProviders in /api/settings). System One follows it too: a /v1/systemone request, and a /v1/decisions one translated to it, is masked once before its tries (serveDecideTries, TestSystemOneMasked). A request masking would change can go to such a model instead (jessyoungyu on X: 「{{百度}}这家公司怎么样」 can't be answered from a placeholder): with Settings › Privacy's Instead of masking, send to set (RedactRouteTo, POST /api/settings/redact-route, which takes only a model MaskRoute passes: unredactedRoute for its provider and fallbacks, or its group), an agent's turn that masking would change (maskHits.n > 0: a warn-only hit doesn't count, and a held-back one stays held back) goes as written to that model, the model asked for left alone, in serve after the request is masked (maskRouteFor in redact.go; the masked copy is thrown away, so streaming and every API go as for any route). If it fails, the request fails: its fallbacks are all unmasked ones by unredactedRoute, and nothing is masked and sent to the model asked for. It is judged again on each request, so a route that has since got a vendor's address, a fallback elsewhere, was turned off, or isn't one of a gateway key's models is ignored and the request is masked as before. Only an agent's own turn is moved (agentTurn, set in serveAgent and cleared by ownAsk): a title, a search stand-in, a picture described, System One and Jev stay masked. count_tokens is counted on the route (countTokens), and a turn of Codex's own model on its ChatGPT sign-in goes there too (codexMaskRoute in codexBackend; masked once to decide, only while it is set). Such a turn, and ChatGPT's web search for it (alphaSearchOn), goes as written when the Codex subscription it is on is set to go unmasked (codexRouteUnmasked; TestCodexSignInUnmaskedSwitch); a plugin's provider is asked through serve (TestPluginProviderUnmaskedSwitch). Speech and video requests are never moved to that model: they are masked unless their own route is set to go unmasked (maskTextHits). Unset, as by default, nothing changes. Tests: TestMaskedRequestGoesToTheModelSet, TestCodexSigninTurnGoesToTheModelSet, TestMaskRouteOnlyForTheAgentsTurn, TestMaskRouteTakesOnlyUnmaskedRoutes (mask_route_test.go) and TestRedactRouteSetting in internal/gui. What a routing group's Jev is told of the turn (the message, the user's message before it and the reply to it) is masked all the same unless Jev's own provider skips redaction too (maskedState in askJev, decide.go): a remote Jev is none of the group's members. The masking is the built-in plugin redact's (gwmw.Masker, Plugin runtime); when the settings ask for masking and no masker serves, or it fails, the request is a 503 and nothing is sent (redacted, gwmw.Masking). A request masking swapped a value in (maskHits.n) is told, on each try, that the placeholders are used as written and filled in before anything runs (placeholderNote, placeholder_note.go; treeMan on Discord: weaker models refused to search with one, asked to verify it, or rewrote it as an example). The note names neither magpie nor a vendor or client. It goes where placeholders first appear, after what is there, so it is new text the first time and the same on every later turn: in the instructions when they or the tools hold one (the last block of Anthropic's system, the end of Chat's first system or developer message, a part after Gemini's systemInstruction's), else on the earliest message that holds one (a text block or part after its content; on Responses a developer message after that item and the tool outputs that follow it). Responses instructions (Codex's base_instructions) is never touched. A conversation's values are masked again each turn and a value found later is masked only in new text, so the note never lands in text the vendor has cached (TestMaskedConversationKeepsItsCachedPrefix goes red with the note in the system prompt). It is not added for a Claude subscription (the bridge puts the caller's instructions in the run's first message, which Anthropic classifies), for a ChatGPT account (Codex's own turns, codexUpstreamOn, never pass here either), or for a Responses turn with previous_response_id, where it would pile up in the stored conversation (notesPlaceholders; TestPlaceholderNotePlaces, TestPlaceholderNoteNotOnClientPaths, TestMaskedRequestTold, TestPlaceholderNoteIsNeutral). count_tokens counts without it. Inside a tool call's arguments (Anthropic's tool_use input, Gemini's functionCall args) and Gemini's functionResponse response, whose keys are the tool's, a field named for a secret (SecretName: api_key, db_pass, Authorization, not sort_key or public_key) has a value of 8 characters or more masked by its name whatever its shape, with secret masking on (#2946, namedSecret); a key anywhere else is the protocol's, mcp_servers[].authorization_token included, and never masks by its name (TestMaskJSONSecretNamesOnlyInToolArgs).
    • With Mask personal data on, each kind in redact.Categories (internal/redact/more.go) is masked unless the user turned it off (redactKinds in settings, Options.Kinds). On by default: US SSNs, passport numbers, IBANs that pass mod 97, birthdays next to a word that says so (a date over a year ago: one in the last year or ahead is the day an agent runs on, dateOK); the word must be right before the date, so a log line's or a file name's date is none, and a time beside the date doesn't make it a log's: a date of birth stored as a time (1990-05-11T16:00:00.000Z) is one (TestBirthdayLogDates; #3878), MAC addresses, and serial numbers next to S/N or the like. Eleven digits from 13 to 19 are a mainland mobile's form and an id's too, so they are a phone only with +86 or 86 before them, as the value of a field whose name says phone (phone, mobile, tel, cell, contact, 手机, 电话, a field named number), or in prose with no id's word right before them (order, id, no., #, 订单号, 编号, 单号, 流水号); under order_id or uid, after 订单号, or with a letter or digit against them they go as written (phoneAt in internal/redact/phone.go; kaichen on X, 10-28). 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. When the user name is on, it goes as a made-up name of 8 lowercase letters, the same for that name every turn and put back in replies like any placeholder (standIn in shape.go), not as {{USERNAME_…}}: with mimo-v2.6-flash a model read C:\Users\{{…}} as a temporary folder and set out to delete it (eerttreeeert on X, 10-28). A user name found once is masked again as known (8 bytes or more) only where it stands as the user's name: a path's part, name@host, a git author, ls -l's owner, uid=501(name), prose, a quoted string; not where code has the same word as a name of its own, joined to another part (developer_dir, self.developer, developer.go), declared, assigned, called, a parameter or a JSON key (nameAlone). A User: line's unquoted value made of words one of which says it holds a user (current_user, UserInfo, loginName) is a variable's or a type's name, not a login (notLineIdent); a quoted one is masked (TestUserNameInCodeIsNoUserName, TestUserLineInCodeIsNoUserName; Tomyu_2034 on X). A public IPv4 or IPv6 address goes the same way as a name that says what it is, public-ip- and eight lowercase letters (public-ip-kvxqmrtz), the same one for that address while magpie runs and never another address's, put back only where it stands as a whole name, in a streamed tool call's arguments too (ipStandIn, restoreAddr; TestIPGoesAsAPublicIPName). Told {{IP_…}}, models asked the user for the real address or searched ~/.ssh for it instead of running ssh (0x0_air on X, 10-28). Told an address from the documentation ranges (192.0.2.0/24 and the like, used from 10-28 to 10-31), they ran ssh but told the user, when asked why it failed, that it was an example address and not their server's, and a 192.0.2. one read as a LAN address (akic404 on Discord, 10-31). A name with no dot reaches nobody if the vendor tries it itself. An EVM address (0x and 40 hex digits) is public, so the local model's finds leave it as written unless a key's name is right before it; a 64-digit private key is still masked (evmRe in modelFits; TestEVMAddressGoesAsWritten). A number written in hex, 0x and 1 to 16 hex digits (an address in reverse-engineering notes, a constant, a flag), is no value of any kind the local model finds, whatever is before it, since the function at an address is often named for a key; a longer one (a key in hex) is masked still (hexLiteral in modelTakes; TestHexNumberGoesAsWritten, TakaNaShi_ShiKi on X). Decimal digits alone that the local model calls a secret are a count, a time or an id unless the name right before them ends in a key's, a token's, a password's or a PIN's word (api_key=, PIN:, 密码是): Claude Code's <total_tokens>14998720 tokens left</total_tokens>, "total_tokens": … and max_tokens: … go as written (numberNamedSecret in modelFits; TestTokenCountIsNoSecret, steven_4422 on Discord). Context rules run only near their words (rule.matches). What reads as an address but ends in a file's extension that no domain has (…@2x.jpg, strings@base.json; fileExt in realEmail), or a scale before an extension that is a domain too (icon@2x.zip, intro@1.5x.mov; scaleExt), is a file's name, for the rule and the local model alike (#3029). A domain needs a dot and labels a host can have, so a disassembly's symbols go as written for both too: system@plt, puts@got.plt, memcpy@GLIBC_2.14, foo@@GLIBC_2.2.5, and system@got (.got is a top-level domain; mailHost in realEmail, TestSymbolIsNoEmail; ch35tnut on X, 10-28). ops@files.zip is still an address. The Settings rows come from REDACT_KINDS in app.js, which TestRedactKindsAreRedacts holds to the same ids and defaults.
    • With Find with a local model on (masking.ModelWanted: on by default since 10-28, settings.RedactModel the user turning it on and RedactModelOff off, this computer's own, kept by KeepOwn; a user with a model downloaded or picked and neither flag turned it off before the default, and RedactModelAuto marks the default's own download), a local model finds what no rule can, a name or an address in free text, under the same switches: a name, address, phone, email or account number is personal data, a secret a secret (modelKinds, modelSpans in internal/redact/model.go). MaskJSON asks it once per request, for every text it would mask, each once (withModel), but for what the agent defines (its tools' and schemas' descriptions, under defKeys), which the rules alone mask, as with the model off, after the rest of the request so a value the model found in a message is masked there too as known: those were 52,577 of Claude Code 2.1.296's 67,532 bytes the model read, and a 4-core server's first request waited out the gateway's 2 minutes (niuniu_8964 on X; 11.5s cold at 4 procs on a Ryzen AI Max+, 2.6s without them, and on three real Claude Code requests the model masked nothing there the rules didn't); its spans join the rules' with a rule's kind kept where both find a value, and ids a vendor or tool made (req_…, toolu_…) are never taken, nor a snake_case word as a name (Codex's sequential_cutoff, #3144), nor one word as a name where what is around it says a thing and nothing says a person: an app's name in a list of names alone, in a list of apps, or beside a thing's word (using, switched to, the … app, vs, 这个软件), so Privacy Filter's Cicada and Mimi in a chat about choosing apps go as written, while a full name, a Chinese name and a first name beside a relation, a greeting, said or he/she are masked as before, and a text of one first name alone goes as written by design (thingNamed in thingname.go; ylorn. on Discord, whose follow-up questions had the names as written while the history had them as placeholders, so the vendor answered about another app), nor as a secret what names a thing: a UUID, a digest with its algorithm's name, a file's path (namesThing; the model takes all three for secrets). A package's name goes as written, for the model and the rules alike (dniray on Discord, v0.1.1917): the module a line of code loads (from ' drizzle-orm ', require('jsonwebtoken'), from x import, use x::, with an editor's line number or a diff's mark before it; moduleAt, codeHead), a manifest's dependency pinned at a version ("drizzle-orm": "^0.36.4", TOML's x = "9"; dependencyAt), a folder under node_modules or site-packages, the module an error could not find (Cannot find module 'x', No module named 'x'; missingModuleAt), a package an install names (pnpm add x; installedAt) or pins with @ (x@0.36.4; pinnedAt), all in packageAt; a value known from an earlier mask (knownSpans) goes as written there too, since once the model took the name for a secret anywhere in a request it was masked on the import line as known (dniray, v0.1.1965), a requirement's name before its pinned version (django-rest-passwordreset==1.4.0; pinnedAfter), a lock file's integrity hash (sha512-…; sriRe in namesThing), a version as the value of a field named for a secret ("js-tokens": "^4.0.0-beta.1"; versionValue in fieldAt and keyAt), and a package pinned at its version as user@host has it (js-tokens@4.0.0: in pnpm-lock.yaml; notPackagePin); TestPackageNamesGoAsWritten and TestModelPackageNamesNotMasked hold them. A field named for a secret and set to nothing takes nothing from the field after it: the SECRET rules let a space stand after = or : (password = hunter2 in a config), and env -i UI_PASSWORD= UI_ADDR=127.0.0.1:39117 ./syncer went with UI_ADDR=127.0.0.1 as UI_PASSWORD's value (mx_albert on Discord); a value that is an assignment of its own after a space (UI_ADDR=, addr=, --listen=) is the next field, read with its own name, so a token there still masks (fieldMatches, nextField in internal/redact/fieldvalue.go; TestEmptyFieldTakesNotTheNext, TestSecretBesideEmptyFieldMasks). The model misses many Chinese names (张伟 after 给, 陈建国 after 客户, however low its threshold) and runs a name it finds on into the words after it (「王芳,她下周一」), so with Privacy Filter a Chinese name is also found by its surname and a word around it that says a person is meant (客户, 我叫, 给…发, …先生, …说, joined by 和 to another name; 和 or 与 says so only after a person, 吴敏和郑浩 but not 判断和边界, 发 or 打 only as the verb, 发了个 but not 关键发现, and a sentence starts after punctuation, not after a space after code, gh pr view 易触发; xuanwo on X; 一下 only after a verb that asks a person, 问一下张伟 but not 改一下文案, a word any subject takes after it, 已经, 明天 or 他, only with a person's cue before it, and 说明 is no 说; zeewell on X), and the model's are cut at punctuation and titles (zhname.go); a surname with nothing around it (王国的, 张开的) is left, and so is a common word that starts with one (zhWords: 文案, 文档, 方案; 毛利, 毛重, 毛巾, since 毛利 is a margin far more often than the Japanese surname, so 毛利低 goes as written: _kaichen on X, 10-28; the model still finds 毛利兰, and neither model nor rule masks 毛利小五郎), the model's own name too when it is that word whole. A name the model or the cues take is also no name when it is an ordinary word (zhWordShaped, zhWordNotName, the one check both go through): a colour (黄绿色, 红色, any that ends in 色 or is colour characters alone: hh05928822 on X after v0.1.1850), a word that starts with a surname from zhWords or zhDict (about 1,550 two-character words from jieba's dictionary, zhdict.txt, its header saying how they were chosen; 边界, 应该, 尚可), or such a word with what makes a longer word after it (关键词, 关键字: wangjunxiao128 on X; 应用层, 毛利率), unless a role before it or a title after it says a person is meant (客户方圆, 江山老师), where a name that is also a word is masked. The surnames stay (黄 starts 黄绿色 and 黄晓明), and 毛利兰, 关羽 and 黄晓明 are still masked. With AstrLink Guard only a nickname is (小王, 老李, zhNick; redact.Options.NamesByModel): Guard at 0.8 finds the full names those cues did in zhname_test's sentences (张伟, 陈建国, 欧阳娜娜…), and misses the nicknames, 孙经理, and all but the surname of 王老板 and 邓总; the cues took words for names (关键发现; xuanwo on X). The model is the user's pick (settings.RedactModelName, pii.Choose; the app's menu beside the switch, pmPick): AstrLink Guard (QuantumNous/astrlink-guard at a pinned revision, Apache-2.0, a 39 MB int8 Multilingual-MiniLM token classifier for Chinese and English), run in magpie's own process on the CPU by internal/pii/guard (an ONNX reader, the XLM-R tokenizer and int8 kernels in Go, NEON/SDOT on arm64 and SSE2 on amd64; its labels named as Privacy Filter's, guardLabels); a text over one window, 510 tokens, is read in windows that overlap by 128, and on the CPU as many windows at once as it has cores, half of GOMAXPROCS and 4 at most (guard.Cores: on every core a long history unread kept a 32-core Linux box at 13 cores' worth for as long as requests came, xinvxueyuan and shensmart on Discord, 10-28): one window's matmuls split over the cores left them idle between, and a 4-core server's first Claude Code request waited minutes (niuniu_8964 on X; 22,488 tokens took 23.9s at 4 procs, 17.9s at once, and 48.8s against 30.5s at 2), and on a Mac through CoreML on the Neural Engine or the GPU (coreml.go, internal/pii/guard/coreml; yyhhyyyyyy on X; Settings › Privacy names which, from CoreML's own compute plan of the compiled model, MLComputePlan on macOS 14.4 and later, the device most of its program's estimated cost is on (coreml.Plan, Model.Backend, Status.Via and Device): it said "on the CPU" under CoreML, yyhhyyyyyy on Discord, 10-27; an M5 Pro's plan puts all of it on the GPU; after a CoreML read fails it says the CPU and why until one doesn't): the same network from the same int8 weights in float16, written from the downloaded model into a program made by coreml_gen.py and compiled once into the model's folder, 512 tokens in about 12 ms where the CPU takes 400, its probabilities within .07 of the publisher's fp32 model where the CPU's are within .13 (the CPU quantizes activations as the int8 model does, CoreML doesn't), so a span near the threshold can fall the other side (a go.mod module path is a secret at .81 on CoreML, .79 on the CPU, .785 in fp32); a window under 16 tokens (coremlMin), a Mac before macOS 13 or any failure goes to the CPU, loaded on the first request and let go after 10 minutes with none; or OpenAI's Privacy Filter. With no pick it is AstrLink Guard, the default; a user who had Privacy Filter on before there was a choice keeps it only while AstrLink Guard downloads, which the first masked request starts and which then saves AstrLink Guard as the pick (masking.picked, toGuard; an hour between tries after a failure). Measured for that default (#3578): on 234 segments of real code and config it found 2 spans where Privacy Filter found 100 (38 of them go.sum hashes after redact's own checks), and with the rules it found 42 of 42 test values to Privacy Filter's 41. Each model has its own download, cache file and turn (backend). AstrLink Guard's turn has guard.Cores() places (guardTurn), so that many requests read at once, and they share those cores: every window, of any request, takes one of guard.Cores() tokens before it reads and more only while they are free (guard.take), so requests together never read on more cores than one did (the 4 promised xinvxueyuan and shensmart above); the model loads once (guardLoading), the idle timer lets go only when no place is held (guardIdle), and a text one request is reading another waits for rather than reading it too (backend.reading). Before, one request read at a time, and an agent's parallel requests queued behind it (yyhhyyyyyy on Discord, 10-28, who asked for 16 at once). Measured at 1, 2, 4 and 8 requests at once (a Ryzen AI Max+ 395 under WSL, 4 cores): 512-byte requests 4.2, 6.1, 8.1 and 8.4 a second where one at a time was 4.2 whatever came, on 1.9 to 3.9 cores, memory flat at about 150 MB; 4 KB requests already read their 3 windows on 3.6 cores alone, so they stay at 0.6 a second (Windows on the same box: 7.5 to 12.1 a second at 1 to 8, 4 KB 0.7 to 0.8, on at most 3.8 cores). Each request on cores of its own would read 20 a second at 8, on 12 cores, and 4 KB at 8 took 20 cores and 521 MB (953 MB on an M5 Pro), so the bound is the cores, not the count, and there is no setting for it. Through CoreML the GPU is the bound: on an M5 Pro 4 KB requests read 23, 20, 25 and 25 a second at 1, 2, 4 and 8, a model per request no faster, so CoreML reads one window at a time, and only the windows under coremlMin or after a failure use the CPU's tokens. Both find at a floor of 0.5 (pii.Floor) and give each span its score (AstrLink Guard: the least of its tokens' probabilities, rounded to a float32 so a cached span reads back the same; Privacy Filter: pf-serve's own), and masking keeps those at the model's threshold or over (pii.Threshold in masking.model): the user's for that model (settings.RedactModelScore, this computer's own; Settings → Privacy's Confidence threshold, pmScore, 0.5 to 0.95), else the model's own (MinScore: Privacy Filter 0.5, AstrLink Guard 0.8, its publisher's). A value known from before follows the same threshold: each value masked remembers the highest score anything found it with (a rule's counts as sure), and one only the model found, under the threshold now, is no longer masked again as known (noteScores, knownSpans in known.go; before, a raised slider changed nothing for a value masked once: _kaichen on X, 10-28). The defaults stay because on the eval a higher one mostly loses values the checks after the model would have kept (Privacy Filter at 0.85 lost a Chinese name; AstrLink Guard at 0.9 a phone in a tool result), while the false alarms it would drop are mostly dropped by those checks already (Yayoi_no_yume on X). Measured again on 2000 segments of real agent traffic (Codex and Claude Code sessions: prompts, tool arguments and results, a quarter with Chinese) and 30 more labelled cases: AstrLink Guard at 0.88 rather than 0.8 drops 3 false alarms (a model id, a sandbox path word, a token counter) and lets a colleague's name and a signed name through; Privacy Filter at 0.88 rather than 0.5 drops 11 (timestamps in paths, log lines, a plugin id) and lets 6 real names and a phone through (4 of the names in the real traffic). Lowering Guard to 0.5 finds 2 more names in the real traffic and 3 more labelled values, for 10 more false alarms (9 of them Claude Code's <total_tokens> counter). Those false alarms are shapes a check can turn away; a threshold can't without losing real values. Privacy Filter is a q8 GGUF (1.6 GB), run by pf-serve (native/privacy-filter, built from privacy-filter.cpp on ggml and released under pf-v* tags; on a GPU it holds the model once, in the device's memory, #3590; every pf-serve keeps the engine's own MoE chunk, PF_MOE_CHUNK at the window's 4096, which an RX 470 through Vulkan read 6-9% faster than 2048 in interleaved runs and Metal ~6% faster, and inherits a value the user set): Settings → Privacy's On downloads both (pii.Download, each checked against its pinned sha256, through magpie's proxy (netproxy.Func, as its other requests; hh0592821 on Discord, whose download went direct before), from hf-mirror first in China (source.chinaFirst) and from hf-mirror after Hugging Face everywhere else, the switch off too (source.modelMirror), so a poisoned or blocked huggingface.co doesn't stop it; hf-mirror serves AstrLink Guard's files itself and sends Privacy Filter's back to Hugging Face) and saves the setting only once they are on disk (/api/privacy-model, privacymodel.go). pii.Find starts pf-serve on the first request, in the model's folder and given the model's file name, never its path (a Windows C program's argv is in the ANSI code page and ggml reads it as UTF-8, so a user folder named in Chinese failed every load with the path in mojibake, AIMetaPhD on X; a pf-serve error that names the file is shown with the whole path) (Metal, Vulkan, else the CPU; one that dies on the GPU, doesn't load there in 40s (gpuLoadTimeout, well inside the gateway's 2 minutes), or doesn't answer in time there twice in a row, is started on the CPU, and Settings says why; a request it didn't answer in time once is tried on the GPU again, since a slow request on a weak GPU is no lost GPU (#3682). The GPU is tried again 10 minutes later, doubling to 2 hours while it keeps failing, with no restart (gpuRetryAfter), and one that answers is the model's again), joins short texts into 12 KB chunks and maps the spans back, cuts a text over 12 KB into pieces of 12 KB at most that overlap by 1 KB (pieces: after a line's end, else a space, of those in the piece's second half the one whose 48 bytes before it hash least (landmark), so a line edited early in a text leaves the pieces after it as they were, else at a rune's start), each kept by its own hash, their spans put back at the text's offsets and merged where pieces overlap (merge: one found twice is one, one cut by a piece's end is whole), and a value of 8 bytes or more found in a text is found wherever else it is in it, as sure as its surest find (spread: the model scored an address on 400 lines alike 0.9 on some and 0.5 on most, wangwu25685333 on X), and asks pf-serve a chunk at a time (#3682: a 480 KB text whole took an RX 470/580 90s and kept nothing when cut off), keeps the last 20000 answers by hash, on disk too (found-<model>.bin beside the model: hashes, offsets, labels and each span's score, never text; a pfound01 file from before scores is read with every span sure, so it masks as it did; written through temp-and-rename, a bad read taken as empty), so a restart doesn't ask the model about every history again (#3682), and ends it after 10 minutes with no request. Its requests take turns on its one pipe (turn), and a request reads the cache again when its turn comes; a request waits for its turn only while its context lives (pii.FindContext, through gwmw.ContextTeller), so one whose client went away leaves the queue (the gateway's 2 minutes leave masking's time out, #3682); the chunk pf-serve is on is finished and kept, so a request sent again asks only about what is left, and between chunks the turn is given up and taken again, by the request waiting with the least left to read (takeTurn, queue), so a short request goes before the rest of every long one (wangwu25685333 on X: a 5 KB request behind two long ones on 4 cores waited 8.3s in the order they came, 4.5s now). The status (pii.Now), pii.Stop and the idle timer never wait for a load or a request: srv.mu is held only to read or set the state, and Stop ends a load or a request under way at once. A request held before routing while it waits for the model is answered 504 saying so, and how to send without it (unroutedMsg); one of an older tag (oldTags, magpie updated since the download) runs until the pinned tag's is fetched (upgrade, on its start), which is then started on the next request and the old deleted (internal/pii). A failure names what ended pf-serve: magpie's own end of a request it didn't answer in time, else its exit status or signal and its last stderr lines past ggml's startup chatter (died, lastSaid). After one, requests are held back at once with that failure, not after a load each, until the model is tried again 30s later, doubling to 10 minutes while it keeps failing (heldBack, retryAfter; lazyeo on Discord, an M2 whose every request waited out the 504). Until the model is on disk the rules mask alone, and its download starts (masking.fetch, an hour between tries; the default's, done, saved by settings.UseDefaultRedactModel unless the user picked or turned it off meanwhile; cancelling it is turning it off). A model the user turned on that fails (didn't start, isn't on disk, held back after a failure) panics, so the request is held back with the 503 above rather than sent with the rules' masking alone (masking.model, strict); the default's finds nothing then, and the rules mask alone. A model that is only slow is waited for at most 2 seconds from the request's masking start when on by default (masking.defaultWait) and 15 seconds when the user turned it on (masking.strictWait): its turn, its load and its reading. Past that, or when the request's context ends first, pii.FindContext answers with what was known of the request's texts by then (its cache: the history read on earlier turns, and the chunks read meanwhile) and a *pii.Partial saying how many it hadn't read; masking.model masks those with the model's finds and the rest with the rules alone, logging it at most once a minute (notePartial), and the request goes. Nothing the rules mask goes as written. Before, the user's model was waited for with no bound and any end of the wait held the request back whole, its known finds thrown away: in a burst of requests with text the model hadn't read, xRayySummers on X (0.1.1877, Linux) saw masking take 1.2s to 290s in one minute and each request it ended was "masking failed, so nothing was sent". Reproduced on 8 cores of a Linux CPU: AstrLink Guard reads about 6 KB a second there (a 125 KB history 20.8s), and six requests at once with 67 to 145 KB of new tool results each took 62 to 110s, all ending near the last, since the turn goes round between chunks; with the bound each went at 15.0s with the history's finds and the model's for 1 to 4 of its 9 texts. masking.find gives a model that doesn't stop for its context 100ms to answer with what it knew (handBack) before giving up on it. AstrLink Guard reads on the CPU, so a long Codex history it hasn't seen took minutes there, and every request queued behind it showed masking with no bound (shensmart on Discord, 10-28, magpie in Docker). The wait is given up even where Find doesn't stop for its context. A request that stops waiting leaves the chunks after the one being read (backend.find), so it doesn't hold the turn; that chunk's answers are kept for the next request. Each model reads a request's unread texts newest first, the last text and a long one's last piece before the rest (backend.missing), since an agent's history is oldest first and what a request adds is at its end; AstrLink Guard joins them into chunks of 4 KB, not Privacy Filter's 12 KB (backend.chunk, guardChunk), so the chunk a request leaves the model finishing past its wait is about a second on 4 cores. The default's request is pii.Bounded: what one went without the model's reading is remembered by hash (backend.sent), and a request after it reads what it adds first and that backlog backlogCap (4 KB) at most, nothing found for the rest, so a history resumed or never read is read a little a request rather than on every core for each one. Measured on a 2 MB, 200-turn Codex history never read, 30 requests 3s apart (TestLiveHistoryCost, gated on MAGPIE_GUARD_FILES): on a 32-core Linux box 33 to 60 CPU seconds a request before, 23 minutes of CPU over the session's 108s (13 cores busy), 6 to 10 after, 4 minutes over 90s (2.7 cores), and on an M5 Pro's CoreML 2.2 CPU seconds a request for the first three before, the first alone after; nothing runs on after the last request either way. A request the user turned the model on for still reads all of it, waited for strictWait.
    • 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-rule with the rule's index and its current value, editRedactRule in internal/gui/api.go). Every rule is checked by redact.CheckRules when 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 masker reads the rules from settings on each call (options in internal/masking), so a change applies to the next request.
    • The user's own masked words (redactWords, Options.Words; Settings → Privacy's Masked words) go as {{TERM_…}} whatever else is on, and come back as written. They match as written, inside longer words too, unless the user asks: Masked words in any case (redactWordsAnyCase, WordsAnyCase) matches in any capitals by Unicode simple folding, and Whole words only (redactWordsWhole, WordsWhole; acmilan_ on Discord) skips a match with a letter, digit or _ beside it, and for a number a . and digit beside it, so ABC masks name='ABC' but not XABCD, and 123456 not 91234567, 0.123456 or 123456.78 (wholeWord in redact.go). Chinese and Japanese letters count as no letter there (wordRune): a word of theirs is found inside their text, and ABC in 用ABC做 is whole. Both are off by default; a page from before them that saves without the field keeps the user's choice (api.go). TestWordsWhole, TestWordsWholeJSON, TestCountTokensRedacted. A word that is a date (1990-05-12, 1990/5/12, 1990年5月12日, May 12, 1990; eight digits alone are not one) matches that calendar date in every common form instead (dateSpans in dateword.go; JackyCcao on X, who masks their own birthday with birthdays off): - / . 、 or a space between, 年月日 or 년월일, with or without leading zeros, 19900512, the month's English name, and day-first or month-first only where the day is over 12 or equals the month (13/05/1990, never 05/12/1990, which is December 5th too; such a word matches only as written). A match never has a digit, or a dot and a digit, beside it, whatever Whole words only says, so 1990.5.12.1 and 11990-05-12 are not that date. TestDateWordEveryForm, TestDateWordNotAnotherDate, TestDateWordDayMonthOrder.
    • With Keep a key's form on (settings.RedactShape, Options.Shape, under Mask secrets; Charles Cao on X), a secret of 16 characters or more, all letters, digits, -, _ or ., goes as a made-up key of its form instead of a placeholder: its prefix kept (sk-proj-, ghp_, AKIA, up to four letters and their separator; keyHead), the same length and separators, and each other character a random one of its kind (a hex key's any hex digit of its case), drawn from an HMAC of the value under the placeholder key, so one key goes as the same made-up one every turn and a vendor's cache still matches (shapeOf, shaped in internal/redact/shape.go). Personal data, the user's words and anything shorter or with other characters go as placeholders still. A made-up key is kept in the masker's memory with the placeholders, so it is recorded, re-masked in what a vendor sealed, and put back wherever the reply has it, before the placeholders (restoreShapes); a stream holds the end of an event that may be the start of one (shapeTail, after the last whole one), and a made-up key the vendor sends back unrestored isn't masked again (outsideShapes). TestShapeKeepsForm, TestShapeJSON, TestShapeStream. Insights › Masking and Settings' Try it mark a made-up key where they mark a placeholder, matching the text against the request's own values only, so a key of the same form the user wrote isn't marked (maskMatches in plugins/redact/page.js; #3599, masking-records and mask-actions GUI tests).
    • What is done with a value found is the user's per kind (#1977, redactActions in settings, Options.Actions, set by POST /api/settings/redact-actions; a kind left out is masked). redact.Warn sends it as written: the masker tells it, with a placeholder no one remembers, and it isn't counted as masked. redact.Block masks it as any other, and the gateway holds the request back with a 400 that names the kind and the value's hint, never the value (blocked, maskBlocked in redact.go); nothing is sent and the record is kept as Blocked (noteBlocked). A value on the Never mask list (redactAllow, Options.Allow, POST /api/settings/redact-allow) goes as written when it is the whole value found, in any case, and isn't told; a longer value it is part of is masked. It wins over every finder, the user's own rules included (a rule's pattern with one value let go), but not over Masked words: a value on both lists is masked, and so is a masked word inside a value the list lets go (apply in internal/redact/redact.go; TestMaskedWordsWinOverAllow). It holds from the next text on: a text sent masked on a route before (a conversation's earlier turns, sent again with each request) keeps the value masked, with the same placeholder, so the vendor's cached prompt still matches; a new text sends it as written (NicoleS76448271 on X, allowkept.go: a hash of the route, the text and the value, two generations of 2^17, in memory only, so after a restart or on another route the value goes as written; TestAllowKeepsSentTextMasked). The request view's value menu adds a value it masked (POST /api/masking/allow). Settings → Privacy's Try it posts a text to POST /api/masking/preview (masking.go), which masks it as a request would be (redact.Preview) and remembers nothing: its placeholders stand for nothing afterwards, its values aren't masked later as seen before, and it returns only the masked text and each hit's kind, finder, action, placeholder and hint. The page keeps the text in no storage.
    • Each request that had anything masked is recorded as it goes to the vendor (noteMasked in masked.go, from chat, the Codex backend, search, images, video, System One, embeddings and audio; count_tokens is masked and not recorded). The masker says what it swapped through gwmw.Teller (JSONHits, TextHits: each placeholder's kind, its finder, redact.ByRule, ByYours, ByWord, ByModel or ByKnown, and a hint of its first characters and its length), and internal/maskrec keeps one line per request in a file per day under ~/.config/magpie/masking, 30 days and 100 MB in all: the agent (the one usage records, callerOf, so a request another magpie passed on is named by the agent it came from, not as magpie; linkaww on Discord), session, provider, model, and each placeholder with its kind, finder, action and hint, never the value. A chat, an embedding or a video whose group can pass it to another member is held in memory until the request is over (noteMaskedUntil, maskrec.Hold), and its line names the provider and model the last try went to, not the first planned, which a failover may never have reached; the list sorts each day's lines by key, since a long request's line is written after later ones. The text around each placeholder as the vendor saw it is kept in memory only, for the last 400 records, and what a placeholder stood for only in the masker's own memory (Teller.Value); after a restart neither is there. A recent call (Call.Masked) and the route trace (Route.Masked) carry the counts and the record's key, which the Gateway and Routing pages' badge opens in Settings → Privacy (/api/masking/*, internal/gui/masking.go). A masker without Teller, a plugin's, masks as before and records nothing. Under a test binary testenv isolated nothing is written (maskrec.inTest). The page's Clear records… (after a confirm) posts /api/masking/clear, and maskrec.Clear removes every day's file whole under the store's lock, with the in-memory text around placeholders; a day it can't remove stays listed and is named in the error. What the masker holds for each placeholder stays, so a placeholder still in an agent's context is put back in its answers.
    • DecidesModel gives a 400 (decisionModelRefused; a decision group, decisionGroupRefused), and count_tokens gives the same 400 before the vendor is asked. For OpenRouter, a variant of a model its decisions list names (inception/mercury-decide:free, picked by hand) is a decision model too (openRouterVariant): OpenRouter lists the model once, and answered such a variant 400 "is a decisions model" on chat/completions (coeo91 on Discord).
    • A gateway key held to some models (keyHolds, #882) gets a 403 for any other model. A routing group passes only through groupAllowed, which every route asks (the model lists' entryAllowed, serve, countHeld, embeddings, images, videos, decision groups, a subagent's and masking's route): a group of the user's own only when the key names it, whatever its members (kautism on Discord), a found group (foundGroup), or any group for a key that names accounts and no model (Identity.AccountModels), when the key may use every member; never a group bound to other keys (groupBarred, see A route group bound to chosen gateway keys), which bars a key held to no model too; a bare name that is both a group of the user's the key may not use and a model it may use is that model for the key (keyGroupFor; TestGatewayKeyGivenAModelIsNotGivenItsGroup). A decision model is one: serveSystemOne and the decision list another magpie asks for (DecidersHeader) hold the key to it, while a group the key names asks its own decider in askJev with no key check (TestGatewayKeyHeldToAGroupKeepsItsDecider); the key editor offers the decision models (GET /api/caller-keys/models, decides, TestCallerKeyModelsOfferDeciders, gateway-key-deciders.test.cjs).
    • A gateway key held to some MCP servers and tools (Key.MCP, access/mcp.go, wakaka on Discord) is held on every MCP route, in mcp_key.go: serveMCP refuses a server it may not use with a 403 (mcpKeyServe), leaves its tools out of tools/list (mcpKeyList) and refuses their tools/call with -32602 (mcpKeyCall); the hub is held per Library server behind it (hubServersOf, hubTools, the hubToolNamed fallback and hubMCPRun, which every hub call goes through); /mcp/<name> and /mcp/run/<name> go through mcpKeyGuard, which reads the request for a refused tools/call (a batch with one gets a 403) and passes the server the body as it read it (strictMCPBody: a JSON-RPC or params key in another case, which Go's decoder would match, is a 400, and a key given twice goes once, as checked) and filters a tools/list answer, JSON whole or SSE event by event (mcpToolsFilter), refusing with a 502 an answer it can't read (a Content-Encoding); /v1/magpie/mcp lists only the key's servers (ownMCPList). An issued key is held to its issuer's list too (Identity.MCPServer, MCPAllows). Tests: TestKeyMCPOwnServer, TestKeyMCPHub, TestKeyMCPProxy, TestKeyMCPRun, TestKeyMCPRelayReadsOneWay, TestKeyMCPFilterRefusesUnreadable; the picker is GET /api/caller-keys/mcp (TestCallerKeyMCPRoutes, gateway-key-mcp.test.cjs). A model's own web search, served through magpie's search, is not an MCP call and is not held by it.
    • A model the user disabled (#1867) gets a 403 for every caller (idOff), before anything is sent; see Disabled models.
    • Sealed tasks (#619) are checked here. A Codex subagent's task its lead's spawn_agent sealed 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 (leadProvider of the request's conversationID, #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, an input_text note 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 conversations affinity.json keeps, 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), and leadFirst reads 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. It also says what is sealed (sealedTaskItself, #1855): the task itself, spawn_agent's message, which the backend returns sealed (encrypted_function_args) and Codex hands the subagent as it came, so fork_turns="none", which only leaves the lead's turns out, doesn't help; nothing in it can be left out for the subagent to go on.
    • 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-subagent read as kind:collab_spawn) before this check, whatever model its lead's spawn_agent asked for (codexSubagentPick in codex_subagent.go): in codexBackend for one of Codex's own bare models, which then goes through serveAgent, and in serve for 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. With "Codex subagents on any model" (settings.CodexAgentsV1) Codex's catalog says V1 for the ChatGPT account's models, the groups one is in, and every model a provider of no sign-in on the Responses API serves (catalog.Model.Seals, provider.CodexSeals): a relay of the ChatGPT backend seals a V2 lead's tasks as the backend does, and its own Codex-shaped entries say V2 (brethhbbm on X, relay/gpt-6-astra). A request carrying a task the ChatGPT backend sealed (sealedTaskIn: a sealed agent message that isn't a MESSAGE, which withoutSealedMessages leaves 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's kindWhy says it. Set to lead (provider.CodexSubagentLead, "Same as the lead"), the model is the one the lead's own turns last went on (codexLeads.lookup: the parent thread's, else the session's, else the gateway key's last turn), with SubagentPick.Lead; codexBackend then picks for any model asked, a magpie model too, and a lead on one of Codex's own models takes the subagent to the ChatGPT sign-in on it (in serve such a lead leaves the request as asked). With no lead turn seen, the request goes as asked. The lead's turns, titles and every other kind are never moved.
    • With no model set for them in Codex's config ([memories] extract_model/consolidation_model, read by agent.CodexSideSet; a config it can't read counts as set), a Codex memory call on one of Codex's own bare models, made in a conversation whose own turns go on one of magpie's models, follows that model instead of going to the ChatGPT sign-in (codexFollowTo in codex_follow.go, cybercaius on Discord). The model is the parent thread's last own turn (x-codex-parent-thread-id or the turn metadata's parent), else its own thread's, else the last one by the gateway key (codexLeads, at most 512 threads), else, before any turn has come through magpie (Codex consolidates its memories as it starts), Codex's config model when it is one of magpie's (servedSession, TestCodexMemoriesBeforeAnyTurnFollowTheConfig). A memory call is read after the turn it was started with (codexMemorySession, above). A model magpie can't resolve now or one a gateway key may not use leaves the call as it came. A subagent never follows: Codex starts a spawn that names no model on its lead's (codex-rs child_config.rs), so a bare model in a subagent's request under a lead on magpie's was named (spawn_agent's model, [agents] default_subagent_model or a role's config), and with no model set for Codex's subagents in magpie it goes on that model (TestCodexSubagentKeepsTheModelItWasNamed, mengxiao on Discord); only settings.CodexSubagentModel moves it (codexSubagentPick). Codex's auto-review follows the session only when settings.CodexAutoReview is session (settings.CodexAutoReviewSession): codexcat then has each of magpie's entries name itself as auto_review_model_override, and Codex's own entries keep OpenAI's, since codex-auto-review is free on a paid ChatGPT sign-in (#1593). On a Free plan it isn't (cybercaius measured it on Discord), so with the setting unset and Codex's live sign-in on the free plan (codexcat.AutoReviewModel, the plan from provider.CodexSignInPlan), it counts as session (TestCodexAutoReviewOnAFreePlan).
    • A model set for Claude Desktop's subagents (settings.DesktopSubagentModel, the Agents page's Claude Desktop "subagent model") is put on a subagent's turn in Desktop's Code tab or Cowork after desktopTurn, the tiers and the groups, whatever model its lead or its tier asked for (desktopSubagentPick in desktop_subagent.go). Desktop runs its Claude Code with CLAUDE_CODE_PROVIDER_MANAGED_BY_HOST=1, under which Claude Code ignores the CLAUDE_CODE_SUBAGENT_MODEL magpie writes into its settings (see agent wiring). A subagent's request is one with x-claude-code-agent-id (subagentOf) from claude-desktop, and only one that offers tools is its turn: Claude Code's tool-less helper calls inside a subagent, on the haiku tier's model, stay where they are, and so do the lead's turns, terminal Claude Code's and every other agent's. The model set must be served by its exact id (provider.DesktopSubagentUnserved: Resolve takes any model name under a provider that is on), enabled, and allowed to a gateway key held to some models (groupAllowed for a group); otherwise the subagent goes on the model asked for and the route trace says why (Route.Subagent, said on the Routing page by subagentWhy, its Kind staying empty). Route.Model and the ledger's Requested keep the model the subagent asked for. count_tokens counts on the model set the same way (countTokens). The setting is read on each request, so a change needs no restart of Desktop, and a provider renamed since it was set is read by its new id (RenamedRef). A Desktop on another computer that reaches magpie with a named gateway key is read as Claude Code (agentOf), so none of Desktop's routing, this included, applies to it. A subagent's turn, moved or not, is never kept as the session's model in claude-desktop.model (desktopTurn's bySubagent): a subagent on the opus tier's model took the session's place until the lead's next turn, and Desktop's titles asked for meanwhile went to it.
    • Desktop's subagent effort (settings.DesktopSubagentEffort, desktopSubagentEffort in desktop_subagent.go) applies to the same subagent tool turns, independently of model replacement. Empty leaves requests unchanged. Set, it takes the place of a request model's effort suffix before the existing attempt-level effort fitting: a member fixed at an effort wins, then this pick fitted within group/model levels, then the turn's or request's effort. withFixedEffort can enable reasoning when it was disabled, or disable it with none on a model that supports that level; a reasonless model is still sent no reasoning fields. countTokens applies the pick after restoring any unmasked body. Route.Effort keeps the incoming effort, Route.SubagentEffort the configured pick, and each try and usage record the level actually sent; the Routing story explains the configured pick even when no model was replaced. A nonempty model pick already classifies the turn, so the effort check reuses it; empty effort costs only a held-settings read. The next request takes a changed or cleared effort without a Desktop restart.
    • Every Claude Code subagent's turn, Desktop's or a terminal's, moved or not, keeps its x-claude-code-agent-id in Route.SubagentID (subagentTurnOf in desktop_subagent.go): a request with the id that offers tools and names no kind, the turn the two settings above take. Claude Code 2.1.295 sends the id from any agent context but the main one; its x-claude-code-request-class and x-claude-code-agent-type hints go only to a first-party base URL or with CLAUDE_CODE_GATEWAY_HINT_HEADERS, so magpie doesn't get them. A Desktop pick or effort that found the turn is trusted, so the body isn't decoded again, and a request without the id isn't decoded at all. The Routing page tags it as Codex's subagents are (tagKind in routing.js): in the request list, the story, the replay and the tray panel, with the reason kindWhy gives Codex's. Kind stays empty, so its purpose stays unmarked in the Purpose filter, as in the ledger and on the Usage page. The ledger's Subagent keeps the same id, and also marks a subagent's tool-less helper calls, which aren't tagged. A route recorded before this has no id and no tag.
    • A request a stand-in of magpie's put on another model than the agent named keeps that model and the rule in Route.Moved (ModelMove{To, Why} in trace.go, set by move in serve): Claude Desktop's moves (desktopMove in desktop.go: desktop-title, desktop-check, desktop-gone, each with a -first form when it went to the first model listed for want of a chat turn or a menu pick, desktop-tier, desktop-beside, desktop-aside), classifier, claude-tier, stand-in (the agent's config), codex-turn (codexMemoryStandIn), dsh-compact (dshCompactTo in dsh_compact.go: DeepSeek Harness's compaction, known by compaction-basic's ask in compactAsks since its llm-pi-ai routes send no x-deepseek-harness-compact, goes on settings.DshCompactModel when it is enabled, served by its exact id and allowed to the key, else stays as asked with a log line; Musikrv77852 on X, #5395, TestDshCompactMoved), dsh-compact-rested (dshCompactElsewhere, the same file: a compaction DeepSeek Harness asks on the model it switches away from, before a turn on another, that no compaction model took, whose provider has every key or account out of its allowance or held for a while (quotaHeld, timedHeld), goes on the same model from another provider, the one with the widest window that is served, allowed to the key and not resting itself (provider.AutoGroupOf); dsh fails the switch over a refused compaction, so a WorkBuddy rate limit held every model the user switched to, Trae CN's included (qtwaiter on X, TestDshCompactLeavesRestedProvider, TestDshCompactStaysUnlessRested). With no such provider it stays as asked, with a log line; a switch from a model nobody else serves still needs the compaction model set) and privacy (maskRouteFor). A subagent's move says its own (Route.Subagent), and a group or Resolve names no move. The Routing page tags such a row Title or Stand-in (movedTag, movedWhy in the routing plugin's client.js), in the list, the replay and the tray panel, and says why in the row's title and once in the story; a kind's tag wins, and its story still says the move, but for Desktop's connection check (connection_check), whose own story says where it went (movedSays). Neo on Discord read Desktop's title on chatflowsai/claude-opus-5-5 (the only Claude-looking id Desktop is shown, so its own pick) served on the chat's agentrouter/gpt-6.1-sol as the model swapped unasked (TestClaudeDesktopMoveSaysWhy, routing-moved-why.test.cjs). Codex backend rewrites done before serve (codexFollowTo, codexMaskRoute) show the moved model as asked and have no Moved.
    • A Chat or Responses client's effort spelled off (reasoning_effort, or reasoning.effort, any case) is read at the top of serve as magpie's own off level, none (offAsNone, plugins#334), and a model asked <model>:off as <model>:none (askedAt): every check and route below reads none, a model with an off level is sent its own spelling of it, and one without goes at its least level as none asked does (fitEffort). off itself is never sent on. saysOff looks for it without parsing the body, which only a body naming it pays for.
    • A level a vendor names in words of its own (catalog.EffortAliases: Trae's light and extra_high, which Our Free Model's plugin lists) is the level it is (EffortLevel): effortOf reads it as low or xhigh, and NearestEffort places a model's own words by it, so low asked of a model listing light is sent as light, and its light as it is (nianshou5 on Discord; TestNearestEffortTakesVendorWords, TestPluginThinkingOff). dsh and Pi offer such a model's levels as theirs, sent in its words (modelEffort in agents.go; TestDshOffersTraeNamedLevels).
    • Rules and image inputs are handled here too.
    • A rule is decided as a user's turn begins and held for the rest of it (ruleFor, rules.go). What counts as the user's own words is one helper, userWords/userSaid in prompt.go, which the turn count (turnIn), the classifier's question (userText), the conversation's key (firstWords, in ruleKey and the affinity scope), the conversation's id where no session header names it (userOpens, in conversationID), Copilot's Auto (lastUserText) and the prompt breakdown's turns (userSays) all go by. It drops <system-reminder …> blocks (a source= attribute too) and any text that begins as an agent writes for the model alone: Codex's <environment_context>, <user_instructions>, <turn_aborted>, <user_shell_command>, <subagent_notification> and # AGENTS.md instructions for …; Claude Code's and ZCode's <task-notification>, <subagent-notification>, agent lists ("Available agent types …", "New agent types are now available …"), TodoWrite and task-tool nudges and rewind notices; ZCode's <plugin_reference>; the Codex app's <in-app-browser-context …>; Reasonix's <session-context …>, its snapshot of the workspace (keeyangyy, #3938). The Codex app's context before ## My request (for Codex): is dropped and what follows it kept (the injected list beside agentsFor). A user message with nothing of the user's in it (and no image or file) begins no turn: after an answer or a tool round it carries the turn on (within), so the turn's rule and stick hold and the classifier isn't asked; right after the user's words it leaves their turn as it began. The classifier is asked about the last user message that has words of the user's, only those words (userText: past 4000 runes, its first 3000 and last 1000). It is told what came before it too (turnBefore, @HirotaNagai on X: a short follow-up said alone, 继续 or fix that, came out the hardest kind): the user's message before it, the same way and cut to 1000 runes (priorCap: the first 750 and the last 250), and the assistant's last reply between the two, its text parts alone and their last 1000 runes. A tool call's arguments, a tool's result, thinking, a search's hits and the system prompt are never in either, and a reply of only tool calls is none. Jev gets them in its state as previous_user_message and previous_assistant_reply beside message, previous_message_kind and previous_message_reasoning, each only when there is one, and its intent, level and effort instructions name the ones there are (jevState, priorAsk in decide.go); a classifier asked in words gets them in <previous_user_message> and <previous_assistant_reply> before <message> (writePrior). Both come from the request the rules parsed, so Privacy masks them as it masks the message, and the answer kept for a message is kept for it with what came before (classify's key). TestTurnBeforeEachProtocol, TestTurnBeforeCuts, TestJevIsToldWhatCameBefore, TestChatClassifierIsToldWhatCameBefore, TestClassifyKeepsAnAnswerPerTurnBefore, TestJevSeesTheTurnBefore. firstWords hashes the words of the first user message that has any, so an instruction file or notice the agent changes beside them doesn't move the conversation to a new key and lose its stick mid-turn (#1826: ZCode's TodoWrite nudge classified as a new, harder turn, and three keys for one ZCode session). TestTurnInSkipsWhatTheAgentPutIn, TestUserTextSkipsWhatTheAgentPutIn, TestFirstWordsAreWhatTheUserSaid, TestIntentHoldsPastWhatTheAgentPutIn.
    • A rule's members go first (ruleOver, applyRule): the members it names, in order, then those the matching rules after it name (ruleOrder), each not resting, then the group's others to fail over to. A member that is a group in the group is one member here: its models keep the order the group's own routing planned them, where ranking each by the group's listed order pinned a rotate group's first member on every request the rule put it first (#2407, TestRuleNamingARotateGroupKeepsItsTurns). That holds within the turn too, at the group's rule and at each nested group's (nestedRules): the one the turn stays on (affinity) stays first while it is of the rule's member that goes first, and the member's others follow it ahead of the group's others, so a failure fails over within the member the rule chose before going outside it. One the turn was kept on outside that member, which took over when the member failed, isn't held there: once one of the member is out of its rest, the turn's next request goes back to it (Affinity.Why rule). Before #1946 (XcodeFish) a held rule's order wasn't applied to a kept turn at all: a coding-quality member failing mid-turn failed over to coding-fast, the parent's first, and the turn stayed there. TestHeldRuleFailsOverWithinItsMember. Two groups in the group may share a model (the same provider, model and effort): it is asked once a request, where the walk met it first, and provider.Member.Also keeps its later places, each with its own path, At (its place in the walk) and Fast. A rule naming the later group has the model as that group does (Member.In, membersNamed), in that group's own order, and the nested rules below it, Fast and the first token's wait go by that group's way down (homed, homeCands). Before #2361 (davisjiahao) such a rule found none of the shared models, read unready, and the group ahead of it answered. A pause rule naming the later group still leaves a shared model to the group ahead of it. rule_shared_test.go.
    • How sure a decision model (Jev) must be of an intent for it to count is the group's own (provider.Group.IntentSure, JSON intentSure, 0 to 1; missing keeps jevSure, 0.4; magpie group set <group> intent-sure=0.25, empty to unset; SaveGroup and the CLI refuse a value outside 0 to 1, NaN too; cloneGroups copies it). readJev keeps Jev's likeliest intent with its sure and marks a topic answer (verdict.Topic); ruleFor applies the group's sure (intentOf), so two groups sharing one classifier and its cached answer each judge it at their own. "none of these" is never an intent, at 0 too, and levels keep the turn before's level when torn, as before. A chat model asked in words answers with no sure and is taken as it answers. The Routing groups page carries the value through every save of a group but has no field for it yet (#5101). TestGroupIntentSure*.
    • A classifier's timeout is global (Settings.ClassifyTimeout, JSON classifyTimeout, seconds, in settings.go). Missing or 0 keeps the 8-second default; saving accepts 1–60 seconds or 0 and rejects negative values or values above 60. Settings.ClassifyWait bounds a hand-edited value above 60 to 60 seconds and uses the default for a value below 1. classifyTimeout() reads it for each call: both askChat in classify.go and askJev in decide.go give the classifier that time, including its provider's failover. A request shares one such wait across every routing group it goes through (Server.askWaited, from the first classifier asked): a nested ruled group asked with less left gets only that, one asked once it is spent goes by its order at once (waitSpent, "spent by the routing group above"), and a classifier or decision key cut short that way is not rested (cutShort). Each nested level had a whole wait of its own before, so three ruled levels whose classifiers didn't answer held a request past the unrouted watch's 2 minutes, a 504 (heatonz on Discord, v0.1.2215; TestNestedGroupsShareTheClassifierWait, TestDecisionKeyCutShortIsNotRested). Settings → Models → Replies → Intent classifier timeout (renderReplies in app.js) offers 8, 15, 30 and 60 seconds and shows a custom valid value as its own choice. A change applies to the next classifier call, with no restart; the existing fallback, 30-second cooldown (classifyRest) and 10-minute answer cache (classifyKeep) still apply.
    • A classifier that can't say which kind a turn is (an error, no answer within classifyTimeout(), an answer that isn't a number, or resting classifyRest after a failure) leaves a turn whose conversation had an intent, still one of this turn's, with that intent (Classified.Fallback is previous, its Error kept), so the turn goes where the turn before went rather than to the group's first member; with no intent before, no rule with an intent matches, as before. The Routing page says the turn kept it (classWhy). The turn's decision itself (turnRules) is kept in memory only: after a restart a turn under way waits for the next one and the stick holds it meanwhile. TestIntentClassifierFailsKeepsThePreviousIntent, routing-intent-fallback.test.cjs.
    • A group's classifier is asked only for that group's own turns: a request whose model is the group (group/<id>, its bare name, or a stand-in an agent's config names it by: Claude Code's tiers, Codex's bare name), or a group in it that its rules or order put first (nestedRules). A request for another model or group asks it nothing. The Routing groups page's card says why the classifier couldn't say the last time that group asked it (GroupClassifierFailure, kept by classifiedFor in ruleFor): the classifier's own words and time, resting or not, until it answers that group, and nothing once the group's classifier changed. Keyed by the classifier model alone, a group nothing reached showed another group's failure on a classifier they share (jjt on Discord). A classifier on a subscription out of its quota is not asked of the vendor again until the reset: out of quota, its account rests until the quota comes back (restAfter: the time the refusal names, else when the account's window renews), and the classifier's call meanwhile gets that refusal back from magpie, at most once each classifyRest. TestClassifierFailureIsTheGroupsOwn.
    • The classifier's requests are magpie's own (#1839). Asked in words, they go out with RouterAgent's User-Agent (magpie-router/1), so their records' agent is magpie and callKind marks them routing; a decision model's (Jev, System One) record is written with Kind: "routing" too. They go to the same key or account as any other request and count in its totals, while usage.Group.Own (Record.ByMagpie: agent magpie or one of its magpie- User-Agents, with search's and image description's) says how many of an account's, key's or model's calls, tokens and cost were magpie's own. A classifier set to a subscription's model (modelRef.Sub, or a group whose first member is one) asks that subscription as every turn begins, twice when it picks both intent and effort in words; the Routing page says so beside it (classifierSub in plugins/routing/client.js). TestIntentRoutesATurn, TestJevPicksTheIntent, TestSummaryCountsMagpiesOwnCallsApart, TestByMagpie, TestServedRefSaysASubscription, own-requests.test.cjs.
    • A rule may name several members (Rule.More after Rule.Use, more in the group's JSON, use=a,b typed; monkeyin_92 on X: one rule, several models, not a rule each). They go first in that order, ahead of the later matching rules' members (ThenUses leaves out every one the rule names) and the group's others: when the first fails or rests the rule's next takes the request, and the hit says so (RuleHit.More; Instead is that next one with Unready false, where an Instead from a later rule comes with Unready true). Uses, SetUses, MapUses, Without and Names in grouprule.go are how every reader goes through them: cleanRules (each must be the group's, each named once, a pause names one), the turn's hold, the tool rounds and compaction (ruleFor, the rule's first that takes the summary), nestedRules and ruleLed (the one of them a nested group's turn stays on), ruleEffort (the rule's useEffort asked of each), ruledEntry (what a group takes is what every one of them takes), a model's rename and removal (a rule goes with its last), ShareGroup and its import (one this magpie hasn't is left out of the rule), the CLI's groups rules and the TUI. The editor draws a chip per member with a + for the next and an × on each while there is more than one (rUses/setUses in plugins/routing/client.js). A rule of one member writes no more, so a group saved before it reads and saves as it was. A magpie from before it reads use alone: its requests go to the first, and the others are plain members in the group's order; if it saves the group, more is dropped. TestRuleSeveralModelsInOrder, TestCleanRulesSeveralModels, routing-rule-models.test.cjs.
    • The editor's rules are checked top first, so their order is theirs to set: a rule's number is its handle (ruleHandle, .rt-rhandle), dragged (dragRows, as the members are) or moved a place with Alt+↑/↓, the rules renumbered at once; the grip beside it shows on hover only, and Move up and down stay under its ⋯ (moveRule). Saved as the group's rules in their new order. routing-rule-drag.test.cjs.
    • A rule can set the reasoning its member is asked for (Rule.UseEffort, useEffort in the group's JSON, use-effort=low typed; #2633, dengtongcai: an intent picks the model and the effort as a pair). It is an output like Use, not a condition like Effort. ruleFor copies it onto the hit (RuleHit.UseEffort) from the rule that put a member first, outer or nested; ruleOver keeps that rule's members, and ruleEffort gives each candidate of them the level fitted to its model's own (fitLevel), which withFixedEffort writes into the request's field for its protocol (Chat's reasoning_effort, Responses' reasoning.effort, Anthropic's thinking budget or output_config.effort) even when the agent asked none. A member fixed at an effort keeps its own; otherwise the rule's beats the model's suffix, the turn's pick and the agent's pick, and isn't bounded by the group's levels. A model whose levels aren't known (Efforts empty) is asked as the agent asked, as with the auto verdict. The members the group fails over to are asked it too (#3664): the effort is the turn's decision, so when the rule's own member is turned away the member that takes the request over is asked the same level, fitted to its model, rather than the agent's. A rule that names the candidate goes before one it only fails over from, and a nested group's rule decides for that group's members only: when the whole nested group fails, the outer group's member outside it is asked as the agent asked, or by the outer group's rule (TestIntentEffortSurvivesTheGroupsFailover, TestNestedRuleEffortStaysInItsGroup). A Gemini-protocol client's request is left as it came, as for every effort magpie sets. cleanRules refuses a value outside provider.Efforts and a pause with one. The try records it (Try.RuleEffort), and the Routing page says the rule set it. rule_effort_test.go, grouprule_useeffort_test.go, routing-rule-effort.test.cjs.
    • 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/b is not under /a/bc; ~ is the home folder; a Windows drive is one with its WSL mount (C:\work is /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 (workDir in workdir.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> or Current working directory: in the system prompt, and OpenCode's Working directory: inside its <env> block. The caller's own layer — the system prompt and its {role: "system"} messages — is read whole, a claude --bare run's CWD: <path> among the forms; a user turn counts only for the forms a caller states in one (<cwd>, OpenCode's <env>, Claude Code's <system-reminder>, which says a folder it moved to): a working-directory line a user message quotes is no caller's word (#4940). Never the model's words or a tool's result, and the last said wins. An agent that says none has no folder, and no folders= 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's RuleHit.Folder is the folder read, and the Routing page tells it beside the rule's folder … condition. TestFolderUnder, TestRuleMatchesByFolder, TestParseRuleFolders, TestWorkDirOfEachAgent, TestRuleByFolder, TestRuleMatchesExceptFolders, routing-folder.test.cjs. Rules by folder are never in a shared group (ShareGroup drops every ByFolder rule).
    • A rule by agent (Rule.Agents, agents=codex,sillytavern) matches the agent the gateway names the request's (agentOf in gateway.go: its magpie-<name> key, else its User-Agent), in lower case (cleanRules, MatchesBesidesIntent, Pauses). A client magpie doesn't know is named by its User-Agent's product name, before the first / or space (usage.AgentOf), so a rule can hold SillyTavern or one's own app (raikyou on Discord). The editor's agent picker lists the agents magpie knows, then those /api/usage?period=30d heard from that it doesn't (not other, nor magpie), and takes a name typed in its filter as the gateway reads a User-Agent (uaName in plugins/routing/client.js, through the picker's field.typed): "MyApp/2.0 (Linux)" is myapp. routing-rule-agent-typed.test.cjs.
    • A rule's field/op/value conditions (Rule.Where, provider.Cond in rulecond.go; when="effort is not off" on the command line; aipha2025 on X) say what the fields above can't, each of which must hold beside them. The fields and ops (CondOps): tokens ≥ > < ≤ a length; effort is / is not off, on or a level, and ≥ ≤ a level, where off is the agent turning reasoning off (Request.ThinkOff) or asking none, ≤ holds for off, and reasoning at no stated level is neither ≥ nor ≤ one; agent is / is not, as Rule.Agents reads agents; subagent is / is not, the request from a subagent its agent started, which only Claude Code (x-claude-code-agent-id, subOf) and Codex (collab_spawn) tell, set on Request.subagent where the rules' request is parsed, so another agent's subagent counts as not one; and message contains, doesn't contain, starts with or matches (a regular expression), upper or lower case alike, against the user's own words of the last user message that has any (lastSaid, so not an agent's reminders), read only when a rule has such a condition (RulesRead); system and last (SucroseMoE on X: a harness's title or compaction call told apart by its own prompt, no model asked) take the same ops against the request's texts as the agent sent them, and hold when one of them does (excludes when none does): system each block of the system prompt (Request.systemParts, systemRaw, read by systemTexts only when a rule asks: Anthropic's system blocks, so Claude Code's billing header is a block of its own; a Chat system or developer message; Responses' instructions and each system or developer item; Gemini's systemInstruction), last each text part of the last user message, reminders included (lastUserTexts; none when it holds only tool results). A regular expression may be written /…/. A request the turn's tool rounds hold (turnIn) keeps the turn's decision, so a last condition is met as the turn begins. Like every other condition they are looked at as a turn begins, and the turn's tool rounds stay with what was decided. Old rules have no where and route as before; a magpie from before Where reads a rule of them alone as one with no condition, which matches nothing. A pause takes agent conditions only. A rule with any never lifts what the group tells agents it can take (ruledEntry). The Routing page edits them in the same pills: the tokens pill's ≥ is a menu of ≥ > < ≤, the reasoning pill's of ≥ = ≠ ≤ with off among its values, the agents pill's of "agent is one of" / "agent is none of", and Subagent and Message are kinds of their own in Add a condition (whereOf, setWhere in plugins/routing/client.js); what the old fields can hold stays in them. The trace names a where condition from Cond.Text in the page's words (condText, then whereText). TestCondHolds, TestParseCond, TestParseRuleWhen, TestRuleWithoutWhereUnchanged, TestRuleWhereDecides, TestRuleMessageIsTheUsers, TestRuleSystemAndLastText, routing-rule-ops.test.cjs.
    • 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, on ruleClock): 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 (cleanRules refuses another condition), and is not a send-to rule: Matches, MatchRule, ThenUses, Ruled and 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, then workDir): 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; with folders=, only requests known to be in them. Embeddings and System One's decision calls have no folder. Paused.Folder/ByFolder carry 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.
    • A rule's hours and days (Rule.Time, provider.TimeWindow) are read on ruleClock in the zone they were set in (TimeWindow.Zone, an IANA name; gaubeebangeel on X: magpie on a cloud server in UTC, its user in Beijing, the hours 8 off). The GUI saves the browser's zone when the hours or days are changed in the editor and leaves a rule's zone alone otherwise; the CLI (magpie group rule add … time=09:00-18:00@Asia/Shanghai or tz=) and the TUI save the one typed, or this computer's (provider.LocalZone: $TZ, time.Local, the /etc/localtime link) when it has an IANA name. A window with no zone, every one saved before zones were kept, stays on magpie's own clock. A zone magpie doesn't know is refused on save (TimeWindow.clean), and one in a file edited by hand makes the window never hold (zoneOf): the rule is as if absent, never always on and never hours off. Zones come from Go's embedded tzdata, so Windows knows them too. /api/groups gives magpie's clock (clock: its zone and offset in seconds), and when it differs from the hours' zone the Routing groups page tells the zone beside them, on the group's rules and in the editor (zoneNote in plugins/routing/client.js): the zone's name, or the server's offset for hours with none. A time is read as typed on a phone's number pad or a Chinese keyboard (MinglunZhu on X): 22, 2200, 930, 22:00, 22.00, 22点30 and full-width digits are those hours, in clockMinutes and the GUI's clockOf alike, and time=22~08 takes ~ and ~ for the dash; 9:5 is still no time (TestRuleTimeTypedLoosely, routing-time.test.cjs). In the editor the hours, added from a new rule's +, take its empty intent box's place. TestRuleTimeWindowInItsZone, TestRuleTimeWindowInItsZoneAtTurnStart, TestRuleTimeWindowUnknownZone, TestParseRuleTimeZone, TestGroupRuleTimeZoneCmd, routing-time-zone.test.cjs.
  3. Candidates come from planGroup for a group or plan for a provider. They are filtered by sealedReaders and allowedCandidates. 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), or at a fixed amount of a window counted in a unit with its total (AccountWindowAmounts, 9won_25273 on Discord: 300 of a day's 1000 credits; held once the window's count reaches it, WindowCaps.limitShare, TestWindowAmountHoldsTheAccount), 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 on codex-auto-review, which OpenAI counts in no window, is held by no usage cap, only by credits it may not spend (freeOnChatGPT, #1593, TestAccountCapLetsAutoReviewThrough); a Free plan's call is capped as any other (TestAccountCapHoldsAutoReviewOnAFreePlan). The account is held while any window is past its own share, and cappedError and 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, autoReset spends a reset on it and it is tried (planned.held). A Codex account let spend its credits is never held or refused for its week, so before a try goes to one whose week its last reading says is used up and that spends a reset when its week runs out, resetBeforeCredits spends one first, one a week at most, in routing and in the relay (resetBeforeCreditsOn); a reset is free and credits cost money (tongzhenbao on X, TestCodexResetBeforeCredits). Otherwise a capped or barred set returns cappedError or barredError. A provider with Stop at the caps on (CapStop, plugins#349) answers that 429 instead of going on to its fallbacks when every primary account is held (plan, TestCapStopSkipsTheFallbacks); off, the default, the fallbacks take it as before. With every account held and no fallback left to take it, a request for a model the user put in routing groups of their own, asked bare (no provider in its id, or Codex's own model that codexAccounts put on codex/, providerPicked), goes on to those groups, in the user's order, each as its own routing orders it (provider.GroupsAfter, groupsAfter, planned again in serve with them after the fallbacks; a group magpie found, hidden or switched off, or one with no other member, is none). The Codex app signed in to ChatGPT asks Codex's own model, never the group built around it, so its capped account answered 429 though a group had two APIs after it (adorable_piglet on Discord, v0.1.3354; TestCappedCodexOwnModelGoesToItsGroup). A request that names the provider (claude/claude-opus-5-5, its flat or aliased spelling, another magpie's call) is that provider's alone (namedProvider): past the cap it goes to the provider's own fallbacks, else the cap's 429, never to a group that merely has the model in it (Anotiaww on X: a Claude account at its cap was answered by a WorkBuddy member of the user's group with nothing said; TestNamedProviderCappedRefuses). CapStop still answers the 429, and a request for the group itself was routed so before (TestCappedSubscriptionGivesWayInGroup). A careful provider (CapCareful, plugins#349, off by default, cap_careful.go) has readCareful read a capped account's usage again before planning when its reading is over 15s old within 5 points of a cap, or over 5m old at all, waiting at most 10s and asking a failed account again at most every 15s; capHold then holds an account whose usage was never read, whose last read failed or whose reading is still that old (carefulDoubt, Weighed.Unread in the trace), as one at its cap is: unknown is not spent (TestCarefulHoldsWhatItCantTell, TestCarefulReadsAgainNearTheCap, TestCarefulEveryAccountUnread, TestCarefulOffByDefault). Planning goes by the last reading, so turns sent together were each planned on the same one: an account a point under its cap took all of them and went past it by what they used between them (dyzdyz010 on Discord: capped at 90%, used to 100%). In serve's walk an account within 5 points of a usage cap (nearCapOf, nearCapPoints, cap_near.go) takes one turn at a time (Server.nearCap, its turn held until the try ends): a turn that finds it busy goes to the next candidate first, the account moved behind them once (nearBehind); the last candidate waits. Once its turn comes capHeld judges it again, by what the reply before it left (Codex's codex.rate_limits, Claude's rate_limit_event), or, when that reply said nothing of the account's usage, by a reading taken again then (nearCapAgain, at most carefulWait); held, it is passed over, and when it was the last the agent gets cappedError's 429. The cap is passed by one turn at most, as a gateway key's limit is, Claude Code accounts as Codex's (TestNearCapTakesOneTurnAtATime, TestNearCapWaitsThenHolds, TestNearCapReadsAgainAfterASilentReply, TestFarFromCapTurnsGoTogether, TestNearCapClaudeAccountsTakeOneTurnEach). A conversation kept on its account by Stays: Strict goes on past the cap as strictKeep keeps it, and takes no turn there (TestStrictAffinityGoesPastTheCap). Then affine moves the conversation's last answerer first, unless it is resting or nearly used up. An X-Magpie-Account header (AccountHeader) pins the request to one account: only that account is tried, and when it can't answer the caller is told why. A header value is ASCII on the wire and fetch refuses one that isn't, so an account whose user isn't ASCII (北冥, plugins#615) is named percent-encoded; pinnedName decodes it, the value as written matches too, and the trace and the call's record name it decoded (TestAccountPinnedPercentEncoded).
  4. The candidate loop calls attempt on each candidate in turn, through a holdWriter. 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 (a key longer each time it is refused so again once its rest has ended: 30 minutes, 2 hours, 8 hours, a day, 3 days, then a week (creditLadder, creditBackoff), the same rung while a rest still runs, a new run after "Try now" (Unrest) or an answer; each such rest, its rung and when it ends, is kept in rests.json beside providers.json (written through a renamed temp file whenever one is set or dropped, saveRests) and read once as the gateway starts to listen (loadRests), so a restart rests out what is left and climbs on from the rung: an ended rest keeps its rung there as in memory, unless it ended over restsKeep (35 days) ago, a key no longer in providers.json is let go, and a file or providers.json that can't be read or parsed adds no rest (PaulT on Discord, TestKeyCreditRestOutlivesRestart, TestKeyCreditRestFileCorrupt); a refusal that names its reset rests till then, and one that says it can pass soon (a Retry-After, OpenRouter's in-flight budget or "can only afford", a "try again in 30 seconds", creditSoon) rests 30 minutes or less and doesn't climb; a remote magpie's model rests 30 minutes as before: PaulT on Discord, TestKeyOutOfCreditRestsLongerEachTime; a ChatGPT account until the reset its refusal names, else until its full window renews, else 5 hours, chatgptCreditRest, and a reading finding its window renewed has it back: PaulT on Discord, TestChatGPTOutOfCreditsRestsLong), out of quota until reset, rate limited until retry-after, otherwise a minute and longer on repeats: doubled each time, up to longestRetry (10 minutes) for a failure and longestRateRest (30 minutes) for a rate limit back as soon as its rest is over, or up to the provider's own restCap in minutes (Provider.RestCapOr, at most MaxQuotaRest; magpie provider rest-cap <id> 4h, #2008: a free key down for hours was asked every 10 minutes). A time the vendor names stands over it as before (TestOwnRestCap). An error failure reads as out of credit is retryable at any 4xx, so the next account or member is asked and this one rests as credit; before, a 400 or 422 counted only by quotaWords, and SuperMagic's 400 「您的可用积分已不足…通过「充值」通道补充积分」 went to the agent with another account of 6,467 points unasked, the empty one never rested (#4095, mycf_711; TestCredit400MovesToTheNextAccount). A shape refusal that also says so (creditWords in shapeRefused) is the credit it says. The failure count is kept per key or account (restKey), and any of its models' answers clears it (served). Each model's own count (restID) is kept beside it and cleared only by that model's answer (servedCandidate): once it is past the account's, a sibling model answered since it last did, so the failure is the model's and it climbs its own ladder and rests alone, its siblings still served (#2241, weizsw: an Antigravity seat's gemini-3.5-flash-lite rested a minute 41 times of 43 while gemini-3.8-flash kept answering; TestModelLadderClimbsPastSiblingAnswers). Every model failing with no answer between still climbs the account's ladder and rests the account, and a candidate naming no model has the account's count alone. rest-cap <id> off (provider.RestCapOff, restCap: -1) is for a relay or account pool whose unknown errors come now and then and pass by the next request (Kismet Alan on Discord): a failure that says nothing of why (failOther: a 5xx, a dropped connection) then rests nobody and isn't counted, its trace rest by: "off" with no time left. A 401 or 403, a model not served, an account's window full, a rate limit (magpie's own 30-minute cap), quota, credit and a restriction still rest it as before (TestRestCapOff). A provider the user added can be set never to rest for a limit instead (provider.LimitRestOff, limitRestOff in providers.json; the editor's Advanced fold, "Set it aside when out of quota or rate limited", ticked by default): a refusal restAfterMarked reads as out of quota, out of credit or rate limited, and any 429, then rests nothing, isn't counted or sunk, and is by: "off"; restDrawer rests no image model of it. The next request is sent to it as usual. It is for a relay whose limits pass in a moment (zoecats on Discord: a local aggregator said "quota exhausted" while it switched upstreams, and magpie answered itself for 30 minutes; TestLimitRestOffKeepsAsking, TestLimitRestOffRestsNothingForALimit). A 401, a model not served and a plain failure still rest it. The shortest cap otherwise is a minute, the first rest; rest-cap <id> 30s is turned away and names off. 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 by restID, 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"). So does a relay pooling accounts (CLIProxyAPI) answering a 5xx no auth available (providers=…; last upstream error: …) whose last upstream error says so (poolLastError): a relay whose ChatGPT accounts lack gpt-6-sol lists it all the same, and its 503 had rested the whole key as an outage. A Google account's Code Assist (the Antigravity and Gemini CLI built-ins) answering 404 NOT_FOUND ("Requested entity was not found.") rests its model the same way, as its endpoint is the same for every model (codeAssistModelMissing; Packing1 on Discord: Argon, listed for a Google AI Pro account, answered 404 and rested the whole account; TestCodeAssistMissingModelRestsTheModel). A refusal for want of quota, credit or rate, for an account its vendor restricted, or for a verify it asks of its account there, from another computer's magpie (a Remote magpie provider, LAN share) rests only the model it was about (remoteModelRest, keyed by restID, in restAfterMarked and rateRest): that magpie serves each of its models from its own providers and rests them itself, so one out of quota there says nothing of the others (bigsteven on Discord: a 429 for one model rested every model on the remote for the 3 hours it named, so a group never moved on to the remote's other models; TestRemoteMagpieQuotaRestsTheModel, TestRemoteMagpieRestrictedRestsTheModel). Such a rest out of quota or credit (Rest.there) still puts the model behind the others, but is never given again without asking (quotaHeld passes it by): that magpie holds its own rests and answers from them at once, and what it serves under a name may have changed there since (zaidu259434 on X: a routing group there moved off a spent Open Design, and this magpie gave Open Design's 402 again until the time it named, never asking; TestRemoteMagpieQuotaIsAskedNotReplayed, TestHandAddedMagpieQuotaIsAskedNotReplayed). Another magpie added by hand, as an OpenAI-compatible provider of the user's own name rather than the preset, is read as one by its reply: a magpie names the provider that answered or held it (X-Magpie-Provider, providerHeader; noteMember, also on a quotaHeld or verifyHeld answer), as no vendor does, and keepRetry notes it as answeredThereHeader, since this magpie writes its own provider into the same header of its reply and the note is kept from the client (lagrangepoint1813 on Discord: "Remote Magpie: Claude Code: You've hit your session limit" answered every model of it, from quotaHeld, for the five hours it named; TestAnotherMagpieAddedByHandRestsTheModel, asked there and held there). Its key refused, the computer unreachable, or the key's own limit there (keyLimited's 429, which carries X-Magpie-Limit-Reset, remoteKeyLimitHeader), still rests it whole: #2077's reporter had a Claude Code session limit on the other magpie refuse its Qoder models here (TestRemoteMagpieRestsTheModel, two gateways over HTTP; TestRemoteMagpieKeyLimitRestsTheKey). The held try keeps that marker only as a note of magpie's own (keepRetry sets keyLimitThereHeader, which holdWriter never passes on), so the rest is whole however the 429 came, and the marker never reaches the agent or a magpie this one answers, which would read it as this magpie's own key limit (#2791, ggbdpq; TestRemoteMagpieKeyLimitRestsTheRemote, TestRemoteMagpieKeyLimitMarkerStaysHere). A 400, 404, 410 or 422 that says the model is retired (retiredWords: OpenCode Zen's 410 ModelDeprecated "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.json beside providers.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 (Unretire in servedCandidate) 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. A provider/model request for it is still sent. A 400 or 422 that says this upstream's API can't take the request's shape (shapeWords: xAI's 422 "unknown item type" (#350), OpenAI's "Unknown parameter", and a limit of a model's own on tool schemas, OpenCode Go's 400 "JSON schema exceeds the maximum nesting depth of 10 levels" on muse-spark-1.3-contributor, #1870), or that it is served on another API than the one asked (wrongEndpoint, once the member has tried every API it has a URL for: #2670, a relay with a Chat URL alone refusing tools with reasoning and none too), rests nobody: the next candidate is asked once (shapeRefused, failShape), and the last one's error reaches the agent. A request missing what every API requires ("field required") isn't one, nor is a 200 that mentions it. A model asking for an earlier reply's reasoning the history doesn't have (reasoningBackRefused in thinking_back.go: Command Code's Beam answering "Missing required parameter: 'messages[1].reasoning_content'" to a second turn, DeepSeek's and Kimi's words for their tool turns) is one too, after any refill refuseThinkingBack makes: the request is whole, and another member's model may not ask for it (EDwinpzy on Discord, TestGroupFailsOverAMissingReasoning); a missing messages or model still stops (TestMissingReasoningIsNotABadRequest). Command Code's Provider API turning a request away with nothing but a trace id (unsaidWords: {"message":"invalid request error trace_id: <hex>","type":"invalid_request_error"}, a 400, or a 422 before) is handled the same way: it turns away a request whose history and asked-for output together are over a limit below the model's listed context (the reporter's A/B: one ~748K-token agent conversation answered 200 with max_completion_tokens 64000 and this 400 with 384000, the model's listed max output), which another member's model may take, and the key is fine (#2313, TestGroupFailsOverCommandCodesBare400). Its overflow, which names the model's context length before the trace id, and an error that names a param, aren't one. A relay's own cap on one request's input that says so (tooLongRe: B.ai's 400 "Input token exceed the limit", on a 380K request under the model's 1M window; #2445, worksyang) is taken as an overflow (overflowed), which no word list of retryable matched: a group's next member that may hold the request is asked (withRoom, failOverflow), nobody rests, another account of the same model isn't asked, and with no member left the agent is told the conversation is too long, so it compacts. The conversation remembers the refusal (noteOverflow in affinity.go, by its stick key and the member's provider and model, with the request's size): its next request at least as large asks that member after the others (behindOverflow, after roomy, so after a rule that named it), behind and not out, until the member answers one (forgetOverflow) or the conversation shrinks below the refused size. Another conversation, and a 413 byte cap, are not affected (#3453, TestOverflowRefusedOnceIsAskedLast). A rate limit worded with input tokens (paceWords) isn't one, and a plain bad request is still asked of nobody else (TestRelayInputCapGoesToTheNextMember). Chinese that names the input rather than the context is one too (tooLongRe's third line: a group member's 400 「内容太长了,请精简输入或开启新对话」, z.ai's 「Prompt 超长」, iFlytek Spark's 「…字数太多,需要精简输入」, 「输入长度超过限制」); before, it was a plain failure that rested the member and asked no other (#4420, MYCF711; TestChineseInputTooLongGoesToTheNextMember). Each names what was sent beside its length, so a field's or the reply's length isn't one, and Chinese pace words (速率, 频繁, 并发, 每分钟…, in paceWords) beside them make it a rate limit, not a size (TestChineseNotTooLong). A 400 or 422 whose message speaks only of length, without naming what is long (lengthWords in fallback.go: 太长, 过长, 精简, 开启新对话, "too long", "too large", "shorten"), with no pace word and no part of the request named (partWords: a picture, a file, the reply, a field), is the request too long for that member once the request is past half its window (saysLength, lengthMargin 0.5 in tooLongUnsaid), not the 1.2 margin a refusal that says nothing needs: a vendor whose own ceiling is under the window it declares answered 「内容太长了…」 at ~730K of a declared 1M (#4420, MYCF711). It then goes as an unsaid overflow goes: to a member with room, nobody resting, else to the agent as "prompt is too long" (TestLengthWordsPastHalfTheWindowGoToTheNextMember). A refusal that says nothing of length is read as an overflow only from the vendors seen to answer one so, by the plugin that serves them (unsaidStatus in fallback.go: Devin's 5xx, Qoder's, Qoder CN's, WorkBuddy's and WorkBuddy AI's 400/413/422, Factory's 413), once the request is 1.2 times past the window (unsaidMargin), the window no less than the most the model has answered here or its list's max_context_window; any other provider's failure, a custom relay's, OpenAI's or Anthropic's, reaches the agent with its own status and words, as does a transport failure from any vendor (#5486, NEKO-CwC; TestRelayFailureKeepsItsOwnWords, TestUnsaidVendorsStillOverflow, TestTransportFailureIsNotTooLong). Under half the window the same words are left as the vendor's error. 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; when every full window that counts the model counts some models only (Allowance.Pooled), only that model rests (restID), and its siblings in their own windows still answer (plugins#817: ZCode's GLM-5.3 gift bucket spent left GLM-5.3-Flash's; TestScopedWindowFullRestsTheModelOnly). A 401 or 403 is the exception: one that names a quota is out of quota already (usedUpWords), and one that doesn't is about the key or the request, so it rests on the backoff ladder whatever the reading says (plugins#243, zygs1083-dotcom: a Factory account read at 98% sat out its week over one plain 403; TestPlain403DoesNotRestUntilTheWindow). A plain 403 (plainForbidden: no quota, credit, rate, verification, restriction or model not served) from a second key or account of the same provider, model and reasoning in one request is the request refused, not each account: neither rests, the first one's rest and counted failure are taken back (forbiddenAlike, unforbid), and the provider's other mates are asked last (matesLast). Before, that one request walked every account of the provider into backoff (TestPlain403OnTwoMatesRestsNeither). One account's plain 403 alone still rests it. A 500, 502 or 503 that says nothing of why (plainUnavailable: no quota, credit, rate, overload, proxy down, ChatGPT reset or protection refusal, and some words) is read the same way when a second account of the same provider, model and reasoning gives it in the same words and status, ids left out (refusalWords), and the provider answered another request within answeringLately (5 minutes, answeredLately, noted in servedCandidate): neither rests, and the last one left isn't asked again after a moment (sameRefusal). Before, one agent's request an upstream always refused (mycf_711 on Discord: 127 of a provider's 128 503s were "AIError AI服务异常", for an empty tool schema) walked every account into backoff and the other agents found them all resting. One account's 503 alone, 503s in other words, and alike 503s from a provider that answered nothing lately (an outage) still rest as before, so an outage is backed off once 5 minutes have passed since its last answer (TestPlain5xxOnTwoMatesRestsNeither). Both quota rests and window rests are held to longestQuota (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 waits fallbackCooldown (1 minute) at the back. An overload is no failure of the account's (vendorOverloaded: a 529, the ChatGPT backend's server_is_overloaded and Anthropic's overloaded_error among them, or a 5xx whose words say overloaded, as Gemini's 503 does): its model rests on that account overloadRest (30 seconds), or as long as a Retry-After asks up to overloadRestMost (a minute), every time alike, and no failure is counted on the backoff ladder (celestial_eagle_99230 on Discord: eight Codex accounts each rested up to the 10-minute cap for ChatGPT's overload, "failed 5 times in a row", leaving nothing to answer). A WorkBuddy account the vendor restricted (#1849: 403 {"code":11140,"msg":"request illegal","displayMsg":{"en":"Your account has been restricted due to unusual activity",…}}) rests restrictedRest (2 hours) as restricted (failRestricted), not the minutes of an unknown failure: only WorkBuddy lifting the restriction, after the user's appeal, brings it back. Both shapes are known: the built-in's wbExplain and the plugin's explained() (0.1.17, the mover's min) end the error with provider.WBRestrictedHint (restrictedSaid), and the vendor's own body, its code 11140 or its words (provider.WBRestricted), counts only from a WorkBuddy candidate (restrictedRefused, isWorkBuddy), as another vendor's 11140 is its own. Bare "request illegal" isn't matched. A vendor's risk control reads the request as well as the account, so a restricted account (failRestricted, ZCode's 3012 too) walls its provider off for the rest of the request (riskRefused, elsewhere; busyNow and roomy's left-out list too): none of the provider's other accounts is sent it, a group's other provider is asked, and with none left the agent is told and the account rests, the last one left too. Before, one request was sent on from account to account and each was restricted in turn (teamtaylor on Discord; TestRiskRefusalNotSentToTheProvidersOtherAccounts, TestRiskRefusalAloneIsToldAndRests). The next request still goes to the provider's next account. A remote magpie's restriction walls off nothing (remoteModelRest). WorkBuddy's 11128 channel refusal stays promptRefused and rests nobody. The Routing page names it "account restricted by the vendor", says the appeal is the way back, and gives the account's row a button that lifts the rest (/api/gateway/unrest) once the vendor has. Every other rest a key or account takes (quota, rate limit, retry-after, a failure's backoff) can be lifted by hand the same way (#1869): "Try now" on its row on the Routing page and beside its rest note in the provider's key list. It ends the rest, and with Sink on puts the key back from the back of the order; the backoff count stays, and a refusal after it rests the key again the usual way. Every lift before its time (Try now, UnrestAll for a replaced key, renewed for windows that renewed) is noted by its rest key (restingUntil.lifted) and handed to the Routing page in the trace (TraceState.Lifted, lifted in /api/gateway/trace), and a lift wakes a page waiting on the trace though no route changed (trace.lifted). The page stops showing a rest or a sink found before its lift, wherever the lift was asked for (zoecats on Discord: Try now in the provider's editor left Routing at 429 until a restart; TestTryNowToldToTheRoutingPage, routing-lifted-elsewhere.test.cjs). With another magpie serving the gateway, Try now lifts nothing (#3555). 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). So does one said in a stream a client is answered whole from (a Codex account is streamed upstream for a stream:false Responses, Chat or Messages request): each decoder gives the refusal's error event status 400 and its code (filterRefused), a whole reply it cut is answered the refusal rather than its words so far, and Anthropic's error shape, which has no code, carries it in refusedHeader; before, it was answered 502 api_error, asked again, and each account rested (#3274). restAfterMarked itself rests nobody, and counts no failure, for a 400 whose error object policyRefusal reads as a refusal, by its code, never by words a body may echo of the request. A refusal after the reasoning went through as it came (a vendor whose reasoning is never held, a trusted DeepSeek member, a hold that timed out) but before a word of the answer or a call is handed over (refusalHandover, refusal_handover.go): when the agent streams Anthropic Messages, Chat Completions or Responses, another candidate is left and refusalAsksAgain allows one more (handsOver), what passes is read event by event (passOver); the refusal's event and everything after it are not sent, an Anthropic block still open gets its content_block_stop, the try fails as a refusal with nothing said (failRefused, nobody rests, matesFirst), and the next try writes through spliceAfter, so its stream is the same reply: Anthropic's message_start is dropped and its block indexes go after those sent; Responses' response.created/in_progress/queued are dropped, output_index goes after the items sent and sequence_number goes on from the last one sent; Chat chunks go as they come. Once text or a call has gone, a refusal is the agent's as before (refusalAfter). Without another candidate nothing changes. A Gemini stream is not handed over, the reasoning item of a Responses stream handed over gets no output_item.done, and the next reply's response.completed lists only its own output (#4604). Zhipu's finish_reason "sensitive" and error 1301 (敏感), DashScope's data_inspection_failed and Volcengine Ark's *SensitiveContentDetected are refusals (filterReasons, sensitiveCode). Its note on the try (and in the error the agent gets when nobody is left) is the vendor's reason, with Anthropic's stop_details category and explanation when it gave them (refusedDetail, #1768: "safety filter: refusal (category cyber)"); none is made up when it gave none. stop_details is carried through the IR (Event.StopDetails), so a Claude subscription run through the claude CLI and a translated Anthropic route keep it for an Anthropic client too. How many more candidates a refusal before any of the reply is asked of is Settings' RefusalRetries (refusalAsksAgain, counted per request in the candidate loop; a group's other members count too): unset, every one left (#248); 0, none (#1925, DD on Discord). A Claude subscription account's refusal of a conversation of retellMost (100K) tokens or more leaves the subscription's other accounts out (tooBigToRetell, otherThanClaudeAccounts): each would be a new Claude Code told the whole conversation, all of it written to that account's cache again, for a refusal about the content it most likely gives too (Aisiverto on X: a 900K conversation refused and told again cost a Pro account most of its 5 hours). The size is the larger of what the account counted and estimate; other members are still asked, and a smaller conversation still goes to the next account (TestClaudeSubscriptionBigRefusalNotToldAgain, TestClaudeSubscriptionRefusalMovesToNextAccount). When nobody is left, an agent on Anthropic's Messages API gets the held refusal itself, the vendor's 200 with stop_reason refusal and its stop_details, streamed or whole (holdWriter.handBack), since that is what Claude Code switches to its fallback model on; a 400 is only an API error to it. Codex and Chat clients still get failTo's 400 (refusedStatus), which they don't ask again for. TestRefusalRetries* in refusal_retries_test.go cover keys, a group and the Claude subscription. 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 own web_search_call in a request that doesn't declare the web_search tool 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 with tools: []). 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 in codexBody, Codex's own sign-in relayed in codexUpstreamOn. It goes in the tools, or for Responses Lite (its header, reasoning.context all_turns, or an additional_tools item already there), which refuses a top-level web_search, in the additional_tools item. A request that offered no tools gets tool_choice none so 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; Codex's own web.run (a function in the web namespace, which Codex offers in place of the hosted tool on a Responses Lite model or with its standalone web search on, and runs through /alpha/search) counts as declaring it, since the backend refuses a request carrying both web.run and the hosted web_search (Savin on Discord, Codex 0.163.0-alpha; TestSearchedConversationUnderWebRun). siwc, API-key requests to openai.com and the legacy /responses/compact are left as they were. The ChatGPT backend also turns a whole request away when one tool name in it, a call's in the input or a tool's in tools, is outside ^[a-zA-Z0-9_.-]+\z (400 "Invalid 'input[83].name': string does not match pattern"; wing3556 on Discord, on a compaction): a call another provider's model wrote with a space, a colon or non-ASCII in its name, kept in the history beside its "no such tool", failed every later turn on Codex. Every request to it sends each such name as provider.CodexToolName makes it (each refused byte _, cut to 55, _ and 8 hex of its sha256, the same on every request), a valid one unchanged and a body with none byte for byte (CodexToolNames): an account's in codexBody, Codex's own sign-in's in codexUpstreamOn (/responses/compact too). A tool the agent declared under such a name is called back by its own: a translated reply through decoderFor (codexNamesBack), a relayed Responses reply through nsTidy.back (codexRenamedIn; TestCodexToolNamesTheBackendTakes). Namespaces, the OpenAI API, Azure and Copilot are not covered (#4875). Command Code turning a model away for its Zero Data Retention setting (its plugin's switch, 0.1.14, which sends x-cmd-zdr: 1; magpie-community/plugins#246) is a refusal of that request's setting, not of the model or the account: the Provider API's 422 with "code":"cmd_zdr_no_providers" and the 400 the plugin makes of Go's error line with "type":"cmd_zdr_no_providers" (zdrCoded, matched as the error's code or type, never by its words, whose "…a different model.","type":"invalid_request_error" read as a model unserved and rested the model on the account). keepRetry notes it beside the error (zdrHeader), since the error the agent gets may keep no code (Anthropic's shape, or the 400's numeric code). It rests nobody, anywhere (restAfterMarked returns by: "off"), so the model answers as soon as the switch is off; it isn't asked of the provider's other accounts at that model, which carry the same header (notMates), nor again after a moment; another member, the provider's other models among them, is asked once, and with none left the agent gets Command Code's words (TestCommandCodeZDRRefusalRestsNothing, TestZDRRefusalNeverRests). Another vendor's refusal in the same words, without the code, still rests the model (TestZDRRefusalIsCommandCodesCodeOnly).
  5. The last candidate's error reaches the agent, with one exception for a group (#1418, patience.go), which a plain provider shares once its same-one retries are spent (below). When every member has failed in a way that passes (busy, its statuses busyStatus: 408, 500, 502, 503, 504, 529, or Cloudflare's 520 to 524, which a relay behind it answers with now and then (TestCloudflareErrorIsTriedAgain; the same-one retries of passing read the same list), that isn't a proxy, a quota, response protection, or an upstream that answered a stream request with a whole reply, which fails the same however often it is asked (didNotStream; the same-one retries of passing leave it alone too, TestStreamlessMemberIsAskedOnce), or a 429 that is a short rate limit, not a plan or credit, nor an account's token wall: a vendor code in wallCodes, Raccoon's user_model_rate_limited, which rests as a rate limit but is asked again neither here nor by the same-one retries, as each ask draws on the bucket it waits for; plugins#512, TestTokenWallFailsFast), and nothing of the reply has been sent, the members that failed so are asked again in turn after a pause (replan). The pause is retryPause doubled each round up to replanLongest() (30 times retryPause, 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 while the group's Patience lasts. A member of a group in the group uses the innermost that sets Patience (innerPatience, #2410), as FirstToken (#2246) and Sink (#2255) do; unset falls back to the group asked for, and an inner PatienceOff skips replan for that member (TestNestedGroupPatienceThroughOuter, TestNestedGroupPatienceInnerOff, TestNestedGroupPatienceFallsBackToOuter). replanRounds (12) is only a backstop that never comes first: the pauses alone add up to PatienceLongest in 11 rounds (with 6, a group set to 240s gave up after 90s of pauses, real-jacket on #1418; TestPatienceIsUsedUp). The budget is the group's Patience, counted from the first time every member had failed, when the agent would have had the error (waitFrom; Group.Waits: 0 follows the default for every group, groupPatience, itself 0 for PatienceDefault, 60s; -1, PatienceOff, turns it off; at most PatienceLongest, 240s). A pause that would end past the budget isn't taken, and the agent gets the error; a member the vendor said is back within a second past its budget (read in whole seconds) is asked as the budget ends (TestReporterResetFitsTheDefaultPatience). The last member out of its quota or credit (not busy), after an earlier member failed in a way that passes, has those earlier ones asked again the same way, and rests as they did (lastSpent): before, the agent had the relay's moment of 503 while the relay would answer a moment on (TestGroupRelayBlipDoesNotEndOnSpentLast). 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 with Again (the pause), Replan (how many are asked again) and Patience (the budget in seconds). The group editor's "Every member busy" row sets it. A plain provider (a provider/model request, its accounts and fallbacks the candidates) first takes the same-one retries passing gives the last one left: lastRetries for a busy vendor, rateRetries for a rate limit, each pause retryPause<<n or a Retry-After of at most longestPause (8s). Past those, or for a Retry-After longer than longestPause, it is replanned the same way, its accounts taking turns as members do, for the provider's own Patience (Provider.Patience, the same values as a group's, set with magpie provider set <id> patience=2m|off|default; the provider editor shows no row for it and its save keeps it, TestProviderSaveKeepsPatience), unset singlePatience (PatienceDefault, 60s), counted from when the agent would have had the error, so it works with no setting and the user's value wins either way (TestSingleProviderOwnPatienceWins; ChatGPT's reset of a large request, codexReset, is left out: Codex is told it at its 503 with what may help, as codexBusy leaves it). A provider's own Patience is for a request to it alone: a group it is in, set or unset, keeps the group's (zoecats on Discord: a local relay's short 429 went straight to Claude Code once the few retries were spent). So a 429 whose Retry-After is 20s is waited out, the stream kept alive past keepHeldAfter; one of an hour, a quota, credit or plan limit, a 401 or 403, a refusal, response protection's 502 and didNotStream are not busy or don't fit the budget, and reach the agent at once as the vendor said them. Its tries are traced with Again alone, no Replan or Patience, so the Routing page tells it as the last one left asked again rather than as a group's members (TestSingleProviderWaitsOutAShortRateLimit, TestSingleProviderPassesALongLimitThrough, TestSingleProviderAgentGoneInTheWait in single_busy_test.go). Codex's own one-account relay (codexUpstreamOn, below) doesn't join it: its request is relayed unchanged outside the candidate loop, and the backend's 429 is always the plan's usage limit (codexBusy never retries one), so the short rate limit this waits out doesn't arise there; its overloads keep their lastRetries and then the subscription's fallbacks. A client that says how long it waits, in seconds (provider.WaitHeader, X-Magpie-Wait: a model test asking a remote magpie sends its own wait, pluginTestWait, 60s, since the remote serves plugins' models), takes neither pause when it would end within clientRoom (10s) of that wait (keptAlive.outlives), and has the error while it still waits; before, the test gave up at 20s on a 502 the remote held through its 60s patience (plugins#827, TestClientWaitBoundsPatience, TestRemoteMagpieProbeWait). Like every X-Magpie- header it goes no further upstream. An agent that goes away in either pause (the same-one retry's or a group's replan) ends the request there with 499: nobody is asked again, and the try whose pause it was is marked Gone (#1894, heng91: a relay down while its proxy was off, the agent's window closed). The Routing page says the agent canceled the request before the retry and lists it as canceled, rather than ending its story on "tried again in 2s", a retry that never came (TestAgentGoneInTheRetryPause, routing-agent-gone.test.cjs). A request its agent cancels, in such a pause or while a try is out (a person stopped the reply, or sent the next message while it came and the agent asked again), is logged 499 "the agent canceled the request" (usage.CanceledBy), with the error type agent_canceled (usage.CanceledErrType), which a middleware's usage rows carry too, so a module tells it from magpie's own limit below without the message. It is no failure: the agent saw no error (#2398). The Requests card and the totals line over the Requests list count it apart (Totals.Canceled); its success share, the Failed filter, the CSV's error column, the Routing page's errors and the Context page's error rate leave it out; the Requests list, the Routing page and Recent calls show it muted, in neither the failed nor the answered colour, from canceled on the row, route and call; and the OTLP export sends its span and its try's with status code 499, no error and no error type (TestAgentCanceledIsNoError, TestAgentCanceledIsNoFailure, TestLedgerTellsCanceledRows, TestContextLeavesCanceledOutOfErrors, TestOTelWaterfallFailureAndCancellation). Codex signed in to ChatGPT, its turn relayed to the backend as it came, gone mid-reply is logged the same 499 (#4866) and counted the same way (TestCodexGoneMidReplyIsNoFailure). magpie's own limit running out on a request it asked of itself is logged 499 too, and stays a failure (#2318, TestCanceledTellsTheAgentFromMagpiesLimit). A record logged before the error type, and a day's history kept before routes said canceled, are read the same way, by status and message (TestHistoryTellsCanceledRoutes). A try that answered is recorded (served, answered) for routing, affinity and usage. A try is added to the route's Tries only as it is asked, so a later try is the record that the gateway went on from this one, and the Routing page tells what came of a try from that, never from where it stood in the order (#2281, xishuchkui-code: an Antigravity 502 empty reply that went on to the next account was told as "an error another account wouldn't fix, so Claude Code gets it"). The one case the record can't show is the last try left out of its allowance after an earlier failure that wasn't one, where the agent is told the earlier error: that try is marked Earlier (routing-went-on.test.cjs).

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 refusal that comes as an error (#2400, Jichao). An error whose own message is, whole, The request was rejected because it was considered high risk is a refusal with no code beside it (highRiskRefusal in policyRefusal): in an HTTP error body or a stream's error event, never in an answer's text, which may quote it. The vendor that sends it isn't known; it says the request was turned away, so it goes to the next candidate under RefusalRetries like any refusal and rests nobody. A refusal error event before any content ends the try at once (eventRefusalError, stop as for any error), so an upstream that keeps the stream open doesn't hold the next candidate back; a refusal's stop or finish marker is still read to the end for the usage and terminator after it. After content, every write is read for a late refusal (refusalAfter), so one whose event: error name and data come in separate writes is still noted, and nothing is replayed. TestHighRisk*, TestRefusalErrorDoesNotWaitForEOF in refusal_error_test.go.
  • An error's own status beats the words (#4855). A provider that already sent its 200 can only say what went wrong in an in-stream error frame — a plugin's runtime watching a clock, aborting at 285s and emitting {"error":{…,"code":"upstream_timeout","status":504}} — and the frame is relayed to the client as it came. The status it names on a member of the error object (namedStatusOf, a number 400–599, status first, Gemini's relays' code; a string code is not one) is what the failure fails and rests as, before streamStatus guesses one from the message's words, wherever the frame is read: a held stream's error event (errOf in streamEvent), a whole 200 body that is only an error (errorReply), a carried error's words (carriedStatus), and a reply already streaming, whose turn rests at the status the sniffer noted on the try (namedStatusHeader, kept from the client; failedNamed/restAfterMarked) — so a terse frame naming 429 rests as a rate limit, not other at a word-guessed 502, and the rest says "Gateway Timeout", not "OK". With no such member, a status the words name as one, "(HTTP 503)" or "(HTTP 503)" (textStatus, httpSaid), counts too, for a 429 or a 5xx only, since a 4xx a message quotes may be someone else's ("the image link answered (HTTP 404)"): wps-lingxi's AuditFailed and AIError frames name theirs that way (mycf_711). A reply already streaming when its frame came is booked at that status as well, in Routing and Usage, though the client's 200 went out. Words magpie wrote itself (magpieSaid: the loop guard's loopGuardSaid, emptyReply, reloopedError) and words saying the request is too long name no status, whatever members they carry: a LAN peer's loop guard frame carries 502 in its Gemini shape, and is no failure of the provider, so it neither rests the route nor is booked as one (lateRests). An error naming no status reads exactly as before. TestRelayStreamErrorFrameSaysItsStatus, TestRelayStreamErrorFrameWithoutStatusAsBefore, TestRelayStreamErrorFrameNamesItsStatusInWords, TestNamedStatusOf in stream_frame_status_test.go.
  • 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 tries when the route took more than one (rec.Tries, from the trace's Tries). 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, marked handed_on; so does any other try that failed, billed something and handed the request on, to another account or member or the same one again (failedRow in serve, written once the next try begins): a Claude subscription run that failed after Anthropic's message_start had written the conversation to that account's cache, and the next account wrote it again, while the Usage page counted the second alone (hhxk233 and Kayrainforest on X; relay keeps the reply start's usage on a failure, TestClaudeSubscriptionFailedTryKeepsItsTokens). A try that failed before anything was billed has no record; usage.Totals.count skips 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, the retried filter). Logs written before handed_on are read the same way: the log index marks a failed, non-rejected record followed by another of the same route id as handed on (routeRows in log_index.go). Counts by account or route (vias, window holds) still count every try. A turn relayed on Codex's own ChatGPT sign-in is recorded as that codex account (codexServed in codex_backend.go), so the account card's window counts it; the Routing view still names the seat OpenAI, an API-key call stays openai with no account, as does one whose chatgpt-account-id isn't the account Codex's auth.json here is signed in to (a Codex in WSL or under another CODEX_HOME), and a row already written without an account is left as it is. Those relay rows are still not a lead's answerer (loggedAnswers, #1367); a row an account answered, its host host as email, still is.
  • A failed call is in app.log too, not only the Routing page and the usage ledger (wjh66 on Discord: Codex's "error decoding response body" after "reconnecting 5/5", and the log had nothing of the turn). record writes each call whose status is 400 or more, or that carries an error, as one line (failedCallLine: agent, model, provider, status, time, the error to 300 characters); the same failure again within a minute is counted into the next line, not written (failedLogEvery), so a client asking in a loop can't fill the log. A Codex reply relayed from the ChatGPT backend that ends before its last event also says which side ended it (codexEndedEarly in codex_backend.go): the read of OpenAI's stream that failed, with its error, or a clean end; and the client gone, a write to it that failed, or the failure passed on as response.failed, with the bytes passed on. reqwest, Codex's HTTP client, says "error decoding response body" for any read of a body whose connection broke, so only this line tells the legs apart. A gateway that ends with requests still in flight logs that they were cut (srv.Shutdown's error; on Windows there is no handover, so an update or quit cuts a stream after shortDrain) (TestCodexReplyBrokenOffLogged, TestCodexClientGoneLogged, TestFailedCallLineOncePerMinute).
  • Each record keeps the service tier three ways (#1784): tier_asked is what the client's body asked (bodyTier; Claude's speed fast reads fast), tier_sent is what that try's last request went out with, noted in forwardOnce after every rewrite (fast picks, Ultrafast to priority on a plan without it) onto the per-attempt wireAt, and tier_served is only what the reply said it ran at (upstreamTier, read by the sniffer and the translated readers), empty when it says nothing; from the ChatGPT backend (CodexBase's host) its auto and default are empty too, since it says them whether priority ran or not (servedTierAt, applied in attempt and codexUpstreamOn). The route's tries carry tier and tier_served the same way. A bridge that doesn't go through forwardOnce (the Claude subscription, Cursor's built-in) leaves tier_sent empty. Code: tier_record.go.
  • An agent's fast pick (settings.FastPicks, the bolt in its picker, #954) may also be in settings.UltraPicks (#1954), offered by the GUI only where one of Codex's accounts lists Ultrafast on the model (provider.CanUltra, UltraModels). fastPick marks its candidates ultra; a try of one goes with service_tier: "ultrafast" on Chat and Responses, and an agent on Messages carries it in the context (withUltra) to forwardTranslated, which sets Request.Ultrafast for the ChatGPT backend. Either way the same check as a client's own Ultrafast ask applies, now on Chat as well as Responses: an account whose list doesn't offer it is put after a mate that does (tierMate), or, with none left, sent priority. A Chat body's own service_tier: "ultrafast" is parsed as Ultrafast too (chat.go). TestUltraPickSentUltrafast.
  • Codex's service tier (settings.CodexServiceTier, a row in Codex's settings, JackyFill on X) sets the service_tier of every request of Codex's, whatever Codex's own /fast asked: empty is as Codex asks (the default, nothing changed), default sends none (standard), priority is Codex's Fast and ultrafast its Ultra Fast (the request values in Codex's ServiceTier; Flex is not offered, since the ChatGPT backend's requests drop it in codex_request.go). codexTiered (codex_tier.go) rewrites the body as it comes in, on both of Codex's ways in: codexBackend (Codex signed in, /backend-api/codex) and the main handler's Codex-on-Responses block, which a websocket turn reaches too. Everything after treats it as Codex's own ask: an account whose list lacks Ultrafast is put after a mate that offers it (tierMate) or sent priority, and a provider that refuses a tier drops it. A model with no provider (gpt-…, Codex's own sign-in, whose plan magpie doesn't know) is sent ultrafast only where one of magpie's Codex accounts lists it on the model (UltraModels), else priority. Another agent's request is never touched, and fast picks still apply after. TestCodexServiceTierSet, codex-service-tier.test.cjs.
  • A usage record carries its prompt's cache beside in and out (#1839): cache_read (tokens read from the vendor's cache) and cache_write (cache creation, Anthropic's cache_creation_input_tokens; cache_write_1h the part written for an hour). in holds neither. Both are written on every record, 0 too, so a prompt that missed the cache reads as that. A record from before then has neither and reads as 0. Every route fills them: Anthropic's messages, Chat (OpenAI's prompt_tokens_details.cached_tokens, DeepSeek's prompt_cache_hit_tokens), Responses (input_tokens_details.cached_tokens) and Gemini (cachedContentTokenCount), passed through or translated, whole or streamed, a plugin's fetch, and the Claude subscription bridge. System One's decision calls report no cache. TestUsageRecordsCacheTokensOnEveryRoute, TestPluginUsageRecordsCacheTokens, TestClaudeSubscriptionUsageKeepsCacheTokens, TestRecordAlwaysCarriesCacheTokens.
  • What the vendor read from its cache reaches the agent in the names its SDK reads, not only the record. A relayed Chat reply whose usage tells the cache in another vendor's names (a relay's Anthropic cache_read_input_tokens and cache_creation_input_tokens, DeepSeek's prompt_cache_hit_tokens or Moonshot's top-level cached_tokens beside a 0 in prompt_tokens_details) is told in OpenAI's too, streamed (chatTidy) and whole (chatWhole), by openAIUsage in chattidy.go: prompt_tokens_details.cached_tokens (and cache_write_tokens), with prompt_tokens and total_tokens made to hold the cached part where the vendor left it out. Every other field stays, and a usage already in OpenAI's names, or with no cache, goes byte for byte; one in OpenAI's names alone isn't even decoded (mayMendUsage). pi-ai, which DeepSeek Harness and Pi use, reads prompt_tokens_details.cached_tokens first, a 0 there too, and maps no Anthropic names at all, so such a relay showed DSH 缓存命中 0% while magpie had counted the hit (B3TT3R on Discord asked; DeepSeek's own API sends both names and was already read right). Relayed Responses and Messages replies, translated replies and a plugin's need nothing: their usage is written in the agent's own names. TestAgentReadsCacheTokensOnEveryRoute, TestPluginAgentReadsCacheTokens, TestOpenAIUsageLeavesOpenAIsAlone, TestMayMendUsageOnlyOtherNames in usage_cache_agent_test.go.
  • 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, an api_error saying " 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-… in anthropic-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 own header.anthropic-beta still goes.
  • A 400 that names betas a provider doesn't take, in Bedrock's words ("Unexpected value(s) x for the anthropic-beta header", unexpectedBetas) or Copilot's ("unsupported beta header(s): x, y", unsupportedBetas), is asked again at once without them, and they are left out for that provider from then on (refuseBetas, markUnfit). Copilot turns away tool-search-tool-2025-10-19, which Claude Code in Claude Desktop's Code tab asks with tool search on, and answers the same request without it (bigcat1800, TestCopilotUnsupportedBetasLeftOut).
  • 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 begins neither as JSON nor as an event stream. A reply whose first bytes are an event stream's (event:, data:, a : comment) is read as one under any Content-Type it names (eventStream, eventsStart): before, a stream under another type (application/octet-stream, say) was held whole and reached the agent only at its end, and one under application/json was a 502 (uk.jent on Discord: MiniMax Code to Grok Build showed each thinking block "Thought for 0.0s"; TestPluginThinkingStreamsAsItComes). Every upstream request goes through it (forwardOnce, and the built-in clients' own: the ChatGPT backend's /responses), so it fails over, rests and is logged as a 502 does, its reason naming the page's title.
  • An error status whose body holds no message of its own says what it was (provider.Unsaid, through APIError and the plan-quota and drawing readers): a web page by its title as plain words, a firewall's block page (EdgeBlocked: Alibaba Cloud's, Cloudflare's "you have been blocked", "used Cloudflare to restrict access" and error code: 1005–1020) with BlockedHint after it, and an empty body under an HTTP status as refused with no details, often a firewall or proxy in front of the API (NoDetails; an empty response.failed event, whose fallback is no status, still reads "upstream stream failed"). A bare "403 Forbidden" told a relay's user nothing (maralica on Discord). A JSON error still reads as its message. TestAPIErrorUnsaid, TestRelayRefusalSaysWhatItWas. Only the first bytes are peeked, which a stream waits for anyway, and a compressed body is left as it came.
  • A 400 that is no error at all, from OpenCode's gateway (openCodeBareRefusal in forwardOnce, #3740), is the 502 it stands for: OpenCode Go answered s-leeq's requests 400 {"model":"deepseek-v4.1-flash"}, the model's name and nothing else, with nothing in or out, and the same request was answered some seconds later (13s to 25s in their timelines). A body any error field names goes on as it came (the missing x-opencode-session refusal among it), and so does a body that isn't a JSON object, or one over 64KB; a body is never cut. Read as the 502, a group's next member is asked, and a lone provider is asked again within its patience, which outlasts that window, where the 400 ended the turn at once. The failure is tied to the request (30 of 214 requests with ~246K tokens of tools, none of 420 with under 1K), so nobody rests for it (restAfterMarked, openCodeBare): the key goes on serving the requests it serves. Only OpenCode's hosts are read this way; every other vendor's bare 400 stays as it came. (TestOpenCodeGoBare400AskedAgain, TestOpenCodeGoBare400ToldAs502, TestOpenCodeGoBare400RestsNobody, TestOpenCodeGoError400Untouched)
  • A 2xx from Zhipu or Z.ai holding the platform's refusal envelope ({"code":1000,"msg":…,"success":false}, which their Responses API at /api/v1 answers a refused key) is the refusal it stands for (provider.ZhipuEnveloped in forwardOnce): 401 for a key refused, 429 for a limit or no balance, as Zhipu's error codes give, so it fails over and rests as those do and the agent is told why. TestZhipuResponsesRefusalIsRefusal.
  • A request refused for its bytes (byteCapRefusal in body_cap.go: a 413, or words such as Command Code's 400 "Request body is 40.1 MB, over the 32 MB limit for one request (33554432 bytes)", EDwinpzy on Discord; never a 401, 403, 429 or a context overflow) is asked again in forward with its oldest history images left out (refitOverCap), up to three times. The cap is the smallest size the refusal names below what was sent, else three quarters of what was sent, and it is kept per provider id for as long as magpie runs (bodyCaps), so the next request near it is fitted in forwardOnce before it goes (withinCap). A request is fitted to three quarters of the cap. Each left-out image becomes a text part, "[An earlier image was left out here to keep this request under its size limit.]", which names neither magpie nor the vendor. The latest user message's images (latestUser: not a tool result, not Codex's compaction prompt) and every text, tool output included, stay; the rest of the body keeps its bytes. When leaving out every earlier image can't bring it under, or it is refused at every size, the agent gets a 413 request_too_large naming the size, the cap and what was kept (overCap), so Codex is told context_length_exceeded and its compaction goes on to the text-only ask (summaryTooLarge, plainCompact) instead of sending the same body into the compaction guard's hold. Every route reaches it, magpie's own (compaction, titles, the classifier, search, vision) included, since they all go through forward.
  • The vendor's reply headers a provider passes on (ReplyHeaders and the default request ids, see providers and accounts, #4145) reach the agent from the reply it is given alone. Every request that can become the agent's reply goes out through forward (relayed, translated, a plugin's fetch, a signed-in account) or retrieveAs/retrieveOpen (embeddings, audio), and each tells its reply's passed headers to the try that asked through the try's context (withReplySink, heardReply in reply_headers.go). The sink is the try's holdWriter (heardUpstream), so a try that fails and is let go takes its vendor's headers with it, a fallback's reply carries the provider that answered's, and a failure released to the agent carries its own vendor's. A reply to another provider (a side model, a searcher) is not heard: the sink takes its own provider's alone. Within a try the last reply replaces the earlier ones (an ask again without a refused beta, a Mantle reroute), and once the try has its status nothing more is heard (a cut reply's continuation). count_tokens writes them straight (passReplyHeaders), and embeddings through heardHeaders. A stream whose headers keepAlive sent before the vendor answered (past keepHeldAfter) has none: they can't follow a status already sent. Not carried: images, video and the Codex backend relay, which copies its reply's headers whole already. TestReplyHeadersPassedOn, TestReplyHeadersOfTheReplyGiven, TestReplyHeadersOnCountTokens, TestReplyHeadersOnEmbeddings.
  • The agent's request headers a provider passes on (PassHeaders, see providers and accounts; 3jRzfF52Qx on X) go with every try forwardOnce makes, so chat, responses, messages, count_tokens, a group's members, fallbacks, signed-in accounts and a plugin's fetch all take them: forwardOnce puts the agent's headers in the try's context under the try's provider id (provider.WithClientHeaders), and Provider.Sign passes the ones that provider lists and no other's. Not carried: embeddings, images, video and the Codex backend relay, which don't go through forwardOnce. TestPassHeadersReachTheProvider, TestPassHeadersOnlyToTheirProvider.
  • A streamed request is never left silent while its vendor says nothing. holdWriter.watch runs beside each try: past keepHeldAfter (3s) it sends a held try's agent the stream's 200 and SSE comments (keepAlive), one every keepHeldEvery (5s), none of the try, so another candidate may still answer in the same stream. It was 15s, and a proxy between the agent and magpie that hangs up on a request with nothing back for about 10s ended every turn slower to its first event: Codex on Windows sends 127.0.0.1 through a Clash-style app's system proxy, 127.* in its bypass list or not, and its turns ended 499 (mrten_95615 on Discord; TestHeldStreamHeardBeforeAProxyCuts). A failure before it is still a status; once the reply passes, it puts a comment between two of its lines after keepaliveEvery of quiet. It stops after keepaliveLongest (5 minutes) with nothing from the vendor. A translated stream (streamTranslated) whose upstream has begun its reply and then says nothing at all, not even a comment (a relay that sends the rest of a long reply in one burst at its end), is kept alive in the client's own protocol by a ticker beside its reader (keepThroughSilence): every keepaliveEvery it sends the client's keepalive (enc.keepalive: a ping for Anthropic, response.in_progress for Responses, a comment for Chat, nothing for Gemini), which also counts as the try heard from, so the held stream's comments go on too; it stops once the upstream has been silent for translatedQuietLongest (30 minutes), past the 10 minutes upstreamHeaderWait gives a vendor to begin and long enough for a long reasoning turn sent whole at its end, after which the client's own timeout ends the wait (youyo.p on Discord: before, Claude Code heard only comments, which its event watchdog doesn't count, and gave up 300s on; TestTranslatedSilenceKeptAliveForABound). An upstream that has answered its headers but sent no byte yet is still waited for under the held stream's comments alone (notAnAPIReply reads its first bytes before the reply is translated). An Anthropic client is sent a ping at most once each pingEvery (1 minute), comments between, and none before message_start: Claude Code's watchdog counts only 30 pings in a row as life, and a ping on every upstream keepalive spent them in the first minute; the SDKs' MessageStream fails on any event before message_start (anthropicEncoder.keepalive, TestTranslatedStreamKeepsClientAlive). 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 than keepHeldAfter sends nothing, so its 429 keeps its Retry-After. A proxy in front such as Cloudflare (125s) otherwise ends the request (#947). Gemini streams get no comments (#934). A vendor that then ignores stream:true and 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 reply under a type that says neither JSON nor a stream is held as a stream when its first bytes are one (sseStart), read event by event like one that says so, so an error among its frames still goes to the next candidate (#1418: it went through at once); a Chat stream a vendor ends with finish_reason:"error" — WorkBuddy's and a DeepSeek harness's word for a turn it failed, not finished (#2471) — is the failure the word says, held for the group's next candidate, and nobody rests, as an empty reply's (TestFinishReasonErrorFailsOver); 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, and any event streamEvent doesn't know to carry text, reasoning, a call or a reply's end (replyEvent), or an item not known that isn't a call or a tool's (streamPart.said): eventLead; Aliceonly on #1418: an unknown event was taken for content and let a frames-only 200 through, and its server_is_overloaded reached Codex with five candidates left) stays held as long as its agent is kept alive, up to holdLead (4 minutes, under the 300s Codex waits for an event; keptQuiet), so a server_is_overloaded that 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 after holdLongest (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 for agentQuietMost (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 no response.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's finishReason (geminiEnds, #1643: usageMetadata is 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 from streamFailure, TestGeminiRelayEndedShort; whatever a relayed stream gets appended, that error or a filled-in finish_reason, begins after a blank line, two newlines when the upstream's last write stopped inside a line, so it is an event of its own rather than more of the half-written one, and the half event itself is dropped: a relayed stream holds the line the upstream never ended back, puts it out when the reply ends whole or is gathered (TestGrokPluginNonStreamLastLineUnended), and throws it away when a failure is appended in its place, for no client can parse it — pi read "malformed server-sent event JSON" off a stream Z.ai reset mid-line, and died before the error after it; a line whose data parses (its JSON whole, or [DONE]) is no half event and goes out before the failure (#2446, #2580, TestPassthroughStreamCutMidLine, TestChatStreamCutMidLineLeavesNoHalfEvent, TestChatStreamCutAfterWholeEventKeepsIt, TestGeminiCompatFinishAfterPartialLine), and a Chat one from Gemini's OpenAI-compatible API (geminiCompat) with no finish_reason, relayed or translated (saysItsEnd; Linka on Discord: the upstream hung up between a whole function call and its finish_reason, and Pi threw the call away as "Stream ended without finish_reason"; that API counts the usage only once the generation is done, so when the last chunk carried it only the finish_reason was lost and it is filled in, tool_calls after a call and stop otherwise, as a relayed chunk before [DONE] or a translated reply's end, and the reply counts as whole (chatTail); only one with no usage at its end is a cut, TestGeminiCompatRelayEndedShort, TestGeminiCompatTranslatedEndedShort) — 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). only one with no usage at its end is a cut, TestGeminiCompatRelayEndedShort, TestGeminiCompatTranslatedEndedShort), and a Chat one from Command Code's API (commandCodeHost), whose slow starts a killed worker ends with no closing chunk at all, relayed (esp32gallery on #2471: 20 of 665 requests in a day, every ledger row a 200 with no stop and no error while the client read "Stream ended without finish_reason"; TestCommandCodeRelayEndedShort, TestCommandCodeTaillessFailsOver) — 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. One such ending is not a cut: a request capped at a short probe's worth (cutVoidTokens, 1024) whose reply spent some of it (thought, said or called something) and then ended cleanly with no end said ended at its length (endsAtProbeCap), and goes as a length stop, translated whole or streamed, and as a response.incomplete at max_output_tokens when a Responses plugin's stream is asked whole (gathered). Open Design's glm-5.3-flash always thinks, spent a model test's 16 tokens on it and ended after content_block_stop, so every plain test of it was this 502, waited out through the patience (plugins#827; TestProbeCapEndsAtLength, TestGatheredProbeCapIncomplete). A reply asked for more, one that spent nothing, or a Gemini or Code Assist one (Gemini ends every reply with its finishReason, MAX_TOKENS included, so one without it was cut: TestGeminiUpstreamEndedShort asks for 256) is still the cut. A relayed stream (passthrough to an agent of the same protocol) is still relayed as it came, with no end added (#5736). A translated reply from an Anthropic or Responses upstream that ended but said nothing (no text, call, search or image) and counted no token at all is no reply either, whatever its end says (repliesCounted, #2086: an Anthropic-compatible proxy's 200 ended a Codex turn as response.completed with no output, no usage and no served model, and Codex didn't ask again). It is the empty reply's to answer (#667): asked again in place, then failed with "an empty reply", streamed or not, for every client (TestUncountedEmptyReplyFails, TestUncountedEmptyReplyFailsEveryClient). Claude's own empty end_turn counts its prompt and stays a whole reply (TestWellFormedStreamsStillComplete). A relayed one is read the same way once: a Responses stream whose response.completed carries no output and counted no token is no reply either, failed before it is let through, held for the group's next candidate, and nobody rests (#2471, MurmuredVelpro: WorkBuddy AI's account ended Codex's turn completed with output: [] and all-zero usage three times running, the healthy members never asked; TestEmptyCompletedFailsOver). A reply passed through in its own protocol isn't read this way, but for that completed.
  • A vendor whose API is the client's own (a relayed request, or a translated one whose upstream error shape is the client's: Chat and Responses share OpenAI's) has its JSON error body go to the client as it came (writeVendorErrorFrom, ne9ko9 on Discord): its status, its own type, a numeric code, param, request_id and every field magpie knows nothing of. Only error.message is magpie's: the provider's name before the vendor's words (a describer asking for another model, the Claude sign-in rewording in claude_signin.go and the agent read it there), with a note where magpie has one (an account's Explain, a region note, the wrong-endpoint note, saysBusy, a 413's byte-limit hint). And a prompt too long for the model (tooLong) sets only the fields that make the client's agent compact: status 400, and type/code (OpenAI's context_length_exceeded), type and the "prompt is too long: " lead (Anthropic's), code/status (Gemini's), each spliced in place (setErrorField) so every other byte stays. A body that isn't JSON, or not in the client's shape, and another API's error are rebuilt in the client's shape (writeVendorError) as before. An error status the hold reads as the safety filter's refusal (policyRefusal) is still told in magpie's words once no one else answers (kept_error_test.go).
  • A reply that said nothing (emptyReply, #667) on emptyAccounts (2) accounts of one provider's model running is about the request, not the account: the candidates of that model that remain aren't asked (emptied in the candidate loop; other providers and the group's other members still are), and nobody rests (vhjjkkhg on X: Alma's Responses turns to Antigravity's Gemini 3.8 Flash went round 8 to 9 accounts over 10+ minutes). TestEmptyReplyOnTwoAccountsEndsTheRequest in internal/gateway/antigravity_empty_bound_test.go.
  • A provider of a key whose errors the user leaves to the client (errors=pass, Provider.PassErrors, set in its editor's Advanced "Errors" menu or with magpie provider set <id> errors=pass; TakesPassErrors keeps it to a provider of a key, never a signed-in account or a plugin's; ne9ko9 on Discord) is asked once. The candidate loop's holdWriter holds nothing for it (pass := c.p.PassesErrors() at the hold choke point; only a stream already begun is held), so no retry, wait, re-plan, refusal handover or next member answers for it; forward asks once after dsRetryGone (magpie's own file ids), passthrough and forwardTranslated return the first failure without a re-ask in another shape, streamTranslated neither continues nor asks again after an empty reply, and restAfterMarked rests none of its keys. Its error goes through passError (pass_errors.go): on the client's own API the vendor's status, Content-Type and body as sent; on another, the client's shape with the vendor's status, type, code (a number too), param and words, nothing inferred (no too-long, busy or 413 words). Retry-After and the rate-limit headers go with it. TestPassErrorsAskedOnce, TestPassErrorsNotInferred, TestPassErrorsOtherAPI in internal/gateway/pass_errors_test.go.
  • A vendor's error keeps its code and param on its way to an OpenAI-shaped client (writeVendorError), where writeError used to set both to null: a status error relayed or translated, and a request refused inside a Responses stream. A Responses stream's error event or failed response whose error is of type invalid_request_error is the request at fault (requestRefused, read by its type, not its words): its Event carries status 400 and the vendor's error (Event.Said), so a client answered whole gets the vendor's 400 with its code and param (the whole-translated path wrote 502 api_error), a reply cut by it isn't resumed (continuation.again), and a translated stream's error says the vendor's type, code and param (saidError), so holdWriter reads it as the 400 it is. Before, the hold read magpie's api_error as a 502: the same request was sent three times, then to the other accounts, and every one rested (magpie-releases#18: the ChatGPT backend answers access_programs naming a program the workspace hasn't got with a 200 stream whose error is access_program_not_enabled). Asked once, nobody rests (codex_access_programs_test.go).
  • An error that reaches the agent in a stream already begun can't carry its status, so streamError says it in the words (saysPassing, #2372, zminds): for a status that may pass (408, 429, 5xx) whose text names none of the words a text-judging agent retries on (Pi decides by its errorMessage alone), it appends (<status>: you can retry your request); a request's own fault (400, 401, 404 …) and a text that already says so are left as they were. TestStreamErrorSaysItPasses holds Pi's own lists; TestGroupLastFailureInStreamSaysItPasses runs a group whose last member fails after the keepalive. A 413 byte cap in that stream says request_too_large in the error text, and Chat and Anthropic name that type, so Pi compacts; Gemini keeps its own status shape (TestStreamedByteCapSaysRequestTooLargeToPi, TestStreamErrorByteCapInEveryShape). Responses' response.failed code for it is context_length_exceeded, the one code Codex compacts on: with server_error it sent the same body five more times ("reconnecting 5/5"), each refused, and never compacted (celestial_eagle_99230 on Discord, an nginx 413 page in front of a DeepSeek model; TestCodexByteCapInStreamCompacts). An overload told so (a 529, or a 5xx whose words say overloaded, saidOverloaded) is server_is_overloaded there, as the ChatGPT backend says one in a stream: Codex shows the model at capacity and stops, where server_error had it reconnect five times, each turn asked again by magpie, and end on the last error alone (wjh66 on Discord; TestCodexKeptAliveOverloadSaysServerIsOverloaded). Codex reads a 413, or a 400 context_length_exceeded, told by HTTP status as an unexpected status or an invalid request and compacts on neither, so when Codex (fromCodex) asked for a stream, a byte cap or an overflow is told in a stream even before one began (keptAlive.compactsInStream, failTo; TestCodexByteCapBeforeStreamCompacts). Another client keeps its status (TestByteCapBeforeStreamStaysStatusForOthers), and so does magpie's own summary ask for a compaction (keptAlive.whole, set for wantsWhole), which is never sent a 200 or a keepalive either: codexCompact reads a 413 as its cue to ask the conversation as text and then compact without a model, and told in a stream it failed 502 instead (#4862, TestCompactionOverByteCapEveryTime, TestCompactionOverByteCapSlowFitting). Nobody rests for either. Wherever the protocol says a model with the error (Chat's first chunk, Anthropic's message_start, Responses' response.created and the events after it), it is the model the agent asked for, as serve has it, an effort on it kept (keptAlive.model; on Codex's own sign-in, the one Codex wrote) (#3728, jilen: with "model":"" fx took Chat's first chunk for a broken one and stopped there; TestStreamErrorNamesTheModel, TestKeptAliveChatErrorNamesTheModel, TestKeptAliveChatOnCodexErrorNamesTheModel, TestKeptAliveCodexErrorNamesTheModel). An error after a reply that already went, a loop cut's, still starts a message of its own after the vendor's, under a new id and no model (#3792).
  • Claude's, GPT's, Gemini's and DeepSeek's reasoning is held (refusesAfterThinking, up to holdThinking, 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 their 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 streams there too: a reply that only reasoned is asked again in place by streamTranslated, the reasoning the agent has kept and the next try's after it (#667), so holding it only kept Codex on a Gemini model with nothing at all, not even response.created, for the whole of its thinking (LuckymanJC on Discord; TestThinkingStreamsWithNoOneElse's gemini cases). DeepSeek's is held since plugins #540: deepseek-v4.1-flash on WorkBuddy reasoned, then ended content_filter with nothing said (the WorkBuddy plugin takes the filter's canned "Sorry, I can't respond to this question." out of such a reply), and with its reasoning already through, the group's next member was never asked (TestDeepSeekRefusalAfterThinkingFailsOver). Where a refusal after the reasoning can still go to the next candidate in the same stream (handsOver: the agent asked for a Chat, Anthropic or Responses stream and another candidate is left; refusal_handover.go), a member whose thinking has gone on to an answer thoughtCleanMost (3) times running has its reasoning as it comes (holdsThinking), and a refusal after it, nothing yet said, is handed over, the next candidate's stream following as the same reply: DeepSeek's whether or not it can be handed over (#4512), Claude's, GPT's and Gemini's only where it can, so their refusal never reaches the agent while another could answer. Held whatever the member answered, a group of one model's accounts showed Claude Code its Claude's thinking only with its text, all at once, and never its thinking with <effort> effort (#4166). A retryable error after the reasoning, nothing yet said (Anthropic's overloaded_error mid-stream), is handed over the same way (passOver), its status and words failing the try as a held one's would, so trusting a member doesn't cost the group its failover; one the next candidate wouldn't be asked for (a request at fault) is the agent's (TestTrustedThinkingFailsOverOnEveryPath: Claude, GPT and Gemini members, refused, overloaded or invalid, to Claude Code, a Chat client and Codex; TestClaudeTrustedThinkingErrorFailsOver). A refusal takes the trust back (thoughtRefused), and the member's next reasoning is held again. TestDeepSeekThinkingStreamsOnceTrusted, TestDeepSeekRefusalHoldsATrustedMemberAgain, TestClaudeThinkingStreamsOnceTrusted and TestClaudeTrustedThinkingStreamsThroughGroup in thinking_streams_test.go. Any other model's reasoning (GLM's, Kimi's…) 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.Write feeds 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 a loopGuard (loop_guard.go). It cuts the reasoning and the text, each apart, into units, its lines and sentences (a list's 1. 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 last loopWindow (256) counted units of either are among no more than loopDistinct (24) different ones, the try is cut (cutLoop): what came with that write goes out, then, after a blank line (two newlines when that write stopped inside a line, holdWriter.atLine, #2446), 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 is reply_loop (usage.LoopErrType), and Usage counts them per model (Totals.Loops), as "{n} looped" beside the model's failures in the Overview's rows and the Requests ranking (#1858, TestLoopsCountedPerModel, usage-loops.test.cjs). 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, through holdWriter.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 reply passed through in the agent's own protocol is asked again once too, at the fallback loop (holdWriter.mayReloop, letGoLoop; #2436, lqisgod: pi's Chat stream to WorkBuddy was cut at once): when nothing of the try has reached the agent yet, in any protocol, its held bytes are dropped; when its reasoning is already passing, only a Chat stream goes on, written up to the end of the tripping event, with the next try's chunks after it. An Anthropic or Responses stream already passing still ends with the error, since a second message_start or response.created can't follow. Each re-ask, in place or at the fallback loop, counts in the usage record's tries. A loop in the text, or after a text or call, is ended at once (TestLoopAfterTextIsNotAskedAgain). 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 (TestLoopGuardLeavesOrdinaryRepliesAlone feeds magpie's own sources and docs through it). A reply sent whole (no stream, or Gemini without alt=sse) isn't read. Settings › Models › Replies › Stop looping replies (noLoopGuard) turns it off.
  • A conversation going round one tool call is answered by magpie and sent nowhere (audie on Discord: Codex Desktop on WorkBuddy's deepseek-v4-pro read the same file 308 times in half an hour, and 340 times that evening, 537 credits). stoppedToolLoop (tool_loop.go) runs in serveAgent before hooks, middleware and routing, and in the Codex backend's passthrough on Codex's own sign-in. It reads the request's own history, so it is per conversation and keeps no state: when the last toolLoopRepeats (8) turns are each the same calls (name and arguments, keys in any order, call ids ignored) answered with the same results (with Codex's Wall time, Chunk ID and duration_seconds taken out, runNoise) and nothing else from the user, the turn is answered in the agent's own protocol, streamed or whole (writeLocalText through relayStatus), with a notice naming the call, in the conversation's own language: conversationLang (reply_lang.go; tenacious_eagle_96548 on Discord, a Chinese conversation told in English) reads the user's own words, newest first, from the whole body (the ask can be past tailOf), not the agent's prompt, a tool's output or a tag block the agent adds (<system-reminder>), and tells the language by script: kana Japanese, Hangul Korean, Han Chinese (Traditional when its common characters outnumber the Simplified ones), German by its common words, else English (toolLoopNotices; Korean names the settings path in English, as the GUI has no Korean). The notice goes upstream with the next turn, so no language's names magpie or a quota (TestToolLoopNoticeInTheConversationsLanguage). Any different result, or a word of the user's, starts the count again; the notice is a turn without calls, so the user's next word goes on. A body with fewer than 8 tool results isn't parsed (mayLoop), and only the newest 64 items of a long one are (tailOf, gjson), ~1ms for a 1.5MB turn (BenchmarkToolLoopCheck). The turn is recorded as Codex's title turns are (answeredHere): the Routing trace as "Tool loop stopped", and a usage row with provider magpie, rejected, its session and an error starting tool loop:. A poll that gets the same answer 8 times in a row is stopped too. Settings › Models › Replies › Stop looping replies (noLoopGuard) turns it off with the reply guard. Verification: go test -tags nogui ./internal/gateway -run 'TestToolLoop'.
  • A Chat request's earlier turns carry the assistant's thinking back in the spelling its own client used: reasoning_content (DeepSeek's, which OpenCode and most clients send), reasoning (OpenRouter's) or reasoning_details (OpenRouter's structured one). A request translated to a non-Chat upstream reads whichever of the three the turn has, in that order, as the turn's thinking (messageReasoning, reasoningText, read by parseChat in chat.go); the passthrough has read all three since mistralThinking (#494), which was the one place that did. The same conversion covers a request translated to Mistral's Chat API (forwardTranslated): the build replays a turn's thinking in reasoning_content for a model whose name says DeepSeek wherever it is served (chatReplaysReasoning), which Mistral refuses — 422 extra_forbidden on messages[].reasoning_content, every follow-up of a Codex tool loop after its first call (#4906) — so the built body goes through mistralThinking too, and its thinking parts reach Mistral as its own replies carry them; a whitespace-only thinking (the " " a tool turn with no reasoning item is given) is dropped, not sent as a blank part. TestTranslatedReasoningAsThinkingForMistral, TestTranslatedToolTurnWithoutReasoningForMistral. Before that the parse layer read reasoning_content alone, so a tool-calling session whose client spelled it another way went on from its second turn without the model's own reasoning.
  • 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 biggest window its next one can't use up before it renews is passed over (Allowance.Unreached, Seat.Unreached, the trace's unreached): when what it has left is more than the next window, a day or longer and counted in the same unit, lets through between its own reset and the biggest one's (Of × the time between ÷ Span), what the next leaves at its reset is lost, so it ranks the account. A month holding less than its weeks add up to still ranks it while they can carry it (#1778); a Volcengine Agent Plan, 20,000 a month and 7,000 a week, goes by its week from about two weeks before its month renews (#5639, louisgreen0726; TestMonthOutOfReachRanksByWeek, TestSmartSpendsAWeekTheMonthCantWait, TestSmartPassesAnUnreachedWindow). Windows that tell only a share, and Ark replies with Percent alone, are never compared. 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, from QuotaWindow.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). When the renewals tie to the hour, Smart goes by that moment once more (Allowance.Lapse, Seat.Lapse), so of accounts renewing together (WorkBuddy's free accounts all reset at the month's end, plugin 0.1.35) the one whose credits left lapse first, after that end, goes first, and one telling none goes after (zhaocai_83020 on Discord). The trace carries both keys as Smart sorted by them, soon (Allowance.Renewal) and lapse (Allowance.Lapse) beside each window's own renews (Weighed.Soon, Weighed.Lapse), and the Routing page's story and rows compare those (renewsBy, cmpRenews, firstWhy, behindWhy): a credit pack ending before the month another account renews with is told as its credits expiring first, a tie broken by the lapse as that, and the order given only where every key ties (#5646, louisgreen0726; TestTraceCarriesSmartSortKeys, routing-story-credits-expire.test.cjs). A route from before soon is read from renews and restarts. Only Smart reads the lapse; Use before expiry, the 90%/98% tiers and rests go by the window's share and reset as before. A row on the Routing page says the share used (the fullest window's, Allowance.For) with when that same window renews (Allowance.Fullest, the trace's usedRenews), not the biggest window's: a Factory account 32% into its week and 16% into its month reads "32% used · renews in 3 days" while Smart still ranks it by its month (#1778). A route from before usedRenews says when only for an account of one window. Affinity keeps a conversation on an account at 90–97%: only SpentShareOf (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 a Kind or 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 for turnQuiet (4s); a session idle past turnStale (30m) starts over. Only a turn that ran at least settings.TurnDoneAlert seconds is told (TurnDone, set by the GUI; nil under magpie serve, so nothing is followed). The ChatGPT backend path (codexBackend) is followed the same way. TestTurnDoneSaidAtTheTurnsEnd, TestTurnDoneCodexBackend, TestToolScan, turn-done.test.cjs.
  • A request's masking record is told to the app for the "Masking alert" notification (Must2333 on X, OnMasked in masked.go, set by the GUI; nil under magpie serve), after maskrec.Hold and with its text around placeholders (Snips, Back) taken out. mask_alert.go keeps the records while settings.MaskAlert is on (off until turned on, in Settings → Usage, hidden with masking) and says only the values a record masked for the first time (maskrec.Fresh, first.go: each placeholder by the key of the first record that had it, read from memory and the days kept, so a conversation's history sent again each turn, or after a restart, is not news; a value sent as written is not one masked). A burst is gathered for maskGather (3s) and said as one, and one is said at most every maskGap (1 minute), what came in between said after it. It says each kind with its count and up to two agents, never a value nor its hint; a click opens the Masking page on the latest record (clickView, masking&key=). A held-back request (noteBlocked) is not said; a value whose records have all aged out (30 days) is new again. TestFreshOnlyTheFirstTime, TestMaskAlertFirstTimeOnly, TestMaskAlertNeverSaysTheValue, TestMaskAlertCoalesces, mask-alert.test.cjs.
  • A resting candidate is tried last (restLast). Of the resting candidates, a request asks only the one whose rest ends soonest, the first in order on a tie (probeOne, #1799). The others aren't asked by that request, so a member that is down isn't asked by every request its rest was meant to spare it from, and a group that is down whole takes one upstream request per request, not one per member. Every ready candidate is still asked in its order. A lone candidate is tried even while it rests, because there is no other. The trace still lists every member, the resting ones with their rest. Only rests are read, and a failure about the request's content or its model rests no member (a model refusal rests only restID), so neither leaves a member out. The same applies in count_tokens, embeddings and rerank, image accounts and a group's System One decision models. A Codex reset (autoReset) still looks over every candidate. This is like AxonHub's error-aware load balancing: the rest and its backoff are the penalty that decays, and the member back soonest is the one asked to show it is back. Keys out of their allowance aren't asked even so, not even the one back soonest or a lone one (#1772: four Ollama Cloud keys out for the week, each asked again and refused on every request). The refusal given again says when they are asked again on this magpie's clock with its offset (heldClock: "20:12 UTC+8", "Oct 16 09:00 UTC+8"), as do the gateway's other held errors (a capped window, a spent searcher or describer): its reader may be a Remote magpie's user on another clock. When every candidate left is a key (not a subscription account, whose resets autoReset may spend) resting out of quota or credit after a 429 or 402, none is asked. The first one's refusal is given again (quotaHeld, its words kept in the rest's said), saying when it is asked again. A key whose rest magpie guessed the length of, the vendor and the user naming no time (creditRest, or quotaRest with no Provider.OwnQuotaRest), is held so only once it was refused so twice in a row (Rest.first): a single refusal may be a moment's, and the next request, the agent's retry first, asks it again (zoecats on Discord: a local aggregator said 429 insufficient_quota "quota exhausted" for the moment it switched upstreams, and every request was answered from its rest of 15 or 30 minutes, which only the provider's "Rests" switch, LimitRestOff, let through before). Held, it is asked again a minute on (Rest.askAt, fallbackCooldown), once, and held again if refused (Rest.asksAt); a time the vendor named, or the user set, holds it from the first refusal to then. The rest itself stays as long as before, so the order still passes it over for a candidate that is ready. The last key left rests too when it is refused so, as the keys before it do, and so does the last account left (a Codex or other subscription account; quotaHeld still holds keys alone, and autoReset lifts the rest of an account it spends a reset of): before, an account last in an in-order group, out of its quota, was never rested, so every request a relay ahead of it failed for a moment went on to it and ended on its 429 (dbydd on Discord; TestGroupSpentLastAccountRests). Any 429 that reaches the agent without a vendor Retry-After, while every candidate tried is resting, carries one: the seconds until the first of them is asked again (soonestBack, by asksAt), none after a key's first refusal. TestRetryAfterALimitIsAsked, TestHeldLimitAskedAgainInAMinute. A quota refusal with no word of when it is back rests quotaRest (15 minutes), or the provider's own quotaRest in minutes (Provider.QuotaRestFor, at most MaxQuotaRest, 8 days; magpie provider quota-rest <id> 7d), or until the time of day the user said its allowance comes back (QuotaResetAt, Provider.OwnQuotaRest; magpie provider quota-rest <id> until 08:00, or until 00:00+08:00 on the vendor's clock; #2008, a free tier's "today's free-model token quota"). Whichever of the two was set last counts. A time the vendor names stands over it, and so does its Retry-After, unless that was more than longestWait (an hour) and so cut to it while the user's own rest is longer: then the user's stands (TestQuotaRestsUntilTheTimeOfDaySet). A key or an account resting on a 429 for the time its vendor named (Rest.By "retry-after" or "resets": a Retry-After, an anthropic-ratelimit-*-reset or x-ratelimit-reset-* header, or a refusal's resets_in_seconds / resets_at), rate limited or out of its allowance, is held the same way when every candidate left rests so (timedHeld, vendorTimed): none is asked, not even the soonest back or a lone one, and the agent is answered with the first one's error and a Retry-After until the first of them is back, set on the held answer too, so neither the same-one retry (passing) nor the patience's rounds take it for a moment's limit. Not a Codex account that spends its resets by itself (autoReset), nor another computer's model (Rest.there), nor a provider with LimitRestOff, which never rests for a limit. The last one left rests on such a 429 too (vendorSaidWhen); one naming no time rests nobody, as before. Before, a key or account limited for 300 seconds was asked again every time the agent retried, about every half a second, until the vendor flagged the accounts (hsjzg58958 on X). Codex's own sign-in, and the account a compaction goes to, are relayed outside the candidate loop (codexUpstreamOn): a 429 there that names its time holds that account in codexHolds (noteCodexHold), and Codex's retries are answered with ChatGPT's own refusal and a Retry-After till then (writeCodexHeld), unless the turn has fallbacks or groups to go on to (codexFallsBack), which take it as they took the turn that held the account (TestCodexHeldTurnFollowsTheGroup); a reset spent or a window started again lifts a hold out of allowance (restarted). Codex's API key isn't held: OpenAI's platform answers it. TestRateLimitedKeysHeldUntilTheirReset, TestRateLimitedCodexAccountsHeldUntilTheirReset. A key listed in keys as well as in key is one candidate (KeysOn), not asked twice. TestAllRestingAnswersFromRest, TestOwnQuotaRest, TestQuotaHeldOnlyForKeysOutOfAllowance, TestFirstKeyListedTwiceAskedOnce.
  • A model its plugin reports busier than the user's Busy models last (settings.BusyLoad, 1 to 9999 (BusyLoadMost-1), past 100 for a vendor that queues, its Custom… field taking any of them, off by default; axelburks on Discord) goes behind the ready candidates, ahead of the resting ones (restLast, busyOf), and its trace row has busy with the load. The load comes from the plugin through plugin.ModelLoad (see provider plugins); one not reported in the last 5 minutes is unknown and keeps its place. A lone candidate is asked whatever its load. A conversation it answered moves, at its next turn, to the ready one that leads (affine's Why busy, busyBehind); within a turn it stays. A turn going round (after), a new conversation spread (readyForNew) or In turn (leastHeld) never lands on it past a ready one. When every candidate is busy, nothing moves.
  • A key resting after an outage that names no time is asked again in the background (rest_probe.go, heatonz on Discord). Behind ready keys, probeOne never asks it before its rest ends, though its vendor may be back in a minute. restAfterMarked marks the rest Probed when it is a key's own (not an account's or a plugin's, not one model's restID), failOther by backoff after a 5xx, a 408 or no connection, with no Retry-After or reset header, at a provider whose List asks over the network (Provider.ListAsks), and long enough for a first ask. keepProbingRests, started in ListenAndServe, then asks the vendor's model list with that key through its proxy (Provider.List, which saves nothing) 1, 2, 5 and then every 10 minutes into the rest, while it is the same rest. When the list answers, the rest is lifted as Try now lifts it (liftedLocked, unsink, the trace's lift). Not asked: rate limits (a list answers while the chat endpoint still refuses, and lifting one early would undo Sink), quota, credit, a Retry-After or reset, a refused key (401, 403, 400), restrictions and verification, each of which ends on its own time or the vendor's. A key a probe lifted that fails again within 30 minutes isn't asked again until it answers a request (probeMissed, probeAnswered in served): the list answered for the vendor, not for its chat. Only the loop's own Server asks (restProbes.asking), so a test's Server never reaches the network. The cost is one list per resting key per step, never one per request. The key list (KeyRest.Probed) and Routing's words for the try (restHow) add "checked in the background, back as soon as it answers". TestRestProbeLiftsAKeyBackUp, TestRestProbeLeavesOtherRests, TestRestProbeOnlyByARunningLoop, rest-probed.test.cjs.
  • A provider whose keys are on different plans (KeyAccount.Plan, PlansMixed; yckonnnn on X) sends each key to its plan's endpoints: every key path takes its copy through WithKey, which moves it there (atKeyPlan), on the first try and on a failover alike. perKeyBarred leaves out a key whose plan's list lacks the model (PlanServing: a pay-as-you-go model id at the Agent Plan's endpoint only answers 404), not shown in the trace; only when no key's plan has it are those keys asked. Embeddings and drawing go through the same perKeyBarred and WithKey; a video started on a mixed provider names its key in the task id (videoStart.onKey, keyMark) so its poll goes to that key's plan. TestKeyPlansEachToItsOwnEndpoint.
  • A subscription's account whose own model list lacks the model (Account.Lists: an Antigravity account's fetchAvailableModels, a ChatGPT or Copilot account's own /models, a plugin account's models) isn't planned while another of its accounts lists it (perKeyBarred's left, planned.unlisted, the Routing page's "unlisted, skipped"). It is the next asked when every account of the subscription that lists the model has been asked and one refused it as a model it doesn't serve (unservedTry: modelRefused, or Code Assist's 404 NOT_FOUND, codeAssistModelMissing), before any later member or fallback (unlistedNext, askUnlisted moves its row from the route's left to its order after the one that refused). A list is fetched once and can be stale: 01huadalang's Gemini 4 was served by one Antigravity account of several, and the one whose list named it refused it with a 404 the agent got while the other could answer. The one that refused rests for that model alone. Not for another refusal (a 403, a quota), a request pinned to an account, a native compaction sealed to one, or a conversation kept strictly on one; a gateway key held to some accounts narrows the unlisted ones too (allowedCandidates). TestUnlistedAccountAskedAfterModelRefused, TestUnlistedAccountNotAskedForOtherRefusals.
  • A member whose model is known to take less than the request isn't asked it (roomy in fallback.go, in serve after the rules, affinity, the image filter and pinTo, before probeOne; dgqyushen on Discord: OpenCode Zen's free DeepSeek V4.1 Flash, 200K, first in a group and a 1M subscription of it second). It is a check before sending, not a retry: the request's tokens are estimated as the overflow fall-over does (estimate, bytes/4 over text, tool arguments and schemas), and a candidate whose window (windowOf: the provider's Contexts, the catalog, ContextOf) is known and no larger is left out of the candidates and of the trace's order, and listed in the trace's left with window set to that window. Asked, such a member only refuses, and a refusal that doesn't say why, for a request short of tooLongUnsaid's 1.2 margin, reached the agent as the vendor's error while the next member had room; it also spent a request against the member's limits. A conversation kept on a member by affinity moves once it outgrows it. Nothing is left out when its window isn't known, when the body doesn't parse, when only one model is among the candidates, or when no candidate holds the request: then the first is asked, and its overflow reaches the agent as one, to compact (withRoom, failOverflow and tooLongUnsaid stay for the window the estimate misses, which counts low on code and high on CJK text). A body shorter than four bytes per token of the least window isn't parsed. count_tokens (a count on the group's first member, not a send) and System One's decision models (short decision text) don't go through it. Those left out are the last resort: when the last candidate with room fails out of its allowance or credit (failQuota/failCredit), nothing before it having failed otherwise (other), and no account is pinned, the ones left out that aren't resting are asked after all, their rows moved from the trace's left to its order, and the one that failed rests as one before the last does. Its overflow tells the agent to compact, where the 429 only told it to wait for an allowance hours away (Kai on Discord: both Claude accounts spent until the next day, the Claude provider's Fallback a Codex model of 272K under a longer conversation, never asked). Another failure (a busy vendor, a bad key) still reaches the agent as it was, the small one not asked. The Routing page keeps a row for a member left out and not asked, saying the request is longer than its window and that it was passed over, and its why list says so (#3749; it used to show it only by its absence from the order). TestMemberTooSmallIsNotAsked, TestMemberTooSmallIsTheLastResort, TestClaudeAccountsSpentFallBackToCodex, TestConversationOutgrowingItsMemberMoves, TestRoomyLeavesWhatItCantJudge.
  • 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 the last reply read from the cache and wrote to it at least cacheWorth (1024) tokens between them (the usage's CacheRead plus CacheWrite, passed to answered) and the cache isn't cold (cacheCold, 5 minutes; for a ChatGPT account chatGPTCold, an hour, as measured on a real account (a thread left 7 to 60 minutes read back from cache all it had sent before), since the ChatGPT backend keeps a Codex conversation cached far longer and a move sends the whole context to the other account uncached; on DeepSeek's own API (api.deepseek.com) deepseekCold, an hour, since DeepSeek clears an unused prefix cache after hours and a Claude Code conversation idle 7 and 26 minutes read 98–99% back, so a second DeepSeek key no longer takes it over after five minutes: coldAfter, which a group's rules read too for keepsEffort). Past that window it stays while the vendor said it keeps at least cacheWorth tokens of the conversation for an hour (hourCache, #2302): a reply with Anthropic's 1-hour writes (cache_creation.ephemeral_1h_input_tokens, the usage's CacheWrite1h, as Claude Code asks of a subscription) keeps what it read plus those for cacheHour, a later reply on the same account and model that reads all of it starts the hour again, and one that reads less (moved, compacted) drops it. The stick keeps it on disk too (cacheHour, cacheHourAt), and a group's rules keep the turn's effort the same hour (keepsEffort). Vendors that report no 1-hour write are unchanged. TestAffinityKeepsAnHourCachePastFiveMinutes, TestHourCacheAfter, TestDeepSeekConversationStaysPastFiveMinutes. What was written counts: a first turn reads nothing and writes the whole prompt (Anthropic's cache_creation_input_tokens), and the second turn stays to read it rather than moving as no-cache and building it again elsewhere (vilicvane on Discord). The stick keeps both, on disk too (affinity.json's cacheWrite, absent in a file from before and read as 0, so such a stick is judged by its read alone), and the trace's Affinity.CacheWrite lets the Routing page say what was read and what was written. A vendor that keeps a prompt cached without reporting it (OpenAI's automatic prefix cache, Gemini) says neither of a turn that read none, so the prompt that turn was sent (the usage's Input) stands for the write and its second turn stays too; a reply that reports no usage at all counts as no cache, as before. TestAffinityKeepsACacheJustWritten, TestAffinityKeepsACacheTheVendorKeptSilently, routing-affinity-cache-write.test.cjs.
  • A conversation kept where it is (Affinity.Kept: Auto with a warm cache, Session, or within a turn) whose key or account fails before anything is sent, in a way that passes (busy: an overloaded 503 or 529, another 5xx that says nothing of quota, a 408), and not as a rate limit (429), a quota, a refusal or a sign-in, is asked once more after retryPause (1s, or a Retry-After up to longestPause) without resting, before the request moves on (keptAgain in affinity.go, jiabubu on Discord: a channel that errs once and is back a moment later had the conversation moved off it at once, to be sent it all uncached elsewhere). Once a request; failing again, it rests and the next is asked as before. A conversation nobody has answered yet, or under Off, moves at once, as it has no cache to keep; Strict's lone candidate is the last one left, asked again as that is (lastRetries). The trace marks the try (Try.Kept with its Again), and the Routing page says it was asked again for what its vendor cached, not that nobody else was left. TestKeptConversationAskedAgainBeforeItMoves, routing-kept-again.test.cjs.
  • Strict (strict, #1797, miniers) never moves a conversation to another key or account (who). Its stick is kept as session's is, and while it is fresh affine keeps only the candidates of that who (strictOnly): its other models stay, so a group's rules still pick among them, but no other account, key or provider is asked, and a resting or spent one is asked anyway. A failure there reaches the agent and rests the account as a non-lone candidate's would (strictAlone), so new conversations go elsewhere. A reply that breaks off after its 200 (#733) forgets the stick under every other mode; under strict it doesn't, so the agent's retry goes back to the same account, member or key, failing there while it fails and going on there once it answers (imwhatiam123 on Discord: a group of Qoder CN and WorkBuddy AI moved a session to WorkBuddy AI, the retry routed as a new conversation; TestStrictGroupKeepsItsMemberPastABrokenReply). Before planning, strictKeep takes the stuck account back from what holds new conversations off it: a usage cap (pl.capped, capHeldOnly), so the conversation goes on past it. An account held for credits it may not spend is answered 429 naming the account and Strict, and nothing reaches the vendor, rather than moved. An account removed, switched off, barred, or not allowed for the calling key is gone, and the conversation moves as under session. The trace says strict even with one candidate. strict_affinity_test.go, stays-strict.test.cjs.
  • A provider's fallback is its emergency path, not a place a conversation stays (01huadalang on Discord). When the one that answered a conversation last is one of a provider's Fallback models (its trace row's Fallback) and the provider's own model stands first in the plan, ready, the next turn goes to the provider, whatever the fallback cached and in every mode but Strict (backToMain in affine, Affinity.Why main). "Ready" is what restLast says: the provider's rest over, which is when the rest restAfter set ends (a minute and backing off for a plain failure, the vendor's named reset or Retry-After for a quota or rate limit, quotaRest 15 minutes when nothing names a time), or earlier when its windows are read full no more (renewed) or a background probe finds it answering (Rest.Probed). While the provider rests, the fallback is ahead of it and keeps the conversation as any answerer does. Within a turn (the agent sending tool results back) the conversation stays on the fallback until the user speaks again: the turn's tool loop runs on reasoning the fallback sealed, which the provider can't read, and the provider is sent the whole prompt afresh at the next turn all the same. Strict is left as the user set it: it never moves a conversation, a fallback's included; the trace then names the provider's ready key or account (Affinity.Main) and the Routing page says the conversation stays on the fallback for Strict while new conversations go to the provider (TestStrictKeepsTheFallbackAndSaysTheMainIsReady, routing-affinity-order.test.cjs). A provider routed In turn goes round its own keys and accounts only: its next turn (after) and a new conversation (leastHeld) pass over a fallback while one of the provider's own leads (standsIn). Before, a fallback was one more seat in the round, so with one key every other turn went to the fallback, and a new conversation went to it as the one nobody was on, the provider ready (01huadalang again, 10-31; TestRotatingProviderKeepsItsFallbackForEmergencies, TestFallbackGivesBackAcrossRoutings). A routing group's members are never Fallback; a group gives a conversation back by its own rules (order, back, below), and a routing group named as a provider's fallback is a fallback here as a whole. Before this, Auto kept a conversation on the fallback by its cache for as long as each turn read it, and Session for the session. TestFallbackGivesTheConversationBackOnceTheMainIsReady. The Routing page says so ("{who}, a fallback, answered this conversation last, but the provider's own {first} is ready again…", affWhy in plugins/routing/client.js); before, main showed no reason at all.
  • A routing group set to In order is tried in the order the user put its members in, and a later member keeps a conversation only until a member ahead of it is ready again (yyhhyyyyyy on Discord: an API key first and a Claude subscription second for Opus, 8 of 10 Claude Code requests on the subscription). One failure of the first member (a 429, a 5xx, a rest) sent a conversation to the second, and Auto affinity's cache kept it there at every turn after, since each turn read what the last had written. Now, with Stays left on Auto, a new turn goes back to the first ready member when it is another member than the one that answered last (backToFirst in affine, Affinity.Why order; another key or account of the same member, or a group in the group, keeps its own affinity). A provider whose own keys or accounts are routed In order does the same among them (CryptoSarom on X: a conversation that went to the second account while the first was resting stayed there by its cache once the first was back): affine gets inOrder from the provider's routing when the request isn't to a group, and backToFirst then compares accounts (candidate.who) rather than members. TestOrderedAccountsGiveTheConversationToTheFirst. Within a turn it stays, on the reasoning the later member sealed, as with main. Stays: Session and Strict are the user's own and keep the conversation where it is. The Routing page says why it moved. TestOrderedGroupGivesTheConversationBackToItsFirstMember, routing-affinity-order.test.cjs.
  • A group routed any other way (Smart, Least used first, By weight and the rest, In turn aside) gives back a conversation a later member took only as a stand-in (01huadalang on Discord, 11-01: Codex on two accounts first in a Smart group, a MiMo key second as the backup; after an outage of Codex's 5 hours, a session that had gone to MiMo stayed there by MiMo's cache once Codex was back, while new ones went to Codex). A member stood in when, as it answered, a member the group lists ahead of its own was resting (a 429, a 5xx: restAfter rests the one that failed before the try goes on) or known all but used up (Used at SpentShareOf): standsInFor, over the plan as it was for the request, by each candidate's place in the group's list (placed in planGroup; a group in the group is one member). The stick keeps it (stick.stoodIn, and stoodIn in affinity.json, absent from a file written before and read as no stand-in) while the same account and model answer on, so a stand-in that routing still puts first after the one ahead is back (Smart's low tier, a week at 92%) gives the conversation back once routing puts the one ahead first. At a new turn, with Stays on Auto, the conversation goes to the first ready member when that one is listed ahead of the stand-in's (backFromStandIn, Affinity.Why back); another key or account of the same member keeps it by its cache. A member routing put first while those ahead of it were ready and had room is no stand-in and keeps its cache as before, so peers of a Smart group don't trade conversations by renewal order. Within a turn it stays; Within a turn and Off route each new turn afresh anyway; Session and Strict keep it where it is; In turn's next turn goes round (after). Routing still decides who is first: Least used first and Smart put a key whose usage isn't told (counted unused) ahead of accounts at 90% or more of a window, so a conversation, and every new one, goes to such a backup while the subscription's accounts are that low (routing's own choice, not affinity's; In order keeps a backup last). TestGroupBackupGivesTheConversationBack, TestGroupBackupStandingInWhileTheFirstIsBackAndBehind, TestGroupMemberPutFirstOnItsMeritsKeepsItsCache, TestGroupStandInStaysWithinATurn, TestGroupMemberGivesTheConversationBackOnceTheOneAheadIsBack, routing-affinity-order.test.cjs.
  • A conversation a rule's hours sent to a member goes where the group routes it once they are over (MinglunZhu on X: a cheaper provider at night, the usual one by day). At a new turn that no rule puts a member first in, ruleFor sets RuleHit.Ended when the last turn's rule had hours that no longer hold, and affine lets go of the conversation (Affinity.Why hours) instead of keeping it on the night's member by its cache; the tool rounds of a turn begun inside the hours stay where they are. Session and Strict affinity, and In turn, keep their own way. The trace says why (affWhy in plugins/routing/client.js). A time rule in a group inside the group doesn't give its conversation back this way yet. TestRuleHoursOverGiveTheConversationBack, routing-time.test.cjs.
  • 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 last heldFor (30 minutes) are on (leastHeld, #946). Ties, resting ones, a provider's fallback while the provider's own leads (standsIn) 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.
  • Requests that come together spread (burstSpread in burst.go, #5242: Moody-Sin and Tericerice sent four at once to three Antigravity accounts, In turn and By pace, and every one went to one account). Routing weighs what each seat served (Tokens) and its allowance, which move only once a reply ends, and a lane counts a request only once its try begins, so requests planned at the same moment were all planned on the same figures; In turn's next turn (after) reads a stick that moves only on an answer too. Once the plan is made (after affinity, rules, pinning, roomy, behindOverflow), burstSpread puts first, of the candidates alike to the first, the one with the fewest requests in flight (inFlight, by candidate.who), ties keeping routing's order, and counts the request there in the same hold of the lock; the count is given back when serve ends. Alike (burstAlike): ready as the first is (not resting, aside, reserved, barred, held, capped, a fallback standing in, credits-last or busy behind), the same fallback, fit, protocol, URL and Via, the rule's member when a group's rule picked one; In turn any of the round; By pace a pace within a tenth (paceAlike, routes.Pace's band), the same Learns, both with room (burstTier 0) and no wallet told apart (sameBalance); Least used within a point used, the same tier and known-ness. In a group, a provider routed its own way (ownRouting) is alike only to its own provider's keys, by its routing, and a group in the group to nothing. Smart, In order, By weight and the others keep their order. Not moved, only counted: a conversation kept (Affinity.Kept), Strict, an X-Magpie-Account pin, a sealed task's lead, a native compaction's reader, and a new conversation leastHeld spreads (In turn, spreadsSessions), which counts those in flight itself (sticks.opening). A plugin's provider and a remote magpie take the same path; the remote spreads over its own accounts, the sessions passed on to it (passOnCaller). Not done: putting a markedly slower account behind (speed is read only for Speed first, speedOf), as a first token's wait goes with the prompt's size and the vendor's queue more than with the account. burst_spread_test.go.
  • Stays: Session or Strict under a routing that picks by what is left (Smart, Least used first, Use before expiry: spreadsSessions) spreads new conversations the same way (connor_yang on Discord: three sessions over three accounts landed on two). leastHeld with ready passes over one routing keeps new conversations off (readyForNew: resting, a key for another protocol, a provider's fallback while its own model leads, one used past lowShare), counts only leads (a key without |agent:), and leaves the turn marks alone. A subagent's first request goes to its lead's key or account while that one is readyForNew (withLead), so a session keeps one account, its subagents included. Held is the last heldFor (30 minutes): a session idle longer counts no more. In order, By weight, Free first, Speed first, Cheapest, Manual and a plugin's routing keep their order. An answered conversation is kept as before; the spread only decides where a new one starts. session_spread_test.go.
  • A session's call to another model than its main conversation's goes to the key or account that main conversation is on (withSession, Affinity.Why lead with LeadModel; #5655, jerrychoi, and iamnil on Discord). Each model's conversation is kept under its own scope (p.ID/model), so Claude Desktop's own Sonnet calls beside an Opus chat (desktop-beside), Claude Code's auto mode classifier and a title were routed as sessions of their own: put by leastHeld, or by Smart's order once their cache was cold, on another account, they ran one session on two accounts at once and drained the second one's 5 hours. The main conversation is the session's largest stick (cache read plus written) under another scope by the session's own id, one a header names (sessionNamed: a conversation known only by its opening's hash has no session, since unrelated ones that open alike share it; no |agent:), answered within heldFor, holding at least cacheWorth (a main with nothing cached goes where its own next turn is sent), and it leads only while larger than the call's own, so the two never follow each other. It is followed for Why first, gone, cold, no-cache, cache and session, by the model routing put first (in a group, another member on that account is another model and is never picked), and only to one readyForNew. It is not followed mid-turn (a kept Within), under Strict, In turn, nor for a subagent (withLead does that), nor past a rest, a reserve, credits or a fallback routing put first. A call moved off its own cache writes it once where the session goes on reading it. The Routing page says so ("Put on {first}, where this session's {model} is…", routing-affinity-lead.test.cjs). session_lead_test.go.
  • 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. One let spend its credits, and holding some by its last /wham/usage (credits.has_credits with a balance over 0, or unlimited; QuotaWindow.Credits, Limit.Credits, Allowance.OnCredits), is not out when a window fills (豆子 and Zhenzhen on Discord): ChatGPT may answer the turn that uses the window up 429 usage_limit_reached before it spends the credits, and the next turn on them. So that 429 is asked again at once, once a request, on the same account, before a reset is looked at, on the routed path (creditsAgain, creditsAsked, Try.Credits) and on Codex's own sign-in's relay (relayOnCredits), rather than ended for the agent, which ended a running session while a new one worked. Refused again, it rests fallbackCooldown (Rest.By credits) and is read again, not until its window renews, and its full windows rest it nowhere else (full is zero for it, spendsCredits). Smart, Pace and Least used put such an account first of the spent tier (routes.Seat.Credits, spentBefore): after those with allowance left, ahead of those used up with nothing to go on with (Weighed.Credits, told on the Routing page). Switching to credits early, at a few percent left, was weighed and not done: the vendor spends credits only once the allowance is used up, so it would only waste what is left. TestCodexCreditsAskedAgainAtTheEdge, TestCodexCreditsNoLongRest, TestCodexCreditsFirstOfTheSpent, TestCreditsFirstOfTheSpent, routing-codex-credits-again.test.cjs.
  • A third way, set per account, spends the credits only after everything else (gokoshiki on Discord: a Codex subscription, then an OpenAI API key, then the subscription's credits): Only after every other account, key and fallback under the Usage card's Use credits, magpie quota credits <account> last, settings.CodexCreditsLast (provider.CodexCreditsLast, SetCodexCreditsMode; on or off clears it, and an account never in it keeps its place, so a setting saved before keeps its order). Such an account is creditsLast while it goes on on its credits (spendsCredits) and a window for the model is used up where off would hold it (Allowance.CapHeld at WindowCaps{Credits: true}; a call ChatGPT counts in no window, freeOnChatGPT, stays). restLast then puts it behind every candidate of the plan, the provider's fallbacks and groups included: ready, then resting, then the credits-last ones in their own order (Weighed.CreditsLast). Affinity doesn't keep a conversation on one while one not on its credits leads (Affinity.Why credits, lastBehind), within a turn too, and In turn's next pick and Smart/Pace/Least used's spreading of new sessions never bring one forward (after, leastHeld, readyForNew). Strict affinity keeps it, as a rule, an X-Magpie-Account pin and a sealed task's lead (leadFirst) still put theirs first. A reset is still spent before its credits when the try reaches it (resetBeforeCredits). Codex's own sign-in's relay has the one account and nothing to put first, so there it is as on. The Routing page tells each: behind the rest, first when every one is, and the conversation moved. TestCodexCreditsLastAfterTheOthers, TestCodexCreditsLastAfterTheFallback, TestCodexCreditsLastNotKept, TestCodexCreditsLastMode, codex-credits-last.test.cjs.
  • A fourth, set per account, spends the credits before moving to another account (jojonas_xyz on X: the account ran out, magpie moved to another by itself, and no setting kept the first one's credits in use). On alone lets the vendor answer on credits, but Smart and Pace still put an account at LowShare (90%) or SpentShare (98%) behind every account with room (tier), Drain counts it used up at SpentShareOf(Drain), and NextLogin moves Codex's own sign-in at the spent share, credits or not. Before moving to another account under Use credits (the Usage card, the menu bar panel, and the account's ⋯ in its provider's editor), magpie quota credits <account> first, settings.CodexCreditsFirst (provider.CodexCreditsFirst; one of first and last at most, on or off clears it) makes an account that spends credits (spendsCredits) a routes.Seat.First: Smart, Pace and Fastest weigh it at tier 0 (seatTier), Drain doesn't count it spent, affinity doesn't move a conversation off it as spent, and readyForNew/standsInFor treat it as having room (Weighed.CreditsFirst). NextLogin keeps Codex signed in to it while one of its windows says it holds credits (spendsFirst); with the credits gone it moves as before. The account magpie moved Codex off says where the setting is, on its First again once it has room tag. TestCodexCreditsFirstKeepsItsPlace, TestCodexCreditsFirstDrainStays, TestCodexCreditsFirstMode, TestCodexStaysOnAnAccountSpendingCreditsFirst, codex-credits-first.test.cjs.
  • A provider can be set to be used first (hzh_1119 on Discord: ChatGPT Pro and Business come with monthly API credit, to be spent on an OpenAI API key before the subscription where both serve a model). Use first on a provider row's right-click (GUI provider/usefirst, provider.SetUseFirst, Provider.UseFirst, copied onto its accounts by accountSettings) makes its keys and accounts routes.Seat.Lead, and Smart (leadFirst) puts those under the spent tier (seatTier below 2) ahead of every other seat it weighs, each side in Smart's own order. Without it an API key, which tells no allowance, goes after every account with room. It counts where Smart weighs several providers together: a model's found group (auto/<model>) or a user's group routed Smart; within one provider every seat shares it, so nothing changes. One resting is passed over as any is, so a 429 insufficient_quota (out of credit, a half-hour rest) or a failure moves the request on to the others. Free quota by expiry orders its paid seats with Smart and so honours it too; the other strategies don't read it. Affinity still keeps a conversation on the one that answered it. The Routing page says why (Weighed.UseFirst, firstWhy), and behindWhy doesn't call one behind it renewing later. TestSmartLeadFirst, TestUseFirstLeadsTheGroup, use-first.test.cjs.
  • A provider can be set never to be a fallback for another model (sonnnnnnnnnnnna on X: an agent on a local uncensored model whose server is down or out of KV room must not have its request sent on to Claude or Codex, whose vendor may ban the account for it). Never a fallback on a provider row's right-click (GUI provider/standin, magpie provider set <id> fallback-for-others=no, provider.SetNoStandIn, Provider.NoStandIn, copied onto its accounts by accountSettings) has standInsOut leave out, in planPaused and planGroup, each of its keys and accounts planned after one of a provider not so set. It runs on the planned order before restLast and sinkPlanned, so a local model that failed and rests still counts as first; a provider request whose own provider is unmarked starts as seen, so one with nothing planned (its model off, every account capped) still keeps them out, and a fallback group's marked members, a marked fallback's unlisted accounts and groupsAfter's groups go the same way. A request that goes first to a marked provider moves on to another marked one, or an unmarked one, as before; a group routed by weight (Smart, Cheapest) that weighs a marked member first sends it the request as the group's pick. The left-out rows carry Weighed.StandIn (and Unlisted), and the Routing page says why (leftWhy, unlistedWord); they don't count toward the cap, held or barred refusals. No classifier reads the request: the model that would judge it is the local one that is down, and any other would send the text somewhere the user didn't choose. TestNoStandInTakesNoOtherModelsRequest, stand-in.test.cjs.
  • 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 refusal of where the request comes from (regionWords: Google's 400 "User location is not supported for the API use.", as Antigravity and Code Assist pass it on, and OpenAI's unsupported_country_region_territory / "Country, region, or territory not supported"; regionRefused) is the network's and the edge's the connection reached, not the account's. It rests no account and counts no failure (restAfterMarked returns Rest.By off, Until now), and the next try goes out on a new connection: regionFresh (in upstreamTransport, around each of its three transports, so under every request the gateway sends through s.client) reads the head of each failed reply, and when it matches it closes the transport's idle connections as the body closes and again before the next request (pending), so the HTTP/2 or keep-alive connection that drew the refusal isn't reused. The last candidate is asked again after retryPause (passing). Refused a second time for the same provider and model within a request (regionAsked in the serve loop), it is the place, not a connection: Google serves some models to no request from where the user is while the same account's other models answer (taoxiaoxin, #5182: Antigravity's gemini-3.8-flash refused, its Claude models answered). Then none of the provider's other accounts is asked that model (notMates), the last isn't asked again (protected), another provider or model left is, and the agent is told the vendor's words with regionNote (through explained, beside Provider.Explain): the vendor doesn't serve that model to requests from that region, it is no account's fault, other models may answer, and a proxy in a served region or another provider gets past it. So a refused model costs two asks a request, not one per account and retries. Before, every Antigravity account was asked on the one kept-alive connection, each refused the same and rested, and the agent got a 400, while a new connection answered 12 seconds on (#5182, ggdayup; TestRegionRefusalDropsItsConnection, TestAntigravityRegionRefusalAsksTheNextOnANewConnection, TestAntigravityRegionRefusalAsksTheLastAgain, TestRegionRefusalRestsNoAccount, TestRegionRefusalOfTheModelEndsAfterOneMoreAsk, TestRegionNote). Not covered: an HTTP/2 connection carrying another stream at that moment outlives the close until it is idle, and the close drops other vendors' idle connections too (one handshake each). A user whose region is refused gets the refusal after the one more ask, a moment later than before.
  • One of Codex's own models on the backend path with no routing to do (codexAccounts false: one ChatGPT account, no usage cap, no key holds, nothing pinned, and the sign-in not known to be out of its allowance, provider.CodexUsedUpKnown, which routes the turn as codex/<model> as a restarted Codex's goes) is relayed as Codex sent it, on Codex's own sign-in, its bytes and headers unchanged and its reply streamed as it comes (codexUpstreamOn with no account): routing was built for more than one account, and that path also keeps the turn's native compaction with the backend. Before, nothing was asked again on it, so an overload went straight to Codex, which doesn't retry the backend's server_is_overloaded itself (夜松云 on Discord). Now a transient overload (codexBusy: what busy calls busy, a 529, a 503 saying overloaded, the backend's in-stream response.failed with server_is_overloaded (#1418); never a 429, a usage limit, an edge's drop of the connection (edgeSaidDrop) or a reset (codexReset)) is asked again of the same account, the same body and headers, up to lastRetries times after retryPause<<n, as the accounts loop asks its last account, and only before any of the reply has reached Codex. A stream is held for it through a holdWriter with its reasoning let through (thinkingShown), kept alive past keepHeldAfter across the tries (one keptAlive), so Codex sees the stream's headers and comments, never a failed try's frames. Nothing rests for an overload. Once the retries are spent, a turn whose codex subscription has fallbacks (codexFallsBack; never a compaction) goes on to them (codexFallBack: the turn served as codex/<model> with the account left out of the candidates, fallbacksOnly, and the same keepalive carried in handedOnKey); without fallbacks Codex gets the last try's failure as the backend said it. The account out of its allowance goes on to the same fallbacks at once, after the credits retry and the automatic reset are looked at (codexAccountOut: a quota, credit or rate refusal, as a status or as a stream's failure before any reply, and a 403 usage_not_included; never a 401, which Codex renews its sign-in on). Before that, Codex was handed the 429 with its fallbacks unused (adorable_piglet on Discord, TestCodexOneAccountSpentFallsBack); with none set it still is (TestCodexOneAccountSpentNoFallbackRelayed). A routing group the user built with the model in it counts as one more fallback after the subscription's own (provider.GroupsAfter in codexFallsBack, and in serve for a turn handed on), so a group of the Codex subscription first and an API after it takes the spent turn (TestCodexOneAccountSpentGoesToItsGroup). Codex's auto-review, on codex-auto-review, which no group or fallback names, goes on where its conversation's own turns go (codexReviewAfter, from codexLeads): to the fallbacks and groups of the conversation's model, or to the magpie model it is on, as codexFallsBack and serve's groupsAfter add them (riverleaf88 on X, TestCodexReviewSpentFollowsTheGroup, TestCodexReviewSpentFollowsMagpieModel). Each try is a HandedOn usage record and a try in the trace. The reply's x-codex-* windows are kept as the sign-in's usage and a usage_limit_reached refusal has it read again at once (heardCodexLimits, codexMayBeUsedUp), as on the accounts path. A success is relayed as before, with nothing held when no retry or fallback is left (TestCodexOneAccountOverloadAskedAgain, …StreamOverloadAskedAgain, …OverloadBounded, …OverloadFallsBack, …OverloadKeptAlive, …RefusalNotAskedAgain in codex_one_account_overload_test.go).
  • A subscription account whose sign-in its vendor revoked (provider.SignInRevoked: 401 token_revoked and the like, #1793) fails as failAuth: the next member is asked at once, nothing rests, and the account is marked (noteSignIn in signin_revoked.go). Its later requests aren't sent while it has that credential: forwardOnce answers them with a 401 of magpie's own (revokedReply), so they too pass on. Compaction on an account of magpie's (compactOn) picks a marked one last. A key's provider answering the same words rests as before.
  • A ChatGPT 401 that says the token sent has expired and asks for a refresh (provider.SignInExpired, #2973) while its exp is ahead renews the account's sign-in once (provider.NoteExpiredSignIn from noteSignIn), keyed on the token sent, so the next request goes with a fresh one; nothing is marked, and the request fails over as any 401 does (Providers and accounts, A token called expired).
  • A sub2api key out of its own limit answers 429 api key 7天限额已用完 (or 日限额, 5小时限额) as rate_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, else quotaRest, 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 through provider.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 (503 No available accounts, or a later version's 429 All 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 429 that says in words it is back within soonest (PatienceLongest, 240s) is a rate limit (failRate), whatever plan words it has besides, unless it speaks of money (creditWords): backSoon reads resetsAfter (now with seconds and Chinese minutes, soonWords: "try again in 30 seconds", "请 1 分钟后重试") and tryAgainIn. A LAN aggregator's "Usage has exceeded the frequency limit. We will switch you to another model. Your usage limit for the original model will reset in 1 minutes." read as a plan used up ("usage limit") and reached the agent at once; now it is busy, rests the minute it says (rateRest reads resetsAt), and a lone provider waits it out within its patience (zoecats on Discord; TestShortResetIsARateLimit, TestShortResetRestsWhatItSays, TestSingleProviderWaitsOutAFrequencyLimit). One that says hours is still out of quota and not waited (TestSingleProviderPassesALongLimitThrough). "Frequency limit" is a rate word, as 频率 is.
  • 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's usage 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 by usedUpWords (上限), 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.
  • A 429 that names in words when the account is back (WorkBuddy's "将在 2026-10-11 20:16:02 UTC+8重置" and "your usage will reset at 2026-10-11 12:37:53 UTC+8, …", #1669; Volcengine Ark's "You have exceeded the monthly usage quota. It will reset at 2026-10-25 23:59:59 +0800 CST.", #3251, #3276) is out of quota in either language (resetsWhen), and rests until that time (resetsWritten, read in the offset written). Only the reset phrasing right beside a whole date and time with its UTC/GMT offset, or its offset as Go prints one (four digits, then the zone's name, which isn't read), followed by 重置 or punctuation, is read, so a refusal cut short isn't read as UTC and another vendor's date in passing is no reset; a time past, not a real date, or further off than longestSaid isn't read: longestWritten (7 days), or longestMonthly (35 days) when the refusal says its allowance is a month's (monthlyWords: Ark's, Zhipu's 1310 "Weekly/Monthly Limit Exhausted"). Such a reset is the one rest out of quota held past longestQuota, to longestMonthly; a window read full or the user's own rest is still held to 8 days (TestMonthlyWrittenResetRestsTheMonth). Ark's windows as its AccessKey reads them (volcPlanQuotas) still reach only its usage card, not routing (#3251). Zhipu's 1308 and 1310 (Z.ai and bigmodel.cn, GLM Coding Plan: "Your limit will reset at 2026-10-15 20:12:13", "您的限额将在 … 重置") write the time with no zone; it is Beijing's, and is read as UTC+8 in those words only (zhipuResets, resetsZhipu), never when a digit, colon or zone of its own follows (Player on Discord: read by nothing, the key rested quotaRest and the refusal said "not asked again before 17:12" while Z.ai said 20:12; TestZhipuRestsUntilItsReset). One that points to the account's other models (otherModels: "切换其他模型", "switch to the other models") rests that model alone (restID). Out of credit or quota on a model that costs credits, where the subscription serves other models free (catalog.Model.Free: WorkBuddy's x0.00, Qoder's is_free, Cline's free models; Provider.PaidBesideFree), rests that model alone too: the free ones draw on no credits (Creat.wu on Discord, TestOutOfCreditLeavesFreeModels). A Credits window leaves the free models out the same way, so an account at 100% isn't ranked spent for them: the WorkBuddy plugin's lists them as notModels (0.1.23), and the built-in's scopes itself by the provider's last fetched list (wbSpareFree; with no list read, every model counts) (plugins#138, hheei: an account at 560 / 560 was still served deepseek-v4.1-flash; TestWorkBuddyCreditsSpareFreeModels). A free model the vendor refuses all the same (WorkBuddy refuses even 0-rate models to an account with no package) rests the account on its own refusal. Cline's daily limit of one free model, 429 "Daily free limit reached on model deepseek/deepseek-v4-flash. Try again in 23h 59m" (the words Cline's own clients read it by, isClineFreeModelLimitMessage), rests that model alone (clineFreeLimit, clineModelLimited, keyed by restID) until the time it names (clineBackIn, tryAgainIn, held to longestWritten; resets), from a provider whose requests reach Cline's API (ClinePinnable: the ClinePass preset, one at cline.bot, the Cline plugin's). The key's other models, free or the plan's, are still served, and the model out of its day is answered with its refusal without asking Cline again (#1398, wuasakura: one free model's 429 sent the whole Cline account to the back; TestClineFreeLimitRestsTheModel, TestClineFreeLimitLeavesOtherModels). Another vendor's same words, and a Cline 429 that doesn't name the model's limit, rest the key as before. WorkBuddy's 429 14018 "Credits exhausted" is out of credit (brokeWords), not a rate limit, on the built-in's raw body and the plugin's insufficient_quota alike (TestCreditsExhaustedIsOutOfCredit). On the rate-limit branch, a reset time the refusal names (resetsAt, or resetsHeader as keepRetry noted it) is believed up to longestQuota, as out of quota believes it, and the Routing page says it rests until then (resets); a Retry-After or a rate-limit reset header is still held to longestWait (an hour) (rateRest). The same rest runs for a plugin's requests: the WorkBuddy plugin passes these 429s on as they come (TestPluginWrittenResetRests). A JSON error body that escapes what isn't ASCII as \uXXXX (Python's json.dumps does by default) has its strings decoded before any word list (creditWords, rateWords, plannedWords, usedUpWords, resetsWhen, …) is matched (wordsOf), so an escaped 余额不足 or 用量 reads as an unescaped one does.
  • A 429 that names a limit per minute or second (minuteWords: per minute, per second, TPM, RPM, PerMinute in Gemini's quotaId, Azure's "token rate limit" and "call rate limit") is a rate limit even when it calls itself a quota, unless it also names a longer window or a plan's limit (longWords: hour, day, week, month, usage limit, 用量, 套餐) or money spent (brokeWords, insufficient_quota) (minuteLimit). Gemini's "You exceeded your current quota … PerMinute", Vertex's "Quota exceeded for …requests_per_minute…" and Azure's rate limit, whose link is aka.ms/oai/quotaincrease, each rested a key the quarter of an hour of a quota with balance left (monater.114514 on Discord); now they rest as rateRest does, a minute or the vendor's Retry-After. Words inside a link (urlWords) don't make a rate limit a plan used up. DashScope words its TPM/TPS limit as a quota too, Allocated quota exceeded, please increase your quota limit. or OpenAI's insufficient_quota; from a DashScope provider (dashScope) those are rate limits (dashScopeRate, in failureOf), while its "Free allocated quota exceeded." and a Coding Plan's hour/week/month stay out of quota, and OpenAI's insufficient_quota stays out of credit (TestMinuteLimitIsNotQuota, TestMinuteLimitRestsAMinute, TestDashScopeAllocationQuotaIsRate).
  • Antigravity's 429 for a model's quota used up writes how long until it is back as Go prints a duration: "You have exhausted your capacity on this model. Your quota will reset after 3h19m30s." (quotaResetAfter, read by resetsAfter beside Factory's "resets in …", held to longestWritten). The account (or, as pooled says, that model on it) rests that long (resets), and the agent's Retry-After says it when no account is left. Unread, it rested quotaRest, so the account first in order was asked again, and refused, every 15 minutes while the next ticked account had its quota (Dani Ariyanto on Discord, 10-24; TestAntigravityQuotaRestsUntilItsReset). Its other 429, "Resource has been exhausted (e.g. check quota).", names no time and rests quotaRest as before.
  • A ZCode plugin account's Start Plan trial entry (<model>-Trial) that the plugin refuses before sending anything rests that entry alone (zcodeTrialRefused, restID), not the account: a 400 "ZCode has no active limited quota for GLM-5.3-Trial" when no live plan holds it any more (the trial ended), and a 429 "ZCode's limited quota for glm-5.3 is exhausted or temporarily unavailable" when its bucket is spent (the plugin names the bucket, the entry less -Trial). Read as failQuota by their words, both rested zcode@…, and the account's GLM Coding Plan models were paused with the trial (#3661, orion-nebula-dev; after skygunner's e04a1b994, which covered the 400). Only the plugin's exact words naming the model asked for count: another model named, a model without -Trial, the words on another status, the account's own quota or key, and the same words from another vendor still rest the account (TestZCodeTrialRefusalRestsTheTrialAlone). An expired trial still kept in a group is asked first and refused locally, as the guessed quota rest is asked again a minute on; the Routing page strikes it as skipped, which the gateway doesn't do for a member no account lists (#3805). ZCode's risk control refusing a trial entry (3012, failRestricted) rests that entry alone too (zcodeTrialRestricted): the entry goes to zcode.z.ai, a dual account's plain models to its GLM Coding Plan on api.z.ai, which kept serving them (young02036 on Discord, 11-07). The plain model's own 3012 rests the account, as on a gift-only account, where it goes to zcode.z.ai too.
  • An account resting out of its window (a Claude account by the time Claude Code's refusal named, resets, or any by window) is back once magpie's reading of its windows (provider.Allowances) finds it full till sooner: the window used below SpentShareOf, or its reset passed, with no other window over the same models still full. The reading tells provider.OnRenewed as the account's UsageAgent and user, and renewed lifts that account's rests out of quota or by window; 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 in restingOf.
  • An account is held at a usage cap (capHeld) or rested out of one model's pool (pooled). A key whose windows magpie reads (provider.TakesUsageCap: readsKeyWindows, OpenCode Go's 5 hours, week and month among them) takes the same cap by its key id (AccountCaps, AccountWindowCaps; @wanggenjidev on X) and is barred in perKeyEvery (keyCapHeld, Provider.KeyCapHeld) once a window is at it, as an account is, and back when that window renews. Windows not read yet, or a read that failed, hold nothing (KeyAllowance keeps the last good reading, TestKeyUsageCapPassesTheKeyOver). CapCareful and the one-turn-at-a-time rule near a cap are an account's only. A key is also held at its own spend cap (below).
  • A key at its spend cap (providers, provider.SpendCap) is barred in perKeyEvery (spendHeld) with a capHold whose spend is set: it is passed over and the provider's other keys and its fallbacks take the request. Routing's row says what it spent of its cap (Weighed.SpendCap, Spent, SpendPeriod, SpendSince). With every candidate held, cappedError answers 429 naming each key, what it spent of its cap and when it is back (the next day or month, or not until a cap in all is raised), and the command that changes it, with Retry-After at the soonest; a cap in all gives none. A spend hold is not a usage cap: capHeldOnly leaves it out, so neither Stop at the caps (CapStop) nor Strict's strictKeep sends a request to a key past what it may spend. TestKeySpendCapPassesTheKeyOver.
  • A 429 for want of rate or quota whose words name the model asked (modelNamed: OpenAI's "Rate limit reached for gpt-4o in organization …", Groq's "for model …", Gemini's QuotaFailure with the model in quotaDimensions, WJaunita45604 on X) rests that model on that key or account alone (modelLimited, restID), with its backoff and its sink, and the other models are asked straight. The name is matched as a whole id (gpt-4o is not gpt-4o-mini). A refusal that names no model, one for want of credit, and a plain failure still rest the key or account whole.
  • A rest of one model alone (keyed by restID: a pool, a model not served, a paid model beside free ones) names that model in the trace (Rest.Model). The Routing page shows it on that model's rows only: the account's other models' rows on the stage, and the account's row under Accounts and keys, don't read as resting. The account's row names the models resting on a line of their own under what it has left, and its Try now lifts their rests. A kept request from before Rest.Model has the model on the end of Rest.Key, which the page reads the same (restModel in plugins/routing/client.js, #1960, routing-model-rest.test.cjs).
  • The Providers page shows a subscription account's rests in force on its row there too: RestsUnder("<provider>@") lists them, providerJSON.accountRests gives them by user in lower case (the account's own, and each model's, with Rest.Model, Until, By and the vendor's words, Rest.Error), and the row's line says which model, why and when it is back, the vendor's words beside it, with Try now lifting it by its key (accountRestLines in app.js). Before, only a key's rest showed there, and a WorkBuddy AI account whose model rested on a 429 "将在 … 重置" read as fine, its credits 82% left (maxleebeta on Discord; TestRateLimitedModelListedUnderAccount, TestAccountRestsInProviderState, account-rest.test.cjs).
  • A group member let go for no first content within the group's FirstToken (hw.slow in gateway.go, 504 "no first token in Ns", failSlow) doesn't rest the first time: a long prompt is slow to start anywhere. Slow again on the same account's model with no answer from it in between, and within slowForget (30 minutes) of its last slow start, that model rests on that account (restSlow in routing.go, keyed by restID, Rest.Model set): a minute from the second time (slowRests), doubling each time after, up to the provider's rest cap (RestCapOr(longestRetry)), and never for a provider whose cap is off. Its answer clears the count (servedCandidate). A request its client cancelled counts nothing, as the cancel is read before hw.slow. The walk has a total budget, groupBudget (540s, under the 600s a client waits): a member asked when little of it is left gets only what is left (hw.budgeted), and when it runs out no further member is asked, nothing rests, and the error names the budget (504 "no member of the group answered within its 540s budget", #5113, mycf_711: nine members at 60s took 660s and the client's hang-up was told as the last member's failure; TestGroupWalkStopsAtItsBudget). Before it, each new request asked the stalled member first again and waited out the whole FirstToken (小八 on Discord: a WorkBuddy account's kimi-k3-1 and glm-5.3 stalled 58 times on the vendor's per-model token limit, 15 times in 17 minutes in one session). The same model on another account and another model on the same account are asked as before (TestSlowStartsRestTheModelOnItsAccount, TestCanceledSlowStartRestsNothing; the Routing page's story, routing-went-on.test.cjs).
  • A plugin's try that isn't the last candidate is sent with x-magpie-fallback: 1 (provider.FallbackHeader, withFallback), so a plugin whose vendor queues the request (Qoder's 10605, CodeArts' queue-status: queued) answers a busy 503 with Retry-After and the queue's reason at once instead of waiting minutes in the queue, and the next is asked; the last candidate isn't told and waits as the vendor's client does (provider-plugins, TestPluginToldAnotherFollows).
  • A 402 is out of credit, unless it speaks of a usage limit (usedUpWords) and nothing of money (creditWords, insufficient_quota): then it is out of quota, and rests only the model when the account's windows say its pool is the one used up (pooled). Factory answers Standard's pool used up with 402 "You've reached your weekly standard usage limit (resets in …). Switch to Droid Core …"; read as credit, it rested the account 30 minutes and its Droid Core models with it (#1979). Both the built-in's windows and the plugin's (Standard's notModels, Core's models) are held to it. As a quota rest it lasts until the time the refusal names (resetsAfter: "resets in 0h 19min", "resets in 2d 3h", held to longestWritten), else the window's end, else quotaRest or the provider's own quota-rest, and is lifted once a reading finds the window renewed (renewed), which a credit rest never was (TestFactoryStandardOutLeavesCore, TestPaymentRequiredReadByItsWords, TestResetsInWords). An account whose windows weren't read yet (a start, or a reading that failed) can't tell the model's pool from the account's, so it rests whole, and narrowWhenRead waits off the request for a reading (AwaitAllowance, up to allowanceWait) and moves the rest to the model alone (restID, the same end) when the reading says its pool is the one used up; no reading in time, or one that says the whole account, leaves the account's rest, as does a rest lifted or made again meanwhile (#2036; TestFactoryStandardOutLeavesCore's unread case, TestResetsInWords). The request itself isn't held for the reading: it has failed over already, and the rest's scope only matters to later requests.
  • Codex offers its image tool (the image_gen namespace, #870) to every magpie provider. When a provider other than a ChatGPT sign-in or openai.com answers a bare 400, attempt asks 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 a functionResponse with 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. A second answer to one call is left out, with the images it carried, before the turns are built (dropSecondAnswers, #2262): Google refuses a call turn whose functionResponse count differs from its functionCall count, and the Chat and Messages builds already keep the first answer. The Responses build (buildResponses) leaves it out the same way. A call made again under the same id takes an answer of its own. A Gemini client that keeps no ids answers two calls of one function by name in their order, and each answer goes to its own call (parseGemini), not both to the latest. TestGeminiDropsASecondAnswer, TestSecondAnswerDroppedWithItsImages, TestGeminiClientUnnamedCallsAnsweredInOrder.
  • A request built for a Messages upstream (buildAnthropic: a Chat, Responses or Gemini client translated) has its tool exchanges mended after its messages are built (pairToolBlocks, #1558, ggbdpq), since Anthropic answers 400 for a tool_use the next message doesn't answer and for a tool_result naming no call of the message before it. A call left unanswered gets the synthetic interrupted result, is_error set, first in the user message after it or in one of its own; a result that answers no call goes as a text block with what it said (its images as they came); a second answer to one call is dropped. A well-formed exchange goes as it was built. An Anthropic client relayed to a Messages upstream isn't mended. anthropic_tool_pairing_test.go.
  • A Responses request bound for anything but a ChatGPT sign-in has its tool exchanges mended in attempt, before it is relayed or translated, plugins included (responses.go). An item inside a run of calls and results (after one of the run's results and before the last, or before any result when the model didn't write it) moves to the end of that run (joinToolRuns, #1752, Edward4226): Codex writes its <image_resize_notice> right after each result whose image it resized, so a batch of two calls had it between their results, and a strict upstream answered 400 (OpenCode Go/DeepSeek "No tool output found for tool call …", Volcengine's "must be followed by tool messages", #1822); a Chat translation answered the second call with a synthetic result. An item carrying a call_id never moves, the model's own reasoning between its calls stays, and its text between them (an assistant message, with the reasoning right before it) goes ahead of the run's first call, so the step's calls stand together: OpenCode Go opens a new assistant message at such text and answered the call before it "No tool output found for tool call …" (#2100). A call opens a run only when a result after it answers it. A result with no call id becomes a user message after its run (orphanedToolOutputs), and a call nothing answers gets a synthetic result at the end of its run (pairToolItems, #1341). TestRelayedCodexImageBatchKeepsItsResultsTogether, TestJoinToolRunsOnlyMovesWhatBreaksARun, TestRelayedTextBetweenABatchsCallsIsAnswered.
  • A Chat client's own body relayed to a Chat upstream (passthrough) has its tool exchanges mended when they don't pair (toolPairsOut in chattidy.go), by the rule a translated one is built with (pairToolMessages in chat.go): Kimi's Chat API, like OpenAI's, turns the whole request away for an assistant's call the tool messages right after it don't answer ("an assistant message with 'tool_calls' must be followed by tool messages responding to each 'tool_call_id'…"), a user message between a call and its answer included, and for a tool message with no call before it ("tool_call_id is not found"), both checked against api.kimi.com/coding on 2026-10-26. Qoder's chat forked at an earlier turn, its model switched to Kimi Code, was refused on every prompt (Paidaixinbao on X). A turn's calls split over consecutive assistant messages join into one first (joinSplitChatCalls); a call left unanswered gets the synthetic interrupted result; an answer to no call becomes the user's text, a parts content by its text parts. A body whose exchange pairs goes byte for byte, answers out of the calls' order included, which Kimi takes (TestChatRelayPairsToolsForKimi, TestChatRelayPairedToolsUntouched).
  • A Chat request has every tool call that came with no id ("", null or none) given one in attempt, before it is relayed or translated, plugins included (chatCallIDs in chat_call_ids.go, #2611, RunMintOn). An upstream that sometimes streams a call without an id (OpenCode Zen's free DeepSeek) has the agent keep it as "", which that upstream takes back, while WorkBuddy AI turns a streamed request carrying one away (400, code 11133) and Anthropic takes no empty tool_use id. The id is made from the call's place in the request, its name and its arguments, never at random, so the next turn's history goes byte for byte and the upstream's prompt cache holds; the tool messages after the call that answer with no tool_call_id take the made ids in the calls' order. A body whose calls all have ids goes as it came. On the reply side, a relayed Chat stream's call whose first fragment has no id is given one, and a later fragment's empty id is left out (chatTidy); a whole reply's call is given one too (chatWhole). TestEmptyCallIDRelayedWithOne, TestEmptyCallIDReachesPluginWithOne, TestEmptyCallIDTranslatedWithOne, TestStreamedCallGivenAnID in chat_call_ids_test.go.
  • A relayed Chat stream's tool call fragment with no index (none, or null) is given its call's (streamCallIndexes in chattidy.go, #3386). Gemini's OpenAI-compatible API sends its calls with none, where the OpenAI contract has one on every fragment: the AI SDK's OpenAI provider (Cursor's Private Inference) turned the chunk away ("expected number, received undefined" at tool_calls[0].index), and OpenAI's node SDK's stream helper kept no call at all. A fragment with an id other than the open call's, or after the first in its delta, is the next call; any other goes on with the open one. So two calls in chunks of their own are 0 and 1, never both 0, which that helper merges into one call. A fragment with an index keeps it. TestChatTidyGivesCallsAnIndex in chattidy_test.go, TestGeminiCompatRelayedCallsHaveAnIndex in gemini_compat_cut_test.go.
  • A translated Chat stream's tool calls are read by index, not as one after another (chatDecoder.toolCall in chat.go). An upstream may send several calls' fragments by turns (index 0, 1, 0, 1…), the first of each with its id and name; read as a new call at each change of index, two calls reached Codex as six function_call items, the first two with {} and four with no name (mysterious_dove on Discord). The open call streams as it comes; a call that starts while the open one's arguments aren't yet whole JSON is held by its index and given whole, in index order, at finish_reason or [DONE]. Every translation from Chat (Responses, Messages, Gemini, a whole reply) reads the stream through it. TestInterleavedToolCallsToResponses, TestInterleavedToolCallsToAnthropic, TestInterleavedToolCallsWhole, TestToolCallsNamedFirstThenArgued in translate_stream_test.go.
  • A relayed Chat reply whose choice made calls and ended stop ends tool_calls, streamed (chatTidy) and whole (chatWhole), as the translations' collector already ends it (collector.finish): told it stopped, a client that reads finish_reason ends its turn with the calls not run (喜欢一个人 on Discord, a relay in front of deepseek-v4.1-flash). Any other reason stays as it came. TestChatCallsEndToolCalls in chattidy_finish_test.go.
  • 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.
  • 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/<slug>, 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). The group stands in for them only for a caller given it: a gateway key that may use none of the groups listing a model alone is listed the model, when it may use it (keyListed over provider.GroupStandIns, on /v1/models and every list catalogFor feeds, /v1/models/{id}, the key's page, Codex's catalog and spawn choices), beside its provider's other models; a key given the group is given the group in its place. The Gateway page's key picker (/api/caller-keys/models) offers them too (luckymanjc on Discord, 11-05: a Remote magpie's key held to codex/* was listed GPT-6-Luna alone; TestKeyNotGivenTheGroupIsListedItsMembers, TestCallerKeyModelsOfferGroupKept). 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), 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<n>__), 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/<key>, named by its hash (keepSignature in gemini_sigstore.go), and the id carries only the key (__tsk16__<key>), 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/<key>.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: 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 (<id>__rk<n>__<key>, carryReasoning and unreasonCalls in 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.<m>.content.<b>) 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), 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), and refuseBoundThinking reads a refusal's indices against that same body. A thinking block signed empty (or with no signature) is left out there too: magpie gives every block a Messages client gets a signature, "" for reasoning it has none for (a Chat or Responses vendor's, Grok on Cursor's plugin), Claude Code keeps such blocks through a compaction, and a group that moves on to Claude mid tool loop was turned away on every turn (citricdu on Discord: Kiro's Claude Opus 5.5 answered a bare invalid_request_error, which refuseBoundThinking can't read). An assistant message left with nothing goes; its text, tool calls and the results stay. The rule reaches every route to an upstream serving Claude (relayed, translated, a plugin's fetch such as Kiro's, Bedrock's us.anthropic.claude-… and Vertex AI's claude-…@ ids, count_tokens). A model that asked for its tool turns' thinking back (thinkingBackNeeded, DeepSeek under another name) keeps the blocks filled in for it. Claude's own signatures (base64), redacted_thinking and other vendors' signatures go as they were; DeepSeek's endpoint and every other upstream get the body byte for byte. TestDeepSeekThinkingThenClaude, TestDeepSeekThinkingThenClaudeResponses, TestWithoutForeignThinking, TestUnsignedThinkingNotSentToClaude, TestGrokThinkingThenClaude.
  • Claude's reasoning goes to a Responses client (Codex) in an envelope and comes back as Claude wrote it (mysterious_dove_96933 on Discord). Anthropic wants a tool loop's next request to have the turn's thinking blocks, signed, and its redacted_thinking whole, or answers 400; Codex with store: false keeps only a reply's items, and of a reasoning item only encrypted_content is opaque. So the Anthropic decoders name a signature as Claude's (KSig with sealAnthropic, Part.SignedBy), and the Responses encoder and renderResponses give each thinking block a reasoning item whose encrypted_content is magpie-claude1: and the block's JSON in base64 (claudeThinking, internal/claudeseal): its summary with it, an empty summary for a block signed with no text, and a redacted_thinking block as an item of its own. parseResponses reads such an item back into the block (claudePart), in order, so anthropicBody sends it as it was; an envelope that can't be read is its summary, as before. A Gemini thought's signature isn't named, and isn't sealed. The envelope goes to no Responses API: passthrough and forwardOnce take it out (withoutClaudeSeals: the item keeps its summary, one with none goes), codexInputAs leaves such an item out for Codex's own models as it does one with nothing sealed, and codexUpstreamOn takes it out before the ChatGPT backend; OpenAI's own encrypted_content is untouched. redact.MaskJSON keeps it whole (a reasoning item's seal), so the placeholders Claude was sent stay in what its signature covers. Claude's subscription names its signatures too, so Codex gets the same items, though its tool loop goes on inside Claude Code's own run, which keeps the thinking itself. TestCodexToolLoopGivesClaudeItsThinkingBack, TestClaudeBlocksNeverGoToAResponsesAPI, TestGeminiSignatureIsNotSealedAsClaudes, TestMaskJSONKeepsClaudeBlocks.
  • A translated Responses reply gives Codex the reasoning items a Responses upstream sent, as it sent them — one that carries its text in it (content parts, another vendor's shape) made over into one magpie could have, its text a summary and nothing sealed, in a reply translated or relayed as it came, for the client to store and replay where OpenAI's rules hold even with magpie disconnected (#2855, the reporter's rollout: 25 reasoning items a DeepSeek phase had left, each with its text in it and a seal of the vendor's own, stuck every later turn on OpenAI with a 400 array too long nothing of magpie's could strip then); any other upstream's reasoning becomes items magpie made: an rs_ id and a summary, nothing sealed. Codex hands them back on every turn. A request relayed as is to OpenAI's API or Azure OpenAI goes without them (withoutBareReasoning) unless store is true, because both look the id up among stored items and answer 400 "Item with id 'rs_…' not found" (#1008). Any other Responses upstream gets them, because a DeepSeek model wants its reasoning back (#388). When one answers 400 naming the input (refusesInput: param is input, or the error names an item by id), as a relay in front of OpenAI does with a message of its own, passthrough asks once more without them and, once that works, leaves them out for that provider and model from then on (bareReasoningRefused, #1044). Codex's compaction offers no tools, so it is relayed even when its turns were translated. The summary request magpie makes offers none either: codexInputAs sends tools: [] and leaves out the additional_tools input item, where Codex's Responses Lite (the entry of a ChatGPT account's gpt-6 model, copied from Codex's own) puts every tool; left in, the model may call one in place of the summary (the likely cause of WuSix's codex/gpt-6-astra "the model wrote no summary" on Discord, not confirmed on a real reply), and a reply with no summary says what it held instead (answeredWith). A reply that called a tool instead (calledTool) is asked once more with the conversation as text (plainCompact), and compacted locally when that writes no summary either: a model deep in an exchange of calls goes on with it whatever it is offered (Lucy on Discord: DeepSeek through group/auto-deepseek-v4-1-flash answered reasoning and an exec_command call 3 times in a row; TestCodexCompactToolCallAsksAgainAsText, TestCodexCompactToolCallEveryTimeCompactsLocally, over Chat, Responses and Messages, a group and a single model). When a provider answers its summary request 404, 405 or 501 (lacksEndpoint), or 400 for an item it didn't find (itemNotFound, a relay in front of either), or a kind of input item it doesn't take (inputKindRefused: Command Code's 400 unsupported_input_item, which takes messages, function calls, their outputs and reasoning only, and Grok's 422 "unknown item type"; as that status, as another magpie's 400 or 502 in front of it, or as an error in the summary's stream; never a 401, 403 or 429), codexCompact asks once more with the conversation as text (plainCompact), then compacts locally (#866, #1008, #5181, #5259), so the refusal never counts toward the guard's three. The text, and magpie's own summary, carry a Codex subagent's agent_message items (its task, the lead's follow-ups) as the user's (itemText). TestCodexCompactUnsupportedInputItemAsksAgainAsText, TestCodexCompactUnsupportedInputItemCompactsLocally, TestCodexCompactUnsupportedInputWordsOnAnAccountFailureStay. So does a summary request refused for its size (summaryTooLarge): a 413 byte cap, or an overflow of the model's window. Codex's remote compaction trims only by its own token estimate against the catalog's window and asks nothing smaller after either, so the turn's context_length_exceeded led to a compaction refused the same way, every time, and the session could neither compact nor go on (celestial_eagle_99230 on Discord: DeepSeek's own API, 1M window, answered 413 "Failed to buffer the request body: length limit exceeded"). The text ask leaves images out, keeps the ends of a long output and the latest 400K characters. TestCodexCompactTooLargeAsksSmaller, TestCodexCompactTooLargeCompactsLocally, TestCodexCompactOtherRefusalStays. Any other failure goes back with its status, said as the compaction's with who answered it (compactFailed: "compaction: (, ) answered the summary request 502 Bad Gateway: …"), the vendor's code, param and Retry-After kept. Not so the compaction Codex runs before a turn on another model, on the model the thread was on: a switch to a smaller window (compaction.reason model_downshift in the turn metadata) or to another compaction hash (comp_hash_changed), the only places Codex names either (maybe_run_previous_model_inline_compact in codex-rs core/src/session/turn.rs). When it fails, Codex asks the turn's own model instead only under its provider named "OpenAI" (compact_model_fallback.rs). Under magpie's provider, the one Codex has while its sign-in is used up (codex.out), the refusal was the turn's, and every turn of that thread asked the used-up account again, restarts or not, while a new thread worked (hiwise_aigc on X). Off CodexPath, codexCompact compacts such a failure locally (previousModelCompaction), whatever the failure, the compaction-failure hold included, and the thread goes on on the model it was switched to. On CodexPath the provider is Codex's own "OpenAI", which asks the turn's model itself, so the failure goes back as before. TestCodexLeavingModelCompactsLocally; Codex 0.162.1 in a sandbox sent the old model's compaction_trigger to /v1 and failed the turn on a 429, and went on to the new model once the trigger was answered. A compaction relayed to OpenAI (/responses/compact on Codex's own model, as a /responses turn) that OpenAI answers with an error status and an empty body, which Codex shows as "unexpected status 502 Bad Gateway: Unknown error", or with a web page, is said in words naming the model, the status, and the account it went to (codexSaidNothing, outrageous_piglet on Discord); an error OpenAI says in JSON goes as it came. TestCodexOwnCompactFailureIsSaid, TestCodexCompactFailureSaysCompaction, TestCodexCompactNoEndpointCompactsLocally. So does the ChatGPT backend's 502 "response protection is unavailable" (protectionRefused): a long history refused so was answered as text. Codex also compacts remotely, a compaction_trigger on /responses that wants exactly one compaction item back, on any provider table named "OpenAI", as CC Switch names its relay tables. magpie points those at /v1 while a magpie model is on, so handle makes the summary there too (codexInput, codexCompact), and magpie's summaries go back to the model as text (#1301). A summary is wanted only whole (askWhole, holdWriter.wantWhole): its stream is held to its end, not let through at its first words, so a reply cut short (errEndedShort), failed halfway (a 429 "Individual quota reached" after some of it) or ended incomplete (endedIncomplete, incompleteReply) fails over to the next candidate like a failure before any of it, and rests the account as that failure would; one that reached its output limit rests nobody. With nobody left, codexCompact answers 502 and never hands Codex the words before the cut as the summary (#2274, huangzuomin: Antigravity cutting each summary short) — but one whose stream merely broke off, with nothing failed or incomplete in it, is followed by magpie's own summary (#3526, Edward4226: Codex told a 502 asked the same huge summary over three times and the guard then held the conversation), as when no model can be asked at all. So is a translated summary serve found cut and answered 502 "the reply ended before it was complete" (summaryEndedShort).. Codex with context_management's experimental mode compacts in the background at every step while the conversation is over its threshold and drops a failed compaction without a word, so a conversation whose summaries keep failing is asked again every few seconds, each paying for the whole history (1169 compactions in 6 hours there). After compactFailsMost (3) failed summaries in a row of one conversation (prompt_cache_key) on one model, each within compactHeldFor (5 minutes) of the last, the next is answered at once with a 400 naming the last failure, which Codex doesn't ask again, and no model is asked until 5 minutes have passed (compactFails in codex_compact_guard.go); a summary that comes clears the count, and a sign-in's 401 or 403 isn't counted. TestCodexCompactCutSummaryFailsOver, TestCodexCompactCutSummaryIsNoSummary, TestCodexCompactKeepsFailingIsHeld. A summary is waited for compactWithin (4 minutes) at most: Codex hears nothing while it is made and gives up on a stream silent for 300s, so a later summary, and a local one made after Codex left, reached nobody, and Codex sent the same history again, 300s each time (#5275, hayden4608: a ~3.1MB summary request still going up a ~10KB/s uplink at 299s). Past it the ask ends (sideTimedOut, logged as magpie's own limit, not the agent leaving) and magpie's own summary goes to Codex while it still waits. A compaction Codex left before it was answered writes nothing and counts as a failure (499), never clearing the count. TestCodexCompactLateSummaryCompactsLocallyInTime, TestCodexCompactLeftBeforeAnsweredStillCounts.
  • An output_text annotation without the offsets OpenAI's schema wants of its kind (a url_citation or container_file_citation with no start_index/end_index, as Volcengine Ark's Responses endpoint writes its url citations) cannot be replayed where that schema holds: the ChatGPT backend refuses the whole request, every turn of the thread, with "Missing required parameter: 'input[n].content[m].annotations[k].start_index'" (#4921; withoutOffsetlessCitations in codex_backend.go, the same leaving-out as a reasoning item's text, #1411). A whole reply streamed as the vendor's own events drops such an annotation in every place a client reads one (dropOffsetlessCitations beside responsesWholeEvents in whole_stream.go, the #2855 rule: what magpie hands a client must be something it could send again); a history that carries one goes to the ChatGPT backend, OpenAI's API and a relay that has turned one away without it, and a refusal naming the parameter is asked again without it (refusesCitationOffsets). The text, a citation with its offsets, and a file_citation or file_path, which OpenAI places by a single index, go as they came (TestCitationsWithoutOffsetsAskedAgainWithout, TestWholeAsStreamDropsCitationsWithoutOffsets, TestCitationsWithOneIndexKept).
  • A reasoning item with its text in it (content parts: DeepSeek's Responses API writes reasoning_text, relayed to Codex as it came) is another vendor's. OpenAI's API and the ChatGPT backend take a reasoning item's content only empty, and refuse the whole request over one with 400 "Invalid 'input[n].content': array too long. Expected an array with maximum length 0" (array_above_max_length). Codex hands the item back on every later turn, so it never goes to them: for one of Codex's own models, codexInput(body, false) leaves it out (and a reasoning item with nothing sealed in it) on /backend-api/codex's /responses and on /responses/compact, before Codex's own sign-in, its API key or a magpie Codex account (compactOn) is asked. Codex compacts a thread before its first turn back on its own model, and a refused compaction shows as that turn's error (jue on Discord). passthrough leaves it out for OpenAI, Azure OpenAI and a Codex account (withoutReasoningText), and for any other upstream once it has refused one (refusesReasoningText, reasoningTextRefused, #1411). OpenAI's own sealed reasoning (encrypted_content, no text) stays, and a DeepSeek model (replaysReasoning) still gets the text. TestForeignReasoningNeverReachesOpenAI, TestReasoningTextLeftOutWhereRefused, TestReasoningTextNotSentToCodexAccount.
  • A conversation that moves to another key, account or vendor carries what the one before sealed (encrypted_content): its reasoning, and the sealed copy an answer's other items may carry: a web search's (web_search_call), and with Codex's output token replay on, each message's and call's (Codex keeps those for a provider named "OpenAI" only, and signed in it reaches magpie as that provider). forVendor takes the copies out for a vendor not OpenAI's, reasoning and compactions aside; between ChatGPT accounts, or a ChatGPT account and an OpenAI API key, all of it goes as it came. One that can't read it says so (foreignReasoning: OpenAI's invalid_encrypted_content, "could not be verified" of reasoning and "Encrypted content could not be decrypted or parsed." of a web search; xAI's "Could not decrypt"), as a 400 or as the stream's error, and serve asks it again without them (withoutSeals): a reasoning item goes whole, any other item keeps all but its encrypted_content (withoutItemSeal), and a compaction keeps its seal. Refused again, or with nothing else sealed, the compaction OpenAI sealed goes (withoutCompaction), unless native compaction is on (below). What was taken out is remembered by its hash for the conversation and the key or account that refused it, for stickKeep (refused, refusedSeals), and its later requests there leave it out up front (withoutRefused); what that one sealed itself still goes along, and a request that stays where its seals were made goes as it came. A refusal doesn't say whose seal it couldn't read, so every one goes, the asked one's own from an earlier stay in the conversation too, and all are remembered. It is the same whatever moved the conversation: a key or account resting, used up or rate limited, the next member of a group, or routing's own pick once its affinity went cold, on the backend path and on /v1/responses alike (#3887, hheei: after such a move a web_search_call another ChatGPT account of the group had sealed was refused, only the reasoning was left out, and every turn failed). Codex's own sign-in, relayed as it came (codexUpstreamOn), is asked again the same way when the backend answers its /responses with a 400 (withoutUnreadable, after the item the refusal names, if any); it keeps no record of what was refused, and a refusal in the stream reaches Codex as it came. TestForeignSealAcrossGroupMembers, TestForeignSealGrokToCodexAccount, TestForeignSealedItemsMoveToAnotherAccount, TestForeignSealedItemsAfterAColdSwitch, TestForeignSealedItemsRelayedToAnotherSignIn, TestSealsTakenOutLeaveTheRest.
  • Native compaction (#1099, off by default): a provider with nativeCompaction on (provider.Provider.CompactsOn; the editor's Compaction row, magpie provider set <id> compaction=native) is asked Codex's compaction_trigger as Codex sent it, and the compaction item it seals goes back to Codex unchanged, not as a magpie1: summary. Only a wire that carries it can be set so (CarriesCompaction): a Responses API, a ChatGPT account, GitHub Copilot (its models asked on Responses; its Claude models keep magpie's summary). The decision is made where handle and codexBackend read the input (nativeCompactionFor, codexInputAs): a group compacts natively only when every member does. Such a request, and a later one carrying a sealed compaction to a provider set so or to the provider recorded as its writer, is relayed, never translated, which would drop the item (keepsCompaction in attempt); a provider that can't be asked it on Responses answers a 400 saying so. The trigger is kept only when a key or account the request would go over (the provider's and its fallbacks', or a group's members', held and capped ones too, not one whose own list lacks the model) can be asked it on Responses (plannedCarrier, read from perKeyBarred without weighing, so a provider routed in turn isn't moved along by the decision). When the vendor lists the model only to keys that speak no Responses there, a key set to Chat say, codexCompact gives magpie's summary through the listed key, as with native compaction off; before, the trigger was kept and refused 400 carrierError with no upstream asked (#2725, ggbdpq; TestNativeCompactionTriggerSummarisedWhenNoListedKeyCarriesIt, TestNativeCompactionTriggerThroughTheListedKeyThatCarriesIt, TestNativeCompactionDecisionLeavesTheTurnsAlone). The key or account that answered is recorded, whoever it is: a fallback or another member that answered the trigger sealed it whatever its own setting, and only it can read the seal (#2271, JasonBuildAI: a fallback's seal went unrecorded, and the next turn was answered 200 without the compacted history; TestNativeCompactionFallbackSealStaysWithItsWriter). It is recorded by the hash of what it sealed (wroteCheckpoint, compactions.json beside affinity.json, 0600, at most 1024 for 30 days). A later request carrying it goes only to that writer (checkpointReaders); a writer whose own list has since dropped the model is tried still, as the last resort an account whose list lacks the model is — it sealed the model's compaction, and no other can read it (planned.unlisted, TestNativeCompactionWriterWhoseListLacksTheModel, #2642: it was refused as "switched off, removed, or no longer serves" though it was on, and switching it on changed nothing). With the writer gone from the candidates, magpie answers 400 checkpointError with the reason its settings give (checkpointGone: the provider removed, the account signed out, its sign-in lapsed, paused while others are on, switched off, kept from the model in Model settings, the key off or gone, the model disabled, or the model or group asked for not going to it), what lets the conversation go on, and whether native compaction is on for the writer's provider now, and never sends it to another key, drops it, or summarises it in its place (TestNativeCompactionWriterGoneSaysWhy). A call Codex makes beside the conversation, on a model of its own choosing with the conversation's history in it (compactionAside: the guardian's auto-review, on codex-auto-review or the model set for it, a memory, a subagent, a title, description, summary, prediction or suggestion), goes on without the seal when the writer isn't among its candidates (withoutCompaction), its instructions, turns since and tool calls kept: it isn't refused, and the conversation's own turns are still held to the writer. Relayed to Codex's own sign-in, a compaction recorded as sealed by a provider other than the Codex subscription (Copilot, an API key's) never goes as it came (foreignToSignin): such a side call goes without it, a turn or a /responses/compact is refused with checkpointError (echo_ts: every auto-review after a Copilot compaction was answered 400 invalid_encrypted_content by OpenAI; TestForeignCompactionLeftOutOfAutoReview). A seal with no record, or one whose provider can't be read, is the sign-in's to judge, as before. One of Codex's own models asked on the backend path is decided as a magpie model is when magpie's Codex accounts serve it (codexAccounts): the trigger is kept only with the codex provider's native compaction on, else codexCompact gives magpie's summary, which any account reads, and no writer is recorded (#2582, ump45nose; before, every such compaction was sealed natively whatever the setting, and the conversation was held to its account; TestCodexOwnModelCompactionHonoursTheToggle). Codex's own sign-in alone, relayed as it came, still compacts natively, unrecorded, as does /responses/compact; but a request carrying a compaction magpie recorded the writer of goes through routing even then (codexSealedFor), so with the writer switched off the one account left isn't sent it. A legacy /responses/compact carrying one is judged at its passthrough (sealedCompact): the writer on in magpie answers it signed as the writer — its own seal while the sign-in can be asked, a key's seal, a request signing with its own chatgpt-account-id, or an unreadable sign-in state relays as it came — and a writer gone is refused with checkpointError's reason, the same words as on /responses (TestNativeCompactionCompactJudgesItsWriter, #2727). The writer matched is the account user the record holds, so two Team seats of one email read as one and such a compact relays as it came. A gateway key held to some accounts (#905) is asked of the account the compact goes to (compactSigninHeld): the writer when it answers it, so a writer the key may not use is refused 403 (sealedCompactHeldError) with nothing asked, and one it may use answers though the sign-in isn't the key's (TestNativeCompactionCompactKeepsTheKeysAccounts). With the writer held at its usage cap or for credits it may not spend, the answer is 429 checkpointCappedError (record checkpointCappedRecord, "native compaction's account at its usage cap"), naming that account, that the others serving the model weren't tried for the compaction, and that neither the routing mode nor how conversations stay changes that: wait for the window, raise or lift its cap, or start a new conversation (#2517, lm0711; before, it read "every account at its usage cap" though another had room; TestNativeCompactionWriterAtItsCap). withoutCompaction (the drop after a refused reasoning item) isn't used for such a request. A route carrying a compaction names its sealer (Route.Compaction), and Routing says that is why no other account was asked, not that it is "the only account on" for the model (#2639; TestNativeCompactionRouteNamesItsWriter, routing-compaction.test.cjs). A refusal of the trigger reaches Codex as the upstream sent it. Not tried against a real upstream; Copilot may refuse a history that holds Codex's web_search items. native_compaction.go, TestNativeCompaction*.
  • A compaction magpie answers itself (codexCompact: a magpie model, Codex's own models through magpie's Codex accounts, a CC Switch table) goes to Codex as a compaction item whose encrypted_content is magpie1: and the summary in base64 (codexsummary.Encrypted), and codexInputAs sends Codex's own summary message in its place (codexsummary.Message: Codex's summary prefix, a newline and the summary, as a user message). Codex keeps the item in its rollout and replays it, and OpenAI refuses it once Codex talks to OpenAI itself (invalid_encrypted_content, LukeMa on X). So sessions.PortCodexRollouts writes that same message into the rollouts in its place (codex_portable.go). A reasoning item carrying Claude's block (magpie-claude1:, above) is written as its summary, as the gateway sends it to OpenAI (TestPortLineDropsClaudeBlocks). It changes only magpie's items, keeps every other line's bytes and the file's line count, mode and time, and drops an unreadable item together with its replacement_history_metadata entry. Every rewritten line keeps its length (fitLine: a shorter one padded with spaces after its JSON, a longer one in a paginated rollout not written), as Codex keeps places in a rollout by byte: a fork's history_base.end_byte_offset and the state database's turn and projection offsets. A shorter parent left a fork's place past its end, and Codex refused to open the fork ("cutoff byte offset is past the source rollout", xybio on Discord); once per Codex home a pass sets each such fork's place again from the ordinal it names (repairLineages). MoveCodexProvider keeps the session_meta line's length the same way and refuses a longer provider id for a paginated rollout. It and MoveCodexThreads (Codex stepping off magpie) hold the thread's writer lock as Codex's own archive does, from before a file is copied until the thread's row has moved: a Codex that has the thread open writes on to the file it opened, and what it wrote after a move was lost (#3751). Such a thread is refused as one written to in the last minute is (ErrActive), and a Codex home without writer locks moves as before. A pass publishes as Codex publishes a compressed rollout: under thread-writer-locks/.coordination.lock, only with the thread's lock free, through a temp file and a rename. A thread a Codex has open is left for a later pass, and a Codex home without writer locks is left alone. It runs 2 minutes after the GUI or magpie serve starts and every 10 minutes after, on Codex Disconnect (3s), and as the GUI quits (3s). Each pass reads what changed since the last whole pass, plus what was held (codex-portable.json). A ported thread was resumed by Codex 0.162.1 against an upstream that refuses magpie1: as OpenAI does. Not tried: a Codex in a WSL distro, whose locks this machine can't take, so it is skipped. TestPortCodexRollouts*, TestPortedCompactionReadsTheSame.
  • The summary ask codexCompact sends a provider that isn't OpenAI's or a Codex account carries Codex's developer messages as system ones (forVendor, developerItemsAsSystem, #2955: a chat-only vendor refuses developer). A relay of a ChatGPT account takes developer alone and refuses system (sub2api, #5067), so a summary refused "System messages are not allowed", or with a relay's bare "Upstream request failed", as a 4xx or as an error event in a 200 stream (roleRefused), is asked once more with the roles as Codex sent them (askAsSent), then as text, then made by magpie, so such a refusal no longer counts toward the hold (compactFails). A summary with no developer message isn't asked the same twice. TestCodexCompactSystemRefusedAsksAgainDeveloper, TestCodexCompactSystemRefusedEverywhereNeverHolds.
  • A Responses request Codex sends a Responses provider is fitted for a backend that isn't OpenAI's before it goes (passthrough): Responses Lite's shape taken off (fromLite): its additional_tools item lifted into tools (liftAdditionalTools, #350), its reasoning.context left out, its Lite marker removed from client_metadata (withoutLiteMetadata), and its X-OpenAI-Internal-Codex-Responses-Lite header not sent on (liteKept). A Codex websocket turn repeats the marker in client_metadata; leaving it beside a removed reasoning.context made a downstream Responses relay forward an inconsistent Lite request, which its ChatGPT backend refused with "requires reasoning.context to be all_turns". A subagent a Lite lead (gpt-6.1-sol) spawns on another model comes in that shape, its model name alone changed, and OpenCode Go's DeepSeek answered it 503 "Endpoint is unavailable" (TangForX on X, TestLiteSubagentLeavesLite). Also the tool search as a function, OpenAI-only fields left out. A relay that checks a request is Codex's own turns that shape away (#1758: 400 "Codex 客户端请求特征无效", 10014). A provider set codexAsSent (magpie provider set <id> codex=as-sent) gets a request from Codex (fromCodex) as Codex sent it, its model name alone swapped, with Codex's own headers (codexClientHeader). That holds when Codex offers web_search too: the request is relayed with it, not translated for magpie's search (searchedForIt), which merged the developer messages into instructions, sent apply_patch as a function, left web_search out and added max_output_tokens (codexAsSent in route; maralica on Discord). spawn_agent's description is still widened with the catalog's models (spawnAgentModels). Off is the default, and a subscription account is never sent so. TestCodexAsSent, TestCodexAsSentWebSearch, TestFromLiteRemovesOnlyTheWebsocketLiteMarker, TestCodexTitleRelayKeepsLiteShapeConsistent.
  • A tool a Chat request's message carries joins the request's tools (liftMessageTools in message_tools.go, #2322). Pi with supportsMidConvoToolAdditions gives a tool it adds mid-conversation as {"role":"system","tools":[…]} with no content, and keeps top-level tools as they were at the start; no Chat API reads tools there, and parseChat read only the top-level ones, so the tool could be called on no route. handle lifts them for every Chat body before serveAgent, so the Chat relay, the schema fixers, redaction (the tool is a tool definition, not message text), the prompt shown and routing all see them; parseChat lifts too, for a body that never came through handle (the Claude subscription bridge's direct callers). Each tool joins once by name and the first definition wins: a top-level tool keeps its own, then the earliest message's, as liftAdditionalTools and a tool_addition (withoutDeferredTools) do. A system or developer message that carried only tools is left out, so it is neither relayed as an empty system message nor joined into the system text as an empty part; one with content keeps its place without tools. Messages stay where they are: the in-place system message the issue also asks for is not this change. TestPiAddedToolReachesEveryRoute sends deephbz's Pi 1.2.0 bytes through the Chat relay, Messages, Responses, Gemini and Codex, and TestPiAddedToolOfferedToClaudeCode through the Claude subscription bridge.
  • A Chat request's tool in another API's shape is put in the Chat shape, {"type":"function","function":{name, description, parameters, strict}} (shapeChatTools in chat_tool_shape.go, #2622, jinyue806): MCP's {"name","description","inputSchema"} (ZCode), Anthropic's input_schema, a bare {"name","parameters"} and Responses' flat {"type":"function","name",…}. No Chat API takes those (SenseNova: "field Tools[0].Type invalid, should be set" and "function cannot be empty"), and parseChat read no name from them, so a translated request offered a tool named "". It runs right after liftMessageTools, in handle for every Chat body and in parseChat, so it holds for every Chat upstream, not SenseNova's alone. A tool with its function, a hosted tool (any other type) and one with no name are left as they came, and a request with none to shape is relayed byte for byte. TestChatToolInAnotherShapeIsShaped sends the report's request with each of its four tools through the Chat relay, Messages and Responses; TestShapeChatToolsLeavesChatShape.
  • Every request to a key+URL provider goes with the User-Agent the inbound request carried, unchanged (userAgentFor in user_agent.go, #1851, nb5p on Discord): a coding plan that serves only the agents it names knows them by it, and a gateway of the user's own behind magpie sees which agent asked. It was once the opt-in passUserAgent; a file that still says it reads the same as the default now. A provider set magpieUserAgent (magpie provider set <id> user-agent=magpie, the editor's "Send the agent's own User-Agent" unticked) goes with magpie's (magpie/<Version>) in its place. One the agent didn't send, and magpie's own (magpiesOwn: another magpie's magpie/…, magpie-router/1, magpie-vision/1, magpie-search/1, and the image tool's <client> magpie-image/1, built from MCP's clientInfo, or behind the MCP router from the first word of the agent's User-Agent), go as magpie; magpie never makes up another client's. forwardOnce sets it for chat, Anthropic, Responses, Gemini and count_tokens; embeddings, images and videos (retrieveFrom, sendWith, remoteVideoContent) set it with stampUA from the caller the request came with (caller.ua, withCaller), and before #1851 went with Go's default. Claude Code's and Codex's own headers are copied after, as before, their User-Agent being the agent's as agentUA has it, and the user's header.User-Agent is put on when the request is signed, so it wins. provider.PassesUserAgent refuses it for a signed-in account, a plugin's, and a vendor whose own client magpie goes as (OwnClient: OpenCode, Cline, Kilo, another magpie); their signing sets their own. To another magpie the request still goes as magpie/<Version> (its attribution headers are trusted only from that), with the agent's User-Agent in X-Magpie-User-Agent (ClientUAHeader, passOnUA, on every route: forwardOnce, embeddings, images, videos; the classifier's decision request names none). The far magpie takes it only from a magpie/ request (callerFrom, as caller.ua, relayed), takes it off what comes in (withCaller), and agentUA hands it to userAgentFor in place of the near magpie's, so the far vendor is sent the agent's; a client that writes the header itself is sent as it is. TestUserAgentPassedOn, TestUserAgentAccountUntouched, TestUserAgentFor, TestPassesUserAgent, TestRemoteMagpieRelaysUserAgent, provider-user-agent.test.cjs.
  • A Chat upstream that wants a turn's reasoning back (chatReplaysReasoning in chat.go: a host or a model, as magpie or the provider names it, with deepseek in it, such as OpenCode Go's deepseek-v4.1-flash, or Command Code's plugin) gets every assistant tool call with reasoning_content, relayed (withReasoningOnToolTurns in passthrough) or translated (buildChat). DeepSeek turns the whole request away ("The reasoning_content in 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 in reasoning or reasoning_details is copied in, and reasoning is then left out (asReasoningContent): a self-hosted DeepSeek server reads the two as one field and refused pi's tool turn, which carried its thinking in reasoning, as "duplicate field reasoning" (ArvinCharl on X, v0.1.1560), while reasoning_details, a list of typed entries that can hold an encrypted one, stays; 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). An assistant message right after a tool result, a reply with no call of its own, gets one too: DeepSeek refuses it the same way (checked 2026-10-12, #1822). A reply to the user, any other model and Mistral (#494) are sent as before.
  • A message content that is a list of plain text parts ([{"type":"text","text":…}], nothing else in a part) is relayed to a Chat upstream as the string it says, the parts joined by a newline (textPartsAsString in chat_text_parts.go, in passthrough before silentAssistantsOut). OpenAI takes either, but a vendor's own server may take a string alone: the Intern discovery API (a custom provider on OpenAI compatible, Atria-Dawn, Discord) answered DeepSeek Harness, whose pi-ai sends every user message as such a list, 422 with an "Input should be a valid string" per message. A list with an image, a file, a thinking part or a cache_control mark stays a list, and every other byte of the body stays as sent; buildChat already writes text as a string. TestChatRelayTextPartsAsString, TestTextPartsAsStringOnlyPlainText.
  • An assistant turn the user cut off before it said anything (only its thinking, an empty text, nothing; an isolated Codex reasoning item; a Gemini thought alone) stays in the agent's history and is sent on every later turn. DeepSeek and Kimi turn the whole request away over an assistant message with neither content nor tool calls, reasoning_content alone included ("Invalid assistant message: content or tool_calls must be set", #2599). Every Chat upstream gets such a turn left out, translated (buildChat, before pairToolMessages) or relayed (silentAssistantsOut in passthrough), by one rule (withoutSilentAssistants in chat.go): the two user messages it stood between join into one, and after a tool result the user's message follows the tool message. A prefill to go on from (prefix, partial, a Resume), a legacy function_call, a refusal and an audio reply stay, and a relayed body without such a turn goes byte for byte. TestChatEmptyAssistantLeftOutFromAnthropic, …FromResponses, …FromGemini, TestChatRelayLeavesOutEmptyAssistant, TestChatRelaySilentAssistantsOnly.
  • Kimi's Chat API (isKimi: the Kimi platform's and a Kimi Code membership's hosts or presets) turns reasoning_details in a message away in any shape: an entry with a stream's index ("the reasoning_details at position 1 entry 0 must not contain streaming index") and any other entry ("… has an invalid type"), checked against api.kimi.com/coding on 2026-10-12. pi keeps another vendor's thinking there (MiMo's, through Command Code, with index: 0), so a conversation routed on to Kimi was refused on every turn (#1765). passthrough sends it to Kimi as reasoning_content (reasoningDetailsAsContent, with the message's reasoning left out once its text is there), which Kimi takes; a message with reasoning_content of its own keeps that. Another upstream that refuses a thinking field "at position N", as Kimi words it (a relay in front of it), is asked once more the same way and marked (refusedInMessages, withoutMessageReasoning).
  • Vertex AI takes a function declaration's parameters as its own Schema object, whose type is required, and turns the whole request away over one schema without it, though the tool is never called: 400 "mcp__cua-driver__drag functionDeclaration parameters.target schema didn't specify the schema type field." (kthink on Discord: dsh with cua-driver's MCP tools, from before cua's own fix in its #4888, on Command Code's google/gemini-3.8-flash, which Command Code's gateway serves on Vertex; target was an anyOf of an untyped oneOf and null, scope a const). A body whose model names Gemini (geminiNamed: the id's last / segment starts with gemini, whoever serves it) has each untyped schema under its tools' function.parameters, parameters or input_schema given its type in place (geminiToolTypes in gemini_schema.go, in forwardOnce, so a plugin's request too): from its enum or const values, its keywords or its branches, null left out (an object's or array's keywords, properties or items, before its values: a string enum beside items typed "string" sent items on a string, and Antigravity turned the turn away with "properties[display].items: field predicate failed: $type == Type.ARRAY", ferock on Discord; TestGeminiToolTypesItemsBeforeEnum), {} or a description alone a string, a tool's root an object. A node whose branches have more than one type, an unresolved $ref or union, and anything under not or if are left as they came, so such a schema can still be refused; every other model's tools go byte for byte. Google's own Gemini API and Code Assist are sent parametersJsonSchema and Antigravity plainSchema, so a Gemini-shaped body isn't walked (TestGeminiToolTypesCuaDriverDrag, with cua-driver's drag schema as its server listed it, TestGeminiToolTypes). plainSchema itself keeps an array's keywords (items, minItems, maxItems) on an array only and an object's (properties, required …) on an object only, and of a type list takes the type its items or properties are for, so a body a magpie from before sends is taken too (TestAntigravityItemsOnlyOnArrays). Google's Schema is an object with a fixed set of fields, so a boolean schema (items: true, a property's true or false) or an x- keyword such as MCP's x-mcp-header (2026-07-28 spec, SEP-2243) turns the whole request away ("Invalid value at '…items.items' (…aiplatform.master.Schema), true" and 'Unknown name "x-mcp-header" … Cannot find field', han_tiv on Discord). plainSchema is an allow-list, so x- keys never pass it; a boolean is {} for true and left out for false (a false property leaves required too, a false items is items {} with maxItems 0). Before typing, geminiToolTypes runs geminiSchemaShapes, which does the same for the relay's case: true is {}, false is left out, x- keywords go (a property named x-… stays), and additionalProperties and the unevaluated… keywords keep their booleans; a schema with neither goes byte for byte (TestAntigravityBooleanSchemaAndXKeys, TestPlainSchemaBooleansAndXKeysEverywhere, TestGeminiToolTypesDropsBooleansAndXKeys). What is left is still JSON Schema, so parametersJsonSchema (Gemini API, Code Assist, Vertex), which runs after it on a Gemini-named body, takes it as before.
  • A tool whose schema has a union (anyOf, oneOf, allOf) at its root is folded to an object root (provider.ObjectRoot; foldsRoots and objectRootsBody in object_root.go, #1271): Anthropic's API turns every request offering one away ("input_schema does not support oneOf, allOf, or anyOf at the top level"). A request translated to Messages always went folded (objectSchema); a Chat or Responses body relayed as it came is folded for xAI from the first ask and for any other upstream once it refused one (rootUnionRefused, retried folded at once). A Messages body relayed as it came, a client that speaks Messages itself (ZCode, Claude Code) to an Anthropic-protocol provider or plugin, went unfolded until 11-04: ziko on X, ZCode with Zed's subscription, Claude refused every request because six of an MCP server's tools (GoAnyAPI's goanyapi_adsense among them) had a root oneOf. It is now folded for every such upstream from the first ask; a server tool (no input_schema) and a schema with no root union go as they came (TestMessagesRootUnionFolded, TestRootUnionFoldedWhereRefused, TestRootUnionFoldedForXAI).
  • A Responses request's top-level access_programs, the Cyber program Codex asks the model under ({"cyber":"standard"} on a subagent it inherits, OpenAI's Daybreak programs, magpie-releases#18), goes only where Codex itself would send it: codex-rs sends it with a ChatGPT sign-in, or an API key on its provider named openai, and to no other provider (cyber_access_program.rs, for_auth, for_provider). In forwardOnce, relayed or built (from Chat too), it goes as it came to a ChatGPT (Codex) account, a host ending in openai.com, another magpie (IsRemoteMagpie, whose own upstream decides) and a relay set codexAsSent when Codex sent the request; every other Responses upstream is sent the request without it (keepsAccessPrograms, withoutTopMember, the rest byte for byte). OpenCode Go answered it, for DeepSeek and GLM, with 503 "Upstream request failed: Endpoint is unavailable." and 200 without it or with null; its Haiku took it (#3172, three reporters' real A/B runs). It is taken out before the user's extraBody is merged, so an access_programs written there still goes. Chat and Messages builds never carry it; a Chat request relayed as it came keeps whatever its client wrote. TestAccessProgramsGoToOpenAIAlone, TestWithoutTopMember, TestCodexAccessProgramsReachBackend.
  • A client that took the gateway for an Ollama server (its /api/tags and /api/show are answered in Ollama's shape) sends Ollama's per-request options beside its Chat fields: Hermes Agent sees /api/tags answer, takes the server for Ollama (detect_local_server_type) and sends /api/show's context as options.num_ctx. No Chat API reads options, Ollama's own /v1 included (its ChatCompletionRequest has none), and the strict ones turn the whole request away: Gemini's OpenAI-compatible API (geminiCompat) over a name it doesn't know (#3097), Mistral with 422 extra_forbidden (lijiho96940561 on X). So every relayed Chat body goes without its top-level options (withoutOllamaOptions, the rest byte for byte, so a tool parameter or a message naming options is untouched), as the Ollama route's own body builder leaves the runner settings out (ollamaChatBody). TestChatRelayLeavesOutOllamaOptions, TestHermesOllamaOptionsNeverReachMistral.
  • Claude Code's deferred tools (ToolSearch, MCP tools that come and go) put blocks of their own in a message: a tool_addition (tool a tool_reference naming the tool, or a tool_definition), a tool_removal, and a tool_reference. Kimi's Anthropic endpoint refuses any of them with a whole-request 400 "Invalid request Error" that names nothing, so once a session had loaded a tool every turn failed (#2042); DeepSeek's takes a tool_addition naming a tool but refuses one defining it, a tool_removal and a message's tool_reference with 422 "unknown variant tool_removal" (both checked against the real endpoints on 2026-10-14). OpenCode Go also rejects DeepSeek inline definitions with a generic 422 "Upstream request failed: Endpoint is unavailable." (checked on 2026-10-15). Kimi and DeepSeek models on OpenCode are never sent these blocks (forwardOnce); a provider that refuses one in those words is asked again at once without them and not sent them again while magpie runs (refuseShapes, shapeDeferred; the retry loop reads a 422 as well as a 400). withoutDeferredTools drops the blocks and a message they leave empty; definitions present only in a tool_addition.tool.definition join the request's tools once by name (an existing top-level definition wins), and a tool_reference inside a tool_result (ToolSearch's answer, which both take) stays. Any other provider is sent them as Claude Code wrote them (anthropic_shapes.go, TestKimiIsSentNoDeferredToolBlocks, TestDeferredToolBlocksRefusedOnceLeftOut, TestOpenCodeDeepSeekInlineTools, TestDeferredInlineDefinitionPreserved).
  • ToolSearch's answer is a tool_result whose content is tool_reference blocks alone. OpenDesign's Anthropic endpoint can't read one: 422 "Failed to deserialize the JSON body into the target type: messages[4]: missing field content" (#2124, the reporter's direct request without magpie fails the same way; the same result with a text block beside the references is taken). A provider that refuses in those words while the request holds such a result is asked again at once with a text block first in each, "Tool is loaded and can be called now." (toolLoadedText, the words a translated route already gives a model in stringOrText), the references and the tool_use/tool_result pairing kept, and is sent it that way while magpie runs (refuseShapes, shapeRefsOnly, withRefsSaid). This is in forward, so /v1/messages, count_tokens and a group's member all get it; a request translated to another API already carries the references as that text. Any other provider is sent the bare references (TestRefsOnlyToolResultRefusedGetsText, TestRefsSaidLeavesOtherResults).
  • A tool Claude Code's ToolSearch loads, translated to a Responses API, used to join the top-level tools on the next request, which changed the prompt from its first bytes and missed the cache on every load (#2660). A deferred tool (defer_loading, Tool.Deferred) that a tool_result's tool_reference names (toolRefs, Part.Loads) now goes, where Request.LoadedInPlace is set, in an {"type":"additional_tools","role":"developer","tools":[…]} item right after the run of tool outputs that loaded it, once, and not in tools (buildResponses): tools loaded by parallel results or one result naming several share one item, a tool named again isn't repeated, and the tool output's text is as before. OpenAI's tool search guide documents the item and that its tools load at the end of the context so the cache is kept. A compacted or edited history whose loading result is gone puts the tool back in tools, a new prefix, as is expected. LoadedInPlace is set (loadsInPlace, in forwardTranslated) for OpenAI's own API with a key (api.openai.com, *.api.openai.com), for a ChatGPT (Codex) account, and for a provider set additionalTools (magpie provider set <id> additional-tools=on); additional-tools=off (additionalToolsOff) turns it off even where it is the default, and default goes back to magpie's. The ChatGPT backend was tried with a real account (#4738, gpt-5.6-terra, gpt-6-luna, gpt-6-sol): it takes the item where it was loaded, the model calls the tool in it, and the next request read 7680–7936 tokens from cache where, with the tool moved into tools, it read none. Nothing else is sent it by default, since xAI answers the item 422 (#350), and no relay, other vendor's sign-in (Copilot) or plugin's vendor has been tried. An upstream that refuses a request holding the item with a 400 or 422 naming additional_tools is asked again with every tool in tools, logged ("turned away additional_tools … loaded tools go in tools from now on") and not sent the item again while magpie runs. Not handled: a tool a tool_addition block loads (an MCP server's late tool, the advisor) stays in tools. TestLoadedToolsKeepThePrefix, TestLoadedToolsInOneItem, TestLoadedToolsWhereNotTaken, TestLoadsInPlaceScope, TestLoadedToolsThroughTheGateway, TestCodexAccountLoadsInPlace.
  • A Responses upstream that wants a turn's reasoning back (replaysReasoning in responses.go: a model with deepseek in its name, on any host but OpenAI's, xAI's, Copilot's and Azure's) gets every reasoning item with a reasoning_text and every tool call after one, relayed (withReasoningText in passthrough) or translated (buildResponses). DeepSeek's /v1/responses turns the whole request away ("The reasoning_text in the thinking mode must be passed back to the API") over a reasoning item without text, one with an empty text, and a function_call whose step (since the last user message or tool output) has no reasoning item. Codex sends all three in a routing group that falls to DeepSeek after ChatGPT: the backend's sealed items (encrypted_content only), magpie's summary-only items, and another member's calls with none (#1104, #1592). DeepSeek reads a step (a run of reasoning, assistant messages and calls) as one assistant message whose thinking is the item it starts with: in the current turn, a step with a call or after a tool output must lead with a reasoning item, so [message, reasoning, call] and [output, message] are refused while [reasoning, message, call] and [output, reasoning, message] are taken (checked against api.deepseek.com on 2026-10-12). Codex sends a step that said something before its call with no reasoning for another model's turn, which magpie used to send [message, reasoning " ", call] and DeepSeek refused intermittently, only while the turn lasted (#1822, through OpenCode Go). An item's own text is kept; one without gets its summary, else a space (noReasoning); each such step leads with its reasoning (reasonFirst): its own first reasoning item moved ahead, else one holding a space. A sealed item keeps its id and encrypted_content; a body already in that shape goes byte for byte.
  • A Messages upstream that wants a turn's thinking back (anthropicReplaysThinking in anthropic.go: a host or a model with deepseek in it, never api.anthropic.com or a Claude model) gets a thinking block on every assistant message with a tool_use or right after tool results alone (refused the same way, checked 2026-10-12, #1822), relayed (withThinkingOnToolTurns in passthrough) or translated (build, which also keeps unsigned thinking as its text there). DeepSeek's /anthropic/v1/messages, thinking (its default, or asked for), turns the whole request away with 400 "The content[].thinking in the thinking mode must be passed back to the API" when such a message has none, and answers any redacted_thinking with 422, a block it can't read. Claude Code sends both in a routing group that falls to DeepSeek after Claude (#1611). A message with no thinking gets one holding a space (noReasoning) first; Claude's redacted_thinking becomes that block, or is left out beside thinking of the message's own. Signed thinking, DeepSeek's own and every other message go as they came. Checked against the real endpoint on 2026-10-11: it takes Claude's signed thinking, unsigned thinking and a space, anywhere in the message. A thinking block magpie sends unsigned (the space, or a turn's reasoning kept as its text) says "signature": "", as aBlock writes thinking even when empty: OpenRouter's /api/v1/messages holds a block's signature to a string and turns a DeepSeek request with none away, 400 "Invalid Anthropic Messages API request" (#2883, #3696), and DeepSeek's own endpoint takes the empty one (checked 2026-10-19). TestOpenRouterDeepSeekThinkingHasASignature.
  • A Messages or Chat upstream whose host and model don't say DeepSeek but whose model answers 400 "The content[].thinking (or reasoning_content) in the thinking mode must be passed back to the API" (thinkingBackRefusal in thinking_back.go) is asked once more with its tool turns filled as above (withThinkingOnToolTurns, withReasoningOnToolTurns), and that provider's model is sent them at once from then on (thinkingBackNeeded in unfit, filled in forwardOnce), on every route to it. A relay serving DeepSeek under another name, or a provider the user named "My Claude", got a routing group's fall from a rate-limited Codex subscription mid tool loop refused, Codex's sealed reasoning having no text to give (qisishiqi on Discord, 2026-11-02). Checked against api.deepseek.com on 2026-11-02: only the tool loop being continued needs it; finished turns and plain replies are taken without. A provider that never asked is sent the turns as before. TestThinkingBackLearnedBehindAnotherName, TestReasoningBackLearnedBehindAnotherName.
  • Every thinking block a Messages client gets says a signature, a string, as Anthropic's own do (its stream starts each block with "signature": ""): Grok Build reads ContentBlock::Thinking as {thinking, signature}, both required, and turned a whole reply away, "missing field signature" (uk.jent on Discord, on the MiniMax Code plugin). The encoder starts a thinking block signed empty (anthropicEncoder.thinking), renderAnthropic and whole_stream.go write the field too, and a reply relayed from a Messages endpoint that wrote none, streamed or whole, gets an empty one (sigFieldTidy in thinking_signature.go, in passthrough); a block already signed goes byte for byte, and redacted_thinking is untouched. magpie never makes a signature up: an empty one is none to every path that sends history on (anthropicBody leaves it out for Anthropic, keeps its text where reasoning is replayed), and a relay sends it back to the vendor that wrote the block, but never to an upstream serving Claude (withoutForeignThinking, above). TestMessagesThinkingIsSigned, TestSignedThinkingRelayedAsItCame.
  • A model writes a whole number in a call's arguments with a fraction of zeros (2500.0, 17277.0, tool_search's limit: 8.0): Grok's on every turn, whoever serves it (#1431), and muse-spark through the gateway (#3152). Codex reads the integer fields it parses as u64, usize or i32 even though their schemas say number, so serde turns away the whole call ("invalid number" for tool_search's arguments). In every reply, every number in a call's arguments written with a fraction of zeros and no exponent loses the fraction: 2500.0 becomes 2500, -3.00 becomes -3. Strings, keys, other fractions (2.5, 2.50) and exponents (1.0e3) stay as written. No tool schema is consulted, since JSON has one number type and one that took 2500.0 takes 2500. The rule runs over the arguments as a stream of text (wholeNums), holding back only a fraction of zeros until the next byte. This gives the same arguments whether they come whole or in deltas cut anywhere, so what a call's deltas add up to is what its done events say. Relayed replies are rewritten in passthrough by intTidy: Responses' function_call items, argument deltas and done events and the completed response; Chat's tool_calls deltas and messages; Messages' tool_use input and input_json_delta, streamed or whole; a whole reply with no call in it is said as it came, undecoded. A glm-5.3-flash* route's stitched CR (crTidy, #4256) is dropped before intTidy sees the reply, since intTidy holds a whole one to its flush (TestStitchedCRAndWholeFloatsBothGo). Translated replies are rewritten at the encoder (wholeEncoder, outside usageEncoder) and at render (wholeResult). Grok's schema quirks stay grokModel's (grok_integral.go).
  • A tool call a model writes into its reply's text, when the request offered tools, is made the call it is (textcalls.go, #823): Hermes' <tool_call>{…}</tool_call>, DeepSeek's DSML (<|DSML|invoke name=…> with its parameters; its mark found as the parse regexes read it, by dsmlMark, not from a list of spellings: any run of pipes, ASCII or full-width or mixed, spaces after < and around /, <||DSML|| too, #2623), DeepSeek's half-Hermes <parameter> form (#917), GLM's <arg_key>/<arg_value> (#906), and the plain <invoke name=…><parameter name=…>…</parameter></invoke> of Claude's and MiniMax's calls, bare or in <function_calls> or <minimax:tool_call> (packinggoodsllc_07668 on Discord: Claude Code through a routing group was shown the invokes as text), read by parseTextCalls. Text after a call read out, other than tags, ends the calls, and it and all after it go: the model went on as if its call had run ("Result: Tool loaded.", then the next call, then "done"), and the agent runs the call and gives it the real result. Each block must name an offered tool and have arguments that can be read; else the text goes on as it came. The text before the first block is kept, what is left of the tags goes, and the reply ends as one that called tools (finish_reason tool_calls, stop_reason tool_use). A DSML close with no block before it (</||DSML|| calls>) is held as a block is, and dropped when it is tags and nothing else. A reply whose model made a call itself has no call read out of its text, but tags and nothing else left in it after the call go, with the spaces before them (喜欢一个人 on Discord: a relay made the calls of DeepSeek's invokes and left the wrapper's close as text). Every route reads it the same way: a relayed Chat stream (textCallTidy), a relayed Chat reply that came whole, JSON or under text/plain or no type (chatWhole with wholeTextCalls, #1845: a stream:false request kept the markup and finish_reason stop), which also covers a vendor that answered a streamed request whole (wholeAsStream), a relayed Messages reply, streamed or whole (anthropicTextCalls: the held text's block start and stop are held with it, the calls become tool_use blocks after it, or in its place when none of its text went), and every translation, which magpie always asks streamed, a plugin's included, whatever the client asked (textCallSee). A relayed Responses reply, streamed or whole, is read too (responsesTextCalls in textcalls_relay.go, #4743, from v0.1.2652): the held text's output_text.done, content_part.done and output_item.done wait with it, and the calls become function_call items after it, in the events and in response.completed's output. Before it, Alma (whose provider of type openai speaks Responses) through a group to DeepSeek, whose preset speaks Responses too, had the reply relayed as it came and got DeepSeek's <||DSML|| calls> as text with nothing run (wishSeikouudoku on X). A relayed Gemini reply the same (geminiTextCalls). Covered by TestTextWritten*, TestInvokeReported*, TestDSMLAlma* (a group of Responses members and a plugin's DeepSeek, from a Responses client, one character to a delta), TestDSMLClose*, TestDSMLBlockClosedWithCalls, TestGLMTextCall*, TestPluginTextWrittenCall and TestQuietWholeReplyStreamed. Relayed Messages streams buffer complete SSE events with tidyEvents (phase.go), so splitting an event header, data and blank delimiter across reads cannot detach headers or join distinct JSON payloads (#4868). Held text-block starts and stops own their bytes so buffer reuse cannot overwrite them. TestAnthropicTextCallsSSEChunksKeepFraming and TestAnthropicMessagesSSEChunksKeepFraming cover native and text-written calls, held text, whole/event/line/byte reads, and CRLF.
  • Structured output is carried across every translation (Format, format.go). It is read from Responses' text.format, Chat's response_format, Anthropic's output_config.format and Gemini's responseMimeType with responseJsonSchema/responseSchema: json_schema with its name, description, schema and strict, or json_object. Each upstream is asked in its own field: text.format on Responses, response_format on Chat, output_config.format on Messages, and generationConfig.responseMimeType/responseJsonSchema on Gemini and Code Assist. An API with no name for it gets response. Messages and the Claude subscription's --json-schema take a schema only, so json_object is told in the system prompt there (inSystem). A 400 or 422 that names the field (refusesFormat: DeepSeek's "This response_format type is unavailable now", a schema Anthropic can't hold) marks the provider and model (formatRefused), and the request is asked again with the format told in the system prompt, as are later requests to that provider and model. A relayed request keeps its format as sent. A Gemini client's format is also still told in its system prompt, as before. A model may still wrap its JSON answer in a Markdown code fence; a client that asked for structured output, in a field or told in the system prompt (wantsJSON), gets the JSON inside a single unlabelled or json-labelled fence when that content is a complete valid JSON value, streamed (fenceEncoder) or whole (unfencedResult), in format_fence.go. Invalid or truncated JSON, other fence languages, text outside the fence, and answers to plain-text clients reach the client as they came. This normalization applies to translated replies; native protocol passthrough stays byte-preserving.
  • A tool's images reach the model on every translation (toolOutput in ir.go reads them from Anthropic's tool_result, Responses' function_call_output, such as Codex's view_image output [{"type":"input_image","image_url":"data:…"}], and a Chat tool message). Anthropic's Messages keeps them in the tool_result. Chat puts them in a user message right after the results, and the result says they follow; Gemini and Code Assist after the function's response. Kiro's results hold text alone, so Kiro's plugin (from 0.1.9 on) sends them with the message that answers the call, and only the latest images go again (#369, #1861). TestCodexToolImageReachesAnthropicPlugin and the Kiro plugin's tool-images.test.mjs.
  • An image's detail (Part.Detail, read from a Responses input_image and a Chat image_url, in a message or a tool's output) is carried on a translation to Chat and Responses (chatImage, chatDetail, responsesDetail in chat.go). Chat takes low, high and auto as they came, and Responses' original, which Chat lacks, as high; an image without one goes without. Responses takes the four as they came, and anything else, none included, as auto (#1474). Messages and Gemini have no such field, so it isn't sent there (mysterious_dove on Discord, Codex: high and original were dropped on the way to Chat; TestResponsesImageDetailReachesChat, TestChatImageDetailReachesResponses).
  • DeepSeek's own API (api.deepseek.com, never a relay or another base) is sent an agent's inline images by file id, not their bytes on every turn (#5407, faithleysath; deepseek_files.go). withDeepSeekFiles, in forwardOnce after the thinking is put back and before the byte cap, finds each base64 data: image a Chat, Responses or Anthropic body holds (walkImages: messages and tool outputs) for a model with flash in its name (deepseek-flash sees images; deepseek-v4-pro reads each as "[Unsupported Image]"), with the provider's key, not on count_tokens, and not where the provider is set imageFilesOff (magpie provider set <id> image-files=off, or the editor's Images tick under Advanced, offered only where provider.TakesImageFiles holds: the one host rule, ImageFilesAt, that dsFilesOn asks; matrix0487 on Discord; TestProviderSaveImageFiles, provider-image-files.test.cjs). An image asked at detail: low stays inline, as a file is read at full size. Each image not held yet goes up once through POST /files on the provider's host (multipart, purpose=user_data, expires_after a day from creation), signed as a Chat request with the candidate's own key; the swap is per key (dsKeyHash beside the image's sha256), so an id never goes with another key. The block becomes Chat's flat {"type":"file","file_id":…}, a Responses input_image with file_id in place of image_url, or an Anthropic image whose source is {"type":"file","file_id":…} with anthropic-beta: files-api-2025-04-14 added, as DeepSeek's files_api, vision, responses_api and anthropic_api guides give them (the Anthropic guide names the file source type and the beta; its field name file_id is Anthropic's Files API's, which DeepSeek says it follows). The ids are kept in deepseek-files.json beside providers.json (temp file and rename; an unparseable one moved to .bad), an id with under an hour left uploaded again, at most 4000 kept. One upload runs per image and key however many requests want it (flights), at most four at once for a request, outliving a cancelled request with its own deadline (20s, plus a second per 64KiB). A failed upload leaves the image inline and rests the key's uploads for ten minutes (dsFilesBreak); a request waits on an upload for dsWaitMax at most and sends what isn't up yet inline. A 4xx whose body names a file-api- id or says a file is gone (dsFileGone) lets the ids go and asks once more with new uploads (dsRetryGone in forward); refused so again, it goes inline. Uploaded bytes count in the request's upstream bytes (#4456). Not covered: a custom_tool_call_output's images (walkImages doesn't read it), and no file is deleted (DELETE /files): each expires in a day. TestDeepSeekImagesByFile, TestDeepSeekImagesInlineElsewhere, TestDeepSeekImageFilesOff, TestDeepSeekUploadFailsInline, TestDeepSeekUploadSlowGoesInline, TestDeepSeekFileGoneUploadsAgain, TestDeepSeekFilesPerKey, TestDeepSeekFilesOneUpload, TestDeepSeekFilesKeptOnDisk.
  • A Gemini client's generationConfig.imageConfig, the size and shape it asks an image model to draw at (imageSize, aspectRatio, and Vertex AI's own fields beside them), is carried as it was sent on a translation to an upstream that speaks Gemini: a custom provider's Gemini URL, Vertex AI, and Code Assist and Antigravity inside their envelope (Request.ImageConfig, buildCodeAssistSent in codeassist.go). A relayed request keeps it as sent. Chat, Responses and Messages have no field for it that magpie knows, so it isn't sent there. A request asked for one body that carries it is translated on the Gemini URL even where the provider has a Chat URL too (One try above); one that doesn't goes to Chat there, unless the user set the model's API to Gemini (#3820, GuoJinguang: imageSize 4K asked through magpie drew 1024x1024; TestGeminiImageConfigReachesTheGeminiAPI, TestGeminiImageConfigReachesCodeAssist).
  • Group members are provider/model[:effort]. A member with a fixed effort is asked for that effort, bounded by the group's levels (#671).
  • A member the user unchecked in its provider's model list is skipped (unpicked in group.go, in membersOff; #3911, timonwong): the provider has picks and its served models lack it, as the Routing page strikes it, and the Routing card says it is not ready (provider.ResolveRoute). A provider with no picks still routes a model its list lacks (#2642), a decision model is still a decision group's, and a request naming the model itself still reaches it (resolveIn takes any provider/model of a provider that is on). group_model_pick_test.go.
  • A member's suffix may join several levels with + (provider/model:low+xhigh, Garydesu on X): the agent picks among them. provider.MemberLevels splits it into Member.Levels and leaves Effort empty, so it isn't fixed; one level is still a fixed effort. The suffix is kept lowest first, each level once, and the whole stays the member's id, so its rules, fast, off and weight are keyed by it as for any member. The gateway fits the agent's ask to the member's own levels (groupLevels returns the candidate's levels first), and the group lists those for it to agents (buildGroupEntries), intersected with the other members' as usual. In the GUI the member's reasoning menu has "Several levels…". Tests: TestMemberSeveralLevels (provider), TestMemberSeveralLevelsFollowAgent (gateway), group-member-levels.test.cjs.
  • A member that follows the group may map the level asked to the level sent (Group.EffortMaps, keyed by the member's id as Members spells it, json effortMaps; groupeffortmap.go; LuckymanJC on Discord: a long task relayed across vendors, where one vendor's high is another's xhigh). With no map, or a level the map doesn't name, it goes as asked, so a group saved before is unchanged. SaveGroup keeps a map only for a plain member of the group (not one fixed at an effort or with several levels, not a group/ member), drops pairs that send the level asked, and refuses a word that isn't a reasoning level. A member rename, a provider rename, a fold, a share and its import carry it (renamedEffortMaps: on a collision the map already spelled so wins). In the gateway the level asked is the model suffix's or the agent's pick, then the turn's pick, then the request's own (askedLevel: agentEffort, and none for an Anthropic request with thinking disabled); the map's target (mappedLevel, ultra read as max) is sent with withFixedEffort, fitted to the model's levels unless it is none, and the trace's try keeps the level asked (mappedFrom). A member's fixed effort and a rule's UseEffort still win. It is per candidate, so fallback and retries send each member its own; count_tokens sends no member effort. The group lists a mapped member's own levels plus the map's keys to agents (mappedLevels in buildGroupEntries). In the GUI the member's reasoning menu has "Map levels…": a level asked, then the one sent or "As asked". The CLI and TUI keep the map but don't edit it. Tests: TestMemberEffortMap* (gateway), TestSaveGroupEffortMaps, TestGroupLevelsWithEffortMap (provider), group-member-effort-map.test.cjs.
  • A group offers agents the reasoning levels its members have in common (groupEntries in group.go), or the ones it names (Group.Levels, #295). A member that doesn't follow the agent's effort is left out of that: one fixed at an effort, one whose levels nothing knows (#597), one that thinks with no levels, one the user made reasonless, and one known not to think (Entry.Quiet), which the gateway sends no reasoning ask (withoutReasoningAsk, quiet.go). A quiet member used to empty the group's levels, so Codex got its entry with no supported_reasoning_levels, showed no effort control and ran at its own medium (#2127, TestGroupQuietMemberKeepsCodexEffortControl).
  • An agent whose config can't carry an effort has one picked in magpie (provider.AgentEffort, settings' agentEfforts; Cursor Private Inference's row, #1003, and Antigravity's, #4838). On an Antigravity account the level picks the family's variant, as a request's own effort does (AntigravitySentID, TestAntigravityAgentEffort). Antigravity's app lists a model with levels once a level, <id>:<level> (agent-wiring), so the level chosen in its own picker arrives as the suffix and outranks the row's pick (TestAntigravityAgentEffort). 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 the effort the rule that put the member first sets (Rule.UseEffort), then a model's :effort suffix, 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.
  • In models.dev, entries from deepseek, kimi-code-plan-cn and kimi-code-plan-global gain none only when they have both a toggle and effort levels; the DeepSeek and Kimi APIs accepted that value in #1098. Other providers keep their listed levels because their APIs may reject none; toggle-only entries remain level-less (mdModel.efforts).
  • 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 in extra_body.google.thinking_config. A 400 or 422 whose error names extra_body, include_thoughts or thinking at all (refusesThinkingConfig) marks the provider unfit for the field (thinking_config), and it is asked again with reasoning_effort alone. Gemini 3 can't stop thinking, so reasoning turned off goes at minimal, its least, or at the model's lowest level where it has no minimal (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 own none or minimal that 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 takes none from gemini-3.8-flash. A refusal that names the levels the model takes (effortLevelsNamed, Command Code's for Qoder's none) 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's minimal) 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's extra_content.google.thought, and such a chunk is read as thinking.
  • A Claude that thinks only adaptively (adaptiveOnly in anthropic.go: Opus, Sonnet and Haiku from 4.6 on, Fable and Mythos 5 and 5.1, read by claudeVersion however 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 as thinking: {type: "adaptive", display: "summarized"} with the effort in output_config.effort, so the client sees the reasoning Opus 4.7 and later otherwise leave out (display omitted by default), and a relay that refuses display is asked again without it (refuseShapes), as is one that refuses a turn's effort on a {role: "system"} message (withoutTurnEffort: a relay's "messages.1.output_config: Extra inputs are not permitted", or OpenRouter's "Mid-conversation reasoning effort (configuration_update) is not supported on " on DeepSeek and GLM, #3696; TestOpenRouterTurnEffortLeftOut), as is one that refuses auto mode's safeguards (Copilot's Messages API: 400 "safeguards: Extra inputs are not permitted" on claude-opus-5.5, #1756; shapeSafeguards, TestSafeguardsRefusedLeftOut), and neither is sent it again while magpie runs; a client's thinking: {type: "enabled", budget_tokens} is turned into the same in forwardOnce (adaptiveThinking), the budget as its nearest effort, above high as max, and display: "summarized" unless the client named its own display, so the thinking that enabled shows stays shown (the refused shapes are taken out after it, and refuseShapes reads the display as it is sent); and Pi, dsh and omp are written to ask it adaptively (AdaptiveThinking: forceAdaptiveThinking, omp's anthropic-adaptive; #1470). A client's xhigh goes as xhigh, except to Opus and Sonnet 4.6, which have no xhigh and are asked max (noXhigh, #1471).
  • A vendor's model that takes its level in output_config.effort beside thinking on (effortInOutputConfig in anthropic.go: Z.ai's GLM-5.2 and GLM-5.3, MiniMax's MiniMax-M3.1-Flash and its -Preview, and any gpt-<digit> id on a Messages endpoint, such as a relay's: it showed every request at medium on the relay's console, zxz8009195489 on Discord, TestGPTMessagesEffortInOutputConfig) is sent the effort there next to the budget: built from a Chat or Responses client's effort (buildAnthropic, when it sends a budget), or added to an Anthropic client's request from its budget's nearest level, fitted to the model's levels (withOutputEffort, in passthrough). A budget alone left GLM at its default, and under an 8192 cap gave MiniMax's medium to max one budget, 7168 (shin4 on plugins#316). A client that asks such a model adaptively, with its level in output_config.effort, has both kept (Z.ai takes adaptive with the level, tried live on GLM-5.3); dsh is written to ask them so (GLM-5.2 and GLM-5.3: AdaptiveWithEffort, forceAdaptiveThinking in dshKindConfig; MiniMax not yet, #3496), since pi-ai's budget path clamps Max to high's 16384 and its Max reached GLM-5.3 as high (01huadalang on Discord, 10-24). Every other model, Claude and MiniMax-M3 included, gets the budget alone. TestGLMEffortInOutputConfig, TestMiniMaxPluginGetsTheNativeEffort, TestNativeEffortLeavesOthersAlone, TestAdaptiveOnOutputEffortModelAsksItsLevel, TestDshMaxReachesOutputEffortModels.
  • A request to an Anthropic endpoint that turns thinking off is sent as the model takes it (thinkingOffAsTaken, in forwardOnce, 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 refuses thinking: {type: "disabled"} and is sent {type: "between_tools"} alone, at effort high at most. Opus 5.5, Fable 5 and Mythos 5 refuse it at every effort and are sent no thinking, at effort low unless one was asked, with classifierRoom added to a reply limit below it, as Claude Code does. Opus 5 and Haiku 5.5 take it only up to high, so xhigh and max are asked as high. between_tools sent to any other Claude goes as disabled, 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 for between_tools (asksBetweenTools), is asked again with it, once; a refusal of disabled at any effort (thinkingOffRefused) is asked again with thinking left to the model, as alwaysThinks is. So is a relay that reads disabled as reasoning effort none and turns that level away naming the ones it takes (Sub2API's gpt-6.1-sol, "does not support reasoning effort "none"; use low, medium, high, xhigh or max", #1465); refusesThinkingOff is the one list of these refusals for both routes. A relayed request refused so marks the model (markUnfit(offRefused)), and its later requests go with thinking left to the model at once until magpie restarts, as auto mode's classifier asks on every action.
  • A Chat or Responses client's reasoning turned off (none, ThinkOff), translated to an Anthropic endpoint (buildAnthropic), goes as thinking: {type: "disabled"}; it went as thinking at a 4096-token budget before (#1636). A model that refuses it (refusesThinkingOff: alwaysThinks, mandatoryReasoning, thinkingOffRefused, or none turned away naming the levels taken) is asked again at its least (thinkingBackOn), and markUnfit(offRefused) sends it so at once until magpie restarts. A translated request's level can differ from the one asked: none and minimal go as low where 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, wireEffort in wire_effort.go). Gemini's builders say theirs their own way and are logged as asked.
  • An upstream that takes a model only with thinking enabled answers a request sent none, or sent it off (thinkingOffUnlessAsked for a vendor's model), with a 400 saying thinking.type must be "enabled" (thinkingNeededRefusal, read off the reply at any depth of a relay's wrapping, never off the provider: cybercaius's own 天翼云 relay turned Claude Desktop's connection check away so, v0.1.1862). It is asked again once thinking at Anthropic's least budget, 1024, with max_tokens raised past it by what was asked and temperature, top_p and top_k left out (withThinkingEnabled), and markUnfit(thinkingNeeded) keeps the model so until magpie restarts, by magpie's name and the vendor's (markThinkingNeeded): relayed, the body is given thinking at once (passthrough); translated, a Messages body once built, and a Chat or Responses one at its lowest effort (thinkingBackOn). forwardOnce doesn't make such a model's enabled adaptive (adaptiveThinking), enabled being the type it said it takes. A non-streaming client's translated request whose refusal came inside a 200 stream is asked again the same way (translate); a streaming client's is not (thinking_needed.go).
  • A model the user ticked no levels of (ModelReasonless in settings, SetModelReasonless; the provider editor's Model settings, or magpie model efforts <provider/model> off) is sent no reasoning field on any route, whatever the agent asks: the candidate loop strips the body with withoutAnyReasoning (quiet.go: Chat's reasoning_effort, reasoning, thinking, enable_thinking and include's reasoning.encrypted_content, Responses' reasoning, Anthropic's thinking of any type and output_config.effort, Gemini's thinkingConfig), the Anthropic relay doesn't add thinking:{type:disabled} for it, and forwardTranslated clears Effort, ThinkOff and Thinking for its other callers. It offers no levels (Efforts, entryFor), is Quiet, and as a routing-group member doesn't take the group's levels away. The learned refusals above cover only reasoning off and Gemini levels; a vendor that answers a plain reasoning_effort with 422 (yuexian7 on Discord) is not learned, so this is the user's switch. TestReasonlessModelSentNoReasoning, TestReasonlessAnthropicRelay, TestGroupReasonlessMemberKeepsLevels, model-reasonless.test.cjs.
  • Levels the user kept of a model's own (ModelEfforts, SetModelEfforts; magpie model efforts, the editor's Model settings, magpie model spec --reasoning) only narrow what is offered (#92): provider.Efforts returns the vendor's list's or models.dev's levels, and fitEffort fits a request to those, so an agent asking xhigh of a model kept to low–high still asks xhigh. A model no list knows levels of can be given them (magpie model spec --reasoning, Dani Ariyanto on Discord); those are then its levels, a request is fitted to them, and it counts as reasoning (entryFor). AutoVision honours the user's ModelImages over the model's own (seesAt). TestModelSpecReachesTheGateway, TestNarrowedVendorLevelsAskAsBefore, TestAutoVisionTakesTheUsersVision.
  • A request to an Anthropic endpoint with temperature, top_p or top_k reaches a model that refuses them without them (samplingAsTaken, beside thinkingOffAsTaken in forwardOnce): 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 "temperature is 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. A model whose own list refuses them (RejectsTemperature, from the catalog's temperature, or a plugin's temperature: false carried by the plugin host, #2492) is asked without temperature and top_p whatever the client speaks: a translation leaves them out (build), and a Chat or Responses request relayed as it came does too (passthrough).
  • Claude Code's auto mode asks the API to review each action (automode.go, Anthropic's auto-mode-classifier-billing): the dangerous-tool-use-… beta, a safeguards field, and safeguard_results in the reply (a stream's in its message_delta). Only Anthropic runs that classifier, so they reach only a route it answers on (AutoModeReviewed): the Claude subscription (the bridge hands them to Claude Code's own binary), a Claude model under any vendor's spelling on a provider with a key (Anthropic's API, a relay, Bedrock, Vertex), and anything on api.anthropic.com. Another subscription's or a plugin's Claude model (Copilot, Kiro, Cursor…) is that vendor's service and isn't reviewed by its name: Copilot turns safeguards away (#1756), the others translate the request, so neither the beta nor safeguards is sent there (TestAutoModeReviewedRoutes, TestAutoModeReviewLeftOffOtherSubscriptions). There the beta, safeguards and the results pass as sent, a whole reply's results moved into a stream's message_delta (anthropicWholeEvents), tool-use ids unchanged. A relayed reply carrying safeguard_results has no call read out of its text (anthropicTextCalls): a call made there would have an id Anthropic never judged, which Claude Code can't match to a verdict, so the text goes as text (xybio on Discord, TestAutoModeReviewedReplyMakesNoCall). To any other model they are taken off (serverReview; a translation never carries them), and magpie never answers a result on Anthropic's behalf. Claude Code then classifies locally and names the gateway in a notice, or, where Anthropic's per-account flag has turned its local classifier off behind a gateway (tengu_bright_dragonfly, read in 2.1.312 to 2.1.316), has no check at all and asks for approval of each action the check would judge ("your requests go through 127.0.0.1:3425, which doesn't pass it through", chenxiang0010 on Discord): only a route above can make auto mode work there, and none of magpie's other routes can; the wiring turns the review off in its settings unless every model it can reach through magpie surely gets the results back (AutoModeAnswered: the subscription or api.anthropic.com, not a relay, which may drop them; claudeReviewEnv, agent wiring, JoyYoung2Lucky on X), which is the page's remedy for a gateway that can't run the checks (1EFLOPS on X: Codex's model behind magpie). Reviewed there means AutoModeReviewable: a reviewed model on a route that reaches the Messages API, since a Claude model asked on a relay's Chat or Responses URL is translated and never carries the review (nexnull on Discord, TestAutoModeReviewableAsksOnMessages).
  • Locally, Claude Code's classifier is a request of its own on the session's model: no tools, a system prompt asking for <block>yes</block> or <block>no</block>, the transcript in <transcript>, a small max_tokens, and no stream; Claude Code 2.1.310 waits 60 seconds an attempt for it. To a model that isn't Claude it goes with classifierRoom (2048) added to a limit below it and asked to reason least (fitAutoModeClassifier): none, or the lowest of the model's known levels. A model whose levels magpie doesn't know (a relay's own name, gpt6.1-sol) is asked for none too, as magpie's own ask (Request.OwnEffort): left to the vendor, a reasoning model reasoned at its default past the 60 seconds and every classifier request ended 499 (CyberCaius on Discord). Its 400 to that effort (ownEffortRefused) is asked again at low when it named the level, and without the effort when it named the field ("Unrecognized request argument supplied: reasoning_effort"), remembered in unfit until magpie restarts (TestAutoModeClassifierReasonsLeastOnAnUnknownModel, TestAutoModeClassifierEffortRefusedGoesWithout).
  • Claude Code's billing line (x-anthropic-billing-header: cc_version=…; cc_entrypoint=…; cch=…;, its own first system block, cch changing every turn) goes on only to a Claude model asked on Anthropic's Messages API (keepsBillingLine in billing_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). 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, which antigravityTurnsAway reads (#666). Once Antigravity has turned such a request away, for agForeseeing (6 hours) after, a candidate loop with someone left after an Antigravity account skips it for a request that carries the line, without asking it (antigravityForeseen, #2156: each Claude Desktop turn waited about a second on the same refusal before the next member). The skip goes in Fallback with the hint, nothing rests, and the agent is told the refusal if nobody after it answers but with a quota. The last one left is still asked, and an old refusal foresees nothing, so a block Google lifts is noticed (TestAntigravityTurnedAwayIsForeseen). Codex's own identity line for its GPT-5 models ("You are Codex, an agent based on GPT-5", "…a coding agent based on GPT-5", any case) is turned away the same way (antigravityTurnsCodexAway): Codex sends its model's prompt as the thread's first developer message, which goes in as the system instruction, and a thread begun on a GPT model keeps it after /model, resume -m or a fork as an agent's thread, so such a thread on an Antigravity model 429'd until Codex's retry limit while dsh on the same account answered (Jodiezzzzzz on X, 10-27). It gets its own hint (antigravityCodexHint: start a new chat on the model, which is sent magpie's own Codex prompt "You are Codex, based on GPT-5.", which Antigravity answers), chosen by antigravityHint. Codex sends its web_search tool every turn, so an Antigravity model's Codex turn goes through magpie's own search (searchReply); its rounds are wrapped in antigravityRound, which tells the 429 (or the reply's error event) the same way and marks the attempt, where before the search path returned the bare 429 that Codex retried to its limit.
  • A request translated to a Chat or Responses upstream that carries no prompt_cache_key of the client's (every Anthropic client's) gets one for its conversation when the provider is OpenAI's API with a key or one the user added by its address (ownCacheKey, cacheKeyOf in gateway.go): a hash, in a UUID's shape, of the session the client names, else of its first user message, so every turn of it has the same key and nothing in it names the client or magpie. A relay can turn a request away without one ("prompt_cache_key is required", CyberCaius's AnyRouter). A vendor's preset, a signed-in account, a plugin, Bedrock and Vertex get none, nor does a provider whose extraBody names prompt_cache_key (the user's value is sent). An upstream whose 400 names the field is asked again without it and not sent it again; another 400 is not asked again for it, so an unrelated refusal is tried as often as before.
  • Claude Desktop's check that a gateway model answers ({"max_tokens":1,"messages":[{"role":"user","content":"."}]}, sent as it starts and by its settings' Test connection on the shortest id it is listed with haiku in it, else sonnet, else opus, else the first model listed; desktopProbe in desktop.go) goes to the model the user chose in one of Desktop's own model menus that magpie still serves (desktopChosen: __model_selector_state in Claude-3p's local-agent-mode-sessions/<account>/<org>/cowork_account_settings.json, in the order Code, Cowork, Chat; cybercaius's DeepSeek in the Code tab, v0.1.2033), unless a session's turn was sent after that file was last written: then the model that turn was for (desktopPicked), while magpie serves it, the newer of the two being what the user is on now (before, the last session's model came first whenever any menu still held it, so the Code tab switched off DeepSeek with Cowork left on it kept the check on DeepSeek, cybercaius on Discord, v0.1.2212), else to Desktop's default model, the first one listed to it (desktopDefault; Desktop's own settings call the first listed model the default), never to the haiku it names, which is another provider's quota, nor, with no menu chosen, to the model the last session ran on (desktopPicked), which can be days old: v0.1.1821 sent it there, a relay's GPT model CyberCaius had left for his routing group, and the relay turned it away (Discord, v0.1.1838). It is asked for 16 tokens upstream (desktopProbeTokens): OpenAI's models refuse fewer, and a relay in front of one (AnyRouter's "bad response status code 400") passes on no floor for tokenFloor to ask again at. A relay that needs prompt_cache_key gets one (above). It is recorded with kind connection_check (KindDesktopCheck), which the Routing page tags "Connection check" with why its model is the id Desktop named and not the one chosen in the conversation: a list with no Claude-named id made the row read "requested deepseek-flash" while the menu's gpt-6.1-sol answered (cybercaius on Discord, v0.1.2212). TestClaudeDesktopProbeToDefaultModel, TestClaudeDesktopProbeToChosenModel. TestClaudeDesktopProbeAsksNoClassifier checks the kind.
  • Claude Desktop's /v1/models tags a model with anthropic_family_tier only when the user picked it for that tier (DesktopTiers, the Agents page's opus, sonnet, haiku and fable). Before, a Claude model magpie served was tagged with its own tier unpicked, so Desktop's Code tab told Claude Code to run its haiku calls (its small, fast model) on whichever provider served a claude-haiku-…: a chat on AgentRouter's gpt-6.1-sol sent them to Leee's claude-haiku-5-5 (cybercaius on Discord). Untagged, Claude Code asks for its own id of the tier. A background call (no tools) or a subagent's turn asking for a Claude model by Claude's own id that is no catalog id (claudeOwnID) stays on the chat's provider (desktopPicked), even when another provider serves a model of that name: servedBeside gives that provider's model of that name, else its newest model of the tier, beside the chat's model first, else the call goes to the chat's model. The provider's Claude models stand in only when the chat itself is on one of them: a chat on Leee's DeepSeek had Claude Code's sonnet calls sent to Leee's claude-sonnet-5-5, which its key may not use (403, CyberCaius on Discord), so Claude Code's own calls in a chat on another vendor's model go to the chat's model, and a tier the user picked takes Claude Code's own id of it even where a provider lists a model by that name (TestClaudeDesktopNonClaudeChatKeepsTierCalls). A lead's turn and an id the user picked for a tier (a catalog id) go as asked. TestClaudeDesktopBackgroundStaysOnChatProvider.
  • While a model is picked for one of Claude Desktop's tiers, magpie's Desktop profile also lists Desktop's models in inferenceModels (DesktopInferenceModels in desktop_list.go), so a pick that isn't a Claude model runs in the Code tab with the prompt of its tier's newest Claude model (behavesAs: claude-opus-5-5, claude-sonnet-5-5, claude-haiku-5-5, Desktop's catalog v3739; claude-fable-5-2, Claude Code 2.1.321's newest Fable, which Desktop's catalog v4371 doesn't list yet), not Claude Code's generic one (moer2831 on Discord). Desktop 4.29 and later hand Claude Code behavesAs only from that list (z3t in its app.asar, 4.4212: modelPicker.options with each entry's behavesAs); the gateway's behaves_as row field feeds Desktop's own effort profile only. A non-empty list replaces /v1/models in Desktop's menus (pzn: a discovered row gives only its name and description, by id), so the list is every row /v1/models gives Desktop, by its id and in its order, each with what Desktop would have read off the row: supports1m for a window of 1M and up, prefer1m (and the row's display_name as labelOverride, where Desktop names the row by display_name) for a model listed by its [1m] id, and a pick's anthropicFamilyTier with isFamilyDefault. Desktop keys the list by name and reads one tier off an entry (FPn in its app.asar, 4.23118: the entry tagged with a tier names its ANTHROPIC_DEFAULT_<TIER>_MODEL), so a model picked for two tiers is tagged with the first (desktopTierOf) and listed once more, after the rows, for each later tier (desktopSharedTiers), by its id's form under a number of its own (desktopTierAlias: magpie-.anthropic., mythos-magpie- or anthropic/magpie-), which aliased reads back to the model, so the gateway serves it as the pick (desktopTierAsked). Before, the later tier had no model: copilot/claude-sonnet-5.5 picked for sonnet and haiku gave Claude Code an empty ANTHROPIC_DEFAULT_HAIKU_MODEL, and its small tasks, WebFetch's page summaries among them, ran on the session's model. The rows stay first, so a new session still starts on the first row. A Claude model picked runs as itself where Claude Code knows it by the id it is listed by; a routing group led by one is listed by its mythos-magpie- and runs as the group's model, as one listed by anthropic/magpie- does (desktopRunsAs; TestDesktopTierSharedPick, TestDesktopGroupPickRunsAsItsModel). Nothing picked (or a pick of a model no longer listed): no list, and Desktop finds the models as before. Picks that can't be read are unknown, and what is written stays. Older builds take the entries' names and drop the rest (2.7032's entry is a zod object, which strips unknown keys). Desktop reads its profile only as it starts, so the tiers' menu says to restart it, and the Agents row's Restart shows (AppBehind reads the profile). TestDesktopInferenceModels.
  • Antigravity answers a system instruction holding one of a few lines with a 429 "Resource has been exhausted" whatever quota is left, on every model (agTurnedAway in codeassist.go): Claude Code's billing line, the Claude Agent SDK's identity line, Codex's identity lines for its GPT-5 models (which a Codex thread begun on a GPT model keeps after a switch), and Hermes Agent's earlier default persona. An Antigravity account's system instruction goes with zero-width spaces after the first and second character of every word of each such line (antigravityCloak, in codeAssistBody; one after the first letter only was turned away again on 11-11 for Claude Code's two lines, with Claude Code 2.1.316's prompt on a real account), which Google lets through and the model reads the same; every other provider, Gemini CLI's sign-in on the same envelope included, is sent the prompt as written. magpie provider set antigravity prompt=as-written (Provider.PromptAsWritten) turns it off. The refusal is still told against the system prompt as the agent wrote it (antigravityTurnedAway): a 400 with the hint for that prompt, the account not rested, and a group skipping Antigravity for that prompt for 6 hours after a refusal (antigravityForeseen).
  • Claude Code's advisor (/advisor, --advisor) is Anthropic's server tool advisor_20260301, its model named as Claude Code names its own: on magpie, by magpie's id (the tier an alias like opus is on), which no vendor knows, so the request was turned away whole (JackChou on Discord). Relayed on Messages (passthrough), the advisor's model goes as the upstream's own name for it when it is the same provider's Claude model, or a Claude id naming no provider (advisorTools in advisor.go); one it can't run there (another provider's, a group, not Claude's) is left out, as is every advisor when the request's own model isn't a Claude model (a vendor's Messages API knows no such tool), and the turn is answered without one. A translation drops it with every other server tool. Claude Code (2.1.300) also puts the advisor in the conversation: a {role: "system"} message whose text ends in its instructions ("# Advisor Tool … call advisor BEFORE substantive work") and a tool_addition naming it. Where the advisor is left out, that tool_addition goes too (and a message it leaves empty), and the instructions become Claude Code's own "The advisor tool is no longer available; disregard the earlier advisor instructions." (withoutAdvisor on Messages, advisorGoneIn in parseAnthropic for a translation): left there, the model called advisor() as one of the agent's tools and Claude Code answered "No such tool available: advisor" (JackChou on Discord). The Claude subscription's run declares only magpie's tools, so it never has one. TestAdvisorModelAsTheUpstreamNamesIt, TestAdvisorLeftOutOnTranslation.
  • Kiro is told where to cache the prompt (plugins#110: a Kiro subscription read 0 from its cache). Its API takes Bedrock's cachePoint: {"type":"default"} on a userInputMessage, an assistantResponseMessage or as a tool entry. The built-in (buildKiro in kiro.go) marks the first message when there is a system prompt, which it folds into that message, and the current message, as buildAnthropic marks Anthropic's. A moved Kiro's plugin (opencode-kiro-auth 0.1.10, the mover's min) turns each cache_control in the Anthropic body it is handed into one, at most 4, the last kept.
  • The cache marks buildAnthropic adds for a Responses client (Codex) to a Claude model last an hour (addedMark, Request.hourMarks; 7eleven on Discord): Codex's turns are often more than five minutes apart, and Codex's own vendor keeps a thread cached an hour (chatGPTCold). A 1h write costs 2x the input price where Anthropic's default 5m costs 1.25x and a read 0.1x or less, so one turn read after a 5 to 60 minute pause, which a 5m mark would have written again, pays for the dearer writes of dozens of turns in quick succession. Every mark it adds has the same ttl, since Anthropic refuses a 1h mark after a 5m one. The client's prompt_cache_retention: "in_memory" keeps them at 5m. A Chat client's marks, a model that isn't Claude's, and marks a client placed itself (an Anthropic client's, relayed as sent) are unchanged. An upstream that answers 400 naming cache_control and ttl (a relay that knows no ttl) is asked again at 5m and remembered in unfit (hourMarksRefused) until magpie restarts. A Claude subscription is served by Claude Code, which asks 1h unless the user picked 5m (Claude subscription bridge). TestResponsesToClaudeMarksLastAnHour, TestHourMarksRefused.
  • 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, or compactLastText when 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's functionResponse with 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 tool's strict that an upstream turns away (toolStrictRefusal in strict_refused.go: "Unsupported Chat Completions API field: tools[0].function.strict", OpenAI-style unknown_parameter, "Extra inputs are not permitted" and pydantic's extra_forbidden on it) is asked once more without it, in Chat's tools[].function and Responses' tools[] alike, and marked for that provider and API (toolStrictRefused): its next requests go without it at once. OpenCode 2 sends "strict": false on every tool through @ai-sdk/openai-compatible, and a custom provider that refused it ended the session (#1980). An upstream that hasn't refused it still gets it, as the ChatGPT backend needs it (#383). TestToolStrictLeftOutWhereRefused (real OpenCode 2.0.25 requests), TestToolStrictRefusalWordings.
  • A history call to a tool the request doesn't declare, which an agent that loads its tools on demand sends (pi's and T3 Code's tool_search: the tools a search found are called in the history but not declared in the next request's tools, and pi sends "tools": [] with no tools left; Gearclickist on Discord), goes as sent where it is taken: OpenAI's Chat and Responses, the ChatGPT backend and Gemini take it, and Anthropic takes a call to a tool it isn't given (undeclared_tools.go). Anthropic refuses calls with no tools at all ("Requests which include tool_use or tool_result blocks must define tools"), so anthropicBody declares a stub for each tool the history called when the request has none (description "Called earlier in this conversation; not available now.", any object as its input) with tool_choice none, as the Kiro plugin declares its history's tools for Kiro. An upstream that turns the request away naming such a tool as not found, unknown or not defined, or that says tools must be defined beside the calls (refusesHistoryTools: a relay in front of Kiro or Bedrock, a vendor checking each name), is asked once more with a stub declared for each tool the history called and tools lacks (withHistoryTools, Chat, Responses and Messages bodies, relayed or translated), tool_choice none only where the client offered no tools, and marked for that provider and API (historyToolsRefused): its next requests carry the stubs at once. A Responses call under a namespace is the namespace's, and a request whose calls are all declared goes as it was. TestUndeclaredHistoryToolRefusedThenStubbed, TestToollessHistoryToAnthropicDeclaresStubs, TestToollessHistoryRefusedOnChat, TestUndeclaredHistoryToolTakenAsSent, TestRefusesHistoryToolsMatch.
  • A Codex custom tool (exec, apply_patch) that a Responses upstream turns away (customToolRefusal in custom_tool.go: DeepSeek's 400 "Unsupported custom tool: 'exec'. Only 'apply_patch' is supported.", #2656; xAI's 422 "tools[N].type: unknown variant custom, expected one of …", Rust's own wording of the type, #3392) ends the relay: passthrough marks the model (customToolRefused) and returns not done, and attempt translates the request on the same API (ownAPI), where each custom tool is offered as a function taking its input and a call comes back as the custom_tool_call Codex runs, its name kept. A marked model's next requests with a custom tool are translated at once; one without stays relayed, and an upstream that never refused them still gets them as sent. A compaction (keepsCompaction) isn't translated, and gets the refusal. Where the refusal reaches a group untranslated it is a shape refusal (shapeRefused): the next member is asked. TestCustomToolTranslatedWhereRefused, TestCustomToolRefusalInGroup, TestCustomToolRefusalWordings.
  • xAI's own API (api.x.ai, wherever a Grok model is served — the Grok subscription's plugin shapes its own bodies, provider's grokShaped) takes none of three things a client's wire puts in wrong (xaiBody in xai_body.go, shaped in passthrough and on the built body in forwardTranslated alike, for a custom-tool refusal puts a Codex request on the translated path from the next turn on; there is nothing to learn, xAI takes none of them at all, #3392's follow-up): Codex hands a sealed reasoning item back with "content": null beside its encrypted_content, which the backend answers "Could not decode the compaction blob. Ensure it is unmodified from the compact response." (the first turn goes through, every one after it 400s) — the null goes, the item otherwise as it came; and Claude Code, its messages carrying a system turn mid-conversation since Anthropic made them GA, sends one that xAI's Messages answers "Invalid request content: Invalid message role." — each folds into the top-level system, its text and blocks (a cache_control kept) as they came, the only place that API takes the role; and a tool's schema can say "required": null where none are (Claude Code's own tools, an MCP server's among them — Anthropic's API takes the null), which xAI's validation of each schema answers "Invalid request content: Schema validation failed: [standard_violation] /required: null is not of type "array"" (the claude calls 400ed once the system turns folded) — the key goes from every shape a body leaves magpie in, input_schema, parameters and function's, at the schema's root or nested, a real array of names kept as it came. TestXAITakesCodexsSealedReasoningBack, TestXAILearnsCustomToolsThenTakesTheReplay, TestXAIFoldsClaudesSystemTurn, TestXAITakesANullRequiredToolSchema, TestXaiBodyDropsNullRequiredInEveryShape.
  • A tool call's arguments reach the client as the vendor writes them, translated too (echo_ts on Discord: Codex on Copilot about 10x slower, an apply_patch shown only once whole). The Responses decoder hands each function_call_arguments.delta and custom_tool_call_input.delta on as a KToolArgs delta (argsDelta), holding back only the one that would make the JSON whole until .done, which endCall checks against the final arguments; the Responses encoder streams a custom tool's input as custom_tool_call_input.delta (customStream in custom_tool.go) before its .done. A Copilot account's Responses request is relayed with a web_search tool in it (searchesItself; checked on a real account 2026-10-17), and Copilot is never picked to search for another provider's model (searchRank). It is translated instead when a tool marks a parameter "encrypted": true (asksSealing, MultiAgentV2's spawn_agent): Copilot seals such an argument and can't read its own seal on the subagent's turn. TestCallArgsStreamWhenTranslated, TestCustomInputStreams, TestResponsesCallArgsStream, TestCopilotRelayedUnlessAskedToSeal, TestCopilotUltraSubagentWithWebSearch.
  • A relayed Responses stream gives each output item the one id its response.output_item.added gave it, in every event after that carries an item_id or an item, and in the output of response.completed, response.incomplete or response.failed (idTidy in itemids.go, applied in passthrough before phaseTidy). GitHub Copilot's /responses gives an item another id in every event (checked 2026-10-19 on a real account, gpt-5.5 with web_search), and Codex starts an item by the added's id and ends one by the done's, so a commentary message was shown twice and a web search never ended (echo_ts on Discord, TestCopilotItemKeepsItsID). An upstream whose ids agree goes through byte for byte (TestItemIDsThatAgreeGoAsTheyCame); a translated reply's ids are magpie's own.
  • A relayed Responses stream to a client that isn't Codex carries only the OpenAI Responses event enum (responsesEnumTidy in responses_enum.go, last in passthrough's chain, after sniff and codexLimitsTap have read the upstream bytes). The ChatGPT backend speaks part of the Codex protocol: codex.rate_limits, codex.response.metadata, response.metadata and a keepalive event, and a typed client (Grok Build through async-openai's ResponseStreamEvent) read one as an unknown variant and lost the whole turn (#4482, crayonlu). Every event whose event: name, or data type where it names none, is outside the enum goes; a keepalive goes on as an SSE comment, so a quiet upstream still keeps the client's idle timer from running out. Codex itself, by User-Agent/originator or a key of its own (fromCodex, agentOf, as codex_own_v1.go tells it), gets every event as it came. The same applies to a plugin's Responses reply, which takes the same path. TestResponsesEventsOutsideTheEnumStayWithCodex, TestResponsesEnumAllowed.
  • 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's capabilities.max_output_tokens (cursorLocalModel), Muse Code's limit.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.Decorate and Provider.replyLimit fill an output only where the vendor gives none). An unknown window or output is published as it is. The catalog keeps the unclamped Entry.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). Outside a group, only a Max output the user set for the model (Entry.OutputSet) lowers a request (userOutput): Claude Code asks a claude-* model for its own full limit (128000 on Opus 5.5) and is told no figure of magpie's for it (claudeOutput), and a key whose quota is held per request as max_tokens times the price turned every turn away (YaCo on Discord, TestUserMaxOutputLowersAPlainProvidersRequest). A vendor's or models.dev's figure doesn't lower it, since it may be stale.
  • /v1/models and /v1/models/{id} give each model magpie knows a price of its pricing in OpenRouter's shape, USD a token as decimal strings: prompt and completion always (a price set at 0 included), input_cache_read and input_cache_write only when that part has a price (catalog.OpenRouterPricing, catalog.PerToken in openrouter.go, which an agent plugin's connect is given too; cleary5779 on Discord, an agent showing what a call costs). The price is the one the Usage page counts the model at (provider.EntryPricer, as EntryPriceIn: the user's own, else the provider's list price or its maker's at its price rate; a subscription's model at its list price; a group only when every member costs the same), the base price only (no Tiers, no 1-hour write). A model no price is known for has no pricing key, never a 0. It is told to the callers magpie_price is (local or sharedWith), whether they ask or not. The list reads the settings, groups and providers once (EntryPricer), and catalog.PricedBy and AtEndpoint look a model up in indexes built once a catalog load (priceIndexOf, endpoints), not by walking every models.dev model a look-up: a 755-model list went from about 38ms to 18ms with pricing on, against about 10ms without, at load 65 (TestModelsListPricing, TestPerToken). Claude Desktop's, Claude Science's, Muse Code's, Codex's and Ollama's lists, the decision, image and video models carry no pricing: their clients read a shape of their own, and an image's price isn't a token's.
  • /v1/models and /v1/models/{id} say each chat model takes tools, a routing group included (toolsTold): models.dev's tool_call: true, beside its reasoning, and OpenRouter's supported_parameters (tools, tool_choice, and reasoning when it thinks), which Kilo's and Cline's lists are read by. A client that judges a model by what its list says found nothing for a group, whose id is the user's own name (psikent on Discord: an SSH client), and gave it no tools. magpie has no model that takes none (a call written as text is read back as one, textcalls.go), so every member of a group takes them and the group says so. No capabilities key is added: Cursor Private Inference reads it as an object (cursorLocalModel), Ollama and LM Studio as arrays of their own words, and no reader of an OpenAI-shaped list agrees on one (TestGroupListedTakesTools). A group's window and output stay its largest member's, its images any member's (#712, #756): the gateway sends a longer conversation, a longer reply or an image only to the members that hold it (roomy, withRoom, withMaxOutput), and the editor's Context hint names the member a longer conversation skips when the windows differ (windy on Discord).
  • A request that names no reply limit, translated to Anthropic's Messages API, which needs max_tokens (forwardTranslated), is sent the model's published limit (askedOutput in maxoutput.go): the user's Max output, else the vendor's list or models.dev, within the window. anthropicBody's defaultMaxTokens (16384) is left only for a model whose limit isn't known. Every Codex turn on a Claude went at 16384 before, and a long thinking and tool turn ran out of it: stop_reason: max_tokens reaches a Responses client as incomplete_details.reason: "max_output_tokens" (#1792, tensornull). A limit the client names goes as it is. The thinking budget fits under the filled limit as under one the client named (TestAnthropicMaxTokensIsTheModels).
  • A Chat Completions request's reply length goes under the name the vendor reads (chatTokenField, retryTokenField in token_field.go, on every request through forwardOnce): max_completion_tokens on OpenAI's own API (provider.OpenAIHost), whose newer models answer max_tokens with 400 "Use 'max_completion_tokens' instead" (GoxxKintBlade on X), and on Azure and Bedrock (asCompletionTokens); max_tokens on DeepSeek (deepseekTokenField); as the client sent it elsewhere, since Zhipu and most relays read max_tokens alone. A 400 whose words name the other field as the one to use (provider.TokenFieldWanted; a limit on the value is not one) is asked once more with that name, the key renamed in place (provider.WithTokenField), and the provider remembered in unfit, so its next request goes so at once (TestChatTokenFieldRetriedWhenNamed). A model's test does the same (tinyBody, probe; TestProbeRetriesTokenFieldNamed).
  • A restart to update on a Mac or Linux hands the listening socket to the new version (GUI shell, handover.go). Inherit gives the new process's ListenAndServe a socket to serve when the address is the same (sameAddr), and calls back once it serves; HandOff has the old one stop accepting at once (stopAccepting: its copy of the socket goes, the new one's keeps it open) and its shutdown wait up to handedOffDrain (15 minutes) for its requests in flight instead of shortDrain (2s). Before that shutdown, each connection it took sends its first request (unreadConns, unreadWait 5s at most): http.Server.Shutdown closes one whose request it reads after it began unanswered (#3568). Requests per minute, concurrency and sticky routing's in-memory state are each process's own: sticky routing is flushed to disk before the socket goes (FlushSticks), but while the old one drains, a provider's limits can be passed by what each has in flight. TestHandedOverGatewayFinishesItsStream, TestHandedOffGatewayTakesNoNewConnection, TestHandedOffGatewayAnswersAConnectionItTook, TestHandedOffGatewayAnswersAConnectionNotedLate, TestInheritedForAnotherAddressIsLetGo, TestToolCallOfTheMagpieBeforeGoesToIt in handover_test.go.
  • An agent's turn (Chat, Responses, Messages, Gemini's generateContent and Codex's backend /responses) that magpie holds before any route is begun for it is watched in counted (unrouted.go; heyusaku6 on X: Codex thought for over ten minutes with the Routing page empty, until Codex and magpie were restarted; what held it wasn't found). After unroutedShow (15s) a route of provider magpie shows it on the Routing page as routing, and gives way to the request's own route once one is begun (noteRoute, trace.drop). While the request is masked its phase is redact (phaseRedact, noteRedacting in redact_phase.go, around every redactedHits and maskTextHits), on /v1/magpie/concurrency and on the route that shows it (Route.Phase), so the row says masking, not routing (fremontdango on Discord: a Claude Code request sat as "routing…" while it was masked). What masking took is kept as a part of magpie's own time, never more than it (maskingMs): Route.Masking and the usage record's masking_ms, shown as Masking in the Routing page's time and the Usage page's detail. It holds no text. TestMaskingIsAPhaseWithItsTime, TestNoMaskingNoMaskingTime in redact_phase_test.go, routing-masking.test.cjs. It is answered 504 after unroutedUnknown (30s) held in no wait magpie knows of, or after unroutedMost (2m) excluding masking and earned upload time (sharwowwow on X: two minutes of spinning before a 504). An upload earns one second per 32 KiB actually read from the wire, capped at the time spent in body reads and eight additional minutes (unmaskedLocked, unroutedUploadRate, unroutedUploadGrace). Thus a non-masking hold ends within ten minutes even for compressed input with negligible decoded output. Wire bytes are clamped before duration arithmetic so large encoded streams cannot overflow the allowance. A large conversation on a slow link can finish past two minutes (#4775); a trickle still exhausts the base budget. Declared length and decoded bytes earn nothing, and a fast upload cannot bank time for a later internal hold. The 60s wire-idle deadline and decoded size cap (512 MiB, more on Codex's own path: codexBodyLimit) still apply (request_bounds.go). An upload that exhausts its allowance is answered 408 with its received byte count and advice to check the link or proxy, compact the conversation or reduce inline images. An internal hold remains a 504; waiting for body room is internal, including before the first read (#4511). Between two reads a body is still arriving while less has come than its Content-Length says or, chunked, until a read has met its end (bodyArriving, bodyEnded): a decoder spends its time between reads too, and a chunked gzip body ended there was answered 504 as magpie's own hold (TestUnroutedChunkedBodyReadWholeHeld504 holds the other side). While an upload earns as fast as it is read, its charged time stands still, so checkMost looks again no sooner than unroutedRecheck (1s) rather than every sliver left (TestUnroutedMostRecheckIsNoSpin). TestUnroutedProgressingUploadOutlastsMost covers TLS through Front with declared, chunked, gzip and zstd bodies; TestUnroutedUploadCreditKeepsIdleDeadline, TestUnroutedUploadTimeIsBounded, TestUnroutedUploadAllowanceHasCeiling, TestUnroutedFastUploadBanksNothing, TestUnroutedEmptyEncodedStreamIsBounded (empty gzip members, zstd skippable frames) and TestUnroutedTrickledBodyAnswered408 cover the remaining bounds. Masking's time, its wait for the local model's turn with it, counts toward neither (masked, checkMost): the model is bounded per piece it reads (classifyTimeout) and per load, and a 480 KB request it took 90s over on an RX 470/580, behind the requests ahead of it, was answered 504 at 2m every time it was sent (#3682). The known waits are counted as they happen and their time added up (noteWait, waited): the request's body arriving (waitedBody, every read of r.Body), masking (noteMasking, from noteRedacting), System One's or the decision model's classifier (askWaited), an image's description (seenBody), Codex's auto reset (autoReset), plugins' gateway hooks (GatewayBegin) and JS gateway middleware, and every notePhase (slot, rpm, upstream, redact), and the body room's queue (bodyRoom.take, at most bodyRoomWait, 100s). Each is named (its kind), and the time spent in each kind is kept (waitKind) for the report below. What is left is magpie's own work (the catalog, parsing, planning, reading the usage log), ~8.5s at its slowest (a cold catalog sync), so 30s gives it room on a loaded machine. With no route and nothing written, the error is sent in its client's protocol, whole (Content-Length, Connection: close) so the client has it while the handler may still be held; its context ends with errUnrouted, its route ends with the error before the answer goes (heldWriter.claim takes the reply, the route is marked done with its status, error and report, then send writes it, all under f.mu, so a client that has the 504 never finds the route still routing, #4200), and the log has every goroutine's stack (at most once in 10 minutes). The handler's writes go through heldWriter, and nowhere once magpie has answered for it. The desktop app's log goes only to stderr, which its user can't reach (Jason on Discord, a Codex request held 2m0s, told to send "magpie's log"), so what held it is also saved as a report (held_report.go): taken while the request is still held, before it is answered (the answer says Connection: close, and a client that closes on it ends the request's context and lets its wait go, #4300), outside f.mu, in HeldDir (<cache>/held, mode 0700; also before the answer, and removed if the request was routed or answered meanwhile), written through a temp file and renamed, the newest heldKept (5) kept. It has the time, version and system, method and path, the model and agent, how long it was held, each kind of known wait and its time ("(under way)" for the one it was in), the body room's state, the requests in flight and every goroutine's stack (function names and lines, no values; 128 KB at most, one dump for a burst within 10s). Never the body or headers. Its file name is Route.Held; the Routing page's story of that request has Copy Report (GET /api/gateway/held/{name}, only a report's own name is read) and, in the app, Open Folder (POST /api/gateway/held/reveal). The 504 and the log line say where it is. TestUnroutedHeldReportSaved, TestHeldReportsKeptAndNamed, routing-held-report.test.cjs. TestUnroutedRequestShownThenAnswered, TestUnroutedShownGivesWayToItsRoute, TestUnroutedUnknownHoldAnsweredSooner, TestUnroutedSlowBodyNotCutOff, TestUnroutedMaskingNotCutOff, TestUnroutedSlotWaitNotCutOff, TestUnroutedMostLeavesOutMasking, TestMaskingModelWaitNotCutOffAtMost.

A route group held to chosen accounts

A routing group may be held to some accounts of a provider (Group.Accounts, entries <provider>/<stable id or KeyID fingerprint> in a gateway key's form; duanckham on X: a personal and a company GPT account, one tool and one gateway, and a group's models must not spend the other's). The rule is the gateway key's (#905, Identity.AllowsAccount): a provider the group names is used only on the accounts it names, one it doesn't name on every account.

  • The asked group narrows the request's identity (heldByGroup in key_models.go, by access.Identity.HeldToGroup): the strict intersection with the key's own list, <provider>/\x00 (heldToNone) when the two share none of a provider, and Identity.Group set to the group's name. Every gate that holds a request to its key's accounts (accountAllowed, allowedCandidates, onKeys, allowedKey) then holds it to the group's, on every route: chat, responses and messages (serve), streamed or not, count_tokens (heldByGroupAt), embeddings, images and video.
  • A group reached through another one, as a member or as a fallback, is held by planLevel's hold and Member.Via (groupHeld): its candidates on an account it leaves out are Held rows with Weighed.HeldBy, which the Routing page's trace tells ("not an account Work may use").
  • Fallback stays within the group's own entries: an allowed account that is resting, out or refused falls to the next member, never to an account the group leaves out. With every allowed account gone the request gets the group's usual error; when a key and the group share no account it is 403 naming the group and the Routing page (keyAccountsError, groupsHeldError), and nothing upstream is asked.
  • provider.SaveGroup resolves each entry (cleanGroupAccounts, provider.ResolveAccount): an account named by the name it is shown by is kept as its stable id, duplicates collapse, and a new unknown provider or account is refused. One the group already held that is gone (signed out, a key rotated) is kept, matching nothing, so the group stays held rather than let off to every account. A shared or imported group carries no accounts (ShareGroup, ImportGroup): they are this computer's. An import whose text carries the id of a group of the user's own (not a found one) replaces that group when the page asks (ImportGroupOver, replace in groups/import; the Import box reads the id itself and says "Replace " before it is pressed): its accounts, folder rules, switch and place stay. TestImportGroupOverReplacesSameID, group-import-replace.test.cjs.
  • The group editor's Accounts section (drawAccounts in the routing plugin's client.js) has a row for each member's provider with more than one account (/api/groups' accounts, groupAccounts in groups.go): "Any of its accounts" until some are ticked in its menu (openPicker, multi). Every save sends the group's accounts, since a save replaces the group.

A member on one account of its own

A member may name one account or key of its provider (EastonXvii on X: Astra on account A, then Astra on B, then Sol on C, tried strictly in that order), so a group's order runs over accounts as well as models. Before it, Group.Accounts was a set for the whole group, with no order between the accounts of one provider, and the user made a group per account.

  • The account is the member id's last part, after its effort and fast: provider/model[:effort][:fast]#<account> (provider.MemberAccount, AccountMark, groupaccount.go). Every list keyed by a member's spelling (rules, Fast, Off, Weights, Placed, EffortMaps, Pick) and membersFound's dedup key therefore tell the same model on two accounts apart, and the vendor is still asked for the model's own id. A group saved before has no #, so it reads as it did.
  • SaveGroup keeps the account as its stable id (memberAccountKept, ResolveAccount: a typed name becomes the id) and refuses one on a group member (group/…, auto/…) and a new one magpie has no such account or key for (checkMemberAccounts); one the stored group had already that is gone is kept, matching nothing, as Group.Accounts keeps its own.
  • The gateway holds such a member to that account alone: planLevel's keys leaves the provider's other candidates out as Held rows (memberHeld, Weighed.HeldOwn with HeldBy the group), and fallback goes to the next member, never to another account of the same model. With routing: order the members are tried top first. The member's account is narrowed further by Group.Accounts and a key's accounts, never widened.
  • Shared and imported groups drop a member's account (withoutMemberAccounts in ShareGroup and importGroup); two members left the same are one.
  • The editor's model row has an account chip (rt-macct in the routing plugin's client.js, for a provider /api/groups' accounts lists, which now also has one a member names): "Any account", each account, and "Also on another account…", which adds the model on another account as a member of its own after the row. memberJSON.Account carries the member's account. The CLI takes #<account> in models= (memberResolver), and the TUI's effort key keeps it.
  • Image and video groups go the same way: drawingTries keeps the same model on two accounts as two tries, matched to the chat plan's candidates by memberHeld, and each try is drawn on a request held to its member's account alone (memberOn, before drawOnAccounts and startVideo). count_tokens counts on the resolved member's account (heldByGroupAt).

TestGroupMemberAccountsInOrder, TestGroupMemberAccountNeverSpills, TestGroupMemberAccountSaved, TestGroupMemberAccountsDraw, TestGroupMembersOnAccounts (CLI), group-member-account.test.cjs.

TestGroupAccountsHoldEveryRoute, TestGroupAccountsFallBackWithinTheGroup, TestGroupAccountsAndAKeysAccounts, TestGroupAccountsSaved, TestHeldToGroup, group-accounts.test.cjs.

A route group bound to chosen gateway keys

A routing group may be bound to some gateway keys (Group.Keys, key ids; Xerxes754 on X: a group for one or two keys that every other key neither sees nor uses). Before it, a key could be held to some groups (a key's Models naming group/<id>), but a key held to nothing reached every group.

  • groupBarred in key_models.go bars a request whose key is not one of the group's, nor issued under one (Identity.Issuer). A request without a key (this computer's own, which key limits never hold) and a call magpie makes for a model the user picked in its settings (magpieChoseKey) are never barred.
  • A key held to some models is asked it in groupAllowed; a key held to none in groupGiven (serve, countHeld, keyGroupFor, embeddings, images, videos, decision groups) and, for the model lists, in keyAllowed and keyListed (/v1/models, /v1/models/{id}, Ollama's tags, the Codex catalog), gated on provider.GroupsBound() so an unbound magpie lists as before. A Codex or Claude Desktop subagent pick and masking's model check ask it too (withGatewayKey). A barred request is a 403 naming the group and the Routing page (groupKeysError), and nothing upstream is asked.
  • A group bound inside another one, as a member or fallback, is reached through the outer group by any key that may use it: bind the outer group too.
  • provider.SaveGroup keeps the stored keys when a save says nothing of them (nil: the CLI, the TUI and the page's card toggles) and clears them on an empty list (cleanGroupKeys trims and dedupes). A shared group carries none, an imported one starts with none, and an import over a group keeps its keys.
  • The group editor's Gateway keys row (drawKeys in the routing plugin's client.js) offers /api/groups' gatewayKeys (groupKeys in groups.go: the user's keys, not issued, read-only or browser ones) in the app's menu (openPicker, multi): "Any gateway key" until some are ticked. A bound key since deleted is listed as deleted so it can be unticked.

TestGroupBoundToKeysIsTheirsAlone, TestGroupKeysKeptBySavesThatDontNameThem, TestGroupKeysListedAndSaved, group-keys.test.cjs.

Remote magpie APIs

GET /v1/magpie/trace answers the routing this gateway has decided, for a magpie on the same computer that does not serve it, whose console plays it as its own Routing page (#2606). A trace names accounts and their emails, what they served, session ids, a folder's last two parts and why accounts rest; it holds no prompt text and no key. So it answers local(r) alone: a request from another address is refused 403, and so is one from loopback that carries a proxy's forwarding header (a tunnel or Tailscale Serve here), or a LAN request while the gateway is shared, whatever key it holds. Rebinding, Origin: null and *.localhost pages are stopped before it by lanGuard and corsGuard, as on every route. A gateway key held to a budget, models or accounts is refused with KeyHeldCode, as /v1/magpie/concurrency and /v1/magpie/quotas refuse it. It answers what Server.Trace holds, plus this process's pid and serves (the command that started it, Serves), so a caller long-polls it with after and wait the way the page's own /api/gateway/trace does. / adds pid and serves too, to a loopback request alone. Server.gatewayTrace in trace.go, and TestGatewayTraceIsLoopbackOnly in trace_peer_test.go and TestHeldKeyToldNoAccounts in quotas_held_key_test.go.

GET /v1/models with X-Magpie-List-Wait: <seconds> is another magpie waiting for this one's list to change (KaCli on Discord). It is answered with an ETag once the list it would be answered is other than the one If-None-Match names, and 304 at the end of the wait (at most 50s, listWaitMost) or as the gateway stops (streamsEnding). The list is looked at again on each of magpie's writes and on each change another process makes to its files (filememo.Written), each look holding the catalog for itself, so the wait is exempt from holdCatalog. It is the list's own route, so the key, lanGuard, corsGuard and a key's models judge it exactly as the list. A wait's answer, 200 or 304, says in X-Magpie-List-Wait how many seconds it held. A list asked without the header is answered the same bytes with the same ETag (private, no-cache), and 304 with no body, at once, when If-None-Match names it (weakly, in a list, or *; clyzhicore on Discord), so a client polling the list pays a few bytes while it is unchanged; a refused list (400) is untagged. The follower (waitRemoteList in remote_follow.go) takes a 304 that came sooner than followQuick and doesn't say it waited as a magpie that doesn't wait (a proxy dropped the header), and leaves it to the schedule rather than asking it each second. modelsOnceChanged and listModelsTagged in models_wait.go, and TestModelsWaitGuardedAsTheList and TestModelsListConditional in models_wait_test.go.

A read-only gateway key (access.Key.ReadOnly, set by add-key or access-key; magpie gateway-key add <name> --read-only, gateway-key access <id> read-only|full, or the key's menu in Gateway → Gateway keys) reads this magpie's stats and uses nothing: a desk display polling /v1/magpie/quotas and /v1/magpie/usage keeps such a key in its flash. readOnlyGuard in readonly.go sits after callerGuard, so the key is known from loopback and from elsewhere, and before withCaller and keyLimited, so nothing is read, reserved or sent first. It judges the pattern ServeMux.Handler routes the request to against readOnlyRoutes (GET /, /v1, the quotas, their history and cards, the usage summary and its requests, the key's limit, the key page and its data, the concurrency, the route events' snapshot and stream, and the status line's /v1/magpie/statusline) and refuses every other with 403 gateway_key_read_only: every model route, count_tokens, the Responses WebSocket's upgrade, every MCP server, Codex's and Gemini's backends, the catch-all and every write (POST /v1/magpie/usage/requests, the quotas' refresh, a Codex reset). A route added later is refused it until it is put in that list. A read-only key is held to nothing else, so heldKey leaves it alone and it reads the usage summary and every account's quotas as a key held to nothing does; none of those routes tells a key's secret. The sharing key can't be read-only: magpie gives it to its own agents (LANSecret). A magpie from before this field reads such a key as a full one. TestReadOnlyKeyEveryRoute in readonly_test.go fails when a route the router has is in neither readOnlyRoutes nor its refused list, and sends each refused pattern, by each method it takes, from loopback and from the network.

A browser key (access.Key.Browser) connects the Magpie Browser extension and nothing else. The GUI writes one into the extension's zip (browserKey in internal/gui/browser.go, add-key with Browser), and the zip lands in Downloads, so a copy of it can turn up anywhere. readOnlyGuard looks at it first: the one route it reaches is GET /v1/magpie/browser/extension (browserKeyRoute), and every other pattern, the browser MCP included, is refused 403 gateway_key_browser_only, from loopback and from the network, however the key is sent. A browser key is ReadOnly too, so a magpie from before the field reads it as read-only, never as full. It can't be given full access or made an issuer (access-key and issuer-key refuse it), and an agent holding one isn't taken to go through magpie (gatewayTakes). The key a magpie from before made for the zip had full access. ScopeOwnBrowserKey, run as the gateway starts serving, and the next download (access.ScopeBrowser) hold the key recorded in browser-key to the extension with the same secret: the extension keeps connecting, and the copy in Downloads loses every model, MCP server and stat. Only a key the GUI made for the zip is recorded there, and the sharing key is never scoped. TestBrowserKeyEveryRoute in browser_key_test.go sends every pattern but the extension's, by each method, from loopback and from the network, and checks no upstream is reached; TestScopeBrowser in internal/access/browser_test.go.

POST /v1/magpie/quotas/codex-reset (Server.codexReset in gateway.go, #3850) spends one of a Codex account's resets, which can't be undone, so its admission is stricter than the quotas': a key is required from loopback too. Every origin exemption corsGuard makes without a key (app schemes, null, loopback page names, a request with no Origin) reaches the handler with an empty access.Caller(ctx).KeyID, and is refused 401 there. A read-only key is refused by readOnlyGuard (and again in the handler), and a held key (heldKey) 403 gateway_key_held even when it is told quotas. The account is named in ?user=, and codexResetsAsked lets one ask per account run at a time (409). It calls provider.SpendCodexReset, the Usage page's own code, then RefreshUsage of that card. TestCodexResetNeedsAFullKey in codex_reset_api_test.go sends it without a key from loopback, Origin: null, an app scheme, a *.localhost page, a rebound Host and a foreign page, then with a wrong, read-only and held key, and expects nothing spent until the full key asks.

POST /v1/magpie/update?version=<v> (Server.remoteUpdate in remote_update.go, nnlrl_75403 on Discord) has this magpie update itself to its channel's latest once v (the asking magpie's version) is newer than its own. It replaces the program, so its admission is the Codex reset's: another machine only while magpie is shared (sharedWith), never a browser (fromBrowser), an enabled key with full access from loopback too (401 without one), a read-only key 403 gateway_key_read_only and a held key 403 gateway_key_held. The work is the updater's, set with SetUpdater by the app (updater.updateAsked) and by magpie serve (serveUpdateAsked); with none the answer is unsupported. It answers a provider.RemoteUpdate (state updating, current, off or unsupported with why) and its own version. TestRemoteUpdateNeedsAFullKey sends it the same refused cases as the Codex reset and expects the updater never called; TestRemoteMagpieAskedToFollow runs provider.UpdateRemotes against a real gateway.

A remote provider serves the conversation, token-counting, System One, embeddings, rerank, Decisions, speech-to-text, 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 is served over HTTP/SSE and over a WebSocket (A Responses WebSocket); magpie's own leg to the ChatGPT backend is a WebSocket for a streamed turn (see Providers and accounts). 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. For a held key (heldKey) it adds what holds it (heldTo), its models, quotas (access.Key.Quotas) and, with that on, quotaProviders, the providers newQuotaScope tells it, so it agrees with the quotas routes and the status line (steven_4422: a key held to Claude's models read limited: false there and 403 on the line). It names no account. TestStatuslineHeldKeyScope. A key may hold up to five limits at once, each in its own window, and a request needs every one (#2227, budget.Reserve: one reservation per window, and a refusal names the spent limit that resets last). The saved key keeps the first limit in limit, which older magpie reads, and the rest in moreLimits. The answer's limit is the one holding the key most (budget.Binding), what older clients read, and limits is each of them (budget.All). Holding a key to its limits is the Key limits plugin's, on the gateway's budget point (Plugin runtime): with it off, a key held to a limit gets 503 and nothing is sent. A limit can count only some models (access.Limit.Models, zola_xynb on X), <provider>/<model> or <provider>/*: its sums are kept per window and scope (sums.scope, window.scope), and count a call only when the provider and model in the usage log match (scopeModels adds a model's other ids). budget.reserve holds a request to it only when the model it names resolves to one of them (servedAs; a group, auto/ or unknown name holds nothing there). Before the reservation, keyLimited puts the key's spent ones on the caller (withSpent, budget.Spent through gwbudget.Spender, its issuer's too, access.Identity.Spent), count_tokens included. Then keyHolds holds the request, magpie's own calls for the key too; modelAllowed refuses a spent model by any of its ids (spentFor); groupAllowed ignores them, so a group stays the key's; groupKeeps and so allowedCandidates, drawingTries, the decision groups and embeddings' group tries leave them out, so a group goes on to the members left from the next request on, midway through a conversation too. Where nothing is left, keyModelRefusal (keyGroupRefusal with a media group's own members, spentAmong on the chat route) answers 429 with the limit's message and Retry-After, not 403, and no X-Magpie-Limit-Reset, so a remote magpie rests the model only; keyLimited's own scoped refusal skips that header too. The model lists (keyListHolds) don't change, budget.Binding prefers a whole-key limit, and a remote's key card leaves such limits out (keyLimitCard). Tests: TestKeyModelLimit* in key_model_limit_test.go, TestScoped* in internal/budget. A local magpie asks it with each of its remote-magpie keys for that key's card on its Usage page (#1547), a window per limit's cap.

A key's MaxConcurrency (young02036 on Discord; access.Key, set by the concurrency-key action, the key row's "at once" badge or magpie gateway-key concurrency <id> <n>|off, 0 to 1000, 0 or unset for no limit) is how many of its requests are in flight at once. One more waits in the key's own lane (keyLanes, apart from the providers' lanes, by "key:"+id), in order and with no bound, shows as slot in Active and the trace, and has its wait in its try's Queued; one whose agent goes away while it waits leaves the queue and sends nothing. A key issued under another (access.Identity.Issuer) waits for a slot of its own, then one of its issuer's. keySlots sits in Handler after withCaller and keyLimited, so the LAN, a remote magpie and each turn of a Responses socket (sent through the handler again) all pass it; keySlotRoutes names the routes it holds, and TestKeySlotEveryRoute fails on a route judged neither held nor free (keySlotFree: GETs, count_tokens, MCP, magpie's own). The routes that go through serve's tries (chat, Responses, Messages, Ollama, Gemini, the Codex backend) take the slot in the try, after keepQueued, so a waiting stream gets its 200 and keepalive comments as it does waiting for a provider's slot. A try on an account within 5 points of its usage cap takes it before the account's one turn at a time (nearCap), its wait still in the try's Queued: taken the other way round, a turn kept on the account after a passing failure held the key's slot and waited for the account's turn, while the turn that had taken it waited for the key's, each till its agent hung up (ox0pine on X: a key held to one provider stuck in routing; TestKeySlotAndNearCapTurnNeverWaitOnEachOther). The rest (embeddings, images, audio, videos, rerank, decisions, System One, native) take it before their handler runs. forward and codexUpstreamOn take it too, so no path of a held route reaches a vendor unheld. The slot is the request's until its handler returns, a stream's to its end; a later take within the same request takes nothing more (keyHold). /v1/magpie/concurrency reports the keys' lanes under keys and counts their waiters in waiting; /v1/magpie/limit says the key's maxConcurrency and issuerMaxConcurrency. Tests: TestKeyConcurrency* and TestKeySlotEveryRoute in key_slots_test.go, TestKeyConcurrency in internal/access, TestGatewayKeyConcurrencyCLI, gateway-key-concurrency.test.cjs.

GET /me is the key page: a gateway key's holder opens it in a browser at the address they reach the gateway at, types their key, and sees that key's own name, limits, usage (today, 7 and 30 days, its most used models) and the models it may use, with the setup for Claude Code, Codex and an OpenAI-compatible client whose base URL is the address the page was opened at (zytszone on X: a department shares one magpie, whose app its people can't be given). The page itself (keypage.html, embedded) is the same bytes for everyone and holds no data, so lanGuard serves exactly GET or HEAD /me (keyPageOpen: no escaped path) to another machine without a key, after the allow list, the rebinding check and the not-shared refusal, which still apply. Its data is GET /v1/magpie/me (keyInfo), which takes the key as every route does (Authorization or x-api-key) and answers only access.Caller's own: no key, a wrong one, one turned off and magpie's own token are 401 alike, and ?key= is refused 400, so a key is never written into an address or a log. It names no account, no other key, no provider and no secret; its models are /v1/models' for that key (keyAllowed), none for a read-only key. Its Claude Code setup writes the picked model as ANTHROPIC_MODEL only; ANTHROPIC_DEFAULT_OPUS_MODEL, _SONNET_ and _HAIKU_ are tiers, the newest Claude model of each family among the key's models (keyPageTiers, no routing group, a tier with none left out), so Claude Code's /model tiers and its small asks on haiku keep their own family (strinah on Discord). The page loads nothing from elsewhere, posts no form and can't be framed (its CSP), keeps the key in the tab's sessionStorage only, and sends it to its own origin with credentials: "omit". Gateway → Gateway keys shows the page's address (MAGPIE_PUBLIC_URL, else the LAN address offered) with a Copy, while shared and with a key (gatewayKeyPage in keys.js). key_page.go, and TestKeyPageTellsAKeyItsOwn, TestKeyPageRefusesWithoutItsKey, TestKeyPageTiersAreTheirFamilys, TestKeyPageTiersPickTheNewest and TestKeyPageOpensWithoutAKey in key_page_test.go; internal/gui/tests/key-page.test.cjs drives the page itself.

GET /join is the same page as the join page (EV_John_Liu on X): with a password set in Settings → Local network → Join with a password (POST /api/settings/join, internal/gui/join.go), another computer opens it, types the password and a name for itself, and gets a gateway key of its own (access.Update("add-key"), named for it or "Joined from

"), shown once and then filled into the page's setup, which adds a magpie tab (`magpie provider add remote-magpie`). The key is listed in Gateway keys and is limited, turned off or removed there like any other. Only a salted PBKDF2-SHA256 hash of the password is kept, in `join.json` (`internal/access/join.go`, 0600, temp and rename); a file that can't be read or parsed means joining is closed. `lanGuard` lets `GET /join` and `GET`/`POST /v1/magpie/join` (`joinPageOpen`, `joinAsked`) through without a key, after the allow list, the rebinding check, mTLS and the not-shared refusal. `joinKey` then refuses a browser's request (`fromBrowser`) unless the Host is this computer's own (`ownHost`: no rebound name, no `*.localhost`) and the Origin is that same address, not missing and not `null`, with `Sec-Fetch-Site` same-origin where sent; curl and scripts are judged on the password alone. Every try from another machine takes a token from the join's own bucket (10, then one each 10s), the right password too, so a guesser and a flood of keys are both held with 429 and `Retry-After`. Neither the password nor the key is logged, and the key goes back in a `no-store` body only. `join.go`, and `TestJoinMakesARevocableKey`, `TestJoinHoldsAGuesser`, `TestJoinRefusesOtherPages` and `TestJoinClosed` in [`join_test.go`](../../internal/gateway/join_test.go), `TestJoinPassword` in `internal/access`; `internal/gui/tests/lan-join.test.cjs` drives the page and the Settings rows.

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, zdrRefused) 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. A single decision provider of several keys or accounts (TypeSafe Jev with a key out of quota, fflake33 on Discord) is asked the same way, at /v1/systemone (serveSystemOne) and as a classifier (askClassifier → askDecider): decideKeys plans its keys in its routing's order (Smart, In order), leaving out a key whose plan has no System One (a Volcengine Coding Plan key beside pay as you go), probeOne leaves out all but the resting one back soonest, and serveDecideTries / askDecideTries ask each in turn as for a group, a refused one resting. Before, every call went to its first key, whatever the others' state. As a classifier, every try shares the one classifier's wait (Settings' Classifier timeout, "its provider's failover included"): once a try spends it, the rest are neither asked nor rested. Each try was given the whole wait before, so a request was held a wait per key or member before its route began (TestDecisionTriesShareTheClassifierWait). A gateway key held to some accounts is asked only on those (allowedCandidates), and refused 403 when none of them serves the model. TestDecisionProviderKeysFailOver. embeddings.go relays retrieval bodies and options (serveRetrieval, under Provider.OpenAIBase: a plugin's fetch whatever API its chat models are on), and transcribe.go speech-to-text's multipart forms through it as sent, rewriting only the model and a masked prompt under the form's own boundary (#2053), and speech.go text-to-speech's JSON with the model rewritten and input and instructions masked; its answer, audio or SSE, is copied to the client as it comes (retrieveOpen, copyAnswer), never read whole (TestSpeechStreamsAsItComes), 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, and passOnUA the agent's own User-Agent in X-Magpie-User-Agent, which the remote sends its key+URL providers in place of magpie's. Conversation forwarding preserves Claude Code and Codex client headers (including Codex's originator) so relays behind the remote can recognize them, all but their User-Agent: forwardOnce puts magpie's back after the copies, or the remote would take none of the X-Magpie-* headers (magpieAsks), and a Claude Code request lost its cache lifetime, agent, computer, hops and User-Agent there (linkaww). The remote knows Claude Code by the User-Agent the near magpie named (claudeCodeAsks, agentUA) and Codex by its originator, and its own copy, ?beta=true and the test-as record go on as for the agent's request (TestRemoteMagpieTakesClientsHeaders, TestRemoteMagpieClientHeaders). 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. The remote names the passed-on agent by one rule (callerFrom, callerOf) wherever it shows who sent a request: usage and sessions, recent calls and the Routing trace, the masking log and the requests in flight (counted runs before withCaller, so active.add reads callerFrom itself). The label never changes access, limits or behaviour, which go by the key and the real sender (agentOf).

Images and video in OpenAI's shape

A caller speaks OpenAI's images and videos APIs to the gateway, whichever vendor draws or films, and gets OpenAI's answers back (draw.go, video.go). The generate_image, generate_video and generation_result tools of Magpie Image call these same handlers in process (s.images, s.videosCreate, s.videosGet), so the MCP and an HTTP caller go through one translation and one set of holds.

Route Takes Answers
POST /v1/images/generations JSON: model, prompt, n, size, quality, background, output_format, response_format {"created", "data": [{"b64_json"} or {"url"}]}
POST /v1/images/edits OpenAI's multipart (image or image[] files, mask), or JSON with image/images (URL, data URL or {"image_url": …}) and mask as generations
POST /v1/videos JSON or OpenAI's multipart: model, prompt, seconds, size, input_reference (first frame), plus last_frame and reference_images OpenAI's video object, status: "queued", an id that names the provider, the vendor's task and the key or account
GET /v1/videos/{id} the video object: queued, in_progress (progress), completed or failed (error)
GET /v1/videos/{id}/content the video (video/mp4, or video/quicktime for a MOV: videoType), or 409 while it isn't made
GET, POST, PUT, PATCH, DELETE /v1/magpie/native/{provider}/{path...} the vendor's own request the vendor's own answer, a stream as it comes (native.go, below)

Each vendor is sent its own request:

Vendor Images Edits Videos
OpenAI-compatible images API (gpt-image, dall-e, a relay) JSON /images/generations multipart /images/edits, mask included; a URL image is downloaded first at <base>/videos only when its list or the user marks a video model (below)
ChatGPT account (Codex backend), SenseNova U1 JSON JSON images: [{"image_url"}], mask: {"image_url"} none
Grok subscription JSON with aspect_ratio JSON /images/edits, images: [{"url"}] /videos/generations: duration, aspect_ratio, resolution, image, reference_images
Volcengine Ark (isArk) /images/generations, watermark: false unless sent, one request per image, ratio as the doc's 2K size, the caller's other fields as sent (stream: true is a 400 pointing to the native route) the same endpoint, images as JSON image (URL or data URL); a mask is a 400 that says to describe it in the prompt Seedance at /contents/generations/tasks (below)
Gemini at Google, a Google sign-in generateContent asking for images the images as inline parts a plugin's Veo through its fetch
OpenRouter /images for image-only models, chat with modalities for the others input_references none
DashScope, ModelScope their own asynchronous image APIs (draw_dashscope.go, draw_modelscope.go) their image fields none
MiniMax API key H3 at /v2/video_generation (below)
Another magpie its images API its images API its videos API, ids wrapped

Every one of these routes goes through requestBody (the body limit, key and origin checks every /v1 route has), a gateway key's model and account holds (keyHolds, accountHolds, videoAsker, videoModelHeld), the user's switched-off models, routing groups in their order, prompt masking (fails closed), and usage records.

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", or, with no kind, domain VideoGeneration or video out without text in output_modalities, as Volcengine Ark's list does (catalog.LiveVideomakers), or the user marks a video model (settings' ModelKinds, provider.SetModelKind, a model chip's right-click Makes… in the editor, #1399); a name alone never makes a model a video maker. A plugin's provider makes videos with the models it says give video, through its fetch on the account that started each (keyMark, markedKey; see provider plugins). A model marked an image model is drawn with (Drawers) and leaves the video makers, and one marked a video model leaves the drawers; only a provider set up with a base URL can be marked (MarksKinds). Start, poll and content go to videoBase (its Chat base, else its Responses base) + /videos, with the agent's User-Agent (magpie's when set magpieUserAgent or the agent sent none) 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.

Volcengine Ark has no OpenAI-shaped videos API, so no Ark key is asked at <base>/videos (filmsOpenAI is false for isArk). Its Seedance models go to Ark's asynchronous content-generation tasks (arkFilms, arkTasks: POST <base>/contents/generations/tasks, polled at GET …/tasks/<id>, https://www.volcengine.com/docs/82379/1520757): the preset's Agent Plan's (PlanVideos), and any other Ark key's (pay-as-you-go /api/v3, or an Ark endpoint added by hand) whose list or picked models name seedance (arkVideoModel, added in customVideomakers; axelburks on Discord). Such a key's video id ends with the key's fingerprint, as a plan key's does, and its poll and download go on that key (videoAsker checks the calling key may use it). volcengineVideoBody turns OpenAI's request into Ark's: the prompt as a text item in content, input_reference as an image_url item with role first_frame, last_frame as last_frame, reference_images as reference_image, seconds as duration (-1, the model picks, kept), and size as the nearest of Ark's tiers by pixels and ratios (arkVideoSize: 3840x2160 is 4k 16:9, 1470x630 is 720p 21:9). A ratio, resolution or duration the caller sends itself is never overridden by size or seconds, so ratio: "adaptive" holds. A content the caller sends is Ark's own and kept whole, its reference_video, reference_audio and draft_task items included: the prompt is put first only when it has no text item, and OpenAI's image fields after it. The prompt is optional with an image or a content (Ark's image-to-video takes none), and an asset:// image of Ark's asset library is kept as it is. Those three (no prompt, asset://, seconds -1) are Ark's alone: arkOnly turns them away with a 400 before any other vendor is asked. The request's other fields OpenAI's API doesn't have (Ark's generate_audio, seed, camera_fixed, watermark, tools, return_last_frame…) go to Ark as sent, masked as the prompt is. A JSON body's values keep their JSON types; only a multipart form's are read as JSON (formValue), so its "false", "42" or [{"type":"web_search"}] goes typed, except Ark's text fields (arkTextFields: safety_identifier "12345" stays a string) (TestArkVideoTakesLastFrameAndItsOwnFields, TestArkVideoFieldTypes). Ark's succeeded/running/failed/expired and its content.video_url are read back into OpenAI's video object (videoObject), with every other field of Ark's task passed on as it came (videoState.Ark, all but arkOwnFields): content.last_frame_url, usage, resolution, ratio, framespersecond, seed, tools, output_format and the rest. Ark's expired is a task that ran past its execution_expires_after unfinished, and is said so. /content fetches that URL (vendorClient) and serves a MOV as video/quicktime (videoType reads the ftyp brand). TestArkKeyMakesSeedanceVideos, TestArkVideoKeepsCallersContent, TestArkVideoFromImageNeedsNoPrompt, TestOnlyArkTakesItsOwnVideoAsks, TestArkVideoSize, TestArkVideoAnswersItsOwnFields, TestVideoType.

Ark's images get the same: the request's fields magpie doesn't read (drawingRead) are drawing.Extra, masked as the prompt is and sent to Ark as they came (sequential_image_generation and its options for a group of images, optimize_prompt_options, tools, layer_decomposition, which needs no prompt, and watermark over magpie's false). n stays OpenAI's: that many requests, each one image or one group. response_format: "url" asks Ark for its URL and answers it; anything else asks for b64_json. TestArkImagesPassOnTheirOwnFields.

The native route

/v1/magpie/native/{provider}/{path...} (native.go) passes a request to the provider's own API as it is, and its answer back as it came, an event stream flushed as it arrives and a large answer copied through, never held whole (axelburks on Discord): for what the OpenAI shape can't carry. GET, POST, PUT, PATCH and DELETE (nativeMethods) are routed.

  • Which providers. One reached with an API key (nativeKeyed: no Account, a Key, not a remote magpie, not Vertex AI): a vendor's or the user's own. A subscription's, a sign-in's or a plugin's account is a 403 that says so; an unknown, off or decide-only provider a 404.
  • Where. The path after the provider, as the caller escaped it, is joined to the host of the provider's first base (nativeProto: Chat, Responses, Anthropic, Gemini), not to the base's path, so a vendor's v2 paths are reached too (nativeTarget). It refuses (400) an empty path, a . or .. segment (%2e%2e and across %2F too), a backslash, a leading or encoded leading slash, ://, a first segment that reads as a scheme, and any URL whose host or scheme, parsed back, isn't the base's. The mux redirects an unencoded .. before the route sees it.
  • Headers. The caller's auth (Authorization, Proxy-Authorization, x-api-key, api-key, x-goog-api-key, Cookie), the browser's and a proxy's, the hop's own and X-Magpie-* are dropped (nativeHeaderDropped), the gateway key's ?key= too (nativeQuery); the rest go as they came. What a proxy says of the caller is proxyIdentity: every name lanGuard reads as forwarded (forwardHeaders: Forwarded, X-Forwarded-For, X-Real-IP, Cf-Connecting-IP, True-Client-IP, Tailscale-User-Login), any X-Forwarded-*, Cf-*, Tailscale-* (Tailscale Serve's user login, name and picture) and X-HC-* (a LazyCat box's ingress: the box account signed in, its role and device), Via, X-Client-IP and X-Original-Forwarded-For. The Codex passthrough and relay to the ChatGPT backend (copyHeaders) and the MCP proxy drop the same; see TestNativeAnyDropsProxyIdentity and TestPassthroughDropsProxyIdentity. A provider's PassHeaders still passes on the names it lists, these too: the user chose them. Sign puts in the provider's key as it takes one, and magpie's User-Agent goes in (stampUA). The answer's hop headers, Set-Cookie, Alt-Svc and HSTS don't come back (nativeAnswerDropped).
  • Redirects. A redirect on the vendor's own origin (scheme, host and port, or http to https on the same host) is followed, signed; any other comes back to the caller as it came, Location included, and the host it names is sent nothing (provider.KeepsCredentials, below).
  • Keys. It is behind the gateway's guards as every route is (a key beyond loopback, lanGuard's Host check against a rebound page, corsGuard: a foreign Origin, null and *.localhost without a key, the key's rate), refused to a read-only key (readOnlyRefused), and refused (403, nativeHeld) to a key held to models, accounts or a spend limit, or issued by one: magpie can't tie a path it doesn't read to a model, and prices no answer it doesn't read, so the OpenAI routes serve such a key. A model the user switched off, named in a JSON body's model, is refused.
  • Masking. With Settings › Privacy masking and a provider not set to go unmasked, the body is decoded as JSON (numbers exact, UseNumber) and its strings masked (fails closed); a body that isn't JSON is a 415, as nothing unmasked may go. Only a request something was masked in has its answer read through restoring, which holds a JSON answer whole to put the values back; every other answer streams through.
  • Record. Each request is a Requests row and a usage record (Operation: "native"), with the tokens a JSON or event-stream answer reports (usageSniffer, read as the path's protocol, nativeSniffed), none otherwise.

Ark's images and video tasks at their short paths under the key's base (nativeArkPath: images/generations POST, contents/generations/tasks POST and GET, contents/generations/tasks/<id> GET and DELETE) are served as they were first (nativeArk): the body must be a JSON object, it is re-encoded after masking, and only Content-Type and Accept go on. TestNativeArkRoute, TestNativeArkStreamsAsItComes, TestNativeAnyForwardsAtTheHost, TestNativeAnyRecordsUsage, TestNativeAnyRefusals, TestNativeAnyStaysOnTheHost, TestNativeAnyRefusesPagesWithoutAKey, TestNativeAnyMasks, TestNativeAnyStreamsAsItComes, TestNativeAnyArkHost.

A MiniMax API key (no account, a Chat, Anthropic or Responses base on api.minimax.io, api.minimaxi.com or api.minimax.cn: filmsMiniMax, minimaxHost; a relay serving MiniMax's models is not one) makes videos with the H3 models, MiniMax-H3, -Highspeed, -Lite and -Max (video_minimax.go, minimaxVideoModels). They are video models only (Films), listed by Videomakers and never added to a chat list. A video starts at <host>/v2/video_generation on that key's own host, so international and Chinese keys each reach their platform, and is polled at <host>/v2/query/video_generation/<task_id>. Its MP4 is task.content.url, fetched as other vendors' video URLs are (vendorClient). minimaxVideoBody sends the prompt and images in content (first_frame from input_reference, last_frame from the request's last_frame, references as reference_image). It turns away frames and references together, or more than 9 references, with a 400 before MiniMax is asked. The duration is 5 unless set, raised to the model's shortest (4, or 5 for Max) and cut at 15. The resolution is the request's own resolution, else derived from size's shorter side among the model's resolutions (H3 768P/2K, Highspeed 768P, Lite and Max 768P/480P). The ratio is the nearest of MiniMax's to size. None is sent with a frame, since the video takes the image's shape. Text alone, and Lite's references, default to 16:9. No callback_url is ever sent. Ids carry the key's mark (markedKey), as a custom provider's do, and a key whose plan doesn't make H3 (codes 2061/2068/2057: a Token Plan key) hands the video to the provider's next key. Failures are said for what they are before MiniMax's own words (minimaxWhy, minimaxError): a bad key (1004, 2049, 401), an empty pay-as-you-go balance (1008, 402), refused content (1026, 1027), a plan without H3, and the rate limit (1002, 1045, 429). A failed task's error.code is explained the same way. AutoVideomaker puts a MiniMax key after every other video maker: H3 is paid by the second, so a subscription that made the videos before keeps making them, and generate_video, which names no model, uses MiniMax-H3 only when nothing else makes videos. Covered by TestMiniMaxKeysMakeH3Videos, TestMiniMaxVideoIsStartedPolledAndFetched, TestMiniMaxVideoBody, TestMiniMaxVideoFailuresSayWhy, TestImageMCPMakesMiniMaxVideos, TestMiniMaxComesAfterOtherVideomakers and TestMiniMaxVideoMovesPastATokenPlanKey.

A key's model patterns and names

A gateway key's models (Key.Models, access/models.go, tsingchao on X) are named one by one (provider/model), by a provider's whole list (provider/*), or by a pattern: an entry that starts with re: is a regular expression, RE2 syntax (Go's regexp), case-insensitive and not anchored (re:^gpt-, re:claude.*(sonnet|opus)). It is tried on the whole provider/model id and on the model part alone, so re:^gpt- and re:^openai/gpt- both take openai/gpt-5. It never takes a routing group (group/…), which a key names itself. Every route that holds a key to its models asks access.ModelAllowed (through Identity.Allows, allows, modelAllowed, keyAllowed), so a pattern holds chat, Responses, Messages, count_tokens, Gemini's path, /v1/systemone, the decision models and every list alike (TestGatewayKeyModelPatternHoldsEveryRoute). CleanModels compiles a pattern when a key is saved and refuses one that is empty or isn't a regular expression; one that fails to compile later (a hand-edited file) matches nothing, never every model. A pattern is for the keys the user makes: IssueKey refuses one, since an issued key's models are named one by one or with *. The model picker (Gateway page, the key's models badge) has a search box over a model's name and id; typing re: and a pattern and pressing Enter adds the pattern; magpie gateway-key models <id> 're:^gpt-' does the same.

A key may also name a model its own way (Key.Aliases, aliases-key, the row menu's Model names, magpie gateway-key aliases <id> name=provider/model …): /v1/models for that key lists the name in the model's place, and a request that names it goes to the model. A name is a single word (no space, * or re:) and a name differing only in case is one name; the model must be one the key may use (ModelAllowed over its own models and accounts), and when the key later loses the model the name is refused (403) and unlisted. identifyCaller rewrites the name once, where the caller's Identity is attached to the request (gateway/key_aliases.go): the JSON body's model (any route, a body of up to 32MB that isn't compressed), Gemini's /v1beta/models/<name>:method, and GET /v1/models/<name>; so every later check sees the real model. Limits: a reply still names the real model, Gemini's list (/v1beta/models) is not renamed, a non-JSON or compressed body is not read for a name, and an issued key has no names (TestGatewayKeyAliasRenamesAModel).

Short-lived gateway keys

A gateway key may expire (access.Key.Expires), and one issued under another key keeps that key's id (Key.Issuer). They are for an orchestrator that gives each sandboxed agent a key of its own that stops working by itself (xazaj on X, moving off an enterprise LLM gateway). access.IssueKey in issue.go makes one, living 1 minute to 30 days (MinTTL, MaxTTL); --tokens/--cost cap it over its whole life, as one hours limit as long as its life from the moment it is issued.

Where it is issued:

  • POST /v1/magpie/keys with {"ttl": "1h" | 3600, "name", "models", "accounts", "tokens", "cost", "readOnly"} answers 201 with the key's id, name, key (the secret, told once, Cache-Control: no-store), expires and what it is held to. GET /v1/magpie/keys lists the keys the caller issued, masked; DELETE /v1/magpie/keys/{id} revokes one. See issue_keys.go.
  • magpie gateway-key issue --ttl 1h [--name n] [--models a,b] [--accounts a,b] [--tokens N] [--cost USD] [--read-only] [--from <id>] [--json] prints the secret alone; gateway-key issuer <id> on|off lets a key issue; gateway-key list shows until <time>, expired, issued by <id> and issues keys.

Who may call the endpoint (keyIssuer): a key the user let issue (Key.Issues, issuer-key in access.Update), from wherever that key is let in, so an orchestrator in a container or on another computer can; or a request with no key that profileRefused passes: loopback, no proxy's forwarding header, no browser's marks (Origin, Sec-Fetch-*, a Mozilla/ agent) and a loopback Host, so neither a page nor a rebound name can. That request may already use every model with no key and could run magpie gateway-key itself, so it gains nothing. A key not let issue, a read-only key (readOnlyGuard refuses the route), an issued key and an expiring key never may; the sharing key may only if the user lets it.

An issued key never outlives or exceeds its issuer. IssueKey clamps its expiry to the issuer's and refuses a model or account the issuer may not use. Then at every authentication (access.Check, which Authenticate, access.On and so every route reach) identityOf folds it into its issuer as the issuer is now: its models are those both allow (foldModels; none in common is a refusal), its accounts are held to the issuer's (foldAccounts), it is read-only if either is, told quotas only if both are, and it expires when the first of them does. An issuer removed, turned off or expired refuses it. What it spends counts against the issuer's limits too: its usage rows carry callerIssuerId (usage.Record. CallerIssuerID), budget.read and budget.Append count a row for both keys, and budget.Reserve reserves on both (Identity.Issuer). GET /v1/magpie/limit answers its expires and issuerLimits.

An expired key, or one its issuer no longer lets in, is answered 401 with why (access.Refused, "the gateway key "sandbox-1" expired at …: ask for a new one") on every route, from loopback too (identifyCaller): a sandbox on this computer whose restricted key ran out would otherwise be let on as a request with no key, which may use everything. Whether a connection already open when the key expires (a Responses WebSocket) is refused at its next turn is untested. An expired key is kept an hour for that message, then access.Prune removes it (every 10 minutes while the gateway serves, and on each issue), with the keys of an issuer that is gone. A turned-off key on loopback is unchanged: it reads as no key.

TestIssuedKeyExpiresOnEveryRoute, TestKeysEndpointWhoMayIssue and TestIssuedKeysSpendTheirIssuersLimit in issue_keys_test.go, and TestIssuedKeyBoundedByIssuer in issue_test.go.

Trading an OIDC token for a key

A CI job need keep no gateway key in its secrets (#4531, xazaj on X): it trades its OIDC token for a short-lived key. The user writes a rule (internal/oidc, kept in oidc-rules.json) with magpie gateway-key oidc add --key <id> --repo owner/name [--ref refs/heads/main] [--environment e] [--claim k=v] [--ttl 1h] [--issuer URL] [--audience a]; oidc list and oidc remove <id> manage them. No rule, no exchange. A rule names:

  • the issuer, GitHub Actions' (token.actions.githubusercontent.com) by default, https only;
  • the audience, magpie-<rule id> by default, so a token asked for one rule opens no other;
  • the claims the token must have, each exact or a path.Match glob. A GitHub rule names repository, repository_owner or their ids with no wildcard, or any repository's workflow could get a token GitHub signs;
  • the gateway key the keys are issued under, which must be let issue (Key.Issues) and not be issued itself, and how long they live (1h by default, MinTTL to MaxTTL).

POST /v1/magpie/keys/oidc with Authorization: Bearer <token> and an optional {"ttl", "models"} (oidc_keys.go) verifies the token (oidc.Match, verify.go): RS256 alone, signed by a key from the issuer's discovery document's https jwks_uri, exp required, nbf/iat with a minute's leeway, the rule's audience and claims, and a jti traded once until it expires. A token is judged only against rules naming its iss, so it can't make magpie fetch from a URL of its choosing. Keys are cached an hour per issuer, read by one request at a time, asked again for an unknown kid at most every 10s, and the last good keys keep serving while the issuer is down; with none ever read nothing is let in. A matching token gets access.IssueKey under the rule's key, named repo@ref (run N), living no longer than the rule, so everything above about issued keys holds: bounded by its issuer, its spend counts against it, turning the issuer off stops both.

The route is one of two keyless exemptions from the key check in lanGuard (oidcExchange: that exact path, POST, no gateway key); the other is a magpie's proof, below. It is answered only while magpie is shared and past the allow list, and a refused token counts against tooManyAuthFails as a wrong key does. A read-only key is refused it. Covered by TestOIDCTokenTradedForKey (oidc_keys_test.go), TestMatchEachCheck, TestKeysCachedAndKept, TestUnreadKeysLetNothingIn and TestAddRefuses (oidc_test.go). Not tried: a real GitHub Actions run against a shared magpie.

POST /v1/magpie/prove (provider.RemoteProvePath, remote_prove.go) is how another magpie looking for this one at a new address (providers-accounts, "A remote magpie that moved") learns it holds that magpie's gateway key before sending it: {"nonce", "key_id"} with key_id the key's sha256 in hex, answered {"proof"}, HMAC-SHA256 under the key of the nonce and the address the connection reached (provider.RemoteProof), or 404 when no enabled key has that id (access.ProveSecret). It carries no key, so lanGuard lets it by (proveAsked: that exact path, POST, no gateway key) only while magpie is shared and past the allow list, the rebinding check and the not-shared refusal still first; corsGuard still judges its Origin, and the handler refuses anything from a browser (fromBrowser). An unknown id from another machine counts against tooManyAuthFails. Only a caller that already has the key's sha256 gets a proof, for a nonce and address of its own choosing under a key it doesn't hold. Covered by TestRemoteProveAnswersOnlyTheKeysHolder (remote_moved_test.go).

The stats and management API

Every route under /v1/magpie/ answers a program on this computer, and another computer only with an enabled gateway key while magpie is shared (sharedWith). A key held to a budget, models or accounts (heldKey) is told its own calls and limit alone:

Route What it answers
GET /v1/magpie/usage?period=today|7d|30d|all the usage summary: totals, by model, agent, provider, account and gateway key
GET /v1/magpie/usage/requests?period=&offset=&limit= the request log, filtered by day, model, agent, provider, account, callerKey (a gateway key's id, an issued one's too), failed=1, retried=1, q, computer, via
GET /v1/magpie/quotas[?kept=1] each subscription's windows; kept=1 without asking a vendor
GET /v1/magpie/quotas/history?days=&provider=&user= what was left of each window over time (45 days at most)
GET /v1/magpie/limit the key's own limits, its expires, and issuerLimits; a held key's heldTo, models, quotas and quotaProviders
GET/POST /v1/magpie/statusline[?format=json] Claude Code's status line, as text or JSON, of the cards scopeQuotas tells the key
GET /v1/magpie/concurrency requests in flight per account
POST/GET /v1/magpie/keys, DELETE /v1/magpie/keys/{id} short-lived keys, above
POST /v1/magpie/keys/oidc an OIDC token traded for a short-lived key, above

Route events for a display

A display on the network (#3387, joe21_eee: an ESP32 screen) shows every agent's requests as they are routed, live, without knowing their sessions, which /v1/magpie/route asks for, and without the full trace (/v1/magpie/trace), which names accounts, folders and errors and stays loopback-only. route_events.go serves two GETs:

  • GET /v1/magpie/route-events/snapshot: cursor, active and routes, every request the trace has that is still going, read together with the cursor under trace.mu.
  • GET /v1/magpie/route-events?after=<cursor> (or Last-Event-ID, which wins): SSE. Each route event has an id equal to its JSON cursor, a kind, the active count after the change and one route, which replaces the display's route of that id. A display removes it when its phase is done or dropped.

A route is routeActivity, an allow list, never a Route with fields taken out: its id (the trace's, base 36, two requests of one session are two ids), start time, agent (the caller's label), the provider of the seat its last try went to (never the seat's id, which names an account or a key's fingerprint), model (the served one once the reply names it), attempt (from 1), fallback (a later attempt, a retry on the same provider included), phase (started, attempt, responding, attempt_done, done, dropped), status, failed, ms (the finished try's, or the request's once done) and ttft_ms. No session, account, key, folder, prompt, reply or error text. Kinds: request_started, attempt_started, first_content, attempt_finished, request_finished, request_dropped, route_changed.

Changes are recorded in trace.begin and trace.update (a diff of activityOf before and after) into a ring of the last 512, under trace.mu; writes to the socket hold no lock. The first content is told as it comes: firstToken.onFirst (s.trace.firstContent, set per try in serve and for the ChatGPT backend's reads in codex_backend.go) writes the try's unexported firstMs, so the full trace's TTFT, told once the try is done, is unchanged. A route that leaves the trace unfinished (drop: an unrouted request's stand-in once its own route begins; trim past twice traceKeep) is told request_dropped and marked offFeed, so later writes to it by the request holding it are told no more: without it a display showed a stand-in going forever.

A cursor that isn't this process's (the ring's epoch), or older than the ring, is answered 409 {"error":"snapshot_required"}; a reader that falls behind mid-stream gets event: reset and the stream ends. Take a snapshot in either case. A heartbeat comes every 15 seconds; a write waits at most 10. The stream ends when the client goes, when the gateway stops serving (Server.streamsEnding, closed first thing in ListenAndServe's drain, so Shutdown doesn't wait its whole drain, 15 minutes on a handover, for a display), when the key it came with is turned off, removed or runs out (access.On, asked at most once a second when there are changes and at each heartbeat), and when magpie stops being shared with a reader on another machine (remoteKeyed). A key rotated keeps its id, so a stream open under the old secret goes on until it reconnects. Nothing is kept on disk.

Who reads it is who reads the usage log (routeEventsAllowed, as usageSummary): this computer, and another machine with an enabled gateway key while magpie is shared; never a key held to a budget, models or accounts (refuseHeld), which is told no one else's requests. A read-only key reads it (readOnlyRoutes), so a display is given magpie gateway-key add Screen --read-only: it can spend nothing. Every route's guards come first (lanGuard, corsGuard): a page sending Origin: null, a *.localhost page, a rebound name and a proxy's client are refused it without a key. A separate key type, as the community patch had, was left out: the read-only key already reads more than this feed (every call's usage), and is the key for a display. TestRouteEventsTold, TestRouteEventsReplayAndRevocation, TestRouteEventsDroppedRouteGoes, TestRouteEventsEndWithTheGateway, TestRouteEventsLiveFallback in route_events_test.go, and TestReadOnlyKeyEveryRoute.

A reply's progress while it is out

A long or reasoning reply otherwise looks stuck on the Routing page (#4951, Canda15). live.go counts each request's reply as it reaches the agent: serve begins a liveRow on the request's inflight (liveBegin, none for the gateway's own requests), and captureResponseWriter.Write, which every byte to the agent passes, calls observe. The route (the full trace only, never routeActivity) gets bytes (every byte written, SSE framing and keepalives included), contentAt (epoch ms of the last write that was not only SSE comments, so a keepalive never moves it) and estTok. trace.liveBytes writes them under trace.mu and bumps the route's Seq, so a long poll gathers them like any change.

estTok is the content written so far (text, reasoning, tool names and arguments, per the agent's protocol, live_content.go) at the rate learned for the provider and model that answer (routed, per try), from streamed replies that did not fail and whose vendor said its output tokens (live_rates.go). Under three such replies there is no estimate and the page shows none. Rates are in memory only (256 pairs), learned again after a restart; an estimate is never learned from.

Cost: observe takes the row's lock and the trace's, neither held while anything blocks. A whole JSON reply (its first byte { or [) is counted in bytes only, never copied or decoded; a stream is cut into lines in place, only a line cut by the end of a write is copied, and a line over 1 MiB is passed over. The ChatGPT backend's chain (codex_backend.go, codexUpstreamOn) writes past the capture writer, so it begins a liveRow of its own and calls observe on each chunk it copies, as the Responses protocol.

The page (plugins/routing/client.js, liveParts, paintLive) shows the numbers on a request in flight's row and beside the account answering it, changed in place each second; after 15 s with no content the account's dot stops pulsing. Nothing stays once the request is done. TestLiveCountsARealStream and the other tests in live_test.go, and routing-live-bytes.test.cjs.

A session's output speed

The Sessions page draws each session's output speed over its last two minutes, the way a token speed chart does (session_speed.go). counted() opens the session's track (curveMeter.open, by the request's agent and sessionOf id; none without a session) for as long as the request is in flight, and liveRow.observe adds the content bytes it counts to it (curveMeter.add). A track keeps a ring of 120 seconds: the bytes of each second, and whether anything of the session's was in flight in it. A second with nothing in flight is a gap (null on the curve): the agent was running a tool, or waiting. Tokens are the bytes at the rate liveRates learned for the provider and model (rate); until it has one the curve is in bytes, rated is false and every number is 0, never a guess.

A round is the run of requests with no pause over curveRound (2 min) between them; its average (over the seconds it wrote in), peak (of a 3 second moving average) and output are kept. A track idle over curveForget (10 min) is dropped, and at most curveMost (256) are kept. The meter's lock is never held while anything blocks; add is a map lookup and an add.

GET /api/speeds (internal/gui/sessions_manage.go, not under /api/sessions, so a poll never counts as reading the agents' sessions) returns []gateway.Speed, newest first. /api/sessions/manage gives each native row its other gateway keys (keys, sessions.GatewayKeys past the first) so a row finds its speed by any of them. The page (plugins/sessions/client.js, speedCell, openSpeed) reads it once a second only while it is shown and the window is in sight, and draws a row's curve and tokens a second now (the round's average once nothing is in flight); a click opens the round's numbers and its gaps. Tests: session_speed_test.go (TestSessionCurveFromARealStream, TestSessionCurveFromCodexOwnSignIn) and sessions-speed.test.cjs.

Turning provider search off

Settings' searcher: "off" disables magpie's provider-assisted search, including Kimi Code's, a GLM Coding Plan's and WorkBuddy's search services 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 GLM Coding Plan, WorkBuddy, 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, unless searchAll is on (next section). An empty searcher still selects a provider automatically; an unavailable named provider (gone, off, can't search) still falls back to that selection. One that is available but fails a search is not replaced by another provider (below).

webSearch enforces the API-only path. Covered by TestSearchProviderOff, TestSearchProviderOffForwarding, TestSearchProviderOffTellsRemoteMagpie, TestSearcherChosen, TestSettingsSearchProviderOff, and searcher-pick.test.cjs.

magpie's search for a model that searches by itself

Settings' searchAll (cybercaius on Discord) gives a model whose provider searches the web by itself (searchesFor) magpie's search too: the searcher and the search APIs, in their usual order, as a model that can't search has. Settings › Models › Web search shows it as "Models that search by themselves", Their own or magpie's; with nothing magpie can search with the row is dimmed and says where to add a search. magpieSearches is the one check: on in Settings, magpie can search for this provider (canSearchFor), and the request isn't magpie's own searcher request (searching), which needs the provider's search. Where it holds, searchedForIt stops the relay of a body that asks for web search, and translate neither picks an API for the provider's own search nor keeps it, so the provider is sent magpie's web_search function tool. With nothing magpie can search with, the provider keeps its own search and the relay as sent.

Not covered: a Codex sign-in's turns relayed as Codex sent them (codexAsSent) and a sealed agent message keep the provider's search, as they keep the rest of the body; the model list another magpie reads (webSearchOf) still says native.

Covered by TestSearchAllTakesTheSearchFromAProviderThatSearches and search-all.test.cjs.

WorkBuddy's search service

A WorkBuddy plan's models (the China build's and WorkBuddy AI's, served by the plugin since the built-in was retired) have no search tool of their own. With nothing else in magpie that searches, canSearchFor was false and Claude Code's WebSearch came back empty (#1798). wbSearch (search_workbuddy.go) asks the plan's own service as WorkBuddy's CLI does: POST <site>/agenttool/v1/search with {"query","type":"text2text","max_results":5}, signed by Provider.Sign and sent by Provider.Do, so a moved account goes through the plugin's fetch. searchesOwn names it for the plan's own models only, before magpie's picked searcher, as with Kimi Code. A {code, msg} refusal (15001 is its search quota) is reported as an error, never as no results. Covered by TestWorkBuddyPluginSearches (Claude Code's literal WebSearch request, the real service's reply bytes, the quota refusal and search turned off).

A GLM Coding Plan's search MCP server

A GLM Coding Plan's key (Zhipu's or Z.ai's) is also given for the plan's Web Search MCP server, which users otherwise add to each agent by hand (young02036 on Discord). glmSearch (search_glm.go) asks it with the provider's own key, nothing to set up: a Streamable HTTP session at <host>/api/mcp/web_search_prime/mcp (provider.ZhipuCodingSearch, only for a provider or key on the plan's /api/coding/paas/v4, since the server serves no pay-as-you-go key), initialize, one tools/call of webSearchPrime with {"search_query"}, then the session's DELETE. The tool's text is read as a list of results, a list in a JSON string or a list under search_result/results/items/data (readGLMSearch); isError or words with no results are reported as an error, the key masked. A provider with several keys asks each of the plan's keys in turn. searchesOwn names it for the plan's own models first, as with Kimi Code, but only while Settings names no searcher (glmSearches): a searcher the user named searches for every model. It is not a searcher choice for other providers' models: a plan with the Responses base already searches by itself there (#660). Covered by TestGLMCodingPlanSearchesForItsModels (a fake server with an event-stream reply, the refusal, a named searcher, a pay-as-you-go key), TestReadGLMSearch and TestZhipuCodingSearchAddress. Not tried against the real server: the docs give neither the tool's arguments nor its reply's shape.

Search results in translated Responses replies

When a search is done for a model (searchReply), or a Responses provider's search is decoded for translation, its KSearch event and collected Search part hold the query and pages found. responses.go's responsesEncoder.event and renderResponses return these as completed web_search_call output items through the shared responsesSearchItem. The action says search, carries both query (older clients) and queries, and lists the nonempty source URLs in action.sources. An actual search with no sources has an empty list; a text answer alone creates no search.

The stream adds and completes each search item, emits response.web_search_call.completed, and keeps the same item in the final response's output. Search events arrive after the search has run, so no earlier progress is fabricated. Search items keep their order among text, reasoning and client tool calls. They carry sources, not invented url_citation annotations: the shared search result has no citation offsets in the model's answer. Native Responses passthrough is unchanged. A client sends the item back in its next input (Codex replays its output). parseResponses leaves it out, as before, unless Claude's signed thinking is in the same assistant run: then the search was magpie's own round for a Claude reply, which Claude wrote as two messages (thinking and magpie's web_search call; then, after the result, more thinking and the answer). searchRoundsBack splits the run there into the call and a result naming the query and the pages found (what the search said was not kept), so the thinking blocks of the latest assistant message are where Claude wrote them. Told as one message, Claude on Bedrock refused the next turn 400 "thinking or redacted_thinking blocks in the latest assistant message cannot be modified" and Codex retried until the stream gave up (oreoft on Discord; TestClaudeThinkingAroundMagpieSearchGoesBackAsWritten, TestSearchWithoutClaudeThinkingStaysOut in claude_search_round_test.go).

This lets a Responses client verify search execution and display source links without sending a separate Anthropic Messages request. Covered by the TestResponsesSearch tests in responses_search_test.go and the Responses cases of TestWebSearchForAModelThatCannot in search_test.go.

Citations in translated Anthropic replies

After a KSearch event (or a Search part), the Anthropic encoder and renderAnthropic cut the text that follows into lines (citer in search_cite.go). magpie's web_search tool asks the model to cite the URLs it uses, so a line that names the URL of a page the reply's searches found, whole (urlIn: not a longer path, a query or another host), is a text block of its own whose citations are web_search_result_location entries for those pages (citesOf), as Anthropic's own search cites them; the lines between run together in one block without citations, and a whitespace-only line is held for the next, so no block is whitespace alone. Streamed, each cited block's citations_delta events come before its text_delta, and the stream buffers only to the end of a line, only after a search. The text itself is the model's, unchanged. encrypted_index is "", like the results' encrypted_content: it is Anthropic's sealed pointer, which magpie can't make. cited_text is what the search said of the page, cut to 150 characters (Hit.Cited: a search API's snippet, or the text an Anthropic searcher's own citation quoted), else "". A reply with no search is said as before. Covered by TestSearchCitedAsAnthropics (streamed and whole), TestNoSearchNoCitations and TestCitesOnlyTheWholeURL. Responses and Chat replies carry no url_citation annotations yet.

While a provider asked by searchReply is queued or thinking, sending only keepalives or response.in_progress, askTranslated reads it with readSSEAlive and hands on a KAlive event after keepaliveGap with nothing else sent. It is nothing of the reply: searchRounds passes it on uncollected, and relay takes it as the provider heard from, begins the client's stream and sends the client's own keepalive (enc.keepalive). Before, relay waited for the first content to make the client's encoder, so Codex heard only the held stream's comments, which its idle timeout doesn't count, and hung up after ~315s (#2316). An error before any KAlive is still a status another account may answer. Covered by TestSearchQueueKeepsCodexAlive in search_queue_test.go. A provider that says nothing at all, not even a keepalive, is handed on a KAlive every keepaliveEvery by the same ticker streamTranslated uses (keepThroughSilence), for up to translatedQuietLongest of its silence.

A Claude subscription run is heard from the same way (keepBridgeHeard, in claude_subscription.go). Its run says nothing before its reply: in the interactive mode a message is told whole from the transcript, and a long conversation replayed to a new Claude Code is prefilled uncached first. The held stream's comments stop at keepaliveLongest, and Claude Code 2.1.316's byte watchdog hung up 300s later, at 599s (#5043). Comments forever would not do: its event watchdog counts no comment and hangs up 600s after the headers. So after bridgeHeardAfter (1 minute) of a quiet run, the run's events gain an empty KStart, which begins the reply (message_start), and a KAlive every keepaliveEvery while it stays quiet, for up to translatedQuietLongest. The client gets the protocol's own pings, held like any frames-only stream (holdLead). The run's own start, later, adds its usage. A failure in the first minute is still a status. The gain is bounded: Claude Code 2.1.316 turns every 10s with bytes into a ping of its own and counts 30 pings in a row, so a stream of pings and comments alone ends 600s after its last other event. The reply's start goes out when the hold lets it go, about 4 minutes in, and the run has until about 14 minutes where it had 599s. A run quiet for longer still ends: only a real event of the reply would keep it. Covered by TestClaudeBridgeQuietRunKeepsClientAlive in claude_bridge_keepalive_test.go.

Which providers search for another model

Searchers() (Settings › Web search's picker) and autoSearcher (magpie's own pick) take a provider by searchRank, and its models by searchableModel, from the same rules that send a provider's own search tool on (searchesItself, modelSearches, remoteSearch). A provider that searches for some of its models only (searchModels: Command Code's Provider API, partSearcher) is offered and picked with those models alone, never under x-cmd-zdr; before, its searching models were left out of both (01huadalang on Discord). So is a plugin's provider with models its list marks searches (pluginSearches: a model that searches the web by itself when asked in plain words, catalog WebSearch "native"): it is asked with no search tool, and searchWith takes a reply that names a link. Before, every plugin's provider was left out whatever its models did (01huadalang, 10-20, of Trae's search model). A client's own web_search to such a model still gets magpie's searcher. A provider none of whose models searches by itself, such as a plugin that marks none and whose config hook doesn't set searches, is not a searcher: its models are given magpie's web_search, and the row's searchLeftOut names it. The models looked at are searcherModels: what the provider lists (Available()) and the ones typed in by hand (Exposed). A custom Responses relay with no model list, marked as searching by itself, has only the hand-typed ones. Before, it was left out of the picker while the page listed it among the relays to pick by hand (axelburks on Discord). Covered by TestSearcherRelayWithoutModelList and TestSearcherPickerOffersResponsesRelay. A key at AI Studio's Gemini API (geminiKeySearches) ranks with a Google sign-in (5), by googleSearch, and like one is Own: its own models search first whoever is named. Before, it searched for its own models only and the picker never listed it (cocoasoda on Discord, TestAIStudioKeySearchesForOthers). A ChatGPT account (Codex's sign-in, codexSearches) searches for another model by the ChatGPT backend's own search, POST <CodexBase>/alpha/search, the request Codex's web.run sends by itself with no model turn (codexSearch, codex-rs ext/web-search): one search_query, the account's small model in model (the backend answered the same for any), allowed_callers: ["direct"], and external_web_access from the client's web_search tool (Request.WebAccess, withWebAccess: false for Codex's "cached", #5018), else true. The output's pages, split on its 80-dash rule, keep their titles and links by the results' ref_id, with the private-use citation marks dropped (codexPages). It is magpie's own pick for the account (autoSearcherReady, searchInTurn via turnModel) and Settings' <id>/@search (codexSearchModel, shown as "its web search"); <id> and <id>/<model> still search by that model, which is also what codexSearchBy falls back on when the backend's search fails. lucy_85908 on Discord: on a real Plus account 151 such searches left the 5-hour window at the same percent, about 2s each, while 51 by gpt-6-luna through /responses took 1% of it, 7-15s each and about 9k tokens in. The fallback model search is still made live: the cached mode reaches only the backend's search. Covered by TestChatGPTAccountSearchesByItsWebSearch, TestResponsesWebSearchModeKept and TestCodexPagesRead. Covered by TestCommandCodeSearchesForOtherModels, TestPluginSearchModelIsASearcher and TestSearcherChosen.

A searcher that fails or finds nothing

modelSearch asks the searcher picked in Settings (or the one magpie picks) first. searchWith tells three outcomes apart: an error, a reply that searched and named no page (errFoundNothing), and a reply with no search in it at all, no server_tool_use or web_search_tool_result (errNotSearched, which is found nothing too). The last is a vendor that ran no search: the tool dropped or left unused, and the model answered from what it knew.

A searcher magpie picked by itself gives way to the next of Searchers(), up to three in all (#669). That fallback is not silent: searchingInstead puts on the search's CallFor the searcher asked first (instead), and why it didn't search (why, nothingFound or notSearched). The Routing row of the search that answered says which searcher was asked first, for whom, why it didn't search, and which one searched in its place (kindWhy).

A searcher named in Settings gives way only to the ones the user put after it, SearcherThen (Settings › Web search's "If it fails" row), in their order. One that can't search now, is the one named, or is the same model is skipped. The first that searches answers, and the row says why the named one didn't search (searchingInstead). No other provider searches in their place (axelburks on Discord asked for this list), unless the named one can't serve at all: every account or key of it out of its allowance (searcherSpent), or its search refused for quota, credit or rate (failure, in searchWith), both errCantServe. Then, after the ones named after it, the searchers magpie would pick search in its place in turn (searchInTurn, up to two more providers), and namedFailed names the one that did. pedestrianz (plugins#635) named Codex to search for Cursor's models; when Codex ran out and Cursor took the turns over, every search failed with it (TestPickedSearcherThatCantServeGivesWay). When every one fails, their errors go back to the model together, as a failed tool result, and the turn goes on; webSearch then asks the search APIs, when any are set up. Covered by TestPickedSearchersInTheirOrder; TestSearcherThenSaved and TestSearcherThenFromSettings cover how the list is saved. Settings only takes a provider Searchers() offers. A save without the list keeps it, since the page's prefsKeep doesn't send it; [] clears it. namedFailed keeps the last search it didn't make, with the one that searched in its place (Instead), and clears it when it next searches. Settings › Web search shows that (SearcherFailed, searchFailed) at the start of the row's help, which wraps whole. Gearclickist on Discord picked Grok. Their grok-4.7 rows were about 1.3k tokens, the size of a request Grok ran no search for (one that searched took 6k-66k on our account). Every search then went on to Codex's gpt-6-astra, a pricier model they hadn't picked. Rows recorded before this, with picked set, still read as before.

Covered by TestPickedSearcherIsNotHandedOn, TestSearchInPlaceOfAutoSaysWhy, TestSearcherFindingNothingGivesWay, search-instead.test.cjs and searcher-pick.test.cjs.

How hard a side model thinks

Settings › Models has a chip beside Image recognition's model and the searcher's (MOMO on Discord): visionEffort and searcherEffort in settings, one of catalog.EffortRank or empty. The chip offers only the model's own levels (ModelEfforts: Efforts, weakest first; visionEfforts, searchEfforts in the settings read), and none for a model whose levels aren't known. A level picked is fitted to the model's levels (sideEffort, fitEffort) when the call is made, so a saved level outlives a change of model. Empty keeps magpie's own: Image recognition at the least level the model has (classifyEffort), the searcher with no level at all. Only these two calls carry it (side_effort.go):

  • askVisionWith sends Chat's reasoning_effort; the image cache key (sightKey) has the level picked in it, so a new pick reads the image again.
  • searchBody sends the searcher's Anthropic body thinking (disabled for none, else enabled with budgetOf's budget, 1024 for minimal) and output_config.effort unless the vendor model is a Claude older than adaptive thinking. The gateway's translation then fits it to the vendor: adaptive thinking or between_tools for new Claude, reasoning.effort for Responses, thinkingLevel for Gemini 3 on Code Assist and Antigravity.
  • A picked level raises the call's max_tokens by its budget (replyRoom), so thinking doesn't spend the reply; the model's own limit still caps it.
  • A provider searching for its own models (ownSearch, Kimi Code's search service) is sent none. A fallback searcher is sent the level fitted to its own model.

Covered by TestVisionEffortPicked, TestVisionEffortOnAnthropic, TestSearcherEffortPicked, TestSearcherEffortOnGemini, TestSideEffortChecked and side-effort.test.cjs.

How many results a search is answered with

A search asks its backend for searchCount(ctx) pages (search_api.go): the count the search named (withSearchCount, the web-search MCP server's web_search count, held to 1 through 20), else the user's SearchCount through Settings.SearchPages: 1 to SearchCountMost (20, the most Brave and Tavily return), and SearchCountDefault (6) when it is 0 (#5545, mdwsk88). Claude Code's WebSearch and Codex's web_search name no count, so the setting is what they get. Each built-in API, a plugin's search hook (cut to the count by pluginPages), Kimi Code's and a sign-in's search are asked for that many; WorkBuddy's is asked for its client's 5 unless the count is over 6. web_search's schema says the setting as its default (searchMCPSchema). Each page carries up to pageText (1500) bytes of its text, so twice the count is about twice what the model reads; whether an API charges more for more results is its own pricing.

The count is set in Settings › Models › Web search ("Results per search", #searchCountRow, 3, 6, 10, 15 and 20 offered, and a count set by hand in settings.json too) through POST /api/settings/search-count, which a save of the page keeps (settingsapi.Apply), and by magpie search count [<n>|default]. Save refuses one out of range. Tests: TestSearchCountSetting, TestSearchCLICount, TestSettingsSearchCountSetOnItsOwn and search-count.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, /v1/tools/search, /search_api/web_search, /SearchPro, TinyFish's root /; SearchVendor.Paths) with the slash at its end trimmed. A URL given ending in that path (…/search for Tavily, any case) is its base: SetSearchAPI saves it without the path, and SearchAPI.Base drops it from one saved with it before, so it is asked once, never /search/search (plugins#509, TestSearchAPIBaseURLWithItsPath). A base of the user's own that itself ends in that path can't be set. 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. Every request sent with a provider's credential has the same rule: the gateway's client, Provider.Do through whichever client it is given (provider.Keyed), the provider package's own reads (usage, balance, models, sign-in refreshes), the Codex relay and a plugin's fetch in the plugin host (followed in host.js, see provider plugins) follow a redirect only to the request's origin, or from http to https on its host (provider.KeepsCredentials in redirect.go). Go would follow one anywhere, https to http included, and keep x-api-key, x-goog-api-key, api-key and a provider's own headers on it, and Authorization too when only the port differs. A redirect elsewhere is the answer, a 3xx the route reports as the vendor's failure. No vendor magpie speaks to redirects its API to another origin; a file a vendor answers by URL is fetched unsigned, by vendorClient. TestRedirectKeepsTheKeyAtItsOrigin, TestRedirectNeverDowngrades, TestNativeRedirectKeepsTheKey, TestChatRedirectKeepsTheKey. 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.

A search API a plugin gives

A plugin's search hook adds search APIs under the id <plugin>:<id> (provider.AllSearchVendors; plugin-tools). askSearchAPI hands one to askPluginSearch, so the keys, their rest after a 401/402/403/429 (SearchRefused), the listed order, the switch, the masked query and the request-log row are the built-ins' own, and the plugin is asked only while it is on. A plugin API has no Base of its own: its URL field shows only when the plugin declares url: true, and then is required. Its pages are cleaned like a built-in's (searchPlain, clipText, six at most). It is asked with the time left of a quarter of the search's limit, and plugin.RunSearch returns when that is out, though the plugin's own fetch may run on until the host's abort reaches it. TestPluginSearchAPI.

The search APIs' order, and one switched off

provider.SearchAPIs gives the search APIs in their saved order, the order apiSearch asks them in, leaving out one not ready and one switched off (SearchAPI.Off, #2286). Added, one goes last. ArrangeSearchAPIs puts them in the order of the vendors named; one not named keeps its place after them, and a vendor not set up or named twice refuses the whole order, so an order sent from a page drawn before one was removed changes nothing. SwitchSearchAPI sets off and keeps the key, URL and place; SetSearchAPI (a new key or URL) leaves off as it was. An API switched off is never asked, by a model's search or by the search MCP, and with every API off, Settings' Search first with row is gone as with none at all. Backup and sync carry off and the order with the rest of the entry: a restore (RestoreSearchAPIs) puts the backup's APIs in the backup's order, one only here after them, and a backup made before off turns every API on.

In Settings › Models › Web search each API's row and its keys' row move as one (.search-unit, searchArrange): dragged by any part of it off its buttons and fields (dragRows, as routing's groups are, #779) or moved a place with Alt+↑/↓, the rows renumbered at once; an order that can't be saved is drawn again as saved. A switch on each row sends {vendor, on}; one off is dimmed and says Off. On the CLI, magpie search off <api>, on <api> and move <api> <n> do the same, and magpie search lists one off as off. POST /api/settings/search-api takes {arrange: [vendors]} and {vendor, on} beside the add and remove it took before.

Covered by TestSearchAPIOrderAndOff, TestSearchCLIOffAndMove, TestBackupSearchAPIsOrderAndOff and search-order.test.cjs.

Asking several search APIs together (mix)

Two or more search APIs marked mix (SearchAPI.Mix, #2845) are asked first, at once (askSearchAPIsTogether), each with its own keys and timeouts as when it is asked alone (askSearchAPIKeys). Their pages go to the model in turn (mixedPages): each API's first in the saved order, then each one's second, a page an earlier one gave left out by its address (pageKey: host in lower case, http and https alike, without fragment or closing slash), at most searchMixMost: two APIs' worth of the count the search asks for (the one it named, else Settings' results per search, 6 by default, so 12), never more than 20. One that fails or finds nothing leaves the others' pages; when none finds anything, the APIs not mixed are asked in order as before. With fewer than two mixed APIs on and ready, a search goes in order as if none were. Nothing is added to the pages to say which API found them, so the text a vendor sees reads as before. MixSearchAPIs marks the vendors named (two or more, set up, each once) and clears every other; none clears all. SetSearchAPI keeps the mark, and backup and sync carry it with the rest of the entry. A mixed search spends every mixed API's quota, takes as long as the slowest, and gives the model up to twice the pages (20 at most). On the CLI, magpie search mix <api>,<api> and magpie search mix off set it, and magpie search lists a mixed one as mix. Settings' page doesn't show or set it yet.

Covered by TestSearchAPIsMixedAskedTogether, TestSearchAPIsMixedOneDown, TestSearchAPIsMixedAllDownAsksTheRest, TestSearchAPIsMixedCapped, TestMixSearchAPIs and TestSearchCLIMix.

A search API's keys

A search API's key may hold several keys, separated by commas (#1477). askSearchAPIKeys asks them in the order searchKeyOrder gives (search_keys.go), each with a quarter of the search's time. By default they take turns (SlouchyQuill on Discord, after dsh-tavily-pool): a counter per vendor moves the first key asked on by one each search. pick order (provider.SearchPickOrder, magpie search add … pick=order, In order in Settings) always starts from the first. Only a refusal (searchRefused: 401, 402, 403, 429, 432, 433) goes on to the next key; any other error ends the search there.

A refused key rests (searchRestFor): 401 and 403 ten minutes ("turned away"), 402 an hour ("out of credit"), a rate limit its Retry-After held to 30 seconds through 10 minutes (a minute without one). 432 and 433 are Tavily's plan and pay-as-you-go limits, out of credit from Tavily only; from any other vendor they rest as a rate limit. Doubao Search (Volcengine) says its error in ResponseMetadata.Error, possibly with a 200, so volcSearchError reads it by its code first: 10401, 10403 and 10409 as 403, 10406, 10408, 10410 and 10412 (no free searches left, none paid for, a plan missing or spent) as 402, 700429 as 429; any other code is a plain error (TestVolcengineSearchAPI). Yuanbao Search (Tencent Cloud, wsa) answers 200 to every request it handled, its error in Response.Error.Code, so wsaSearchError reads the code: AuthFailure.*, UnauthorizedOperation (a wrong key) and ResourceNotFound (the service not opened) as 403, ResourceUnavailable (an account in arrears), LimitExceeded and ResourceInsufficient as 402, RequestLimitExceeded.* as 429; any other code is a plain error (TestWSASearchAPI). TinyFish says its error with its status (401 a wrong key, 402 INSUFFICIENT_CREDITS once the day's free searches are spent with an empty wallet, 429), read as any other API's (TestTinyFishSearchAPI); it takes no count and answers one page of about 10, cut to the count. A resting key is not dropped: it is asked after every key that isn't, the one back soonest first, so a search still has every key to fall back on. A key that answers wakes. Rests are held by vendor and a hash of the key (searchKeyID), never the key itself, and the vendor's error has the key masked (provider.MaskSearchKey, tvly-…abcd) before it is logged or returned.

The query a search API, a Kimi Code plan's or GLM Coding Plan's search service or WorkBuddy's search is asked is masked as Settings → Privacy says (maskedQuery in redact.go; a plan set to go unmasked, provider.SkipsRedaction, gets it as it is). A searcher model is asked through serve, which masks its request the usual way. An agent's call to the search MCP carries its query with the values put back, so before this it went out as the agent wrote it (lc on Discord); searchMCPRun puts the values back in what it returns (redact.Restore). What a model's own web_search finds goes back to its vendor as found, placeholders and all.

What each Tavily key has used is read from GET /usage with that key (search_quota.go, readTavilyUsage): the key's own limit when it has one, else its account plan's plan_limit and plan_usage, shared by the account's keys (a free account's keys have limit null); both null is no limit. A read that fails or a reply missing those fields is unknown, with why, never 0 used. A read is kept two minutes (Tavily allows /usage 10 times in 10 minutes) unless asked fresh. A key at its limit with no pay-as-you-go credit left rests an hour as "used up"; a later read that finds credit wakes a key resting for that or for being out of credit. magpie search lists each key's use, read fresh.

The keys as a list

Settings › Models › Web search shows an API's keys as a list under it (辰林鸭~ on Discord), as a provider's accounts are: each key masked on a row of its own with a tick that switches it off or on, Show, Copy and Remove, one or several added at once (split by commas, semicolons or lines; the reply says how many were new and how many it had), and the order changed by dragging or Alt+↑/↓. A key resting says why and until when on its row ("asked last until 14:05: rate limited"), from SearchKeyRest and SearchQuota.Ref; with Tavily's quota, what it has used is beside it, and In turn / In order and Check again sit on the row.

The list is provider.SearchAPI.SearchKeys() (search_api.go). Key stays the keys that are on, comma-joined, so the gateway (a.Keys()) and an older magpie never ask one switched off; keyList is written only while a key is off, and with every key on the file is as before. A Key that differs from the list (written by a magpie that knows no list, or synced from one) wins: its keys are on in its order, a key the list had off and it doesn't name stays off after them. The last key on can't be switched off or removed from the list. The GUI names a key by SearchKeyRef (a hash), never by its value: POST /api/settings/search-keys takes add, ref with on or remove, or arrange, and /api/settings/search-key reads one key by its ref for Show and Copy. Saving an API with no key (a new base URL) keeps its keys, off ones too; a key typed in the API's own field replaces the list, every key on. Backup and sync carry the keys switched off with the rest, or drop them with the rest when keys are left out.

Covered by TestReadTavilyUsage, TestSearchKeysTakeTurnsRoundRobin, TestSearchKeyRefusedRests, TestSearchRestFor, TestSearchQuotas, TestSearchKeyNeverInFull, TestSearchAPIKeysTakeTurns, TestSearchKeyOffAndWhyItRests, TestSearchKeyList, TestSearchKeysKeyWins, TestSearchKeyListFromSettings, TestBackupSearchKeysOff, TestSyncSearchKeysOff, search-keys.test.cjs and search-key-list.test.cjs.

A search API's asks in the request log

Each ask of a search API with one key is a row of the request log (cybercaius on Discord: which search API a search used couldn't be seen). logSearchAPI in search_api.go writes it after every askSearchAPI in askSearchAPIKeys, a refused key and the next one each a row: Source search (usage.SourceSearch), Kind web_search, the agent the search was for (searchFor's CallFor.Agent, else magpie), the API's name as Requested, its host, the key as searchKeyID and masked (provider.MaskSearchKey), how long it took, and how it ended: 200, the API's status when it refused the key, the error, or "found nothing". Provider stays empty: deepseek is a provider's id as well as a search API's. The query is never kept: the error is cut to the transport's own error and host when Go's says the URL (an API asked by GET carries the query there), and the query, plain or escaped, is taken out of what the API said back.

The rows ride the probes' lane (IsProbe): listed under the Web search purpose and found by the API's name in the search box, counted in no total, budget or provider share, and never exported (observeLedger), so telemetry, which reads no usage row, has nothing new to send. The Usage page's Requests tab badges one "Search API" with the host and masked key where the provider goes. A searcher model's request is a model row of its own, as before. A plan's own search service (Kimi Code's, a GLM Coding Plan's, WorkBuddy's: ownSearch, through logOwnSearch) is a row the same way, under the plan's provider id and name, badged "Web search".

Each such ask is on the Routing page and in Recent calls too, with its exchange in the request archive when that is on (axelburks on Discord: the Routing page didn't say which API answered, and the row had no archive). logSearch calls keepSearch in search_archive.go before the row is written: a done route, agent magpie with For the agent the search was for, Kind web_search, the API's or service's name as the model and its host (a plan's provider id) as the provider, its seat the masked key or the account. The row gets the route's id (RouteID) and the archive's name (Archive), which the Requests tab opens. Each ask runs with a searchWire in its context (withSearchWire, one per key or account); the place that sends it fills it (tapSearch: the request as signed, its body, and the answer as it is read, the last exchange standing, so GLM's MCP search keeps its tools/call). A plugin's search API is noted as magpie handed it to the plugin (notePluginSearch, method PLUGIN, the key masked) and what came back. The key an ask went with is replaced with its masked form in the path, query, headers and both bodies before anything is kept (taken), and the archive's own scrub takes Authorization and the like out as for every call. Bodies are kept up to RequestArchiveMaxMB (a longer answer is marked cut) and Recent calls keep their own 256 KiB; with the archive off nothing is archived, but the route and Recent call are still there. Covered by TestSearchAPIAskIsRoutedAndArchived, TestSearchAPIKeyInQueryNotArchived, TestPluginSearchAPIRoutedAndArchived, TestKimiPlanSearchRoutedAndArchived, TestGLMPlanSearchArchivesItsToolsCall, TestSearchRowKeepsRouteAndArchive (internal/gui), usage-ledger-search.test.cjs and routing-side-calls.test.cjs. Not covered: web_fetch (search_fetch.go) and a vendor's own search (search_native.go), which magpie doesn't send.

A search a provider's model runs with its provider's own tool is a row the same way when its reply shows it (cybercaius on Discord: DeepSeek searched and Usage showed nothing). searchTally in search_native.go counts Anthropic's server_tool_use blocks named web_search (DeepSeek's Anthropic API answers them too) and usage.server_tool_use.web_search_requests, and the Responses API's web_search_call items: what a stream named as it went (a block's start, an item done, by id), what a whole reply or the stream's end listed, and what the usage said are counted apart, and the most of them is the count. The usage sniffer of a relayed reply and both translated readers feed it (Usage.searches), and after the request's own row logNativeSearches writes one row a search, at most 20: Source search, Kind web_search, the request's agent, provider id, host and model, status 200, no query and no time of its own. An event is parsed for it only when it holds server_tool_use or web_search_call. A provider whose reply doesn't show its searches (a Chat API's model that searches inside, with nothing in the reply but text) has none to show, and DeepSeek's Chat API has no search tool at all.

Covered by TestSearchAPIAsksAreLogged, TestSearchAPIFailureKeepsNoURL, TestOwnSearchIsLogged, TestWorkBuddyPluginSearches, TestSearchAPIRowsListedNotCounted, TestOwnProviderSearchesAreLogged, TestSearchRowsListTheirPurpose and usage-ledger-search.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).

Its second tool, web_fetch (search_fetch.go, #2286), reads a page by its URL for an agent with no fetch tool of its own. The URL is the agent's, so it is downloaded as a caller's image is (webFetchClient, which is publicClient): public addresses only, every resolved address checked and pinned, through at most five redirects each checked the same, wherever the request came from (a name a fake-IP resolver answers in 198.18.0.0/15 is read through its TUN or a proxy on this computer, as an image is: see the guard below, #2593). It reads for at most 30 seconds and 5 MiB. An HTML page is decoded from its charset and given as Markdown (htmlText: headings, lists, links made absolute, code; scripts, styles and hidden elements dropped), other text as it is, anything else is a tool error, and so is a status of 400 or more. It answers max_chars characters (20000 by default, at most 100000) from offset, and says the offset the rest starts at. Each call reserves the calling key's limit as a search does. TestWebFetchReadsAPage and TestWebFetchOnlyPublic.

A POST's body is read by readMCPBody, up to 1 MiB here and 32 MiB for vision and for a signed-in server's /mcp/{name}. A longer body is refused whole with 413, before any message in it runs or is passed on: the length is told from the bytes read, one past the limit, not from Content-Length, so a valid message padded past the limit is never run as its prefix (#1766). TestOwnMCPRejectsOversizedBody and TestMCPProxyRejectsOversizedBody cover it.

Covered by TestSearchMCPServesWebSearch, TestSearchMCPWithNoSearcher, TestSearchMCPGuarded, TestSearchMCPHeldToKeyLimit, TestSearchMCPRoutedAsTheAgentsCall, TestSearchQueryMasked and search-mcp.test.cjs.

A model that turns an image away

Whether a model sees is its provider's list's word (ImageInput), else the served entry's (blindTo), and a list that says nothing takes models.dev's modalities for the model (catalog.SeesImages). A list's modalities are read as models.dev words them (catalog.Kinds): OpenCode Go's /models names media types (image/jpeg, video/mp4, application/pdf), which read word for word held no image, so every Go model was text-only (zeo9901 on Discord); a list saved that way is mended when read (mendKinds). A relay's copy of a model can take text only where models.dev says it sees: xyenon (Discord) picked provider-1/DeepSeek-V4.1-Flash in pi with Image recognition set, magpie sent it the raw image, DeepSeek answered 400 "unknown variant image_url", and since that reads as a shape refusal (shapeWords) the request went on to the fallback, the same model at provider-2, which sees. The image was never described.

A 400, 415 or 422 whose words say images aren't taken (imageRefused: unknown variant image_url/input_image/image, OpenAI's "only supported by certain models", OpenRouter's "no endpoints found that support image", vLLM's "not a multimodal model", 不支持图片 and the like) now marks the model blind for the server's run (refuseSight, Server.blind; blindTo checks it first). With a describer (seer), the same candidate is asked again at once with the images described (seenBody, or the group's seenGroup; the try's failure is failSight), before any fallback or other member, and later requests are described up front, for a direct pick and a group alike. The pick and the describer the user set win over another provider's copy of the model.

With no describer (Image recognition off, or nothing that sees), going on to a candidate whose copy sees is the only way to answer, so that is kept on purpose (TestRefusedImageWithNoDescriberGoesToOneThatSees).

Covered by TestPickedModelThatRefusesAnImageIsGivenItDescribed (direct, user group and auto group, over Chat, Responses and Messages) and TestImageRefused (vision_refused_test.go).

An image the describer can't describe

seer names one describer, and before kelvinjason11 on X ("图片识别好像只支持一个模型识别 没有fallback") that was the only one asked: when it failed (a 5xx, out of its allowance, a timeout, an image it turned away, an empty answer) the latest turn's image failed the request, though other models that see were enabled. describe now asks through describeWith: the describer first, always, and when it fails, the next model that sees, as AutoVision ranks them (seersRanked, the ranking autoVision takes its first from), passing over the models already asked and any that turned an image away (sightRefused). Up to visionTries (3) models are asked, within visionWaitMost all told (each try is given what is left, askVisionWith's most). A model out of its allowance is not asked in another's place: seersRanked puts those last, so the first being out means every one is. A request whose context ended (the agent canceled it) asks no other.

  • The description's header names the model that described it (seenBody, sight.by).
  • The Routing row of a description asked in another's place carries CallFor.Instead (the one asked before it), Why (its error) and Picked (it was Settings' pick), and says so (kindWhy), as a search in another searcher's place does. Each try is a row of its own.
  • When none answers, the error is the first's reason as before, then "nor could X, asked in its place: why" for each other one (visionFailed).
  • sights keeps a description under the image (sightKey): a base64 data URL's decoded bytes, else the URL, with the level picked in Settings. Not under a model: the image sent again next turn is asked of no one, whichever model is picked now (AutoVision's pick changing between turns had a long conversation's every image described again, Pkh on Discord), and a new image is asked of the pick first again, so a pick that failed once is not given up for good. The same bytes sent on another protocol, or under another media type, are described once (seenBody dedupes by the key too). A failure is still not kept.
  • Completed descriptions of inline images are also appended to vision-cache.jsonl in magpie's config directory before their waiters are released (saveSight), and restored by New. A restart or update therefore doesn't describe a conversation's history again. Only inline images are persisted: their keys come from their bytes, while a URL can later name different bytes and stays process-local. The private (0600) file keeps the same 2048-entry LRU on reload; a JSON-malformed or crash-truncated record is skipped without hiding the other records, and is copied to a private .broken-* file before a later compaction drops it. An inline description is counted from its creation until it has saved or failed; gateway shutdown waits for that count to reach zero, so a canceled request's completed description isn't lost on exit. Appends and compaction are serialized across gateway processes by vision-cache.jsonl.lock; compaction rereads the latest file under that lock before atomically replacing it, so a handover can't overwrite another gateway's new record. A lock or disk-write failure only loses the persistence optimization, never a description that already succeeded.

This differs from a searcher named in Settings, which gives way to no other provider: a failed search still leaves the search APIs and the model's own answer, while an image that isn't described fails the turn.

Covered by TestPickedDescriberThatFailsGivesWayToTheNextThatSees, TestAutoDescriberThatFailsGivesWayToTheNext, TestNoDescriberAnswersNamesEach, TestPickedDescriberThatAnswersIsTheOnlyOneAsked, TestCanceledDescriptionAsksNoOther (vision_fallback_test.go) and vision-instead.test.cjs.

A description is no one request's

A description is asked once (describe) on a context of its own (context.WithoutCancel of the first asker's, with its own cancel): every request that sends the image while it is being described waits on the same one (sight.waiting). One whose agent cancels it stops waiting; the description goes on for the others, and only the last to go stops it and takes it out of sights, so the next to send the image asks again. Before, the description ran on the first asker's context: its cancel failed the description for every other request waiting on it with "context canceled", and took it out of the cache, so the next turn read the image again. A reply that came whole is kept though its asker ended as it came (askVisionWith reads the reply before the context). Once the model has answered, sight.answered also keeps cancellation from stopping the save: a completed inline description is written before its waiters are released, even if the last waiter left during that write.

In seenBody, an image waiting for one of the visionParallel slots when its request ends is asked of no one: before, each queued image went on to serve with a dead context, and one canceled request put a row for each image on the Routing page in a few ms (Pkh: 63 in ~60ms).

A description's serve runs on its request's context, so its route is noted on that request's inflight (noteRoute) and stands in for it on the Routing page while it waits; when the images can't be described, the request is given a route of its own, ended 499 when its agent canceled it and 502 else (notDescribed), and its usage record names it. One magpie answered for, held too long (giveUp), keeps the route that showed it. A routing group's request, routed already, ends 499 too when its agent canceled it.

Covered by TestSameImageDescribedOnceWhateverDescribesIt, TestOneRequestGoneLeavesTheDescriptionToAnother, TestCanceledRequestAsksNoMoreDescriptions and TestCanceledWhileDescribingKeepsItsRoute (vision_dedupe_test.go). Restart reuse, cancellation during a save, failed writes, truncated records, cross-Server compaction, duplicate records, the LRU and URL behavior are covered by TestDescriptionSurvivesGatewayRestart and vision_cache_test.go.

Image recognition as an MCP server

VisionMCPPath, /mcp/magpie/vision, serves the model that describes images to a model that can't see them (seer: Settings › Models › Image recognition, else AutoVision's) as an MCP server with one analyze_image tool (JonahFu on X). serveMCP is shared with the web search server, so it is answered, guarded and Origin-checked the same way, with a 32 MB body so an image fits as a data URL, and each call reserves the calling key's limit (budget.Reserve). The tool takes image and an optional prompt. With no prompt it is described as a model's image is (describe, the same cache and visionSystem); with one, describeWith asks the prompt beside it under visionAskSystem, with the same fallback as a description (see "An image the describer can't describe"). image is an http(s) URL or a data:image/…;base64, URL, passed on as they are, or an absolute file path (~/ and file:// taken), read into a data URL up to 20 MB when http.DetectContentType says it is an image. A path is read only for a local caller: another machine's path names nothing here, a shared magpie's files aren't its callers', and a request through a proxy or tunnel isn't local. The description's route is marked CallFor{Agent, MCP: true}, so Routing says the agent called analyze_image. Image recognition off or no model that sees is a tool error that says where to pick one. Settings › Models shows the address (#visionMcpRow, below Image generation).

Covered by TestVisionMCPAnalyzesImage, TestVisionMCPWithNoSeer, TestVisionMCPGuarded, TestVisionMCPHeldToKeyLimit and vision-mcp.test.cjs.

Image generation as an MCP server

ImageMCPPath, /mcp/magpie/image (image_mcp.go), serves Settings › Models › Images › Image generation as a Streamable HTTP MCP server with the tools the stdio Magpie Image server has (internal/imagemcp): generate_image, generate_video and generation_result (JonahFu on X: magpie in Docker in gateway mode has no Library, so no stdio server). Their schemas are the gateway's ImageToolProps, VideoToolProps and ResultToolProps, which the stdio server takes too, adding only its path argument. It is served by serveMCP, so it is guarded as the vision server is: local or a shared magpie's caller, a refused Origin 403, POST only, a 32 MB body, and each call reserves the calling key's limit. An input image goes through mcpImageSrc, the vision server's reader: a URL or data URL as it is, a file path only for a local caller.

A drawing runs images in-process on a clone of the request (inProcess, the caller and key kept), so it is routed, counted and held to the key's models as /v1/images/generations and /v1/images/edits are. It runs as a job under context.WithoutCancel for at most 15 minutes; the tool answers within 20 seconds, else with an id that generation_result waits on. Each image comes back as MCP image content (up to 5 MB each) and at a URL under /mcp/magpie/image/files/ (a vendor's URL is fetched first). The file store is in memory, kept an hour and 256 MB at most, oldest first out. A file and a job belong to the gateway key that made them: another key gets 404 (KeyID). The URL handed out carries ?t=<exp>.<sig> (imageFileToken: HMAC-SHA256 of the file's name, its expiry and the making key's id, under a secret made at the first file and kept only in memory), so it opens with no header, in a browser too (dhanyqaz on Discord: a model relays the link to a person). lanGuard lets a keyless GET or HEAD of a file with a t through (imageTokenAsked) after the allow list and sharing are judged, and imageMCPFile serves it only when the token is that file's, unexpired, and its key still on (access.On); anything else is the 401 a keyless request gets. A wrong key with a token is still 401, a page's Origin still 403, and the token names neither the key nor its id. Rotating the key keeps its id, so its links stay good for the rest of their hour (they never held the secret); turning it off or removing it ends them at once. The URL's base is MAGPIE_PUBLIC_URL when set, else the request's scheme and Host. A video is started through videosCreate and polled through videosGet in-process; when done the tool gives /v1/videos/<id>/content, which needs the same key. Image generation Off (settings.ImageGen == "off") is a tool error that says where to pick a model, checked before the arguments. Nothing is written into the agent's project. Settings › Models shows the address (#imageMcpRow, below #visionMcpRow).

generate_image and generate_video take an optional model (XYenon on Discord), in image_mcp_models.go. mediaModels lists what may be asked, as provider/model: Settings' default first (Drawer, videomaker), then each provider's OfferedDrawers (a model the user unticked is left out) or OfferedVideomakers (likewise), from providers that are on and not decide-only. mediaModelsFor keeps only those the calling key may use (refAllowed: allows, or groupAllowed for a group ref). The schema's model is an enum of them, or, past 40 (mediaEnumMost), a description naming three. pickMediaModel takes a listed ref (a ChatGPT account's other GPT Image name through ListedDrawer), a bare id only one provider has, or a newer model of a family a provider serves (drawsFamily, grokVideoFamily). Anything else is a tool error that names the models the key may use, and nothing is drawn. Left out, Settings' default is used, as before. The model chosen is put in the request's model, so the images and videos APIs' own key check (keyHolds, keyModelError) refuses one the key may not use, the same check /v1/images makes. The stdio Magpie Image server can't read providers (WSL, a gateway elsewhere), so it copies the gateway's model property from this server's tools/list and asks the JSON-RPC method magpie/media_model (MediaModelMethod; not a tool) which model one asked for stands for. An older gateway's -32601 passes the model through as named. Covered by TestImageMCPDrawsWithTheModelAsked, TestImageMCPModelHeldToTheKey, TestImageMCPVideoModelAsked and imagemcp's TestGenerateTakesTheModel.

Each answer also carries _meta for a client that acts on it rather than reads it: usemagpie.ai/pending is the id to wait on (PendingMeta, beside the text that says to call generation_result), and usemagpie.ai/files lists each file made (FilesMeta, MadeFile: its URL, and inline when the image is in the content too). magpie tool (tool_cli.go) is such a client: it lists and calls the tools of every server in OwnMCPServers (image, vision, web search, plugin tools) over HTTP with the local token and the magpie-tool/1 User-Agent, waits on a pending id, and saves the files (imagemcp.Target names them, never over a file). It starts nothing of its own (#3318) and refuses an unknown or missing parameter before calling. Covered by TestToolDrawsThroughTheGateway (the real gateway, a fake vendor) and the other TestTool* tests.

Covered by TestImageMCPDrawsAndServesTheImage, TestImageMCPSaysWhenOff, TestImageMCPGuarded, TestImageMCPHeldToKeyLimit, TestImageMCPSlowDrawingIsWaitedOn, TestImageMCPMakesVideos, TestImageMCPMakesMiniMaxVideos, TestImageMCPIsServed and image-mcp.test.cjs.

Which of magpie's own MCP servers are on

GET /v1/magpie/mcp (OwnMCPPath, own_mcp.go) lists the MCP servers above that are on now, as {"servers":[{"name","title","path"}]}, each named as its initialize names it, with its path on this gateway. It is for an app that gives a model the Library's servers and wants magpie's own beside them: the community chat page's "use all of magpie's MCP servers" read only library.json, so web search, image recognition and image generation never reached its chats (ferock on Discord). A server is listed while an agent mounting it would get working tools: magpie-web-search while plugins/search serves and something searches (canSearch, so Off in Settings › Models › Web search with no search API leaves it out), magpie-vision while a model sees (seer, not Off), magpie-image while a model draws (drawer, not Off), and magpie-tools while plugins/tools serves and a plugin that is on gives a tool (plugin.ToolsOn; a note that can't be read lists it, and its tools/list tells). The list holds no secret, so a read-only gateway key may read it (readOnlyRoutes); the route is otherwise guarded as every /v1/magpie/* route is, and a caller mounts each path with the same key it called with. OwnMCPServers is the fixed list magpie tool walks; this one follows the switches. Covered by TestOwnMCPNoneWhenNothingIsOn and TestOwnMCPLists*WhileOn.

Side models magpie picks: allowance first

When magpie picks the model itself (AutoVision for image recognition, autoSearcher and the turn in modelSearch for web search), it picks before routing runs, so routing has one provider to try and would try it "all the same" while every account of it rests. Each request would then be refused upstream again (#1801). spentModel (fallback.go) says a model is out of its allowance when every candidate routing would try for it is barred at a usage cap, resting for quota or credit (not for rate), or has a full window (candidate.full), and when it is back. smallModel (smallReady) prefers models that aren't spent, and the pickers rank a provider with allowance above any tier or searchRank. With every one spent they still name a pick, so seer/Described and canSearch, which tell agents what magpie offers, don't flip with a window. Such a pick isn't asked: askVisionWith (autoSpent) answers with the reason and when it is back, and modelSearch (searcherSpent) skips it, puts spent searchers after the others and joins the reason into its error. A model named in Settings is asked as before (an image it can't describe goes on to the next model that sees, see "An image the describer can't describe"), and a searcher named there is not handed on to another provider when it fails (see "A searcher that fails or finds nothing"). Image and video generation (AutoDrawer, AutoVideomaker) are not held this way.

Covered by TestAutoVisionPassesOverOneOut, TestAutoVisionTierAmongThoseWithAllowance, TestSpentModelAcrossAccounts, TestVisionDoesNotAskSpentDescriber and TestSearcherPassesOverOneOut.

Hidden image models

A provider's editor lists its image models (gateway.Drawers, the drawIds of /api/providers) apart from its chat models, each ticked. Unticking one saves its id in provider.HiddenDrawers (providers.json, and an account's picks entry through withPicks). It is a deny list beside Models, not an entry in it: an image id in Models would be offered to agents to chat with, and the allow list would make hiding one picking every chat model by hand. A Save that leaves hiddenDrawers out keeps the old list; [] ticks them all again.

gateway.OfferedDrawers is Drawers less the hidden ones. It is what lists image models to pick from or picks among: AutoDrawer, drawerObjects (another magpie's X-Magpie-Drawers list) and Aside's image options. Settings › Models › Images (settingsState) leaves them out too, except the one picked there. A hidden model still draws: resolveDrawing and drawingModel read Drawers, so a request that names one, or a Settings › Models › Images pick made before it was hidden, draws as before. That pick stays listed as picked, and imageGenHidden puts a line under the row that it is unticked and leaves the list once another is picked. Refusing a model outright is Disabled models, below.

The editor shows each image model by its name where it has one (drawNames), with the id as the chip's tooltip: a ChatGPT account's gpt-image-2, the id Codex CLI asks for, is its one GPT Image, since its backend draws with the model it picks whichever is named (#1865; StarBits on X read the id as an old model). Unticking it still saves the id.

AutoDrawer never picks a GPT Image that a newer one set up supersedes (gptImageGenOf: by version, gpt-image-2.6 over 2.5 over 2, unversioned dall-e and chatgpt-image-latest under them all; then the base or Sunburst over Flare over mini). An OpenAI key's list names 2.5 and 2.6 with no price while models.dev prices gpt-image-2, so cost alone took the old one. A GPT Image with no price is costed as the newest priced one, as OpenAI prices them alike. A ChatGPT account's GPT Image is never superseded, as its name says nothing of what draws, so the plan's images stay Automatic's choice. Another kind of model that costs less is still the cheaper choice. TestAutoDrawerTakesNewestGPTImage, TestAutoDrawerKeepsChatGPTsOwnPick, chatgpt-image-chip.test.cjs.

Video models are listed the same way, under Video models (axelburks on Discord: an Ark key's Seedance had nowhere to be ticked). The editor's filmIds are gateway.VideomakersOf the listing it already has, and an unticked one is saved in provider.HiddenVideomakers, kept and cleared as hiddenDrawers is. gateway.OfferedVideomakers is Videomakers less the hidden ones, read by AutoVideomaker, videomakerObjects and mediaModels(true). A hidden one still makes its video when named: bareVideomaker, videosCreate and arkFilms read Videomakers.

Settings › Models › Images › Video generation (#videoGenRow, under Image generation, gone while that is Off) picks the model a video request that names none is made with, the Magpie Image MCP's generate_video and /v1/videos alike (Discord #feedback: a custom provider's model marked a video model by hand was made with only when Automatic happened to take it). settings.VideoGen holds a provider/model or a group ref; videomaker takes it while VideomakerMissingOf finds it among its provider's Videomakers (on, not decide-only; a group through mediaGroupFirst), and AutoVideomaker otherwise. A save of a model that makes no videos is refused (settingsapi), a save that doesn't send videoGen keeps it, and a pick that stops making videos is videoGenMissing: the row says so and Automatic makes them meanwhile. The list (videoGenModels) is every Videomakers model of such providers, a hidden one only when it is the pick. With none, the row says how to mark one (right-click in the provider's Model settings, Makes › Video model; kept in sight), with a Providers › link to that page. The row is drawn by videogen.js, imported when Settings draws Image generation, so it weighs nothing on the core. TestVideoGenPicksAMarkedModel, TestVideoGenCheckedAndKept, TestVideoGenModelsListed, video-gen-pick.test.cjs.

An Ark key's list marks its video and image models by domain (VideoGeneration, ImageGeneration) and modalities.output_modalities, with no kind; catalog's live parse reads both, so Seedance is a video model there and no longer a chat model, and 3D, embedding and other models that give no text are left out (TestFetchArkMarksVideoModels, on a captured list). An Ark list fetched before has Seedance among its chat models until the next fetch; customVideomakers still counts any Seedance id an Ark key lists or picks as a video model.

Covered by TestHiddenDrawerLeavesListsButStillDraws, TestImageModelsHidden, internal/gui/tests/image-models-hide.test.cjs, TestHiddenVideomakerLeavesListsButStillFilms, TestVideoModelsHidden and internal/gui/tests/video-models-hide.test.cjs.

Disabled models

Settings › Models › Disabled models, magpie model disable|enable|disabled and POST /api/settings/disabled-models keep settings.DisabledModels (#1867): patterns, each an exact id or a glob (* any run of characters, / among them; ? one), matched ignoring case against a model's <provider>/<model>, its bare id and the bare id's last segment (internal/provider/disabled.go). Nothing is disabled by default.

  • Lists: buildEntries (entriesOff) leaves a disabled model out of the catalog, so /v1/models, the agents' model files and pickers, Codex's list, Muse and every routing group go without it; membersIn (membersOff) skips it as a member and Deciders as a decision model. codexModels drops a disabled one of Codex's own, and codexListTag changes with the list so Codex fetches it again.
  • Requests: the gateway refuses it with a 403 in each API's shape (internal/gateway/disabled.go), model <id> is disabled in magpie …, at the choke points #882 holds keys at: serve (every chat, Responses, Messages and Gemini request, magpie's own side calls, a session that was on it, a Codex sub-agent put on it), perKeyBarred (no candidate is planned for it: a group's next member, a provider's Fallback), countTokens and Gemini's :countTokens (countOff), serveSystemOne, serveDecisionGroup and postDecide (every decision call), draw, video and embeddings, and codexBackend for one of Codex's own bare models. A bare id the catalog no longer has is refused as disabled, not 404 (provider.BareDisabled). A group with a member left goes on without the rest; one with none left is refused, naming its disabled members (provider.GroupDisabledOut). A Codex sub-agent pick onto a disabled model is kept on its lead's model (codexSubagentPick, "it is disabled in magpie").
  • A settings.json that can't be read is never "none disabled": the list read last stays in force, and with none read since start every request is refused until it is fixed (DisabledUnknown); SetDisabledModels writes nothing over a file it couldn't read.
  • Only requests through magpie are covered: an agent signed in to the vendor itself is not, which the Settings row says.
  • Tests: TestDisabled* in internal/gateway, internal/provider, TestModelDisableCmd, TestDisabledModelsSetting, and internal/gui/tests/disabled-models.test.cjs.

Model ids without the provider

A client moved from another proxy (love1sbug on X, from CLIProxyAPI) keeps asking for gpt-5.6-sol, and picks from /v1/models, where magpie lists only codex/gpt-5.6-sol. A bare request already routes (Model resolution, above); the list didn't offer it. "Provider in model names" (PlainNames) changes labels only, never ids.

Settings › Network and sharing › Model ids without the provider, POST /api/settings/bare-ids (settings.BareModelIDs, provider.SetBareModelIDs), off by default. On, models lists every row it listed before, unchanged and first, then one row per bare model id (provider.BareEntries, internal/provider/bare.go): the row of the entry that id reaches, with its label, under the bare id. GET /v1/models/{id} answers a bare id the same way (provider.BareEntry).

  • Which entry: the gateway's own resolution, so the list never offers what a request would not reach. A found or user group the id names (groupForIn, as GroupFor) gives the group's row; else resolveIn (as Resolve) gives the first provider in the Providers order that serves it. So a model several providers serve is listed once, and answered by its group with found groups on, else by the first provider, as before. The list is not per agent: an agent whose own subscription serves the id is answered there (ownFirst, see Model resolution), and with found groups off an agent with a subscription of its own is refused an id several other providers serve (provider.OffSpread).
  • An id already in the catalog as is (a group's or a provider's own id) is not listed twice. Group rows themselves add nothing.
  • The target must be in the list shown: a gateway key held to some models sees only the bare ids that reach one of its models, so a key held to b/* doesn't see glm-5.3 that would go to a.
  • Never for another magpie (DrawersHeader), whose remote provider would list each model twice, nor for Claude Desktop's list, which has its own shape.
  • No agent file changes: magpie still writes provider/model ids (magpieModels), so turning it on or off rewrites nothing.
  • Tests: TestBareModelIDsReporterCase (Codex gpt-5.6-sol listed bare and answered on Chat, Responses and Messages, the list unchanged when off), TestBareModelIDsShared (several providers, found groups on and off, a held key, another magpie) in bare_ids_test.go, TestBareModelIDsSetting in internal/gui, and internal/gui/tests/bare-ids.test.cjs.
  • A URL magpie downloads but didn't choose itself is downloaded from public addresses only, wherever the request came from (image_fetch_guard.go). That is an image a caller names (an /v1/images/edits or /v1/images/generations reference image, for an images API that takes files, Gemini's own API or Code Assist: fetchPicture in draw.go, publicClient), a page web_fetch reads (webFetchClient), and an image or video a vendor answers by URL, which what the model was asked to draw or do can steer (the inline download for a b64_json caller in draw.go and /v1/videos/{id}/content in video.go, vendorClient; generate_image's own download in internal/imagemcp, PublicClient). Every address the host resolves to must be public (publicAddr, which is internal/netguard's Public, the rule a provider's icon uses too: not loopback, RFC 1918, fc00::/7, link-local with 169.254.169.254, CGNAT 100.64/10, unspecified, multicast, documentation, reserved, benchmarking, Teredo, nor an IPv4-mapped, NAT64 or 6to4 form of one; an AAAA record Loon synthesizes for an A answer in the same reply, fd27:712::/96 with that IPv4 address inside, is left out and the A answer judged in its place, dropLoon), and the request goes to the address checked, so a name that resolves elsewhere the second time changes nothing; a direct connection is checked again on the address dialled (guardDialer). Through a proxy the proxy is sent that address, never the name (an https:// CONNECT or SOCKS keeps the name for TLS and Host; a plain http:// URL through an HTTP proxy is asked for by the address in Host too). A fake-IP resolver's answer is the one shape let past that (#2593; ggbdpq, with h4rk8s's and TomXPRIME's reports): Clash's TUN with fake-ip, Clash Verge, Surge's enhanced mode and Loon answer every name in 198.18.0.0/15 (netguard.FakeIP), so with one on every download was refused as a private address. A name (never an address literal) whose every answer is in that range is fetched: with no proxy (pure TUN) its fake address is pinned and dialled, the dial guard letting that one address in, and the TUN carries it; through a proxy on this computer (a loopback address or localhost, onThisComputer) the proxy is given the name, never the fake address, which a real proxy can't route (h4rk8s: a CONNECT by the name went through where one by its 198.18 address failed), and a plain http:// request's Host is the checked name, never the caller's own; through a proxy elsewhere it is refused. The fake-IP resolver's own AAAA beside its fake A answer (an IPv6 address in fc00::/7 or 2001:2::/48 while an A answer is in 198.18.0.0/15, netguard.FakePaired: mihomo's fake-ip-range6, which Clash Verge Rev turns on by default as fdfe:dcba:9876::1/64 or fills in as 2001:2::/64; jiezhengj, whose every web_fetch was refused) is left out by dropLoon and never dialled, the fake A answer judged and pinned in its place. An answer with any other address beside the fake ones (private or public) is judged as any, so a fake one beside 192.168.x is refused. The trust this asks for is the fake-IP resolver's: which host the name stands for, and so where the TUN or the proxy connects, is decided where magpie can't see, and a name that really points at the user's network is reached if that resolver's rules send it there. A provider's icon was already fetched this way (publicIP in internal/provider/icon.go, #252), and shares the rule. TestFakeIPNameGoesToALocalProxyByName, TestFakeIPNameDialledThroughTheTUN, TestFakeIPWithItsIPv6Answer, TestFakeIPRefusesTheRest in fakeip_test.go. Each redirect, up to 5, is checked the same, and a caller's image must sniff as an image. A request from this computer gets nothing more: a reverse proxy or relay in front of magpie on the same host makes every request it carries arrive from loopback, so where a request came from is never a reason to reach a private address. Two things are: settings.json's fetchPrivate (settings.FetchPrivate, none by default, no Settings page, this computer's own and never brought by a sync or restore), a list of names, name:ports, IPs and CIDR ranges the user lets magpie download from (allowFor; a settings.json that can't be read lets nothing extra in), and for a vendor's URL the host:port of that provider's own endpoints, which the user named themselves (a provider on the LAN that serves its images from itself). A vendor's image that can't be downloaded is answered by its URL, never dropped; its video is a 502 naming why. A URL left for the vendor to fetch (a chat model's message) is the vendor's to fetch.

Instruction roles on translated Responses turns

A Responses request translated back to Responses keeps its system and developer input messages in place, including messages added after an assistant reply (parseRequest in gateway.go, readResponsesFor in responses.go). Its top-level instructions stays separate. Offering web_search to a custom provider that is not known to search natively can select this path even when no search is called. Previously it lifted initial instruction items into instructions and changed later ones into user reminders, so a Codex Plan-to-Default transition lost its developer authority.

This does not change the Claude subscription or other APIs' existing cache-preserving mapping. If the upstream falls back from Responses to another API, that API's builder applies the existing mapping through responseInstructions; building it leaves the native request intact. TestResponsesInstructionRolesThroughSearch checks the upstream-bound roles and positions, TestCodexSearchAnsweredOnResponses checks both sides of a search round, and TestResponsesInstructionsOtherAPIsUnchanged compares the other builders with their previous output.

A Responses WebSocket

Codex speaks Responses over a WebSocket to its own provider, which magpie's wiring is (openai_base_url on the Codex backend path), and only there names the reply a turn follows (previous_response_id) and sends what came after it; over HTTP it sends the whole conversation, images and all, each turn (#4058, kevinzhow and neighbads on X). magpie answered the upgrade 426 (a87dc1ff2) until #4058. responses_ws.go serves it on /v1/responses, /responses and the Codex backend's /responses, with Codex's protocol (codex-rs responses_websocket.rs):

  • Each response.create text frame is one turn, served as the POST it stands for: the upgrade's own request (URL, Host, address, headers but the socket's own and OpenAI-Beta: responses_websockets) with the frame as its body, type, previous_response_id and generate taken out, and client_metadata's turn state and responses-lite flag as the X-Codex-Turn-State and X-OpenAI-Internal-Codex-Responses-Lite headers Codex sends over HTTP. It goes through the whole handler the upgrade came in on (socketEntry, outside Front and Handler), so the allow list, rebound, the key, corsGuard, keyLimited, routing, failover, usage and the log judge every turn as an HTTP one: a key turned off or past its limit refuses the next turn (TestResponsesSocketGuards). The upgrade itself passed those too, and coder/websocket's Accept refuses a browser Origin whose host isn't the Host. holdCatalog holds each turn, not the socket.
  • The reply's events go back a text frame each; the reply's headers as Codex reads them on a socket (response.metadata with x-codex-turn-state, openai-model and x-reasoning-included; codex.response.metadata with x-models-etag, the backend's own event given magpie's tag as modelsEtag gives it; codex.rate_limits from the x-codex-* windows), to Codex alone: a client that isn't Codex gets none of them, as on the HTTP route (TestSocketHeaderFramesOnlyForCodex, #4482). A whole JSON reply is told as its stream would be. A refused turn is an error frame with the status, the error object and the headers Codex acts on (Retry-After, x-codex-*, x-ratelimit-*).
  • The conversation a turn continues is the socket's own: each completed reply's input and output (in the order of output_item.done, as Codex adds them), the last two kept (socketKeep; a warmup's and its first turn's). A turn naming one is sent the whole conversation, so a provider or account other than the last one's sees what it would over HTTP. An id the socket doesn't hold, from another socket, or a failed reply's, is answered previous_response_not_found, on which Codex opens a new socket and sends everything. prevResponses isn't used: Codex says store: false.
  • generate: false (Codex's warmup) is answered locally with a response.created and response.completed of its own id; nothing is sent upstream.
  • response.interrupt naming the reply in flight cancels its request and is answered response.interrupt.accepted, then an interrupted response.incomplete; one naming another reply, or none in flight, response.interrupt.failed. Other frames during a turn wait for it.
  • An upstream cut the gateway tells as response.failed goes back as that frame, and the reply isn't kept; a stream that still ends with no terminal event closes the socket 1011, as an HTTP stream would be cut (TestResponsesSocketCutReplyFails). Binary frames close it 1003.
  • Run's shutdown ends each socket going away (1001) once its turn is answered, through clientSockets.drain beside srv.Shutdown (a hijacked connection isn't the server's), and refuses new ones 503.
  • Not covered: the leg to the vendor is the whole conversation each turn, as before (for the ChatGPT backend, a socket per turn: see Providers and accounts); what is saved is Codex's upload to magpie, and, when the provider is another magpie, the leg between the two magpies (below). A socket's conversation doesn't outlive the socket or the gateway.

A Responses request that names the response it follows

A Responses client may send only its new input with previous_response_id (kevinzhow on X: every turn sent the whole conversation again, images included). previousResponse in prev_response.go runs in serveAgent before anything else reads the body.

  • Every Responses reply magpie passes with status 200, not failed or cancelled, is kept by its id with the conversation it answered (input, then output) in prevResponses: in memory only, least recently used first out past 256 MB, each kept 6 hours (prevTTL, prevCap). A request with store: false keeps nothing. Codex over HTTP sends store: false with the whole input and never names a previous response (only its websocket request has the field), so nothing changes for it. On a WebSocket it names one, which the socket keeps itself (below).
  • A turn is kept for the caller that made it (prevScope): its gateway key, the remote magpie it came through, and the address of a keyless remote caller. Another caller naming the id is told it isn't there.
  • A request naming a kept id is given the conversation whole (previous_response_id taken out, the kept items before its own input), so every route, translation and masking below sees what it would have seen had the client sent it all. The stored items are what the client sent, and masking runs on each request as it goes, so a stored secret is masked the same way on every later turn.
  • An id magpie doesn't keep (never seen, another caller's, expired, or lost to a restart) gets OpenAI's 400 previous_response_not_found (writePrevNotFound) on a route that translates, before anything is sent. A Responses relay is sent the request as it came, and its own answer reaches the client.
  • Where the provider keeps responses itself (prevKeeps: an API key, no plugin, on api.openai.com, Azure, or Ark's /api/v3 pay-as-you-go Responses) and it answered the previous turn on the same key (prevRoute), with store not off, the request goes as the client's new input with the provider's own id (prevDelta), so images aren't uploaded again. A provider that says it doesn't know that id (prevRefused) is sent the whole conversation at once.
  • A kept turn remembers which provider and key its reply came from (made, any relayed reply, kept upstream or not). A conversation going on with another one is sent the items magpie brings back without the ids that name them where they were made (prevElsewhere): an item that may go without its id (idOptional) loses it, reasoning stays only with its encrypted_content, and the client's new input is as sent.
  • An upstream that says the response or an item belongs to another of its resources (prevForeign: Azure OpenAI behind a relay that spreads one key over several resources, hykql's report; the text was not reproduced against Azure) is asked once more with the conversation whole and those ids taken out. Only a request whose conversation magpie holds is asked again, and only with a body that differs: an id magpie doesn't hold, or a refusal with nothing of magpie's to take out, is passed on as before.
  • A ChatGPT account's streamed turn goes on its conversation's kept socket as a delta after the backend's own previous_response_id (codexKept, see Providers and accounts).
  • Not covered: the kept turns don't outlive the gateway, and a kept-id request is still read and masked whole on this computer before the delta is cut.

Turns to another magpie

Two magpies that share their gateways (LotusDecoder on X: one in China, one in the US, each the other's provider) sent the leg between them the whole conversation every turn. Codex says store: false, so prevResponses and prevDelta don't apply. remote_delta.go handles it in passthrough, after prevDelta and only on Responses.

  • A Responses request to a remote magpie (IsRemoteMagpie) whose body names no previous response and whose input is a list of items asks the other magpie to keep the turn: X-Magpie-Keep-Turn: magpie/<version>, put on in passOnCaller.
  • The other magpie honours the header only from a request shaped as a magpie's hop (keepTurnAsks): the value starts magpie/, and the User-Agent is magpie's, or Codex's (forwardOnce passes Codex's headers on as Codex sent them). It then keeps the turn in prevResponses whatever store says, under the caller's prevScope and the same caps, and answers X-Magpie-Kept-Turn: 1. An id such a request names that it doesn't hold gets previous_response_not_found before anything is sent, never relayed to a vendor that might ignore it (keptTurnLost in serveAgent).
  • The header comes off every request as it arrives (withCaller), and X-Magpie- is never a passable request header, so no vendor is sent it. A client that copies a hop's headers is kept to its own scope and the caps, as store: true would have it.
  • When the reply says it was kept, this magpie records the turn per route and scope (remoteTurns): a SHA-256 of each input item as sent (after masking and translation), each output item's type, id and call_id, and the other magpie's response id. At most 16 per route and scope, 32 MB in all, each for prevTTL.
  • The next request whose input starts with exactly those items, then as many items as the reply had with the same type and call_id (and id where both have one; Codex sends its items back without ids), and then at least one more, goes as the items after them with previous_response_id. Anything else goes whole: an edited or shortened history, another answer in place of the reply, a request naming its own previous response, or a magpie that never said it keeps turns (one from before this).
  • A delta the other magpie refuses (prevRefused: it restarted, or let the turn go under its cap) is sent again whole at once, the record is dropped, and that route goes whole for 30 minutes (remoteRefusedWait).
  • Not covered: the reply's output is matched by type and ids only, so a client that edits the text of the last answer (no ids) is sent a delta over the answer the other magpie kept. Tools and instructions still go every turn. The other magpie's kept turns are in memory only.

What runs once on a hop to another magpie

A request an agent sends to a Remote magpie passes two gateways, and each one used to mask it and run its routing in full (YeYaka88 on X: gateway, routing and masking all twice). Measured with two sandboxed magpies and a vendor answering 503: one agent request asked the vendor 35 times over 174s, the remote's 7 tries over 33s run again by each of this magpie's same-one retries and patience rounds; and the remote ran the masker over text already masked.

  • Masking runs where the request is sent from. After masking, serve (and countTokens) puts what it masked by on the request's context (withMaskedAs, ownMaskedAs: this build's version and masking.Fingerprint, a hash of every setting that changes what is masked, the local model and its threshold among them, never the words themselves), and passOnCaller sends it as X-Magpie-Masked-As. The other magpie skips its own pass only when the value is its own (maskedBefore), and passes it on to a further magpie the same way. Other settings, another build, no header, a request not a magpie's (magpieAsks) or a remote that sends masked requests to a model of its own as written (RedactRouteTo, which needs its own pass) mask again, as before. The values stay on the sending computer: the remote records and forwards placeholders, and the sender puts the values back. The header comes off every request as it arrives (withCaller) and every request to a vendor. A client holding a key could send it to skip the remote's masking, of its own request only.
  • A failure the other magpie answered after its own routing names its provider (X-Magpie-Provider, kept as answeredThereHeader by keepRetry). passing doesn't retry it on the same remote, and patience doesn't put it in its next round (routedThere): the remote's own retries and patience had their turn. This magpie's other members are still asked, and a remote that can't be reached, or refuses before routing (its key, the key's limit), is asked again as before.
  • Both gateways still record the call in their own ledgers (each computer's Usage), and the remote's Routing page shows its own trace.
  • TestRemoteMagpieMasksOnce, TestRemoteMagpieMasksWhatItIsNotToldWasMasked and TestRemoteMagpieRoutedFailureNotAskedAgain in remote_magpie_once_test.go, TestFingerprint in fingerprint_test.go.

A model's own system prompt

The system prompt the user gave one model (provider.ModelSystemPrompt, liucl on X) is added to every request for that model, after the agent's own (withModelSystem in model_system.go). It is added in the agent's protocol in serve's candidate loop, after triedOn and before any translation or a plugin's fetch, so chat, Messages, Responses, Gemini and a plugin's model all get it once, on the candidate that serves it: a fallback to another model gets that model's own, or none. count_tokens adds it too (countOn), so the count is of what is sent.

It is only ever appended. Codex's base_instructions, Claude Code's identity block and any agent's own prompt stay first and unchanged:

  • Anthropic: a string system gets it after a blank line; a block array gets one more text block; none gets system.
  • Chat: the last of the leading system or developer messages gets it after a blank line (or one more text part); none gets a system message first.
  • Responses: a developer message goes after the leading system or developer items, instructions untouched; a string input becomes that message and the user's. A request that names previous_response_id gets none, since the turn it follows had it.
  • Gemini: systemInstruction (or system_instruction) gets one more part.

Empty is the default and sends the body byte for byte as before. magpie's own asks (search and vision side calls, Codex titles, the router's classifier) get none. TestModelSystemAfterTheAgentsPrompt, TestModelSystemNoneLeavesTheBody, TestModelSystemNotOnMagpiesOwnAsks, TestModelSystemReachesItsModelOnEveryRoute, TestModelSystemOtherModelSentAsBefore, TestModelSystemReachesAPluginsModel in model_system_test.go.

Verification

go test -tags nogui ./internal/gateway -run 'TestGroupAsksOneRestingMemberNotEach|TestLoneRestingMemberStillAsked|TestRetrievalGroupAsksOneRestingMember|TestProbeOne|TestLoop|TestLongReplyThatDoesNotLoop|TestQuiet|TestSilentHeld|TestRotateSpreadsSessions|TestRouting|TestSmartRouting|TestFallback|TestNoFallbackForOtherErrors|TestLastFallbackErrorReachesTheAgent|TestRateLimitedSinksToTheBack|TestTryNow|TestRenewedToldToTheRoutingPage|TestGroupRateLimitedSinks|TestAffinity|TestSeveralKeysOnTakeOverFromEachOther|TestModelNotInPlanRestsTheModelNotTheKey|TestSubscriptionAccountsTakeOver|TestGroup|TestTrace|TestImageTool|TestCodexNoCredits|TestCodexCredits|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|TestMaskedRequestGoesToTheModelSet|TestCodexSigninTurnGoesToTheModelSet|TestMaskRoute|TestCORS|TestForeignPagesRefused|TestAIStudioThinking|TestGeminiThoughtsThroughLocalProxy|TestGeminiRefusedLevel|TestGeminiThinkingOffAtItsLowest|TestThinkingOff|TestTranslatedEffortLoggedAsSent|TestTranslatedThinkingOffRefused|TestSub2APIThinkingOffRefused|TestRefusesThinkingOff|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 'TestMemberTooSmallIsNotAsked|TestMemberTooSmallIsTheLastResort|TestClaudeAccountsSpentFallBackToCodex|TestConversationOutgrowingItsMemberMoves|TestRoomyLeavesWhatItCantJudge|TestPayloadTooLarge|TestOverflow|TestContextOverflow|TestRelayInputCap|TestEveryVendorsOverflow'
go test -tags nogui ./internal/gateway -run 'TestPlain403|TestOrderedKeepsAnAccountAt98|TestPromptRefusalRestsNobody'
go test -tags nogui ./internal/gateway -run 'TestVertex'
go test -tags nogui ./internal/gateway -run 'TestWeightedKeys|TestAccountWeightSharesRequests'
node --test internal/gui/tests/key-weight.test.cjs internal/gui/tests/account-weight.test.cjs internal/gui/tests/routing-weight-chip.test.cjs
go test -tags nogui ./internal/gateway -run 'TestPreviousResponse|TestUnknownPreviousResponse|TestPrevStore|TestRemoteMagpieSentTheNewInputAfterAKeptTurn|TestRemoteMagpieLostTurnSentWhole|TestOlderRemoteMagpieSentWhole|TestRemoteMagpieEditedHistorySentWhole|TestKeepTurnOnlyFromAMagpie'
go test -tags nogui ./internal/gateway -run 'TestBedrock'
go test -tags nogui ./internal/gateway -run 'TestPublicAddr|TestEditImageURL|TestPrivateDialer|TestFetchPrivateEntries|TestVendorImageURLAtPrivateAddress|TestVideoContentAtPrivateAddress'
go test -tags nogui ./internal/gateway ./internal/provider ./internal/cli ./internal/gui -run 'TestDisabled|TestModelDisableCmd'
node --test internal/gui/tests/disabled-models.test.cjs
go test -tags nogui ./internal/gateway ./internal/gui -run 'TestBareModelIDs'
node --test internal/gui/tests/bare-ids.test.cjs
go test -tags nogui ./internal/gateway -run 'TestTextWritten|TestGLMTextCall|TestPluginTextWrittenCall|TestQuietWholeReplyStreamed|TestDSMLAlma'
go test -tags nogui ./internal/gateway -run 'TestAutoMode|TestClaudeBridgeSafeguard|TestSafeguardsRefused'
go test -tags nogui ./internal/gateway ./internal/gui -run 'TestModelSystem|TestProviderSaveModelPrefs'
node --test internal/gui/tests/model-system-prompt.test.cjs
go test -tags nogui ./internal/gateway -run 'TestCreditsExhaustedIsOutOfCredit|TestOutOfCreditLeavesFreeModels'
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|TestVisionMCP|TestWorkBuddySearchesForItsModels|TestWorkBuddyPluginSearches|TestAutoVisionPassesOverOneOut|TestAutoVisionTierAmongThoseWithAllowance|TestSpentModelAcrossAccounts|TestVisionDoesNotAskSpentDescriber|TestSearcherPassesOverOneOut'
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/provider -run 'TestCodexCompressed|TestCodexWarmGoesZstd'
go test -tags nogui ./internal/gateway -run 'TestCodexAccountTextTurnGoesZstd|TestCodexRelayedTextTurnGoesZstd|TestCodexTurnAskedAgainGoesZstdAgain|TestCodexCompactAndAPIKeyStayPlain|TestKeyProviderTurnStaysPlain|TestCodexResetJudgedByTheBytesSent'
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.