huangfuyafei on X: in Usage → Requests, OpenBot's calls show OpenBot, but
OpenMausBot's show Claude Code. OpenMausBot (milind-soni/OpenMausBot,
read at 9f67fa5) runs the real Claude Code CLI as its engine.
server/drivers/claude.ts's claudeEnvironment deletes
CLAUDE_CODE_ENTRYPOINT and adds no header of its own, so a request
carries Claude Code's User-Agent and nothing else. magpie wrote the
"magpie" engine in ~/.openmausbot/config.json with the gateway's plain
token (keyAt), so the gateway's agentOf fell through to the User-Agent
and named Claude Code. OpenBot is told apart by its /agent/openbot path.
- internal/agent/openmausbot.go: the engine's ANTHROPIC_AUTH_TOKEN and
ANTHROPIC_API_KEY are agentKeyAt("openmausbot", gw), the key naming
OpenMausBot (as desktopKey does for Claude Desktop). An engine written
before gets the key at the next sync (ombMerged makes the routing keys
magpie's); OpenMausBot reads the file when it starts.
- internal/gateway: claudeCodeInside is Claude Code's User-Agent under
another agent's path or key (Claude Desktop apart). claudeTierStandIn
and observedKind (claudeCodeAs) treat such a call as Claude Code's, so
the haiku/sonnet/opus tier stand-in and the auxiliary marking of
tool-less helper calls still apply inside OpenMausBot. Real Claude Code
on the plain token or magpie-claude is unchanged.
- docs/subsystems/agent-wiring.md, gateway-routing.md say so.
Run (mote, through mote-run; mote at load 21-137 on 18 cores, mica at
92-108 on 12 with another session's full suite, so mote as the lesser):
- go test -count=1 -timeout 45m ./internal/gateway ./internal/agent
./internal/usage at the pre-rebase head 3c9d79d28+change: agent ok,
usage ok; gateway FAIL on three known reds, none in this change's code:
TestOpenCodeGoOwnFreeModelGetsNothingOfOpenCodes (#7117; 3 of 3 red on
a clean origin/main 6bb90df8e too), TestSearchQueueKeepsCodexAlive/
progress at load 137 (#7090, pings=3 complete=false; 3 of 3 green on
main and head after), and the doneHold fake's close-of-closed-channel
panic (#6505, #6690).
- At the rebased head (on 6bb90df8e): -count=3 of TestClaudeCodeInsideAnApp,
TestClaudeTier*, TestStandIn*, TestAgentInPath and the two reds above:
all ok but #7117; -run 'OMB|OpenMausBot|Omb' ./internal/agent ok;
GOOS=linux and GOOS=windows go vet of both packages ok; gofmt -l clean.
- Broken by hand: on the old openmausbot.go/gateway.go/observe.go,
TestOpenMausBotEngine and TestOpenMausBotKeepsTheUsers fail (token
"magpie") and TestClaudeCodeInsideAnApp fails (404 for
claude-haiku-4-5-20251001: no tier stand-in under the OpenMausBot key).
Not tried:
- a real OpenMausBot run against the gateway (the key and the agentOf
path are tested; the app was read, not run);
- OpenMausBot's own "claude" engine, inheriting ~/.claude/settings.json
pointed at magpie: it sends the plain token with Claude Code's
User-Agent and is still counted as Claude Code;
- the classifier stand-in (automode.go) stays keyed on agent=="claude":
it follows the user's ~/.claude /model, not OpenMausBot's Claude home;
- the observedKind assertion calls claudeCodeAs directly, not through
observeRequest;
- a key change alone doesn't offer Restart (ombPart leaves the key out);
a running OpenMausBot needs a restart to send the new key.
- No GUI change: OpenMausBot's name and icon already exist.
779 KiB
Gateway routing and fallback
The gateway is magpie's local LLM endpoint (127.0.0.1:3425 by default). It
serves Chat Completions, Responses, Anthropic Messages and Gemini. It finds
the provider, key or account and model for each request. When the upstream
doesn't speak the agent's API, the gateway translates. When an upstream
fails before any of the reply is sent, the gateway moves to the next
candidate.
This page covers how a request is routed. Plugins that change requests and replies are in Gateway middleware. Subscriptions served by a plugin are in Provider and plugin ownership.
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.
A found group is not in providers.json; only its removal is ({"id", "hidden": true}), so taking that record out by hand brings the group back. Removing
every found group at once (provider.DeleteGroups, the Routing page's
select-all Remove) also turns found groups off (SetAutoGroups(false),
xwang_sh on X), so a model a provider lists later brings no new one; the
removed records stay and turning them on again restores the groups as they were.
A found group can go without the user removing it: one of its two providers
is removed, or its list no longer has the model. Reseat moves an agent's
config off it, but a conversation saved on it (a Codex thread names its
model in every turn and in the compaction before a model switch) still asks
for it. provider.AutoStandIn sends such a request to the model from a
provider that still serves it, the same model and never another, as it does
while found groups are off or a provider is kept out of them; a group the
user changed or removed gets none. With no provider serving the model the
request is still 404, and unknownModel says the model is gone and to pick
another for the conversation instead of listing every id
(provider.GoneAutoGroup; canlee886 on X, TestFoundGroupGoneGoesToItsModel).
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. An app that runs the real Claude Code with a key naming the app (OpenMausBot's engine) is counted as that app, and is still Claude Code for its tiers and helper calls (claudeCodeInside: Claude Code's User-Agent under another agent's path or key, Claude Desktop apart; TestClaudeCodeInsideAnApp). 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), OpenAI's unary /v1/responses/compact (also without /v1; responses_compact.go, #7281: relayed as it came to /responses/compact under the provider's base only for a key's provider asking the model on Responses, its sealed item's writer remembered as a native compaction's is; any other candidate is left out, and none left is a 400 saying to compact on /responses), /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. A WebSocket upgrade on /v1/realtime or /realtime is a Realtime API session (below, A Realtime session). 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). A model its vendor lists with the maker's name left off is merged by the model it is (mergeKeyIn, catalog.Unprefixed): Kimi Code's k3.1-pro, whose entry in the provider's own models.dev catalog names moonshotai/kimi-k3.1-pro, is in auto/kimi-k3.1-pro with OpenCode Go's and Devin's kimi-k3.1-pro (tmr11235 on X, who had to add it by hand). The canonical alone never merges a model, as models.dev gives Kimi Code's k3.1-pro-highspeed the canonical kimi-k3.1-pro and k3-256k kimi-k3: the id must be the canonical's with a maker's name (letters) taken off the front, or go on past it to a model models.dev knows by that name before the whole id (k3.1-pro-highspeed is kimi-k3.1-pro-highspeed; k3-256k stays its own). A relay whose catalog says nothing of its k3.1-pro is not merged on a guess. The id such a model had a group by before (auto-k3-1-pro, Kimi Code with Kimi Code China) is the group's Former, so an agent still set to auto/k3.1-pro is served (TestFoundGroupTakesAModelListedWithoutItsMaker, TestFoundGroupOfUnprefixedIDsAloneIsTheModels). 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 (Quota first) in a group that pools (Quota first, 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 Quota first. TestFreeFirstReachesAGroupInItLeftOnTheDefault. So does a member whose provider routes other than Quota first (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 Quota first, 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), expiring (free quota by expiry) or fit (small context first). 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: Quota first is routes.Quota first, 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). Quota first, usage and pace weigh a subscription by its allowance (allowances), and a key by its own usage windows when magpie reads them (keyAllowance: a sub2api key given a 5-hour, day or 7-day limit, or a key bought as a plan, such as Kimi Code's or a GLM Coding Plan's); any other key has none. A Remote magpie is weighed by the card of the provider serving the model there, as last read from it (provider.RemoteAllowance: the model's longest provider path with a card, claude for claude/claude-sonnet-5-5, the account there with the most left for the inner model): before #6708 (zzh11223311 on X) a group of Remote magpies had every member not known (used 0 in the trace) and went by tokens and stickiness alone. It never waits: when the routing weighs the remote against another and its cards are older than 30 seconds, they are read again in the background (one read at a time per remote; the remote answers from the cards it keeps), so a request to one Remote magpie alone sends it nothing more (TestRemoteMagpiesWeighedByTheirCards). A remote too old to tell what routing reads of its windows stays not known. A Remote magpie is still not an account for cap holds and Codex credits (candidate.allowance). Among accounts a plugin reads as prepaid wallets (a window's balance, #3950), Quota first, 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, 免费, 试用, 体验, 體驗; for a Remote magpie member, of the plan on the subscription card it is weighed by, provider.RemoteSeat, which has no Account here: #6708, TestRemoteMagpieFreePlanSpentFirst). 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 Quota first 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 fit (provider.SmallFirst, routes.SmallFirst; yg6888 on X, Cursor's Composer at 200K and Grok 4.7 at 256K never answering in a Quota first group of 1M models) goes by each member's context window: its strategy sets ByWindow, so weighRouted fills Seat.Window from windowIn (the provider's own Contexts, else the catalog's, read once per weighing), and routes.SmallFirst takes Quota first's order and sorts it stably into three bands: a seat of a provider set to be used first, then the rest with room, then the all but used up (seatTier 2); within a band the smaller known window first and an unknown one after every known one, a tie in Quota first's order. It never picks one too small: roomy has already left out every member whose window the request is estimated past (and keeps it as the last resort as for any routing), so the first left is the smallest that holds the request. The trace's rows carry context for the Routing page's story ("its 200K context window is the smallest that holds this request"). A group's only: provider.normalize drops it from a provider, whose keys serve one window, and the CLI refuses it there. Nothing changes for a group not routed fit; TestSmallContextFirstGroupKeepsTheBigOneForLongRequests (gateway), TestSmallFirstOrdersByWindow (routes) and routing-small-first.test.cjs hold it. 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 (Quota first'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 Quota first 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 Quota first 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; the ZCode plugin declared two from 0.1.40 to 0.1.67, and since 0.1.68 declares none and holds its Start Plan to six requests in flight from the address itself, since a user's other accounts sat unused, mathfournity on X) 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. A drawing's resolution tier, 1K, 2K or 4K (resolution, or a size that is one; tierOf, settleTier in draw_tier.go), is asked of each vendor in its own field: Gemini's imageConfig.imageSize, a chat image model's image_config.image_size, OpenRouter's resolution, Grok's resolution (1k or 2k), Ark Seedream's size (a tier or its pixels), MiniMax's area, and gpt-image-2 and later as WxH pixels in their limits (imagesAPISize); gpt-image-1, DALL·E and SenseNova get none. A request whose tier its vendor answers with a 400 or 422 is asked once more without it (tierRefused). The Magpie Image MCP asks Settings → Models → Images → Image resolution (imageResolution, unset is the model's own; skingstyle48487 on X) when the agent names neither size nor resolution, and says the pixels drawn when they are under the tier asked (ImageTier, PixelsSaid); the row is drawn by videogen.js beside Video generation. TestTierReachesEachProtocol, TestImageTierPrecedence, TestImagesAPIResolution, TestImageMCPAsksTheSetResolution, image-resolution.test.cjs. |
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; an inline image is counted from the size its header gives by the rule of the vendor whose protocol the request speaks (Anthropic's 28 px patches in the model's tier, OpenAI's 32 px patches or 512 px tiles at the part's detail; prompt_image.go, @paiven_x on X), one whose size can't be read, and a Gemini request's, at 1600; 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 |
A request body that stops moving while the transport holds a chunk is
bounded by bodyStall (upstream_stall.go). stallGuard cancels that try,
closes its connection, and waits for the close to finish before retrying
once with a fresh body. Cancellation alone wakes RoundTrip before the
close is complete: retrying then can send headers on the old connection
and count an extra attempt at the vendor. TestStalledBodyRetryWaitsForConnectionClose
holds the close to check this ordering; TestBodyStalledByFlowControlIsGivenUp
checks the two attempts against an HTTP/2 server that never reads the body.
Routing recipes
A routing group's templates (provider.Templates in
grouptemplate.go; the Routing
page's cards, then its Templates menu; magpie group template) are groups
for needs most users have, made of the user's own models. Each only sets
what the engine already has: members, a routing, rules, a classifier. Which
model is strong or cheap comes from list prices and release days, never a
list of names.
| Template | Routing | Members | Made when |
|---|---|---|---|
Hard to strong, easy to cheap (smart) |
order, with intent rules and a classifier | the strongest model and a cheap one | a cheap model exists |
Cheap first (thrifty) |
order, the strongest for high reasoning | up to two cheap models, then the strongest | a cheap model exists |
Never stuck (steady) |
order | the strongest model of up to three providers | two providers |
Plan first (plan) |
order | as steady, the providers billed by a plan (Provider.BillingKind) ahead of pay-as-you-go ones |
a plan provider, and two providers |
Fastest first (fast) |
fast |
as steady |
two providers |
Spread evenly (even) |
rotate |
the one strongest model, from up to four providers that serve it | any model |
Pick by the need. A subscription to spend before any key: Plan first. The
quickest answer: Fastest first. One model shared over several accounts or
relays, so none runs dry: Spread evenly. A provider down or out of quota
mustn't stop the agent: Never stuck. A cheap model for most turns: Cheap first.
Hard turns to a strong model, easy ones to a cheap one: Hard to strong, easy to
cheap. A template that can't be made says what it lacks (Need*) and has no
buttons. Adding one saves a group beside the user's others, never over one.
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's "generate commit message" and pull request text
(commit_message, pull_request_message, commit_pull_request_message) are
side turns of the same kind, each asked for in a schema of its own
({"message"}, {"title","body"}). A model behind the Chat or Anthropic API
never sees the schema, so codexCommit hands its plain text back in that
shape (commitJSON, the first line of message cut to 72 characters).
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).
The Codex app's prompt suggestions (thread_source ambient_suggestions,
and ambient_suggestion_safety for the check of what they found; usage's
Suggestions) are an agentic background turn that reads the project and
connected apps. The app asks for the model its server config names
(codex_ambient_suggestions_model_slug, gpt-6-luna) with provider model
fallback on, so on magpie as Codex's provider they ran on the provider's
default model, often auto (@0xcb198609 on X: 76.9k tokens on
deepseek-v4-pro). Codex has no config key for that model; its Settings ›
Configuration › Homepage suggestions turns them off. CodexSuggestions
(provider.CodexSuggestionsModel) puts both calls on a model or group of
magpie's: codexSuggestionsTo in
codex_suggestions.go, in
serve as the codex-suggestions move, and on the Codex backend before
the / split, carrying the asked model to serve (withSuggestionsAsked)
so the trace and ledger keep it. A model that is disabled, unserved or not
the key's leaves the call as asked, with a log line (compactRefused).
codexOwnOffMagpie leaves such a call to magpie when the setting is on
(codexSideSet). Empty, the default, changes nothing
(TestCodexSuggestionsMoved, TestCodexSuggestionsLeft,
codex-suggestions.test.cjs).
Runtime path
handle(proto)reads the body and the model (requestBody,requestModel), then callsserveAgent. Every route that reads an agent's body (each API, count_tokens, Gemini's, embeddings, images, videos, System One, the Codex backend path) reads it throughreadBoundedRequestBodyinrequest_bounds.go. It decodes aContent-Encodingofgziporzstd(decodedBody; Codex sends zstd to a custom provider's/v1/responsestoo, #1223) and drops the header, so the provider is sent plain JSON, with one exception: a ChatGPT account's turn (POSTCodexBase/responses, from the accounts loop inforwardOnceor relayed bycodexUpstreamOn) is compressed again with zstd and a window of at most 2 MiB, as Codex's own client sends it (provider.CodexCompressed; openai/codexresponses_request_compressionandhttp-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, andcodexDroppedjudges a reset by the bytes that went on the wire.codexDroppedalso 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, andkeyLimitedon it) reads tocodexBodyLimitinstead: a sixteenth of the machine's memory (memLimit, elseproc.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);writeErroradds to any 413 it isn't holding that this is a byte limit, not the model's context, and to/compactor start a new conversation (TestOverLimitSaysWhoseAndWhatToDo). Every shape but Gemini's types a 413request_too_large, Anthropic's own type, which pi's overflow table knows: pi compacts and tries once more rather than stopping on an OpenAI-shapedapi_error(@wilsonxuuuu on X,TestPayloadTooLargeSaysRequestTooLargeToPi).keyLimitedreads 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 (textBodyinbody_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).serveAgentruns the middleware chain, thenserve.serveredacts secrets in the request (redacted;redact.MaskJSONleaves 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 ownelement_token(any other name withelementin it,element_api_key, is a credential's as before), a barekey(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-leveltools,tool_choice,response_format,text,generationConfig,stream_options, the client's ids inclient_metadataand the like, and the tools of a Responsesadditional_toolsortool_search_outputitem), 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'sname,typeordatainside its arguments too, but for signatures,data:URLs and opaque blobs (sealedText); a held tail is kept per string, so a Responses event's randomobfuscationnever takes the hold from itsdelta; 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 noX-Magpie-Masked-As(withMaskedAsis 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,awayHostin app.js; a name of the user's own DNS is asked about, only while it is on, throughPOST /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 (unmaskedMembersover 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, asnativeAny) follow the same rule (TestUnredactedProviderDrawsWhole,TestUnredactedProviderMakesVideosWhole,TestUnredactedProviderArkNativeWhole); Settings › Privacy lists the providers set so, each opening its editor (Sent unmasked,unmaskedRowin plugins/redact/settings.js,unmaskedProvidersin/api/settings). System One follows it too: a/v1/systemonerequest, and a/v1/decisionsone 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 modelMaskRoutepasses:unredactedRoutefor 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, inserveafter the request is masked (maskRouteForinredact.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 byunredactedRoute, 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 inserveAgentand cleared byownAsk): 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 (codexMaskRouteincodexBackend; 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 throughserve(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) andTestRedactRouteSettingin 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 (maskedStateinaskJev,decide.go): a remote Jev is none of the group's members. The masking is the built-in pluginredact'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'ssystem, the end of Chat's first system or developer message, a part after Gemini'ssystemInstruction'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). Responsesinstructions(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 (TestMaskedConversationKeepsItsCachedPrefixgoes 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 withprevious_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'stool_useinput, Gemini'sfunctionCallargs) and Gemini'sfunctionResponseresponse, whose keys are the tool's, a field named for a secret (SecretName:api_key,db_pass,Authorization, notsort_keyorpublic_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_tokenincluded, and never masks by its name (TestMaskJSONSecretNamesOnlyInToolArgs).- A routing group says how its requests are masked (
Group.Redact, set in the group's editor under Masking;provider.RedactOn,RedactOff, unset follows providers).offsends to every member as written whatever its provider says,onmasks to a member whose provider is set to go unmasked, and in a group in a group anyonwins overoff(walkpasses it down inMember.Redact;Member.Unmasked,provider.UnmaskedBy). Every route that reaches the group asks the same way:unredactedRoute(p, model, isGroup, ms)(a provider's fallback groups andprovider.GroupsAfter),unmaskedMembers,maskedFor/MaskRoute,candidate.unmasked()(embeddings, images, video, decide, count_tokens). Global masking off still masks nothing; a shared group never carries it (export and import clear it, an import over a group keeps the old one). A save that doesn't name it keeps it,followclears it. Guarded byTestGroupRedact*ingroup_redact_test.go. - With Mask personal data on, each kind in
redact.Categories(internal/redact/more.go) is masked unless the user turned it off (redactKindsin settings,Options.Kinds). On by default: US SSNs, passport numbers, IBANs that pass mod 97, birthdays next to a word that says so (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 namednumber), 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 (phoneAtininternal/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 (standIninshape.go), not as{{USERNAME_…}}: with mimo-v2.6-flash a model readC:\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). AUser: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~/.sshfor 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 (0xand 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 (evmReinmodelFits;TestEVMAddressGoesAsWritten). A number written in hex,0xand 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 (hexLiteralinmodelTakes;TestHexNumberGoesAsWritten, TakaNaShi_ShiKi on X). A public video's id is no value of any kind the local model finds either: a Bilibili BV id (BV1and nine base58 characters) or av number by its own shape, and a YouTube video's, playlist's or channel's id only where its link is right before it (watch?v=,list=,youtu.be/,/shorts/,/embed/,/live/,/channel/), since 11 base64url characters alone may be a key's; both real models took every BV id in a script's list for a secret (publicIDinmodelFits;TestPublicVideoIDGoesAsWritten, eval casebilibili-bvids, jimlee0824v2 on X). A key with such a shape whose name is before it is still the rules'. 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": …andmax_tokens: …go as written (numberNamedSecretinmodelFits;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;fileExtinrealEmail), 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, andsystem@got(.gotis a top-level domain;mailHostinrealEmail,TestSymbolIsNoEmail; ch35tnut on X, 10-28).ops@files.zipis still an address. The Settings rows come fromREDACT_KINDSin app.js, whichTestRedactKindsAreRedactsholds to the same ids and defaults. - With Find with a local model on (
masking.ModelWanted: on by default since 10-28,settings.RedactModelthe user turning it on andRedactModelOffoff, this computer's own, kept byKeepOwn; a user with a model downloaded or picked and neither flag turned it off before the default, andRedactModelAutomarks 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,modelSpansininternal/redact/model.go).MaskJSONasks it once per request, for every text it would mask, each once (withModel), but for what the agent defines (its tools' and schemas' descriptions, underdefKeys), 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'ssequential_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 (thingNamedinthingname.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'sx = "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 inpackageAt; 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-…;sriReinnamesThing), a version as the value of a field named for a secret ("js-tokens": "^4.0.0-beta.1";versionValueinfieldAtandkeyAt), and a package pinned at its version as user@host has it (js-tokens@4.0.0:in pnpm-lock.yaml;notPackagePin);TestPackageNamesGoAsWrittenandTestModelPackageNamesNotMaskedhold 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 = hunter2in a config), andenv -i UI_PASSWORD= UI_ADDR=127.0.0.1:39117 ./syncerwent withUI_ADDR=127.0.0.1as 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,nextFieldininternal/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 fromzhWordsorzhDict(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 byinternal/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 ofGOMAXPROCSand 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,MLComputePlanon macOS 14.4 and later, the device most of its program's estimated cost is on (coreml.Plan,Model.Backend,Status.ViaandDevice): 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 bycoreml_gen.pyand 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 hasguard.Cores()places (guardTurn), so that many requests read at once, and they share those cores: every window, of any request, takes one ofguard.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 undercoremlMinor 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.Thresholdinmasking.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,knownSpansinknown.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 bypf-serve(native/privacy-filter, built from privacy-filter.cpp on ggml and released underpf-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_CHUNKat 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). Both models live underpii.Root(): magpie's cache, or the folder the user picked under Settings → Privacy › Advanced › Models folder (settings.RedactModelDir, this computer's own, kept byKeepOwnand never set by a settings save; MetalHqa on X, whose C: drive held 1.6 GB). Every path (dir,guardRoot, so the model, its cache files, pf-serve and the CoreML program) is made from it at the moment it is used. Picking one moves what is downloaded (pii.MoveTo,folder.go): a rename where both are on one disk, else a copy checked by sha256 read back, the setting switched only after it, and the old subfolders (privacy-filter,astrlink-guard, never the picked folder itself) deleted last; a failure puts back what it moved and keeps the old copy and the setting. A folder that isn't absolute, isn't writable, or lies inside what is moved is refused, and a picked folder that has gone (its disk unplugged) is not made again by a download, which fails saying so. Downloads and Remove wait out a move.pii.Findstartspf-serveon 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>.binbeside the model: hashes, offsets, labels and each span's score, never text; apfound01file 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, throughgwmw.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.Stopand the idle timer never wait for a load or a request:srv.muis held only to read or set the state, andStopends 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 endedpf-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 bysettings.UseDefaultRedactModelunless 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. Once a request the user turned it on for runs out its 15 seconds with texts unread, the model is behind, and the next requests wait only the default's 2 seconds until one is read whole or a minute passes (masking.behind,waitFor): before, each request in a burst waited the full 15 seconds while the backlog grew, serially, so routing waited past the gateway's 30s (vsoullai on X, #4856;TestStrictModelBehindWaitsTheDefault). Past that, or when the request's context ends first,pii.FindContextanswers 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.Partialsaying how many it hadn't read;masking.modelmasks 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.findgives 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 whereFinddoesn'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 ispii.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 backlogbacklogCap(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 onMAGPIE_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, tostrictWait, but goes once only that backlog is left (afterSent, a*pii.Partial): such a text goes as it went on the same route (redact.sentSpans), so the model's finds in it only make a value known for later text (learnLate), and the model reads on after the request, to the request's own bound, keeping what it finds for the next. Before, a resumed or never-read history was read until the 15s ran out on every request: a 60-turn Claude Code session resumed (TestRealLatencyOfALongSession, gated onGUARD_REAL_DIR) waited 15s, 15s, 15s, 7.8s on 4 cores of a 32-core Linux box and 15s on eight requests in a row on one core (gaubeebangeel on X, 11-13: first tokens at 30-40s with masking on, 10-15s off). On another route such a text has the model's finds of now, none until it is read, and goes with the rules' alone; a value the model would have found late in it masks new text from the request after the read, not the one it went with. What a request adds is still waited for: 16 KB of new tool output a turn is about 3s on 4 cores and 8s on one, the model's reading on the CPU. - With Mask secrets on, the user's own masking rules (
redactRules,redact.Rule: a placeholder name and a prefix or an RE2 pattern,internal/redact/rules.go) run before magpie's. Settings → Privacy adds them, removes them, and edits one in place (POST /api/settings/redact-rulewith the rule's index and its current value,editRedactRuleininternal/gui/api.go). Every rule is checked byredact.CheckRuleswhen settings are saved; an edit that doesn't compile, matches the empty string, repeats another rule or names a rule no longer at that index is refused with the rules left as they were. The masker reads the rules from settings on each call (optionsininternal/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, soABCmasksname='ABC'but notXABCD, and123456not91234567,0.123456or123456.78(wholeWordinredact.go). Chinese and Japanese letters count as no letter there (wordRune): a word of theirs is found inside their text, andABCin 用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 (dateSpansindateword.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, never05/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, so1990.5.12.1and11990-05-12are 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,shapedininternal/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 (maskMatchesinplugins/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,
redactActionsin settings,Options.Actions, set byPOST /api/settings/redact-actions; a kind left out is masked).redact.Warnsends it as written: the masker tells it, with a placeholder no one remembers, and it isn't counted as masked.redact.Blockmasks 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,maskBlockedinredact.go); nothing is sent and the record is kept asBlocked(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 (applyininternal/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 toPOST /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 (
noteMaskedinmasked.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 throughgwmw.Teller(JSONHits,TextHits: each placeholder's kind, its finder,redact.ByRule,ByYours,ByWord,ByModelorByKnown, and a hint of its first characters and its length), andinternal/maskreckeeps 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 asmagpie; 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 withoutTeller, 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, andmaskrec.Clearremoves 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. DecidesModelgives 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 throughgroupAllowed, 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:serveSystemOneand the decision list another magpie asks for (DecidersHeader) hold the key to it, while a group the key names asks its own decider inaskJevwith no key check (TestGatewayKeyHeldToAGroupKeepsItsDecider); the key editor offers the decision models (GET /api/caller-keys/models,decides,TestCallerKeyModelsOfferDeciders,gateway-key-deciders.test.cjs), and the decision groups beside the chat groups, whichCatalogleaves out (switched-off ones not; Kautism on Discord,TestCallerKeyModelsOfferDecisionGroups); a key naming one is given its models at/v1/systemonethroughgroupGiven, one that doesn't is refused (TestGatewayKeyNamingADecisionGroup). - A gateway key held to some MCP servers and tools (
Key.MCP,access/mcp.go, wakaka on Discord) is held on every MCP route, inmcp_key.go:serveMCPrefuses a server it may not use with a 403 (mcpKeyServe), leaves its tools out oftools/list(mcpKeyList) and refuses theirtools/callwith -32602 (mcpKeyCall); the hub is held per Library server behind it (hubServersOf,hubTools, thehubToolNamedfallback andhubMCPRun, which every hub call goes through);/mcp/<name>and/mcp/run/<name>go throughmcpKeyGuard, which reads the request for a refusedtools/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 atools/listanswer, JSON whole or SSE event by event (mcpToolsFilter), refusing with a 502 an answer it can't read (a Content-Encoding);/v1/magpie/mcplists 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 isGET /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_agentsealed goes only to a ChatGPT account, or back to the Responses provider that answered the lead (leadProvider, a relay of the ChatGPT backend such as Sub2API, #1109), relayed as it came even when web search is offered. A lead's turn carrying its subagent's sealed reply (send_message) goes back to the Responses provider that answered the lead's own conversation (leadProviderof the request'sconversationID, #1237); otherwise it is refused before anyone is asked (sealedReader,sealedTaskError). A sealed message (Message Type: MESSAGE, not a task) that nobody asked can open is left out instead, aninput_textnote naming its sender in its place (withoutSealedMessages, #1613): a lead on a chat provider whose subagent is on one of Codex's own models goes on, as the subagent's final result still reaches it as text. Only a sealed task (NEW_TASK, or an item with neither header) is refused. Who answered is first what affinity remembers; when affinity has let it go (30 days since, a restart past the 4096 conversationsaffinity.jsonkeeps, or the lead's last reply broken off,unanswered), the usage log's answers to the lead's thread and the request's own conversation in the last 30 days count too (loggedAnswers, #1367), andleadFirstreads the lead's key or account from them. A refused or failed call and a title answer nothing, and Codex's own sign-in is told of as the ChatGPT backend. The refusal names who sealed the task when it is known, and says how to go on with it. It also says what is sealed (sealedTaskItself, #1855): the task itself,spawn_agent'smessage, which the backend returns sealed (encrypted_function_args) and Codex hands the subagent as it came, sofork_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-subagentread askind:collab_spawn) before this check, whatever model its lead'sspawn_agentasked for (codexSubagentPickincodex_subagent.go): incodexBackendfor one of Codex's own bare models, which then goes throughserveAgent, and inservefor any other. Any model magpie serves can be set (provider.SetCodexSubagentModel, #1633): a task handed as text (a lead magpie served on a chat provider, or multi-agent V1) is read by any model. 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 aMESSAGE, whichwithoutSealedMessagesleaves out) is put only on a ChatGPT account's model; set to another, the subagent stays on the model asked for, which the sealed gate below handles as with nothing set. When magpie doesn't serve the model set now, or a gateway key held to some models may not use it, the subagent goes on the model asked for too. The route trace keeps both models and the reason it stayed (Route.Subagent), and the Routing page'skindWhysays it. Set tolead(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), withSubagentPick.Lead;codexBackendthen 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 (inservesuch 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 byagent.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 (codexFollowToincodex_follow.go, cybercaius on Discord). The model is the parent thread's last own turn (x-codex-parent-thread-idor 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 configmodelwhen 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-rschild_config.rs), so a bare model in a subagent's request under a lead on magpie's was named (spawn_agent'smodel,[agents] default_subagent_modelor a role's config), and with no model set for Codex's subagents in magpie it goes on that model (TestCodexSubagentKeepsTheModelItWasNamed, mengxiao on Discord); onlysettings.CodexSubagentModelmoves it (codexSubagentPick). Codex's auto-review follows the session only whensettings.CodexAutoReviewissession(settings.CodexAutoReviewSession):codexcatthen has each of magpie's entries name itself asauto_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 thefreeplan (codexcat.AutoReviewModel, the plan fromprovider.CodexSignInPlan), it counts assession(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 afterdesktopTurn, the tiers and the groups, whatever model its lead or its tier asked for (desktopSubagentPickindesktop_subagent.go). Desktop runs its Claude Code withCLAUDE_CODE_PROVIDER_MANAGED_BY_HOST=1, under which Claude Code ignores theCLAUDE_CODE_SUBAGENT_MODELmagpie writes into its settings (see agent wiring). A subagent's request is one withx-claude-code-agent-id(subagentOf) fromclaude-desktop, and only one that offers tools is its turn: Claude Code's tool-less helper calls and WebSearch subrequests taken by a served haiku pick are left to their own routing, 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:Resolvetakes any model name under a provider that is on), enabled, and allowed to a gateway key held to some models (groupAllowedfor a group); otherwise the subagent goes on the model asked for and the route trace says why (Route.Subagent, said on the Routing page bysubagentWhy, itsKindstaying empty).Route.Modeland the ledger'sRequestedkeep the model the subagent asked for.count_tokenscounts 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 inclaude-desktop.model(desktopTurn'sbySubagent): 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,desktopSubagentEffortindesktop_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.withFixedEffortcan enable reasoning when it was disabled, or disable it withnoneon a model that supports that level; a reasonless model is still sent no reasoning fields.countTokensapplies the pick after restoring any unmasked body.Route.Effortkeeps the incoming effort,Route.SubagentEffortthe 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-idinRoute.SubagentID(subagentTurnOfindesktop_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; itsx-claude-code-request-classandx-claude-code-agent-typehints go only to a first-party base URL or withCLAUDE_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 (tagKindinrouting.js): in the request list, the story, the replay and the tray panel, with the reasonkindWhygives Codex's.Kindstays empty, so its purpose stays unmarked in the Purpose filter, as in the ledger and on the Usage page. The ledger'sSubagentkeeps 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}intrace.go, set bymoveinserve): Claude Desktop's moves (desktopMoveindesktop.go:desktop-title,desktop-check,desktop-gone, each with a-firstform when it went to the first model listed for want of a chat turn or a menu pick,desktop-tier,desktop-search,desktop-beside,desktop-aside),classifier,claude-tier,stand-in(the agent's config),codex-turn(codexMemoryStandIn),dsh-compact(dshCompactToindsh_compact.go: DeepSeek Harness's compaction, known by compaction-basic's ask incompactAskssince its llm-pi-ai routes send nox-deepseek-harness-compact, goes onsettings.DshCompactModelwhen 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),codex-suggestions(codexSuggestionsTo, above),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) andprivacy(maskRouteFor). A subagent's move says its own (Route.Subagent), and a group orResolvenames no move. The Routing page tags such a row Title or Stand-in (movedTag,movedWhyin 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 onchatflowsai/claude-opus-5-5(the only Claude-looking id Desktop is shown, so its own pick) served on the chat'sagentrouter/gpt-6.1-solas the model swapped unasked (TestClaudeDesktopMoveSaysWhy,routing-moved-why.test.cjs). Codex backend rewrites done beforeserve(codexFollowTo,codexMaskRoute) show the moved model as asked and have noMoved. - A Chat or Responses client's effort spelled
off(reasoning_effort, orreasoning.effort, any case) is read at the top ofserveas magpie's own off level,none(offAsNone, plugins#334), and a model asked<model>:offas<model>:none(askedAt): every check and route below readsnone, a model with an off level is sent its own spelling of it, and one without goes at its least level asnoneasked does (fitEffort).offitself is never sent on.saysOfflooks 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'slightandextra_high, which Our Free Model's plugin lists) is the level it is (EffortLevel):effortOfreads it asloworxhigh, andNearestEffortplaces a model's own words by it, solowasked of a model listinglightis sent aslight, and itslightas it is (nianshou5 on Discord;TestNearestEffortTakesVendorWords,TestPluginThinkingOff). dsh and Pi offer such a model's levels as theirs, sent in its words (modelEffortinagents.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/userSaidinprompt.go, which the turn count (turnIn), the classifier's question (userText), the conversation's key (firstWords, inruleKeyand the affinity scope), the conversation's id where no session header names it (userOpens, inconversationID), Copilot's Auto (lastUserText) and the prompt breakdown's turns (userSays) all go by. It drops<system-reminder …>blocks (asource=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 (theinjectedlist besideagentsFor). 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 itsstateasprevious_user_messageandprevious_assistant_replybesidemessage,previous_message_kindandprevious_message_reasoning, each only when there is one, and its intent, level and effort instructions name the ones there are (jevState,priorAskindecide.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.firstWordshashes 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.Whyrule). 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, andprovider.Member.Alsokeeps 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, JSONintentSure, 0 to 1; missing keepsjevSure, 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;cloneGroupscopies it).readJevkeeps Jev's likeliest intent with its sure and marks a topic answer (verdict.Topic);ruleForapplies 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, JSONclassifyTimeout, seconds, insettings.go). Missing or 0 keeps the 15-second default (8 before ESern29751 on X: a classifier that reasons, MiniMax thinking even asked for none, Grok 4.6 and GPT-6 Luna going no lower than low, took 4 to 10 seconds over a real routing prompt and was cut off on most turns;TestReasoningClassifierAnswersInTheWaitUnset); saving accepts 1–60 seconds or 0 and rejects negative values or values above 60.Settings.ClassifyWaitbounds a hand-edited value above 60 to 60 seconds and uses the default for a value below 1.classifyTimeout()reads it for each call: bothaskChatinclassify.goandaskJevindecide.gogive 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 (renderRepliesinapp.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 chat classifier's call the wait ends is magpie's own limit (askChat's context has asideTimedOutcause, as an image's description's does, #2318): its usage row is a 499 that says "magpie stopped waiting: its decision model had no answer in …", a failure, not "the agent canceled the request". - 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 restingclassifyRestafter a failure) leaves a turn whose conversation had an intent, still one of this turn's, with that intent (Classified.Fallbackisprevious, itsErrorkept), 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 byclassifiedForinruleFor): 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 eachclassifyRest.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 andcallKindmarks themrouting; a decision model's (Jev, System One) record is written withKind: "routing"too. They go to the same key or account as any other request and count in its totals, whileusage.Group.Own(Record.ByMagpie: agentmagpieor one of itsmagpie-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 (classifierSubinplugins/routing/client.js). Its questions are the group's spend, so they are held to the accounts the turn is (classifierHeldinrules.go, carried byaskWaitedtoaskChat,askDeciderandaskDecisionGroup; AWilsonPeng on X: a group held to one of two ChatGPT accounts whose classifier was its own member asked on both): the group'sAccounts, the account its member names when the classifier is that member (each one's, for a model in it once per account), and the caller's (a gateway key's, a group above), never a key's models. A failure rests the classifier for those accounts alone (classify'srest).TestClassifierModelHeldToItsGroupsAccount,TestClassifierModelHeldToTheKeysAccount,TestIntentRoutesATurn,TestJevPicksTheIntent,TestSummaryCountsMagpiesOwnCallsApart,TestByMagpie,TestServedRefSaysASubscription,own-requests.test.cjs. - A group with no rules routes by its Routing (Quota first unless set otherwise, and it does not judge how hard a task is: the member whose allowance renews soonest first, ties in the listed order, the next taking over on a failure), and the editor says so in a line under Rules (
rHint2inplugins/routing/client.js, @canlee886 on X: it said nothing of it); with one model or routed Manual it says what holds the rules back instead.routing-rule-example.test.cjs. - A rule may name several members (
Rule.MoreafterRule.Use,morein the group's JSON,use=a,btyped; 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 (ThenUsesleaves 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;Insteadis that next one withUnreadyfalse, where anInsteadfrom a later rule comes withUnreadytrue).Uses,SetUses,MapUses,WithoutandNamesingrouprule.goare 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),nestedRulesandruleLed(the one of them a nested group's turn stays on),ruleEffort(the rule'suseEffortasked 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),ShareGroupand its import (one this magpie hasn't is left out of the rule), the CLI'sgroups rulesand 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/setUsesinplugins/routing/client.js). A rule of one member writes nomore, so a group saved before it reads and saves as it was. A magpie from before it readsusealone: its requests go to the first, and the others are plain members in the group's order; if it saves the group,moreis 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'srulesin their new order.routing-rule-drag.test.cjs. - A rule can set the reasoning its member is asked for (
Rule.UseEffort,useEffortin the group's JSON,use-effort=lowtyped; #2633, dengtongcai: an intent picks the model and the effort as a pair). It is an output likeUse, not a condition likeEffort.ruleForcopies it onto the hit (RuleHit.UseEffort) from the rule that put a member first, outer or nested;ruleOverkeeps that rule's members, andruleEffortgives each candidate of them the level fitted to its model's own (fitLevel), whichwithFixedEffortwrites into the request's field for its protocol (Chat'sreasoning_effort, Responses'reasoning.effort, Anthropic's thinking budget oroutput_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 (Effortsempty) 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.cleanRulesrefuses a value outsideprovider.Effortsand 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/bis not under/a/bc;~is the home folder; a Windows drive is one with its WSL mount (C:\workis/mnt/c/work) and a\\wsl$\<distro>or\\wsl.localhost\<distro>share is the distro's own path; case doesn't count on macOS and Windows, nor ever for a drive. A rule outside folders (Rule.ExceptFolders,except-folders=~/big-task; #1606, Ti800) matches when the folder is in none of them, and an agent that says none isn't known to be in one, so it matches; a rule may have both (Rule.ByFolder,inFolders). The folder is read from the request only when a rule of the group has folders or except-folders (workDirinworkdir.go), in each agent's own words, taken from captured requests: Claude Code's- Primary working directory: <path>(its</>as entities;(was <old>)after a change dropped), Codex's<environment_context><cwd>, Pi's<cwd>orCurrent working directory:in the system prompt, and OpenCode'sWorking directory:inside its<env>block. The caller's own layer — the system prompt and its{role: "system"}messages — is read whole, aclaude --barerun'sCWD: <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 nofolders=rule matches it (unknown, never empty). The same reading tells a plugin's fetch where its agent works (provider-plugins). A pause rule may hold by folder too (below). The trace'sRuleHit.Folderis the folder read, and the Routing page tells it beside the rule'sfolder …condition.TestFolderUnder,TestRuleMatchesByFolder,TestParseRuleFolders,TestWorkDirOfEachAgent,TestRuleByFolder,TestRuleMatchesExceptFolders,routing-folder.test.cjs. Rules by folder are never in a shared group (ShareGroupdrops everyByFolderrule). - A rule by agent (
Rule.Agents,agents=codex,sillytavern) matches the agent the gateway names the request's (agentOfingateway.go: itsmagpie-<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=30dheard from that it doesn't (notother, normagpie), and takes a name typed in its filter as the gateway reads a User-Agent (uaNameinplugins/routing/client.js, through the picker'sfield.typed): "MyApp/2.0 (Linux)" ismyapp.routing-rule-agent-typed.test.cjs. - A rule's field/op/value conditions (
Rule.Where,provider.Condinrulecond.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;effortis / 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;agentis / is not, asRule.Agentsreads agents;subagentis / 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 onRequest.subagentwhere the rules' request is parsed, so another agent's subagent counts as not one; andmessagecontains, 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);systemandlast(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 (excludeswhen none does):systemeach block of the system prompt (Request.systemParts,systemRaw, read bysystemTextsonly 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),lasteach 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 alastcondition 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 nowhereand 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,setWhereinplugins/routing/client.js); what the old fields can hold stays in them. The trace names awherecondition fromCond.Textin the page's words (condText, thenwhereText).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, onruleClock): the group's own rules and each nested group's on the way down to a member, a group named taking all its models, and a model named taking it wherever a group in the group has it (#625). It runs before planning, on every request rather than once a turn, so the model is not first, not a failover, and not kept by affinity, and comes back as soon as the hours end. It holds by hours, days, agents and folders only (cleanRulesrefuses another condition), and is not a send-to rule:Matches,MatchRule,ThenUses,Ruledand the compaction rules leave it out. A send-to rule naming a paused model finds it unready and the group routes as without it. The trace keeps what was paused (GroupRef.Paused), and the Routing page says so. Every model paused answers 503 (pausedError) naming each rule. Embeddings go by the same pauses; manual groups have no rules (Live), so none pause there. A pause by folder (#1606, Ti800: a subscription's quota kept for the long task in one folder,pause=<model> except-folders=~/big-task) reads the folder only when such a pause is on the way (provider.PausesByFolder, thenworkDir): outside its except-folders, which includes a request that says no folder (a subagent's or a small model's that doesn't), the model is left out; withfolders=, only requests known to be in them. Embeddings and System One's decision calls have no folder.Paused.Folder/ByFoldercarry what was read, and the Routing page says the folder or that none was said.rules_pause_test.go,TestPauseByFolder,TestPauseByFolderRule,TestParsePauseByFolder,routing-pause-folder.test.cjs. - A rule's hours and days (
Rule.Time,provider.TimeWindow) are read onruleClockin 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/Shanghaiortz=) and the TUI save the one typed, or this computer's (provider.LocalZone:$TZ,time.Local, the/etc/localtimelink) 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/groupsgives 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 (zoneNoteinplugins/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点30and full-width digits are those hours, inclockMinutesand the GUI'sclockOfalike, andtime=22~08takes~and~for the dash;9:5is 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.
- A routing group says how its requests are masked (
- Candidates come from
planGroupfor a group orplanfor a provider. They are filtered bysealedReadersandallowedCandidates. An account past its share is held out of the candidates (capHeld): a usage cap's share, each window at its own where the account gives it one (AccountWindowCaps, willz on Discord: 50% of the five hours, 40% of the week), 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 Claude account is held the same way, at 100% of a plan window with no cap of its own, when Spend extra usage is off (ClaudeNoExtraUsage, on by default, the Claude editor's Advanced; baksili_ on X: past its plan Anthropic bills it as extra usage), or once its extra usage has reached a cap set on its Usage credits window (Allowance.extraCapped, never before its plan is used up); the trace marks itExtraUsageandcappedErrorsays "set not to spend extra usage" (TestClaudeNoExtraUsageHoldsTheAccount,TestClaudeNoExtraUsageHoldsAtThePlan,TestClaudeExtraUsageCapHoldsAtThePlan). The warm-up sends neither such account anything while it is used up (codexWarmer.held,TestWarmUpSendsAHeldAccountNothing). A window set aside holds at an amount cap too, as its count reaches it (TestAsideWindowAmountCapHolds). A ChatGPT account's call oncodex-auto-review, which OpenAI counts in no window, is held by no usage cap, only by credits it may not spend (freeOnChatGPT, #1593,TestAccountCapLetsAutoReviewThrough); a Free plan's call is capped as any other (TestAccountCapHoldsAutoReviewOnAFreePlan). The account is held while any window is past its own share, andcappedErrorand the trace name the fullest such window's share and cap. When every candidate is held and one held for its credits spends its resets by itself,autoResetspends a reset on it and it is tried (planned.held). 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,resetBeforeCreditsspends 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 returnscappedErrororbarredError. 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 thatcodexAccountsput oncodex/,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 lone ChatGPT account is held the same way when Codex reaches it through magpie (connected beside its sign-in, or failing over): past its cap,codexAccountssends Codex's own-model turn throughserve, and the provider's fallbacks answer it (not_4O4 on X,TestCappedLoneCodexAccountGoesToItsFallback); the account row then says so instead of "Codex still uses it". 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).CapStopstill 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) hasreadCarefulread 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;capHoldthen holds an account whose usage was never read, whose last read failed or whose reading is still that old (carefulDoubt,Weighed.Unreadin 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 comescapHeldjudges it again, by what the reply before it left (Codex'scodex.rate_limits, Claude'srate_limit_event), or, when that reply said nothing of the account's usage, by a reading taken again then (nearCapAgain, at mostcarefulWait); held, it is passed over, and when it was the last the agent getscappedError's 429. A reply tells the usage as its turn begins, without that turn, and turns sent before the account came near its cap may still be out on it, other sessions' among them (yalifesign on X: capped at 90%, five sessions at once, used to 100%). So an account is near its cap by its reading plus what its turns not in it yet will spend: the turns out at the vendor and those come back since the reading last moved, each at what a turn spent as the usage moved up (Server.nearCapOf,turnSpends, at mostmaxTurnSpend). Near it, the turn also waits for every turn out on the account (lanes.out,lanes.idle; while one is out it goes to the next candidate first), and reads the usage again when a turn on it came back since its last reading (lanes.endedagainstUsageRead; a lane slot the request already holds, handed it bywaitMate, is its own,lanes.idle'sown;TestCapHoldsUnderParallelSessions,TestNearCapReadsAgainAfterATurnCameBack,TestNearCapWaitsForTurnsAlreadyOut,TestTurnSpendsAhead,TestLaneIdleLeavesItsOwnSlot). The cap is passed by the turns out as the account came near it, then 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 asstrictKeepkeeps it, and takes no turn there (TestStrictAffinityGoesPastTheCap). Thenaffinemoves the conversation's last answerer first, unless it is resting or nearly used up. AnX-Magpie-Accountheader (AccountHeader) pins the request to one account: only that account is tried, and when it can't answer the caller is told why. 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;pinnedNamedecodes it, the value as written matches too, and the trace and the call's record name it decoded (TestAccountPinnedPercentEncoded). - The candidate loop calls
attempton each candidate in turn, through aholdWriter. The writer holds the reply until it is clearly passing. A candidate that fails before anything is sent rests (failure): out of credit for 30 minutes (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 inrests.jsonbesideproviders.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 overrestsKeep(35 days) ago, a key no longer inproviders.jsonis let go, and a file orproviders.jsonthat 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 (aRetry-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 tolongestRetry(10 minutes) for a failure andlongestRateRest(30 minutes) for a rate limit back as soon as its rest is over, or up to the provider's ownrestCapin minutes (Provider.RestCapOr, at mostMaxQuotaRest;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 errorfailurereads as out of credit isretryableat any 4xx, so the next account or member is asked and this one rests as credit; before, a 400 or 422 counted only byquotaWords, 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 (creditWordsinshapeRefused) 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 restby: "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,limitRestOffin providers.json; the editor's Advanced fold, "Set it aside when out of quota or rate limited", ticked by default): a refusalrestAfterMarkedreads as out of quota, out of credit or rate limited, and any 429, then rests nothing, isn't counted or sunk, and isby: "off";restDrawerrests 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> 30sis turned away and namesoff. A 400, 403, 404 or 422 that says the model isn't served (unservedWords) and says nothing of quota, credit or a rate limit rests only that key's or account's model (modelRefused, keyed byrestID, its backoff counted apart): its other models are still served first in order (#1235, SenseNova's 403 "model is not available in the current token plan"; Anthropic's 404 for a model the account may not call, through Claude Code "It may not exist or you may not have access to it." and from the APInot_found_error"model: …", ZacharyZhang on X,TestClaudeModelNoAccessRestsTheModelOnly). So does a relay pooling accounts (CLIProxyAPI) answering a 5xxno 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 404NOT_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 byrestID, inrestAfterMarkedandrateRest): 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 (quotaHeldpasses 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 aquotaHeldorverifyHeldanswer), as no vendor does, andkeepRetrynotes it asansweredThereHeader, 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, fromquotaHeld, 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 carriesX-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 (keepRetrysetskeyLimitThereHeader, whichholdWriternever 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 410ModelDeprecated"Model exo-free has been deprecated.", whose own model list still names it; MOMO on Discord) rests only that model the same way, is retryable so a group's next member or another provider of it is asked, and is remembered (provider.Retire,retired.jsonbesideproviders.json): the model leaves that provider's entries in the catalog (buildEntries), so /v1/models, every agent's model list and the found groups go without it, until a request on it is answered again (UnretireinservedCandidate) or a week has passed. A refresh of the vendor's list doesn't bring it back early, since that list is where it still is. Aprovider/modelrequest for it is still sent. A 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 andnonetoo), 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 (reasoningBackRefusedinthinking_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 refillrefuseThinkingBackmakes: the request is whole, and another member's model may not ask for it (EDwinpzy on Discord,TestGroupFailsOverAMissingReasoning); a missingmessagesormodelstill 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 withmax_completion_tokens64000 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 aparam, 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 ofretryablematched: 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 (noteOverflowinaffinity.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, afterroomy, 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 (速率, 频繁, 并发, 每分钟…, inpaceWords) 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 (lengthWordsinfallback.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,lengthMargin0.5 intooLongUnsaid), 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 (unsaidStatusinfallback.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'smax_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 withinansweringLately(5 minutes,answeredLately, noted inservedCandidate): 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 tolongestQuota(8 days), so a reset time read wrong (a year off) doesn't bench the account for that long. The next candidate is then tried. A failed provider waitsfallbackCooldown(1 minute) at the back. An overload is no failure of the account's (vendorOverloaded: a 529, the ChatGPT backend'sserver_is_overloadedand Anthropic'soverloaded_erroramong them, or a 5xx whose words say overloaded, as Gemini's 503 does): its model rests on that accountoverloadRest(30 seconds), or as long as a Retry-After asks up tooverloadRestMost(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",…}}) restsrestrictedRest(2 hours) asrestricted(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'swbExplainand the plugin'sexplained()(0.1.17, the mover'smin) end the error withprovider.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;busyNowandroomy'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). Anthropic turning a Claude account off (claudeAccountOff,claudeOffWords: "This organization has been disabled.", which Anthropic answers as a 400invalid_request_erroras well as a 403; Claude Code's "Your account is on hold", which the bridge gives a 403,bridgeFailed; and "disabled Claude subscription access" / "OAuth authentication is currently not allowed for this organization"; and a flagged account's "Your account can't receive replies from Claude right now", a 403 (RiverOnVenus on X; Claude's apps show 「您的账户暂时无法接收 Claude 的回复」), either apostrophe or "cannot") is read as restricted too, for a Claude subscription account or a key on api.anthropic.com, not a relay's: its 4xx isretryable, so a group moves on, and like Google's suspension (googleSuspended) it is a ruling on the account, so it walls nothing off and the provider's other accounts are asked. Before, the 400 ended the request at the disabled account (Ramon317317 on X;TestClaudeAccountOffMovesToNextAccount,TestClaudeOrgDisabledGroupMovesOn,TestClaudeAccountOffScoped). Anthropic's third-party refusal (#4503) and a content refusal stay as they are. WorkBuddy's 11128 channel refusal stayspromptRefusedand 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,UnrestAllfor a replaced key,renewedfor windows that renewed) is noted by its rest key (restingUntil.lifted) and handed to the Routing page in the trace (TraceState.Lifted,liftedin/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 astream:falseResponses, 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 inrefusedHeader; before, it was answered 502api_error, asked again, and each account rested (#3274).restAfterMarkeditself rests nobody, and counts no failure, for a 400 whose error objectpolicyRefusalreads 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 andrefusalAsksAgainallows 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 itscontent_block_stop, the try fails as a refusal with nothing said (failRefused, nobody rests,matesFirst), and the next try writes throughspliceAfter, so its stream is the same reply: Anthropic'smessage_startis dropped and its block indexes go after those sent; Responses'response.created/in_progress/queuedare dropped,output_indexgoes after the items sent andsequence_numbergoes 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 nooutput_item.done, and the next reply'sresponse.completedlists only its own output (#4604). Zhipu'sfinish_reason"sensitive"and error 1301 (敏感), DashScope'sdata_inspection_failedand Volcengine Ark's*SensitiveContentDetectedare 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'sstop_detailscategory and explanation when it gave them (refusedDetail, #1768: "safety filter: refusal (category cyber)"); none is made up when it gave none.stop_detailsis 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 ofretellMost(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 andestimate; 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 withstop_reasonrefusaland itsstop_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 getfailTo's 400 (refusedStatus), which they don't ask again for.TestRefusalRetries*inrefusal_retries_test.gocover 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 ownweb_search_callin a request that doesn't declare theweb_searchtool is refused so, whatever the account, model or turn (a plain turn, a thread's description, a compaction, Codex's own text compaction for a custom provider withtools: []). Every request to the ChatGPT backend with such a history therefore declares cached-only search ({"type":"web_search","external_web_access":false},provider.DeclareSearch): an account's incodexBody, Codex's own sign-in relayed incodexUpstreamOn. It goes in the tools, or for Responses Lite (its header,reasoning.contextall_turns, or anadditional_toolsitem already there), which refuses a top-levelweb_search, in theadditional_toolsitem. A request that offered no tools getstool_choicenoneso the model can't search; one with a forced choice keeps it. A history without a search, or a request that declares search already, is relayed unchanged; Codex's ownweb.run(a function in thewebnamespace, 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 bothweb.runand the hostedweb_search(Savin on Discord, Codex 0.163.0-alpha;TestSearchedConversationUnderWebRun). siwc, API-key requests to openai.com and the legacy/responses/compactare 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 intools, 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 asprovider.CodexToolNamemakes 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 incodexBody, Codex's own sign-in's incodexUpstreamOn(/responses/compacttoo). A tool the agent declared under such a name is called back by its own: a translated reply throughdecoderFor(codexNamesBack), a relayed Responses reply throughnsTidy.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 sendsx-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).keepRetrynotes 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 (restAfterMarkedreturnsby: "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). - 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 statusesbusyStatus: 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 ofpassingread 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 ofpassingleave 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 inwallCodes, Raccoon'suser_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 isretryPausedoubled each round up toreplanLongest()(30 timesretryPause, 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'sPatiencelasts. A member of a group in the group uses the innermost that setsPatience(innerPatience, #2410), as FirstToken (#2246) and Sink (#2255) do; unset falls back to the group asked for, and an innerPatienceOffskips replan for that member (TestNestedGroupPatienceThroughOuter,TestNestedGroupPatienceInnerOff,TestNestedGroupPatienceFallsBackToOuter).replanRounds(12) is only a backstop that never comes first: the pauses alone add up toPatienceLongestin 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'sPatience, 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 forPatienceDefault, 60s; -1,PatienceOff, turns it off; at mostPatienceLongest, 240s). A pause that would end past the budget isn't taken, and the agent gets the error; 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 (notbusy), 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 withAgain(the pause),Replan(how many are asked again) andPatience(the budget in seconds). The group editor's "Every member busy" row sets it. A plain provider (aprovider/modelrequest, its accounts and fallbacks the candidates) first takes the same-one retriespassinggives the last one left:lastRetriesfor a busy vendor,rateRetriesfor a rate limit, each pauseretryPause<<nor a Retry-After of at mostlongestPause(8s). Past those, or for a Retry-After longer thanlongestPause, it is replanned the same way, its accounts taking turns as members do, for the provider's ownPatience(Provider.Patience, the same values as a group's, set withmagpie provider set <id> patience=2m|off|default; the provider editor shows no row for it and its save keeps it,TestProviderSaveKeepsPatience), unsetsinglePatience(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, ascodexBusyleaves 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 pastkeepHeldAfter; one of an hour, a quota, credit or plan limit, a 401 or 403, a refusal, response protection's 502 anddidNotStreamare notbusyor don't fit the budget, and reach the agent at once as the vendor said them. Its tries are traced withAgainalone, noReplanorPatience, so the Routing page tells it as the last one left asked again rather than as a group's members (TestSingleProviderWaitsOutAShortRateLimit,TestSingleProviderPassesALongLimitThrough,TestSingleProviderAgentGoneInTheWaitinsingle_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 (codexBusynever retries one), so the short rate limit this waits out doesn't arise there; its overloads keep theirlastRetriesand 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 withinclientRoom(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 everyX-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 markedGone(#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 typeagent_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'serrorcolumn, 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, fromcanceledon 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 saidcanceled, 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'sTriesonly 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 markedEarlier(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
messageis, whole,The request was rejected because it was considered high riskis a refusal with no code beside it (highRiskRefusalinpolicyRefusal): 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 underRefusalRetrieslike any refusal and rests nobody. A refusal error event before any content ends the try at once (eventRefusalError,stopas 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 whoseevent: errorname and data come in separate writes is still noted, and nothing is replayed.TestHighRisk*,TestRefusalErrorDoesNotWaitForEOFinrefusal_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,statusfirst, Gemini's relays'code; a string code is not one) is what the failure fails and rests as, beforestreamStatusguesses one from the message's words, wherever the frame is read: a held stream's error event (errOfinstreamEvent), 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, nototherat 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'sloopGuardSaid,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,TestNamedStatusOfinstream_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
trieswhen the route took more than one (rec.Tries, from the trace'sTries). A try a vendor refused or turned away (hw.refused,hw.turnedAway) still writes its own record, for what it billed and why it failed, markedhanded_on; so does any other try that failed, billed something and handed the request on, to another account or member or the same one again (failedRowinserve, written once the next try begins): a Claude subscription run that failed after Anthropic'smessage_starthad 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;relaykeeps the reply start's usage on a failure,TestClaudeSubscriptionFailedTryKeepsItsTokens). A try that failed before anything was billed has no record;usage.Totals.countskips such a record for calls and failures. A request failed only when the agent got an error (LostRequest); one answered after a failed try is counted beside it as answered on a retry (Totals.Retried,RetriedRequest, theretriedfilter). Logs written beforehanded_onare read the same way: the log index marks a failed, non-rejected record followed by another of the same route id as handed on (routeRowsinlog_index.go). Counts by account or route (vias, window holds) still count every try. A turn relayed on Codex's own ChatGPT sign-in is recorded as that codex account (codexServedincodex_backend.go), so the account card's window counts it; the Routing view still names the seat OpenAI, an API-key call staysopenaiwith no account, as does one whosechatgpt-account-idisn't the account Codex's auth.json here is signed in to (a Codex in WSL or under anotherCODEX_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 hosthost as email, still is. - A failed call is in
app.logtoo, 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).recordwrites 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 (codexEndedEarlyincodex_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 asresponse.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 aftershortDrain) (TestCodexReplyBrokenOffLogged,TestCodexClientGoneLogged,TestFailedCallLineOncePerMinute). - Each record keeps the service tier three ways (#1784):
tier_askedis what the client's body asked (bodyTier; Claude's speed fast readsfast),tier_sentis what that try's last request went out with, noted inforwardOnceafter every rewrite (fast picks, Ultrafast to priority on a plan without it) onto the per-attemptwireAt, andtier_servedis 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) itsautoanddefaultare empty too, since it says them whether priority ran or not (servedTierAt, applied inattemptandcodexUpstreamOn). The route's tries carrytierandtier_servedthe same way, on Codex's own sign-in (codexUpstreamOn) too, which before set only the route'stier, so a/fastturn there showed nothing (Anotiaww on X). The Routing page's request row shows a try's tier as a quiet tag beside the model (fastforpriority,Ultrafast,flex; an in-flight row the route's asked tier), with the served tier in its title when the reply said another (rowTierinplugins/routing/client.js,routing-service-tier.test.cjs). A bridge that doesn't go throughforwardOnce(the Claude subscription, Cursor's built-in) leavestier_sentempty. Through a Remote magpie the other magpie's word is taken (JackyFill on X: Codex → magpie1 → magpie2 → a ChatGPT account, Fast on in magpie2 alone, was loggeddefaulton magpie1): a try asked by another magpie (magpieAsks) says on its reply's header the tier it sent its vendor (X-Magpie-Tier-Sent,nonefor none) and, when that vendor'sauto/defaulttell nothing,X-Magpie-Tier-Unsaid: 1(stampTier, from the holdWriter'swriteHeader). The asking magpie takes them from a remote magpie's reply alone (tierThereinheardReply; a vendor'sX-Magpie-headers are never passed) and records them as its try'stier_sent(sentThere) and an unknowntier_served(servedThere); a chain of magpies passes the farthest one's on. A reply whose headers a keepalive sent before the try answered carries neither, and the asking magpie keeps its own record. Code:tier_record.go. - A record is priced at its tier (
Record.billedTier:tier_servedwhen the reply named one, so an OpenAI API call askedpriorityand run atdefaultis billed at the default; elsetier_sent, which is what a ChatGPT backend row has, itstier_servedbeing empty).catalog.TierPricereads the price from the model's models.devexperimental.modes: the mode whoseprovider.body.service_tieris the tier, or whosespeedisfastfor Claude'sfast, underopenaioranthropic. That price stands only where the row's price is that entry's standard one, so a relay's rate or the user's own price is left as it is. The pricing pages agree: OpenAI's Fast (Priority processing until 2026-07-30) is twice gpt-6.1-sol's standard and Ultrafast six times, Flex half; Anthropic's fast mode is twice Claude Opus 5.5's. A mode lists no long-context price or 1-hour write, so the standard's are scaled by the mode's own ratio. A tier OpenAI prices as a dated multiple of the standard (tierTimes: GPT-6.2 Astra's and Sol's Ultrafast, 3 times through 2027-02-28 and 6 times from 2027-03-01, Pacific time, which models.dev lists with no cost) is the standard times the multiple of the call's own day (catalog.TierTimes), every part and long-context rate with it; the price caches key on that day's rate (Record.tierKey), so calls either side of the change price apart (TestDatedUltrafastPricedAtItsDay, mu33410 on X; before, those calls were priced at the standard rate). The Usage page, a key's spend limit (NewCoster) and a subscription window's API value (apiPricer) all price through it (TestFastCallsPricedAtTheirTier, Archivemylife on X). Before this, every tier was priced at the standard rate. - An agent's fast pick (
settings.FastPicks, the bolt in its picker, #954) may also be insettings.UltraPicks(#1954), offered by the GUI only where one of Codex's accounts lists Ultrafast on the model (provider.CanUltra,UltraModels).fastPickmarks its candidatesultra; a try of one goes withservice_tier: "ultrafast"on Chat and Responses, and an agent on Messages carries it in the context (withUltra) toforwardTranslated, which setsRequest.Ultrafastfor 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, sentpriority. A Chat body's ownservice_tier: "ultrafast"is parsed as Ultrafast too (chat.go).TestUltraPickSentUltrafast. - A group's member may be Ultrafast as well as fast (
Group.Ultra, a subset ofFast,Group.SetMemberTier; the member's button steps Standard speed, Fast, Ultrafast whereultraOK;ultra=inmagpie group), and a model has its own speed (settings.ModelTiers, "/" topriorityorultrafast,provider.SetModelTier, Model settings andmagpie model tier; kdajenks on X). The gateway sends it on a direct pick for an agent with no fast pick of its own (provider.ModelTier, the branch afterIsFastPick), through the samefastPick, so an account without Ultrafast is sentpriority. A group member goes as the group says, and every summary of it says which: the group's card in Routing, its manual pick's buttons and menu (speedIninplugins/routing/client.js, from the member info'sultra), the TUI's member list andmagpie groupsay Ultrafast of an Ultrafast member and fast of a Fast one, and a route's try carriesWeighed.UltrabesideFastso its tag says Ultrafast too; before, all but the CLI said fast (OoopsHh on X,group-member-fast.test.cjs,TestGroupMemberUltrafastShown). On a provider the user added by its address (OwnFast, a GPT or o-series model on an OpenAI API) the member's button goes on to Ultrafast when OpenAI offers the tier on the model: one of Codex's accounts lists it, or Codex's ownmodels_cache.jsonentry for the slug does (codexcat.OwnOffers, the entryownTiersalready offers Codex), and the tier is only asked for, as its Fast is: a provider that turns the field away is asked again without it (KoiLx0 on X). A fast member never goes slower than the provider's extraBody asks: itsservice_tierultrafast(forced or not) makes a Fast member go Ultrafast (extraUltra), a slower one (flex) gives way to the member's Fast, and a forced!service_tierstill goes as written over all of them (TestFastMemberOwnProviderExtraTier,TestCanUltraOwnProvider,group-member-fast.test.cjs).TestModelTierSentToEveryAgent,TestGroupMemberUltrafast,model-speed.test.cjs. - OpenAI's own API serves
service_tier: "ultrafast"on the models its Ultrafast mode names, GPT-6.2 Astra, GPT-6.2 Sol, GPT-6 Astra and GPT-6.1 Sol (provider.OpenAIUltra, a dated snapshot too), on its Responses only (OoopsHh on X: in Docker an OpenAI key's GPT-6 Astra had Fast and no Ultrafast, since every Ultrafast offer came from a Codex account's or CLI's list). On 11-18 api.openai.com's/v1/responsestook the tier for those four and answeredInvalid service_tier argumentfor GPT-6 Sol and GPT-6.1 Terra;/v1/chat/completionsanswered that for every model. SoUltraOnoffers Ultrafast on an OpenAI key's Responses (and on a provider added by its address,OwnFast) for those models,buildResponsessends it to api.openai.com for them alone (another model goespriority), and a Chat Completions request to api.openai.com that would carry it, a client's own ask included, goespriorityinstead (chatNoUltra, in thetierMatecheck). Another vendor's model is untouched.TestOpenAIKeyUltrafast,TestCanUltraOwnProvider. A Codex (ChatGPT) account's list is asked with the newest Codex magpie knows (codexVersion), and with none at hand, as in Docker, withcodexClientVersionor npm's latest (codexPublished); the backend lists GPT-6.2 and Ultrafast only from 0.166.0, so the fallback is kept at or above it (TestCodexFallbackListsUltrafast). - Codex's service tier (
settings.CodexServiceTier, a row in Codex's settings, JackyFill on X) sets theservice_tierof every request of Codex's, whatever Codex's own/fastasked: empty is as Codex asks (the default, nothing changed),defaultsends none (standard),priorityis Codex's Fast andultrafastits Ultra Fast (the request values in Codex'sServiceTier; Flex is not offered, since the ChatGPT backend's requests drop it incodex_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 sentpriority, 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 sentultrafastonly where one of magpie's Codex accounts lists it on the model (UltraModels), elsepriority. Another agent's request is never touched, and fast picks still apply after.TestCodexServiceTierSet,codex-service-tier.test.cjs. - A client's
service_tier: "fast", Codex's own name for its Fast mode, is read aspriorityon Chat and Responses as the main handler takes the body (fastTierincodex_tier.go, before the Codex and key tiers above and beforetier_askedis noted), andcodexBodysends it asprioritytoo. Codex itself never sendsfast: itsServiceTier::from_request_valuereadsfastandpriorityalike as Fast andrequest_valuesendspriority(openai/codexcodex-rs/protocol/src/config_types.rs). Before,fastwas dropped on the way to a ChatGPT account (codexBodykept onlypriorityandultrafast) and never set the IR's Fast (Archivemylife on X). Claude's equivalent isspeed: "fast"(Anthropic's ownservice_tier,auto/standard_only, is about capacity, not speed), already read as Fast. The ChatGPT backend's reply saysautoand thendefaultwhether priority ran or not (servedTierAt): on gpt-6.1-sol afastask decoded at about 29 tok/s against about 22 without, both answereddefault.TestFastTierWordReachesCodex,TestCodexBodyServiceTier. - The Codex client magpie presents to the ChatGPT backend (
settings.CodexClient, a row in Codex's settings, ouhthuo on X) is Codex CLI by default (originator: codex_cli_rs,User-Agent: codex_cli_rs/<ver> (<os>; <arch>) <terminal>) ordesktop:originator: Codex DesktopandCodex Desktop/<ver> (<os>; <arch>) unknown (Codex Desktop; <app build>), as codex-rsdefault_client.rsbuilds it from the originator the app sets. Only these two values are accepted.codexClientHeadersininternal/provider/codex_request.gois the one place both headers are set, so a model request (codexSign), the account calls (/wham, resets, token refresh, device sign-in) and a test asked as Codex all follow it; the sign-in's authorize URL keepscodex_cli_rs. A real Codex client's own originator never reaches the backend on a signed-in account:codexSignreplaces it, which this setting now chooses. - A usage record carries its prompt's cache beside
inandout(#1839):cache_read(tokens read from the vendor's cache) andcache_write(cache creation, Anthropic'scache_creation_input_tokens;cache_write_1hthe part written for an hour).inholds 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'sprompt_tokens_details.cached_tokens, DeepSeek'sprompt_cache_hit_tokens, Moonshot's top-levelcached_tokens, Mistral's older top-levelnum_cached_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_tokensandcache_creation_input_tokens, DeepSeek'sprompt_cache_hit_tokens, Mistral'snum_cached_tokensor Moonshot's top-levelcached_tokensbeside a 0 inprompt_tokens_details) is told in OpenAI's too, streamed (chatTidy) and whole (chatWhole), byopenAIUsageinchattidy.go:prompt_tokens_details.cached_tokens(andcache_write_tokens), withprompt_tokensandtotal_tokensmade 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, readsprompt_tokens_details.cached_tokensfirst, 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,TestMayMendUsageOnlyOtherNamesinusage_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, anapi_errorsaying " refused magpie's credential (HTTP 401): …" with x-api-key said as "API key", and any other error such a request is told keeps its status with x-api-key said as "API key", as does a stream's error after its 200 (keepsSignIn,claude_signin.go). Recent calls and the usage log keep the provider's status and message. Any other 403, and a request with magpie's key or an API key, is answered as before. The sign-in's beta (oauth-…inanthropic-beta) isn't passed on either (askedBetas), so a provider gets the request as Claude Code with magpie's key sends it; a provider's ownheader.anthropic-betastill goes. - A 400 that names betas a provider doesn't take, in Bedrock's words ("Unexpected value(s)
xfor theanthropic-betaheader",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 awaytool-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 underapplication/jsonwas 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, throughAPIErrorand 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" anderror code: 1005–1020) withBlockedHintafter 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 emptyresponse.failedevent, 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 (
openCodeBareRefusalinforwardOnce, #3740), is the 502 it stands for: OpenCode Go answered s-leeq's requests400 {"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 missingx-opencode-sessionrefusal 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/v1answers a refused key) is the refusal it stands for (provider.ZhipuEnvelopedinforwardOnce): 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 (
byteCapRefusalinbody_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 inforwardwith 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 inforwardOncebefore 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 413request_too_largenaming the size, the cap and what was kept (overCap), so Codex is toldcontext_length_exceededand 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 throughforward. - The vendor's reply headers a provider passes on (
ReplyHeadersand 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 throughforward(relayed, translated, a plugin's fetch, a signed-in account) orretrieveAs/retrieveOpen(embeddings, audio), and each tells its reply's passed headers to the try that asked through the try's context (withReplySink,heardReplyinreply_headers.go). The sink is the try'sholdWriter(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 failurereleased 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 throughheardHeaders. A stream whose headerskeepAlivesent before the vendor answered (pastkeepHeldAfter) 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 tryforwardOncemakes, so chat, responses, messages, count_tokens, a group's members, fallbacks, signed-in accounts and a plugin's fetch all take them:forwardOnceputs the agent's headers in the try's context under the try's provider id (provider.WithClientHeaders), andProvider.Signpasses the ones that provider lists and no other's. Not carried: embeddings, images, video and the Codex backend relay, which don't go throughforwardOnce.TestPassHeadersReachTheProvider,TestPassHeadersOnlyToTheirProvider. - A streamed request is never left silent while its vendor says nothing.
holdWriter.watchruns beside each try: pastkeepHeldAfter(3s) it sends a held try's agent the stream's 200 and SSE comments (keepAlive), one everykeepHeldEvery(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 afterkeepaliveEveryof quiet. It goes on for as long as a translated stream's do,translatedQuietLongest(30 minutes) with nothing from the vendor, and then the try is ended: the client gets a 504 " sent nothing for …", as its stream's error event when the reply has passed, and nothing is tried again after so long a wait (holdWriter.endStuck). Before, the comments stopped atkeepaliveLongest(5 minutes) and the client met only its own idle timeout: pi's "stream idle timeout after 300000ms" on a relayed Claude (Wing8Aqua on X;TestQuietClaudeStreamKeptAlivePastFiveMinutes,TestQuietClaudeStreamStuckEndsWithAnError). 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): everykeepaliveEveryit sends the client's keepalive (enc.keepalive: a ping for Anthropic,response.in_progressfor 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 fortranslatedQuietLongest(30 minutes), past the 10 minutesupstreamHeaderWaitgives 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 (notAnAPIReplyreads its first bytes before the reply is translated). An Anthropic client is sent a ping at most once eachpingEvery(1 minute), comments between, and none beforemessage_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'MessageStreamfails on any event beforemessage_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 thankeepHeldAftersends nothing, so its 429 keeps itsRetry-After. A proxy in front such as Cloudflare (125s) otherwise ends the request (#947). Gemini streams get no comments (#934). A vendor that then ignoresstream:trueand answers 200 with its reply whole has it sent as the agent's stream (wholeAsStream: Chat, Responses, Anthropic), not as the stream's error, while a 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 withfinish_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 group member's reply that ends having said nothing at all — no text, no reasoning, no call, in an event that says nothing itself: a Chatfinish_reasonother thanlength,erroror a filter, Messages'end_turn,stop_sequenceortool_use, acompletedResponses reply, Gemini'sSTOP— is held as no answer while a member is left (eventEmptyEnd,holdWriter.emptyFails, 502emptyEnded), so the next member answers and nobody rests; a reply held whole is judged in the one parsesettlealready makes (readWhole), and the last member's empty reply, or a model asked alone, goes as it came (#6712: an AI Studio plugin's 200 with a role chunk andstop;TestEmptyStopFailsOverToTheNextMember,TestEmptyStopEndsAtTheLastMember); 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 eventstreamEventdoesn'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 itsserver_is_overloadedreached Codex with five candidates left) stays held as long as its agent is kept alive, up toholdLead(4 minutes, under the 300s Codex waits for an event;keptQuiet), so aserver_is_overloadedthat comes after it is a failure the next candidate answers (#1418: let through at 15s, the ChatGPT backend's failure 36s in ended Codex's turn with sub2api, next in the group, never asked). A stream whose agent can't be kept alive (Gemini's) is let through afterholdLongest(15s), as before. Codex counts only events toward that 300s, not comments, so the bound is the request's, not each try's: once Codex on Responses has heard no event foragentQuietMost(4 minutes) since the request began or its last event (keptAlive.tooQuiet), the try in hand is let through (scan,keepQuiet), and no group replan or same-one retry is taken whose pause would end past it (fadenoob on Discord: held tries and replan pauses added up past 300s and Codex reconnected on "idle timeout waiting for SSE"). A translated reply whose upstream stream stops before it said its reply had — an Anthropic one with no stop_reason and no message_stop, a Responses one with noresponse.completed, the same two a relayed one is told by (sniff.whole; a Chat stream may end without[DONE]and be whole), a Gemini or Code Assist one whose last chunk has no candidate'sfinishReason(geminiEnds, #1643:usageMetadatais no end, Vertex AI sends it on every chunk; a chunk with no candidate at all is the empty reply's to answer, #667), and a relayed Gemini one told the same way (#1644; it ends in Gemini's own{"error":{"code":502,…,"status":"UNAVAILABLE"}}data line fromstreamFailure,TestGeminiRelayEndedShort; whatever a relayed stream gets appended, that error or a filled-infinish_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 nofinish_reason, relayed or translated (saysItsEnd; Linka on Discord: the upstream hung up between a whole function call and itsfinish_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 thefinish_reasonwas lost and it is filled in,tool_callsafter a call andstopotherwise, 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 alengthstop, translated whole or streamed, and as aresponse.incompleteatmax_output_tokenswhen 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 aftercontent_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_TOKENSincluded, so one without it was cut:TestGeminiUpstreamEndedShortasks 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 asresponse.completedwith 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 emptyend_turncounts its prompt and stays a whole reply (TestWellFormedStreamsStillComplete). A relayed one is read the same way once: a Responses stream whoseresponse.completedcarries 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 withoutput: []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 owntype, a numericcode,param,request_idand every field magpie knows nothing of. Onlyerror.messageis magpie's: the provider's name before the vendor's words (a describer asking for another model, the Claude sign-in rewording inclaude_signin.goand the agent read it there), with a note where magpie has one (an account'sExplain, 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, andtype/code(OpenAI'scontext_length_exceeded),typeand 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). - What the agent reads of a vendor's error puts the vendor first, so a user can copy it to the vendor as it was said (@gptchan404 on X,
upstream_said.go). The first line is the provider's name, then the vendor's own words (provider.VendorWords:APIError's reading with none of magpie's hints), then what the vendor named it by,(HTTP <status>, <code>, request id <id>), leaving out any part its words already hold. A plugin's message is its vendor's words, then the plugin's advice after " — " (asprovider.Explainjoins them). Only the part before the dash is the vendor's (pluginWords), and the advice goes on magpie's line. magpie's own notes follow on a line of their own,magpie: …. This applies to every client protocol, whole and streamed (upstreamToldinwriteVendorErrorFrom), and to a safety-filter refusal no one else answered, whose magpie line is<model> refused this request (safety filter: <code>) via <provider>(refusalTold). Only the agent sees it this way. A try's held reply keeps magpie's reading (holdWriter.retold, applied byretellas the bytes leave for the agent), because the rest, the rate hold, the retired model, the verify hold and the failover all read the held bytes andcall.Error, which are unchanged. A held verify answer (verifyHeld) is magpie's own, with no vendor asked, and keeps its one-line form (upstream_said_test.go). - A reply that said nothing (
emptyReply, #667) onemptyAccounts(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 (emptiedin 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).TestEmptyReplyOnTwoAccountsEndsTheRequestininternal/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 withmagpie provider set <id> errors=pass;TakesPassErrorskeeps 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'sholdWriterholds 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;forwardasks once afterdsRetryGone(magpie's own file ids),passthroughandforwardTranslatedreturn the first failure without a re-ask in another shape,streamTranslatedneither continues nor asks again after an empty reply, andrestAfterMarkedrests none of its keys. Its error goes throughpassError(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,TestPassErrorsOtherAPIininternal/gateway/pass_errors_test.go. - A vendor's error keeps its
codeandparamon its way to an OpenAI-shaped client (writeVendorError), wherewriteErrorused to set both to null: a status error relayed or translated, and a request refused inside a Responses stream. A Responses stream'serrorevent or failed response whose error is of typeinvalid_request_erroris the request at fault (requestRefused, read by its type, not its words): itsEventcarries 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 502api_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), soholdWriterreads it as the 400 it is. Before, the hold read magpie'sapi_erroras a 502: the same request was sent three times, then to the other accounts, and every one rested (magpie-releases#18: the ChatGPT backend answersaccess_programsnaming a program the workspace hasn't got with a 200 stream whose error isaccess_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
streamErrorsays 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 itserrorMessagealone), 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.TestStreamErrorSaysItPassesholds Pi's own lists;TestGroupLastFailureInStreamSaysItPassesruns a group whose last member fails after the keepalive. A 413 byte cap in that stream saysrequest_too_largein the error text, and Chat and Anthropic name that type, so Pi compacts; Gemini keeps its own status shape (TestStreamedByteCapSaysRequestTooLargeToPi,TestStreamErrorByteCapInEveryShape). Responses'response.failedcode for it iscontext_length_exceeded, the one code Codex compacts on: withserver_errorit 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) isserver_is_overloadedthere, as the ChatGPT backend says one in a stream: Codex shows the model at capacity and stops, whereserver_errorhad 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 400context_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 forwantsWhole), which is never sent a 200 or a keepalive either:codexCompactreads 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'smessage_start, Responses'response.createdand the events after it), it is the model the agent asked for, asservehas 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 toholdThinking, 4 minutes) so that a refusal after it goes to the next candidate unseen (#248). It is held only while one could: on the last candidate a refusal isn't asked again, so 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 bystreamTranslated, 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 evenresponse.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 endedcontent_filterwith 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 answerthoughtCleanMost(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 itsthinking with <effort> effort(#4166). A retryable error after the reasoning, nothing yet said (Anthropic'soverloaded_errormid-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,TestClaudeThinkingStreamsOnceTrustedandTestClaudeTrustedThinkingStreamsThroughGroupinthinking_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.Writefeeds every streamed try, passed through or translated, a key's, a built-in subscription's or a plugin's (a moved WorkBuddy's fetch in the plugin host,TestLoopEndsWorkBuddysReply), in each of the agent's protocols, to aloopGuard(loop_guard.go). It cuts the reasoning and the text, each apart, into units, its lines and sentences (a list's1.or a decimal is no sentence's end), compared without case or a closing stop. A unit with no word in it (a letter run with no digit: not a brace, a rule,0x00, a hash or a row of numbers) isn't counted. When the lastloopWindow(256) counted units of either are among no more thanloopDistinct(24) different ones, the try is cut (cutLoop): what came with that write goes out, then, 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 isreply_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, throughholdWriter.onLoop; cdredfox on X, WorkBuddy AI's DeepSeek v4 flash): the agent keeps the reasoning it has, the next try's follows it in the same stream, as an empty reply's re-ask does (#667), and only a loop on that try ends the reply with the error (TestReasoningLoopIsAskedAgain). A 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 secondmessage_startorresponse.createdcan'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 (TestLoopGuardLeavesOrdinaryRepliesAlonefeeds magpie's own sources and docs through it). A reply sent whole (no stream, or Gemini withoutalt=sse) isn't read. Settings › Models › Replies › Stop looping replies (noLoopGuard) turns it off. - 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 inserveAgentbefore 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 lasttoolLoopRepeats(8) turns are each the same calls (name and arguments, keys in any order, call ids ignored) answered with the same results (with Codex'sWall time,Chunk IDandduration_secondstaken out,runNoise) and nothing else from the user, the turn is answered in the agent's own protocol, streamed or whole (writeLocalTextthroughrelayStatus), 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 pasttailOf), 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 providermagpie, rejected, its session and an error startingtool 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) orreasoning_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 byparseChatin chat.go); the passthrough has read all three sincemistralThinking(#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 inreasoning_contentfor a model whose name says DeepSeek wherever it is served (chatReplaysReasoning), which Mistral refuses — 422extra_forbiddenonmessages[].reasoning_content, every follow-up of a Codex tool loop after its first call (#4906) — so the built body goes throughmistralThinkingtoo, 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 readreasoning_contentalone, 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. Quota first 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'sunreached): 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 withPercentalone, 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, fromQuotaWindow.RunsOutAt;Allowance.Renewal): the WorkBuddy plugin (0.1.14) sends it on its Credits window as the soonest end of a package with credits left (cdredfox on X). When the renewals tie to the hour, Quota first 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 Quota first sorted by them,soon(Allowance.Renewal) andlapse(Allowance.Lapse) beside each window's ownrenews(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 beforesoonis read fromrenewsandrestarts. Only Quota first 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'susedRenews), 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 Quota first still ranks it by its month (#1778). A route from beforeusedRenewssays when only for an account of one window. Affinity keeps a conversation on an account at 90–97%: onlySpentShareOf(98%, 100% In order) stops it (affine), while the 90% tier (lowShare) orders only conversations nobody has answered. - A turn's end is told to the app for the "Task done alert" notification (itieniu on X,
turndone.go). The trace follows each agent session's turn (turns, keyed by agent and session): a request is of the turn unless it has aKindor is a Claude Code subagent's (agentTurnOf), and its reply is scanned on the way to the agent for a tool call in any wire format (toolScan, a JSON value such as"type":"tool_use"or"finish_reason":"tool_calls", never a key or text). The turn is done when no request of it is going, the last reply was whole, under 400 and called no tool, and nothing more came forturnQuiet(4s); a session idle pastturnStale(30m) starts over. Only a turn that ran at leastsettings.TurnDoneAlertseconds is told (TurnDone, set by the GUI; nil undermagpie serve, so nothing is followed). The ChatGPT backend path (codexBackend) is followed the same way.TestTurnDoneSaidAtTheTurnsEnd,TestTurnDoneCodexBackend,TestToolScan,turn-done.test.cjs. - A request's masking record is told to the app for the "Masking alert" notification (Must2333 on X,
OnMaskedinmasked.go, set by the GUI; nil undermagpie serve), aftermaskrec.Holdand with its text around placeholders (Snips,Back) taken out.mask_alert.gokeeps the records whilesettings.MaskAlertis 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 formaskGather(3s) and said as one, and one is said at most everymaskGap(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 onlyrestID), so neither leaves a member out. The same applies incount_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 resetsautoResetmay 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'ssaid), saying when it is asked again. A key whose rest magpie guessed the length of, the vendor and the user naming no time (creditRest, orquotaRestwith noProvider.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 429insufficient_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;quotaHeldstill holds keys alone, andautoResetlifts 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 vendorRetry-After, while every candidate tried is resting, carries one: the seconds until the first of them is asked again (soonestBack, byasksAt), none after a key's first refusal.TestRetryAfterALimitIsAsked,TestHeldLimitAskedAgainInAMinute. A quota refusal with no word of when it is back restsquotaRest(15 minutes), or the provider's ownquotaRestin minutes (Provider.QuotaRestFor, at mostMaxQuotaRest, 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, oruntil 00:00+08:00on 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 itsRetry-After, unless that was more thanlongestWait(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": aRetry-After, ananthropic-ratelimit-*-resetorx-ratelimit-reset-*header, or a refusal'sresets_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 aRetry-Afteruntil 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 withLimitRestOff, 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). A rest out of quota or credit till a time the vendor named is lifted only when a reading finds its window started again in fact (restarted, #2718); a reading that finds the window full no more while that time still stands (renewed) lets the hold go once for that time, without lifting the rest (askOnRenewalLocked,restingUntil.renewAsked), so the next request asks the vendor: a reset bought on the vendor's side (Zhipu's 重置卡) was answered with the held refusal till the time it named (RookieRicardoR on X;TestRenewalAsksAVendorTimedRestOnce). Refused again with the same time, it is held till it, whatever readings say. 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 incodexHolds(noteCodexHold), and Codex's retries are answered with ChatGPT's own refusal and aRetry-Aftertill 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 inkeysas well as inkeyis 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 hasbusywith the load. The load comes from the plugin throughplugin.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 Whybusy,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,probeOnenever asks it before its rest ends, though its vendor may be back in a minute.restAfterMarkedmarks the restProbedwhen it is a key's own (not an account's or a plugin's, not one model'srestID),failOtherbybackoffafter a 5xx, a 408 or no connection, with no Retry-After or reset header, at a provider whoseListasks over the network (Provider.ListAsks), and long enough for a first ask.keepProbingRests, started inListenAndServe, 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; an Azure key that answered before is the exception below), 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,probeAnsweredinserved): the list answered for the vendor, not for its chat. Only the loop's ownServerasks (restProbes.asking), so a test'sServernever 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. - An Azure key that answered before and is refused 401 rests suspended (
azure_suspended.go, canlee886 on X). An Azure subscription with a spending limit (a student's, a trial's) is disabled when its credit runs out and enabled again on its own when the credit renews; meanwhile every request 401s with "Access denied due to invalid subscription key or wrong API endpoint", the words a wrong key gets.restAfterMarkedreads afailOther401 asfailSuspendedwhenazureSuspendedholds: no account,Provider.IsAzure, and the key has answered a request (provider.LastServedatprovider.ServedID, served.json, kept 30 days) or is resting suspended already (so a rest that ends while Azure still refuses stays one after the answer leaves the file). It restssuspendedRest, a day, bysuspended, andprobeabletakes it whatever its status: the background ask above lists the resource's deployments with the key (azureModels), refused the same while the subscription is off, and lifts the rest as soon as the list answers, or a request does (served). One 401 is enough: a 401 is about the credential, never the model or the request, and on a key that worked a transient one is lifted by the first ask a minute in, as the old one-minute backoff would have let it back. A key 401 from its first request (new, mistyped, or edited, itsKeyIDanother) has no answer on record and fails as before:failOtheron the short backoff, shown "401 · failed", never asked in the background; a served.json that can't be read is no answer on record too. Azure's alone: a 401 says nothing of why elsewhere, and a list that answers without the key (OpenRouter's is public) would lift a key the vendor still refuses. Not covered: a 403, a key whose last answer is over 30 days old after a restart (rests are in memory), and the last candidate of a request, which rests only for quota, credit or a timed rate limit and so is asked again by the next request as before. No setting: the probe finds the day Azure enables it, so there is no "back on day N" to type in. The key list says "suspended by the vendor" with the background words, and Routing'srestHowsays the vendor has likely suspended it.TestAzureKeyThatAnsweredRestsSuspendedTillItAnswers,TestAzureKeyNeverAnsweredIsABadKey,TestSuspendedIsAzureOnly,TestSuspendedOutlivesItsLastAnswer,azure-suspended.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 throughWithKey, which moves it there (atKeyPlan), on the first try and on a failover alike.perKeyBarredleaves 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 sameperKeyBarredandWithKey; 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'sfetchAvailableModels, a ChatGPT or Copilot account's own/models, a plugin account'smodels) isn't planned while another of its accounts lists it (perKeyBarred'sleft,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,askUnlistedmoves 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 (
roomyinfallback.go, inserveafter the rules, affinity, the image filter andpinTo, beforeprobeOne; 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'sContexts, 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'sleftwithwindowset to that window. Asked, such a member only refuses, and a refusal that doesn't say why, for a request short oftooLongUnsaid'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,failOverflowandtooLongUnsaidstay 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'sleftto 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'sCacheReadplusCacheWrite, passed toanswered) and the cache isn't cold (cacheCold, 5 minutes; for a ChatGPT accountchatGPTCold, 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 forkeepsEffort). Past that window it stays while the vendor said it keeps at leastcacheWorthtokens of the conversation for an hour (hourCache, #2302): a reply with Anthropic's 1-hour writes (cache_creation.ephemeral_1h_input_tokens, the usage'sCacheWrite1h, as Claude Code asks of a subscription) keeps what it read plus those forcacheHour, 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. A change the user makes to how it is routed counts at the conversation's next turn under Auto, whatever is cached: a reorder of a provider's accounts (provider.NoteReordered,reorderedSince), and a change of a group's routing, kept as the group'sRoutedAtbySaveGroupso the CLI's and TUI's changes reach the gateway too (reroutedSince; #6708: picked by hand to A, then Use before expiry, the conversation stayed on A by a 2.8k-token cache;TestReroutedGroupTakesTheConversationAtItsNextTurn). Session and Strict, and a turn under way, keep it. Routing ranking another member first on its own merits does not move a warm cache ofcacheWorthor more: the ranking moves with every reading, and a move pays the whole prompt again uncached. 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'scache_creation_input_tokens), and the second turn stays to read it rather than moving asno-cacheand building it again elsewhere (vilicvane on Discord). The stick keeps both, on disk too (affinity.json'scacheWrite, absent in a file from before and read as 0, so such a stick is judged by its read alone), and the trace'sAffinity.CacheWritelets 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'sInput) 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 afterretryPause(1s, or a Retry-After up tolongestPause) without resting, before the request moves on (keptAgaininaffinity.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.Keptwith itsAgain), 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 freshaffinekeeps only the candidates of thatwho(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,strictKeeptakes 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 saysstricteven 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
Fallbackmodels (its trace row'sFallback) 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 (backToMaininaffine,Affinity.Whymain). "Ready" is whatrestLastsays: the provider's rest over, which is when the restrestAfterset ends (a minute and backing off for a plain failure, the vendor's named reset or Retry-After for a quota or rate limit,quotaRest15 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 neverFallback; 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…",affWhyinplugins/routing/client.js); before,mainshowed 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
cachekept 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 (backToFirstinaffine,Affinity.Whyorder; 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):affinegetsinOrderfrom the provider's routing when the request isn't to a group, andbackToFirstthen compares accounts (candidate.who) rather than members.TestOrderedAccountsGiveTheConversationToTheFirst. Within a turn it stays, on the reasoning the later member sealed, as withmain. 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 (Quota first, 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 Quota first 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:
restAfterrests the one that failed before the try goes on) or known all but used up (UsedatSpentShareOf):standsInFor, over the plan as it was for the request, by each candidate'splacein the group's list (placedinplanGroup; a group in the group is one member). The stick keeps it (stick.stoodIn, andstoodIninaffinity.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 (Quota first'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.Whyback); 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 Quota first 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 Quota first 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,
ruleForsetsRuleHit.Endedwhen the last turn's rule had hours that no longer hold, andaffinelets go of the conversation (Affinity.Whyhours) 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 (affWhyinplugins/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 lastheldFor(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 (
burstSpreadinburst.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),burstSpreadputs first, of the candidates alike to the first, the one with the fewest requests in flight (inFlight, bycandidate.who), ties keeping routing's order, and counts the request there in the same hold of the lock; the count is given back whenserveends. 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 andVia, 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 sameLearns, both with room (burstTier0) 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. Quota first, In order, By weight and the others keep their order. Not moved, only counted: a conversation kept (Affinity.Kept), Strict, anX-Magpie-Accountpin, a sealed task's lead, a native compaction's reader, and a new conversationleastHeldspreads (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 (Quota first, 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).leastHeldwithreadypasses 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 pastlowShare), 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 isreadyForNew(withLead), so a session keeps one account, its subagents included. Held is the lastheldFor(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. - Least used first spends credits about to lapse first (kudi3699 on X, 11-12: a WorkBuddy account half through a pack ending in March, with check-in credits ending tomorrow, ranked by the whole pool's share and was never picked).
Allowance.Lapsingis what a window loses atRunsOut(RunsOutLeftofOf, at most what is left) as points of the used share, in full when it is within a week and not at all past it (11-12, kudi3699 again: a fade across the week left a 20-credit check-in reward under the threshold); an amount not told is zero, never guessed.routes.Seat.Lapsingat 0.1 points or more (urgent) puts a seat with room ahead of the rest, the soonestLapsefirst, then the share used as before; one at 90% or more is not helped. Any plugin whose usage window sendsrunsOutAtandrunsOutgets it.TestLeastUsedSpendsLapsingFirst,TestLeastUsedSpendsWorkBuddyCheckInCreditsAboutToLapse,TestAllowanceLapsing. - 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.WhyleadwithLeadModel; #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 byleastHeld, or by Quota first'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 withinheldFor, holding at leastcacheWorth(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 Whyfirst,gone,cold,no-cache,cacheandsession, by the model routing put first (in a group, another member on that account is another model and is never picked), and only to onereadyForNew. It is not followed mid-turn (a keptWithin), under Strict, In turn, nor for a subagent (withLeaddoes 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_creditswith a balance over 0, orunlimited;QuotaWindow.Credits,Limit.Credits,Allowance.OnCredits), or as Codex itself hears it on every reply, the 429 included (x-codex-credits-has-credits,-unlimitedand-balance, both bools required, an image limit's left out; andcreditson acodex.rate_limitsevent:heardCodexCredits,codexEventCredits,provider.NoteCodexCredits; 123xtv03k on X, 11-15: an account used up on its plan stopped where Codex alone went on on its bought credits), is not out when a window fills (豆子 and Zhenzhen on Discord): ChatGPT may answer the turn that uses the window up 429usage_limit_reachedbefore 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 restsfallbackCooldown(Rest.Bycredits) and is read again, not until its window renews (the relay's hold too,noteCodexHold); a rest taken for a used-up window before its credits were known is lifted once they are, heard or read (provider.OnCredits,creditsKnown), and its full windows rest it nowhere else (fullis zero for it,spendsCredits). Quota first, 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.TestCodexCreditsHeardOnTheRefusal,TestCodexCreditsKnownLiftsTheRest,TestCodexCreditsRead,TestNoteCodexCreditsKeepsThem,TestReadingTellsCreditsBought,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 iscreditsLastwhile it goes on on its credits (spendsCredits) and a window for the model is used up where off would hold it (Allowance.CapHeldatWindowCaps{Credits: true}; a call ChatGPT counts in no window,freeOnChatGPT, stays).restLastthen 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.Whycredits,lastBehind), within a turn too, and In turn's next pick and Quota first/Pace/Least used's spreading of new sessions never bring one forward (after,leastHeld,readyForNew). Strict affinity keeps it, as a rule, anX-Magpie-Accountpin 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 plugin's account whose window says it goes on on credits (
credits: true, provider-plugins.md: a Kiro month used up with a trial left) is on its credits as a ChatGPT account let spend them is (spendsCredits), with no setting: Kiro spends the plan's credits before the trial's, the plan's are lost at the month's reset and a trial's last a year. Used up for the model where a window stops it (pastWindows), it goes after the provider's accounts with room and before those used up with nothing left, each in its routing's order (creditsBehind,behindOthersinweigh), under every routing but Pick account by hand; a group's heads keep the group's order. The trace marks itWeighed.CreditsLast, so affinity doesn't keep a conversation on it while one with room leads (lastBehind); the Routing page doesn't show the mark. The Kiro plugin sendscreditsonly while anACTIVEbonus has credits left that outlast the month's reset (0.1.41).TestPluginCreditsAfterTheOthers. - 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 Quota first and Pace still put an account at
LowShare(90%) orSpentShare(98%) behind every account with room (tier), Drain counts it used up atSpentShareOf(Drain), andNextLoginmoves 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) aroutes.Seat.First: Quota first, Pace and Fastest weigh it at tier 0 (seatTier), Drain doesn't count it spent, affinity doesn't move a conversation off it asspent, andreadyForNew/standsInFortreat it as having room (Weighed.CreditsFirst).NextLoginkeeps 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 byaccountSettings) makes its keys and accountsroutes.Seat.Lead, and Quota first (leadFirst) puts those under the spent tier (seatTierbelow 2) ahead of every other seat it weighs, each side in Quota first's own order. Without it an API key, which tells no allowance, goes after every account with room. It counts where Quota first weighs several providers together: a model's found group (auto/<model>) or a user's group routed Quota first; within one provider every seat shares it, so nothing changes. One resting is passed over as any is, so a 429insufficient_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 Quota first 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), andbehindWhydoesn'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 byaccountSettings) hasstandInsOutleave out, inplanPausedandplanGroup, each of its keys and accounts planned after one of a provider not so set. It runs on the planned order beforerestLastandsinkPlanned, 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 andgroupsAfter'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 (Quota first, Cheapest) that weighs a marked member first sends it the request as the group's pick. The left-out rows carryWeighed.StandIn(andUnlisted), 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'sunsupported_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 (restAfterMarkedreturnsRest.Byoff,Untilnow), and the next try goes out on a new connection:regionFresh(inupstreamTransport, around each of its three transports, so under every request the gateway sends throughs.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 afterretryPause(passing). Refused a second time for the same provider and model within a request (regionAskedin 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 withregionNote(throughexplained, besideProvider.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. - OpenRouter's 403 for a free model it serves only to the agent apps it lists ("… is only available on agentic harnesses", routing step "Gate Free Endpoints by Agentic Harness";
provider.HarnessOnly) is about the app the request came from, not the key or the model. It rests nothing and counts no failure (restAfterMarkedreturnsRest.Byoff), and a group's next member is asked as after any 403. Read as the key's 403, it set every model of the OpenRouter key aside (Wade111999 on X;TestOpenRouterHarnessOnlyRestsNothing).APIErrorputsHarnessOnlyHintafter the words, so a model test, magpie's own request and no listed app's, says why it was refused and that the model without:freehas no such gate (TestHarnessOnlyTestSaysWhy). magpie never names an app it isn't. Not covered: whether OpenRouter takes an agent's request through magpie as that agent's, since agents send OpenRouter's attribution headers only to openrouter.ai itself. - One of Codex's own models on the backend path with no routing to do (
codexAccountsfalse: 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 ascodex/<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 (codexUpstreamOnwith 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'sserver_is_overloadeditself (夜松云 on Discord). Now a transient overload (codexBusy: whatbusycalls busy, a 529, a 503 saying overloaded, the backend's in-streamresponse.failedwithserver_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 tolastRetriestimes afterretryPause<<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 aholdWriterwith its reasoning let through (thinkingShown), kept alive pastkeepHeldAfteracross the tries (onekeptAlive), 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 ascodex/<model>with the account left out of the candidates,fallbacksOnly, and the same keepalive carried inhandedOnKey); 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 403usage_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.GroupsAfterincodexFallsBack, 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, oncodex-auto-review, which no group or fallback names, goes on where its conversation's own turns go (codexReviewAfter, fromcodexLeads): to the fallbacks and groups of the conversation's model, or to the magpie model it is on, ascodexFallsBackand serve'sgroupsAfteradd them (riverleaf88 on X,TestCodexReviewSpentFollowsTheGroup,TestCodexReviewSpentFollowsMagpieModel). Each try is aHandedOnusage record and a try in the trace. The reply'sx-codex-*windows are kept as the sign-in's usage and ausage_limit_reachedrefusal 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,…RefusalNotAskedAgainincodex_one_account_overload_test.go). - A subscription account whose sign-in its vendor revoked (
provider.SignInRevoked: 401token_revokedand the like, #1793) fails asfailAuth: the next member is asked at once, nothing rests, and the account is marked (noteSignIninsignin_revoked.go). Its later requests aren't sent while it has that credential:forwardOnceanswers 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 itsexpis ahead renews the account's sign-in once (provider.NoteExpiredSignInfromnoteSignIn), 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小时限额) asrate_limit_exceeded. It is out of quota (plannedWords), not rate limited: it rests till the window it filled renews when its windows as last read say so, elsequotaRest, and its windows are read again (staleKeyAllowance). A reading that finds that window full no more (the limit raised in the relay's panel, or the key's usage reset) lifts the rest (renewed, told throughprovider.OnRenewed), as a Codex reset spent does an account's; the key's other rests stay. While it rests out of its windows, they are read again each time it is planned (restingOf, once a minute at most), so this holds where nothing weighs it by them: an ordered group. The relay out of accounts for everyone (503No available accounts, or a later version's 429All available accounts are currently rate-limited) says nothing of the key's windows: it backs off as any failure or rate limit does, never to the window. A key's windows count only its own spend, so other users draining the relay's accounts show up as those errors, not in the windows. - A 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):backSoonreadsresetsAfter(now with seconds and Chinese minutes,soonWords: "try again in 30 seconds", "请 1 分钟后重试") andtryAgainIn. 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 isbusy, rests the minute it says (rateRestreadsresetsAt), 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'susage limit reached|<unix>). A relay's 500 "当前模型 gpt-5.5 负载已经达到上限,请稍后重试" names its load, not the key's allowance: it was read as out of quota byusedUpWords(上限), which rested the key till a reset and kept a group's Patience from waiting it out (#1418). The quota words (usedUpWords) still apply to a 4xx. - 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 thanlongestSaidisn't read:longestWritten(7 days), orlongestMonthly(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 pastlongestQuota, tolongestMonthly; 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 restedquotaRestand 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 asnotModels(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 byrestID) until the time it names (clineBackIn,tryAgainIn, held tolongestWritten;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'sinsufficient_quotaalike (TestCreditsExhaustedIsOutOfCredit). On the rate-limit branch, a reset time the refusal names (resetsAt, orresetsHeaderaskeepRetrynoted it) is believed up tolongestQuota, as out of quota believes it, and the Routing page says it rests until then (resets); aRetry-Afteror a rate-limit reset header is still held tolongestWait(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,PerMinutein 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 asrateRestdoes, a minute or the vendor'sRetry-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'sinsufficient_quota; from a DashScope provider (dashScope) those are rate limits (dashScopeRate, infailureOf), while its "Free allocated quota exceeded." and a Coding Plan's hour/week/month stay out of quota, and OpenAI'sinsufficient_quotastays out of credit (TestMinuteLimitIsNotQuota,TestMinuteLimitRestsAMinute,TestDashScopeAllocationQuotaIsRate). - The Qwen AI platform's Token Plan (
qwenPlanBusy: theqwen-token-planpreset, or a provider attoken-plan.maas.qianwenaiapi.com) answers many requests at once with that same 429,Allocated quota exceeded, please increase your quota limit, its quota far from used, and the request asked again a moment later is served (pelikanade on X).passingread it as out of quota (failureknows no vendor), so the agent had the 429 after one try. NowpassingForandbusyFor(qwen_plan_busy.go) take it as a rate limit: the last one left is asked again up torateRetriestimes after jittered pauses of about 1, 2 and 4s (jittered, half to one and a half of each, so one burst's requests don't come back together), then within its patience; a group's member that isn't last is asked again in place as often (planAgain) before the group moves on, and only then rests asdashScopeRatesays, a rate limit's minute. Nothing reaches the agent before. DashScope's pay-as-you-go hosts and the Bailian and Alibaba Cloud Token Plans keep the one try, their 429 resting as a rate limit as before (#6950;TestQwenPlanConcurrencyIsAskedAgain,TestQwenPlanConcurrencyInAGroup,TestOtherVendorsAllocatedQuotaUnchanged,TestQwenPlanBusyScope). - 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 byresetsAfterbeside Factory's "resets in …", held tolongestWritten). The account (or, aspooledsays, that model on it) rests that long (resets), and the agent's Retry-After says it when no account is left. Unread, it restedquotaRest, 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). agy's own notice for an account's quota used up, "Individual quota reached. Please upgrade your subscription to increase your limits. Resets in 1h18m40s.", is read the same way; the agy-cli plugin (0.1.87) ends such a turn with arate_limit_errorin those words, mid-reply or not, where before it went to the client as the reply and the next account was never asked (@Airan_FS on X;TestAgyCLIQuotaNoticeRestsUntilItsResetAndFallsOver,TestAgyCLIQuotaNoticeMidReplyStillRests,TestAgyQuotaNoticeResetIsRead). Its other 429, "Resource has been exhausted (e.g. check quota).", names no time and restsquotaRestas 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 asfailQuotaby their words, both restedzcode@…, 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 bywindow) is back once magpie's reading of its windows (provider.Allowances) finds it full till sooner: the window used belowSpentShareOf, or its reset passed, with no other window over the same models still full. The reading tellsprovider.OnRenewedas the account'sUsageAgentand user, andrenewedlifts that account's rests out of quota or bywindow; its rests for a rate limit, its credit, a verification or a failure stay, as a key's do, and so does every rest of other accounts still out of their windows. Planning reads every account candidate's allowance, ordered groups included, so this needs no step of its own inrestingOf. - A plugin's window that says no models (
model,models,notModels) but is named by a model id its provider serves counts that model only (provider.namedModelWindows): Google AI Studio's plugin (@dorokuma/magpie-gemini-web'sai-studio) tells each model's cooldown as a window named after it, used 100 until it ends. Read as the whole account's, gemini-4-hydrogen's daily 429 held the account from every model till the reset, while argon still answered (WangYeruo on X). Its window for every model ("所有模型") stays the account's. A window kept this way has amatches, sokeepLastdoesn't write the reading down (TestPluginWindowNamedByModelCountsThatModel,TestAIStudioModelDayRestsTheModel). - 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 inperKeyEvery(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 (KeyAllowancekeeps the last good reading,TestKeyUsageCapPassesTheKeyOver).CapCarefuland 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 inperKeyEvery(spendHeld) with acapHoldwhosespendis 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,cappedErroranswers 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, withRetry-Afterat the soonest; a cap in all gives none. A spend hold is not a usage cap:capHeldOnlyleaves it out, so neither Stop at the caps (CapStop) nor Strict'sstrictKeepsends 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 inquotaDimensions, 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-4ois notgpt-4o-mini). A refusal that names no model, one for want of credit, and a plain failure still rest the key or account whole. Antigravity's quota refusal (antigravityPoolSpent: agy's "Individual quota reached … Resets in …", relayed by the agy-cli plugin, and Code Assist's "You have exhausted your capacity on this model") names no model but is the model's pool's, as Google counts Antigravity per pool (Claude and GPT, Gemini apart): it rests the model too, so the account's other pools are still asked andtimedHelddoesn't answer them from the rest (BruceLu73129013 on X). Only on a Google sign-in (googleSignIn: Antigravity, Gemini CLI, and the antigravity and agy-cli plugins); another vendor's "individual quota reached" rests what it did (TestCodexCompactCutSummaryFailsOver). agy-cli's usage windows are display only (aside), so no reading narrows the rest for it. - 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 beforeRest.Modelhas the model on the end ofRest.Key, which the page reads the same (restModelinplugins/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.accountRestsgives them by user in lower case (the account's own, and each model's, withRest.Model,Until,Byand 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 (accountRestLinesin 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.slowingateway.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 withinslowForget(30 minutes) of its last slow start, that model rests on that account (restSlowinrouting.go, keyed byrestID,Rest.Modelset): 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 beforehw.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 wholeFirstToken(小八 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 abusy503 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 Claude account's refusal worded "You've reached your Fable limit" (also "hit";
claudeFamilyLimit) names the family whose own limit it is, found in the model's id: that model rests on the account, its others keep being served (YsiCing on X: Opus was refused with it). "usage", "session", "weekly" or no word there is the account's.TestClaudeNamedModelLimitRestsThatModelOnly. - A Claude account's plain 429
rate_limit_errorfor a model, naming no window (no 5-hour, session, weekly, usage or organization words, and noanthropic-ratelimit-unified-representative-claimoffive_hourorseven_day), is that model's rate limit, as Anthropic counts them per model: that model rests, rate-limit ladder and sink included, and the account's other models are still asked (claudeModelRate, kaitokiku on X: Fable rate limited showed "限流" on Opus too;TestClaudeModelRateRestsThatModelOnly). A refusal of a window that counts every model rests the account as before. - 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'snotModels, Core'smodels) 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 tolongestWritten), else the window's end, elsequotaRestor the provider's ownquota-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), or whose reading holds a window of some models only (Claude's Opus, Sonnet or Fable week) with none known full, can't tell the model's pool from the account's, so it rests whole, and (Allowance.Scoped;TestClaudeFableWeekRestsFableOnly, kaitokiku on X: Claude Code's "You've hit your limit" names no window)narrowWhenReadwaits off the request for a reading (AwaitAllowance, up toallowanceWait) 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_gennamespace, #870) to every magpie provider. When a provider other than a ChatGPT sign-in or openai.com answers a bare 400,attemptasks it once more without the tool (image_tool.go). This happens both passed through and translated. If that works, the provider is marked unfit for the tool (tool:image_gen) and isn't offered it again. If it doesn't, the tool is restored and the 400 stands (#949). - A turn the agent stopped with its tool call still out is replayed by the client with the call and no result, and Google's APIs turn a history whose call turn goes unanswered away with 400, every later turn of the conversation with it. The Gemini build (
buildCodeAssistSent, which serves a Google sign-in, Vertex AI and a custom provider's Gemini API alike) answers such a call with the synthetic result the chat build pairs an interrupted turn's call with (pairToolMessages, #1275), right after the calls (pairFunctionTurns, #1560): beside the answers the client sent there, or in a user turn of its own before what the user said, since a turn mixing afunctionResponsewith text is turned away too (#1533), and so is one mixing it with an image: on Vertex AI a tool's images (Codex's view_image) go in a user turn of their own after the response (buildCodeAssistSent, Voo_Ler on X); 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 whosefunctionResponsecount differs from itsfunctionCallcount, 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 atool_usethe next message doesn't answer and for atool_resultnaming no call of the message before it. A call left unanswered gets the synthetic interrupted result,is_errorset, 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's own body relayed to a Messages upstream (passthrough: an API key, a relay, a plugin's fetch) and sent to count_tokens is mended by the same rule when its exchange doesn't pair (toolBlocksPairedintool_blocks_paired.go), a result after other content of its message moved first too, and words an assistant message wrote after one of its calls moved before its first call (callsLast;pairToolBlocksdoes the same for a built message,blocksCallsLast), thinking left where it was and an empty text block dropped, since DeepSeek refuses a text block after a call with "messages.N.K:tool_useids were found withouttool_resultblocks immediately after" even when the next message answers it (checked against api.deepseek.com/anthropic on 2026-11-19; wizcheu on X, deepseek-flash at max effort through Claude Code,TestWordsAfterACallGoBeforeIt,TestCallsLast); the messages it didn't have to change keep their bytes, and a body whose exchange pairs goes byte for byte. Before, Claude Code or Claude Desktop relayed with a reply cut after its parallel calls were told showed "400 due to tool use concurrency issues" on every later turn (miwanzi on Discord). A Claude subscription's turn goes through the bridge, which writes the history as text, so it isn't refused for this.anthropic_tool_pairing_test.go,TestToolBlocksPairedLeavesAPairedBodyAsItCame,TestMessagesRelayMendsABrokenToolExchange,TestCountTokensMendsABrokenToolExchange. - 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 acall_idnever 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 (toolPairsOutinchattidy.go), by the rule a translated one is built with (pairToolMessagesinchat.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 inattempt, before it is relayed or translated, plugins included (chatCallIDsinchat_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 emptytool_useid. 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 notool_call_idtake 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,TestStreamedCallGivenAnIDinchat_call_ids_test.go. - A relayed Chat stream's tool call fragment with no
index(none, or null) is given its call's (streamCallIndexesinchattidy.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" attool_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.TestChatTidyGivesCallsAnIndexinchattidy_test.go,TestGeminiCompatRelayedCallsHaveAnIndexingemini_compat_cut_test.go. - A translated Chat stream's tool calls are read by
index, not as one after another (chatDecoder.toolCallinchat.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 sixfunction_callitems, 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, atfinish_reasonor[DONE]. Every translation from Chat (Responses, Messages, Gemini, a whole reply) reads the stream through it.TestInterleavedToolCallsToResponses,TestInterleavedToolCallsToAnthropic,TestInterleavedToolCallsWhole,TestToolCallsNamedFirstThenArguedintranslate_stream_test.go. - A relayed Chat reply whose choice made calls and ended
stopendstool_calls, streamed (chatTidy) and whole (chatWhole), as the translations' collector already ends it (collector.finish): told it stopped, a client that readsfinish_reasonends 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.TestChatCallsEndToolCallsinchattidy_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_callswith no call left after the drop endsstop(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,TestToolCallsFinishWithNoCallsStaysWholeinchat_call_name_test.go. - A native Codex model-list request (
GET /backend-api/codex/models) may carry its ChatGPT bearer beside a managed gateway key (x-api-key,x-goog-api-keyor?key=).identifyCallerchecks the gateway key and records its caller as usual, keeping the ChatGPT authorization separately (keepCodexListAuth). OnlycodexModels, after the gateway guards, restores it on a request copy for both the backend cache identity and the upstream ask; gateway credentials are removed from that copy. A gateway key alone is not a ChatGPT sign-in and gets 401 rather than borrowing the server's account. Other routes keep the internal-token normalization.TestCodexModelsKeepOAuthBesideGatewayKeycovers the full server path (#5197). - 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'sX-Models-Etagtagged withprovider.CodexListTagso a change has Codex ask again. A Codex there only for account failover, not connected (CodexOwnOnly,agent.CodexOwnOnly; #1385), gets the backend's alone, tagged withprovider.CodexOwnListTag; neither tag contains the other, so connecting or disconnecting has Codex fetch the list again. The user's picks on the codex provider (provider.CodexNativePicked) narrow the backend's listed models. They keep its hidden ones (visibility: "hide"), which no picker shows. One of those iscodex-auto-review: when the list lacks it and no reviewer is set, Codex's auto-review runs on the conversation's model at low effort (#1460,TestCodexModelListPicksKeepHidden). 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"), behindListedFor/CatalogFor) keepsCodexOwnentries, so the Agents page shows its Codex section, its picker offers them as magpie's, and the desk file andspawnChoiceslist 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 isotheror its User-Agent's name, never""), is givenCatalog(): a group listing alone keeps a signed-in subscription's models out of its list too.88e6fb9cfhad 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 (keyListedoverprovider.GroupStandIns, on/v1/modelsand every listcatalogForfeeds,/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 tocodex/*was listed GPT-6-Luna alone;TestKeyNotGivenTheGroupIsListedItsMembers,TestCallerKeyModelsOfferGroupKept). A backend answer that says the sign-in itself is revoked (provider.SignInRevoked, a 401token_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 401token_expiredamong 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/listwithlimit: 100and never for the next page (ChatGPT.app 26.1013, openai.chatgpt 26.51021; the CLI's/modellists every one). Socodexcat.FitOwnranks 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 incodexMerged; a ChatGPT account'scodex/…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 themodel_catalog_jsonmagpie writes (codexcat.CatalogUsed).codexListTagcarries a tag of the used set (codexcat.UsedTag), so the ETag andX-Models-Etagchange when Codex uses a model it hadn't;usage.CodexUsedis read again a minute on, or at once whenAppendwrites a Codex call to a model it doesn't hold (codexUsedNew).TestCodexModelListKeepsUsedModelsInTheAppsHundred,TestCodexCatalogKeepsTheKeysUsedModelsFirst,TestFitKeepsUsedModelsWhereTheCodexAppReads,TestCodexUsed,TestCodexModelListKeepsOwnModelsInTheAppsHundred,TestFitOwnKeepsCodexsOwnInTheAppsHundredandTestCatalogUsedKeepsChatGPTOwncover 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; eventsKThinkStart,KSealed,KTextSiginir.go), so each thinking block or reasoning item stays apart, whole or streamed, and a seal is written only for its own API (sealedBy). Anthropic'sredacted_thinkinggoes back raw (to DeepSeek as a thinking block, below), and a thinking block signed with no text keeps its signature (aBlockstill writes"thinking": "", #1447), on Claude's subscription too. A Responses reasoning item keeps its id, summary andencrypted_content, and goes back to a Responses upstream as it came when it has no reasoning text (sealedReasoning; text, another vendor's, is still left out for OpenAI, #1411). Gemini'sthoughtSignaturestays on the call it signed and on text; a later call of a signed step goes without one, and only an unsigned step or Claude on Antigravity getsskip_thought_signature_validator. Another API's agent gets the call's signature in its id, as on chat (#687), with its length in the mark (__ts<n>__), so an id a client shortened carries no signature and the call goes as unsigned (#1536); it gets no one else's seal. The signature itself is kept in magpie's folder,gemini-signatures/<key>, named by its hash (keepSignatureingemini_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 innativemode), and every request is fitted to its provider (ownSignaturesinforwardTranslated,chatCallSignaturesandgeminiBodySignaturesinpassthrough): another provider's signature goes asskip_thought_signature_validatoron 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 (foreignReasoninginaffinity.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),serveasks 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 isfail: 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>,carryReasoningandunreasonCallsinreasoning_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:refuseCarriedremembers what the request's calls carried as refused by that key or account, andtranslateleaves those items out of this and every later request to it (withoutRefusedCarry, scoped to the try's provider throughwithSealScope). 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),forwardasks 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,withoutRefusedThinkinginthinking_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 thethinking-binding-controlsbeta'sdrop_blockfor 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
signatureinthinkingblock"). 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,forwardOnceleaves them out of every request to an upstream serving Claude (api.anthropic.com, or aclaude-model name;withoutForeignThinkinginthinking_bound.go), andrefuseBoundThinkingreads 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, whichrefuseBoundThinkingcan'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'sus.anthropic.claude-…and Vertex AI'sclaude-…@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_thinkingwhole, or answers 400; Codex withstore: falsekeeps only a reply's items, and of a reasoning item onlyencrypted_contentis opaque. So the Anthropic decoders name a signature as Claude's (KSigwithsealAnthropic,Part.SignedBy), and the Responses encoder andrenderResponsesgive each thinking block a reasoning item whoseencrypted_contentismagpie-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 aredacted_thinkingblock as an item of its own.parseResponsesreads such an item back into the block (claudePart), in order, soanthropicBodysends 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:passthroughandforwardOncetake it out (withoutClaudeSeals: the item keeps its summary, one with none goes),codexInputAsleaves such an item out for Codex's own models as it does one with nothing sealed, andcodexUpstreamOntakes it out before the ChatGPT backend; OpenAI's ownencrypted_contentis untouched.redact.MaskJSONkeeps 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 longnothing of magpie's could strip then); any other upstream's reasoning becomes items magpie made: anrs_id and a summary, nothing sealed. Codex hands them back on every turn. A request relayed as is to OpenAI's API or Azure OpenAI goes without them (withoutBareReasoning) unlessstoreis true, because both look the id up among stored items and answer 400 "Item with id 'rs_…' not found" (#1008). Any other Responses upstream gets them, because a DeepSeek model wants its reasoning back (#388). When one answers 400 naming the input (refusesInput:paramisinput, or the error names an item by id), as a relay in front of OpenAI does with a message of its own,passthroughasks once more without them and, once that works, leaves them out for that provider and model from then on (bareReasoningRefused, #1044). Codex's compaction offers no tools, so it is relayed even when its turns were translated. The summary request magpie makes offers none either:codexInputAssendstools: []and leaves out theadditional_toolsinput 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 anexec_commandcall 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 400unsupported_input_item, which takes messages, function calls, their outputs and reasoning only, Grok's 422 "unknown item type", and a local Qwen server's 400 "Unsupported input item: agent_message" (cyberestro on X;inputKindWordsreads the words with a space or an underscore); 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),codexCompactasks 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'sagent_messageitems (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'scontext_length_exceededled 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.reasonmodel_downshiftin the turn metadata) or to another compaction hash (comp_hash_changed), the only places Codex names either (maybe_run_previous_model_inline_compactin codex-rscore/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). OffCodexPath,codexCompactcompacts 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. OnCodexPaththe 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'scompaction_triggerto/v1and failed the turn on a 429, and went on to the new model once the trigger was answered. A compaction relayed to OpenAI (/responses/compacton Codex's own model, as a/responsesturn) 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, acompaction_triggeron/responsesthat wants exactly one compaction item back, on any provider table named "OpenAI", as CC Switch names its relay tables. magpie points those at/v1while a magpie model is on, sohandlemakes the summary there too (codexInput,codexCompact), and magpie's summaries go back to the model as text (#1301). A 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 endedincomplete(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,codexCompactanswers 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). AftercompactFailsMost(3) failed summaries in a row of one conversation (prompt_cache_key) on one model, each withincompactHeldFor(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 (compactFailsincodex_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 forcompactWithin(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_textannotation without the offsets OpenAI's schema wants of its kind (aurl_citationorcontainer_file_citationwith nostart_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;withoutOffsetlessCitationsincodex_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 (dropOffsetlessCitationsbesideresponsesWholeEventsinwhole_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 afile_citationorfile_path, which OpenAI places by a singleindex, go as they came (TestCitationsWithoutOffsetsAskedAgainWithout,TestWholeAsStreamDropsCitationsWithoutOffsets,TestCitationsWithOneIndexKept). - A reasoning item with its text in it (
contentparts: DeepSeek's Responses API writesreasoning_text, relayed to Codex as it came) is another vendor's. OpenAI's API and the ChatGPT backend take a reasoning item'scontentonly 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/responsesand 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).passthroughleaves 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).forVendortakes 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'sinvalid_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, andserveasks it again without them (withoutSeals): a reasoning item goes whole, any other item keeps all but itsencrypted_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, forstickKeep(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/responsesalike (#3887, hheei: after such a move aweb_search_callanother 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/responseswith 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
nativeCompactionon (provider.Provider.CompactsOn; the editor's Compaction row,magpie provider set <id> compaction=native) is asked Codex'scompaction_triggeras Codex sent it, and the compaction item it seals goes back to Codex unchanged, not as amagpie1: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 wherehandleandcodexBackendread 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 (keepsCompactioninattempt); 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 fromperKeyBarredwithout 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,codexCompactgives magpie's summary through the listed key, as with native compaction off; before, the trigger was kept and refused 400carrierErrorwith 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.jsonbesideaffinity.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 400checkpointErrorwith 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, oncodex-auto-reviewor 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/compactis refused withcheckpointError(echo_ts: every auto-review after a Copilot compaction was answered 400invalid_encrypted_contentby 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, elsecodexCompactgives 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/compactcarrying 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 ownchatgpt-account-id, or an unreadable sign-in state relays as it came — and a writer gone is refused withcheckpointError'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 429checkpointCappedError(recordcheckpointCappedRecord, "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'sweb_searchitems.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 acompactionitem whoseencrypted_contentismagpie1:and the summary in base64 (codexsummary.Encrypted), andcodexInputAssends 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). Sosessions.PortCodexRolloutswrites 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 itsreplacement_history_metadataentry. Every rewritten line keeps its length (fitLine: a shorter one padded with spaces after its JSON), as Codex keeps places in a rollout by byte. A line the full message makes longer in a paginated rollout (a short summary under Codex's long prefix) is never left with magpie's seal, which OpenAI then refused for good (hey_boyce on X: "The encrypted content for item cmp_magpie_… could not be verified"):fitShorterwrites the summary under a short heading, then cut to fit, then with no heading, and as a last resort a standalone item asmagpie_compaction, a type Codex reads as unknown and never sends. Insidereplacement_historysuch an item would go (Codex sends it asother, and OpenAI refuses "Invalid value: 'other'", codex-cli 0.165.0 and 0.169.1), so a compaction or reasoning item retired there is left out with its metadata entry, and one an earlier pass retired there is taken out (retiredInList). A pass state from before this (codex-portable.jsonwithoutrefit) makes one whole pass again for the rollouts left so. The gateway's last line: a 400 naming acmp_magpie_item asks again with its summary message in its place (withoutItem,TestRefusedMagpieCompactionGoesAsText): a fork'shistory_base.end_byte_offsetand 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).MoveCodexProviderkeeps the session_meta line's length the same way. A longer provider id for a paginated rollout leaves that line as it was and moves the thread by its row in Codex's state database alone, where Codex reads a paginated thread's provider from; before, it was refused ("keeps its history by byte, and "magpie" is longer than the provider it names", @xMopf7RF on X). With no row to move, it is refused with nothing changed (sessions.StuckError), and the Sessions page says why, that the session stays on its provider, and that Delete clears it into magpie's trash (TestMoveCodexProviderPagedByRow,TestMoveCodexProviderPagedNoRow,sessions-codex-provider-stuck.test.cjs). It andMoveCodexThreads(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: underthread-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 ormagpie servestarts 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 refusesmagpie1:as OpenAI does, and by codex-cli 0.169.1 against OpenAI itself with the reporter's item and an id-less one retired, a retired reasoning item in its replacement_history taken out. Not tried: a Codex in a WSL distro, whose locks this machine can't take, so it is skipped.TestPortCodexRollouts*,TestPortedCompactionReadsTheSame. - The summary ask
codexCompactsends 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. - Open Design's amr-link (its plugin,
opendesign, or a provider at amr-link.open-design.ai:openDesign) answered Codex's compaction on every model with 400[code=upstream_error] Provider returned error, while the turns around it went through (Mugenrikka on X; not tried on a real account). Codex's compaction is its one request with"tools": [], and the summary ask addstool_choiceandparallel_tool_callsfor #292's relays; a Responses request relayed to amr-link goes without an emptytoolsand the two beside it (withoutEmptyTools, inpassthrough), and every other upstream is sent them as before. A summary amr-link still refuses in those words counts asupstreamFailed(vendorUnsaidWords): it is asked as sent, then as text, then made by magpie, never handed to Codex as the 400.TestOpenDesignCompactionSendsNoEmptyTools,TestOpenDesignCompactionRefusedAsksAsTextinopendesign_compact_test.go. - 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): itsadditional_toolsitem lifted intotools(liftAdditionalTools, #350), itsreasoning.contextleft out, its Lite marker removed fromclient_metadata(withoutLiteMetadata), and itsX-OpenAI-Internal-Codex-Responses-Liteheader not sent on (liteKept). A Codex websocket turn repeats the marker inclient_metadata; leaving it beside a removedreasoning.contextmade a downstream Responses relay forward an inconsistent Lite request, which its ChatGPT backend refused with "requiresreasoning.contextto beall_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 setcodexAsSent(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 offersweb_searchtoo: the request is relayed with it, not translated for magpie's search (searchedForIt), which merged the developer messages intoinstructions, sentapply_patchas a function, leftweb_searchout and addedmax_output_tokens(codexAsSentinroute; 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(liftMessageToolsinmessage_tools.go, #2322). Pi withsupportsMidConvoToolAdditionsgives a tool it adds mid-conversation as{"role":"system","tools":[…]}with no content, and keeps top-leveltoolsas they were at the start; no Chat API reads tools there, andparseChatread only the top-level ones, so the tool could be called on no route.handlelifts them for every Chat body beforeserveAgent, 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;parseChatlifts too, for a body that never came throughhandle(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, asliftAdditionalToolsand atool_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 withouttools. Messages stay where they are: the in-place system message the issue also asks for is not this change.TestPiAddedToolReachesEveryRoutesends deephbz's Pi 1.2.0 bytes through the Chat relay, Messages, Responses, Gemini and Codex, andTestPiAddedToolOfferedToClaudeCodethrough 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}}(shapeChatToolsinchat_tool_shape.go, #2622, jinyue806): MCP's{"name","description","inputSchema"}(ZCode), Anthropic'sinput_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"), andparseChatread no name from them, so a translated request offered a tool named "". It runs right afterliftMessageTools, inhandlefor every Chat body and inparseChat, so it holds for every Chat upstream, not SenseNova's alone. A tool with itsfunction, a hosted tool (any othertype) and one with no name are left as they came, and a request with none to shape is relayed byte for byte.TestChatToolInAnotherShapeIsShapedsends 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 (
userAgentForinuser_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-inpassUserAgent; a file that still says it reads the same as the default now. A provider setmagpieUserAgent(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'smagpie/…,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.forwardOncesets it for chat, Anthropic, Responses, Gemini and count_tokens; embeddings, images and videos (retrieveFrom,sendWith,remoteVideoContent) set it withstampUAfrom 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 asagentUAhas it, and the user'sheader.User-Agentis put on when the request is signed, so it wins.provider.PassesUserAgentrefuses 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 asmagpie/<Version>(its attribution headers are trusted only from that), with the agent's User-Agent inX-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 amagpie/request (callerFrom, ascaller.ua,relayed), takes it off what comes in (withCaller), andagentUAhands it touserAgentForin 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 (
chatReplaysReasoninginchat.go: a host or a model, as magpie or the provider names it, withdeepseekin it, such as OpenCode Go'sdeepseek-v4.1-flash, or Command Code's plugin) gets every assistant tool call withreasoning_content, relayed (withReasoningOnToolTurnsinpassthrough) or translated (buildChat). DeepSeek turns the whole request away ("Thereasoning_contentin the thinking mode must be passed back to the API") when a tool call made since the user's last message has none, which a client sends for a turn it saw no thinking on: another model's, a translated one (#1462). The turn's own thinking goes back as it came; one sent inreasoningorreasoning_detailsis copied in, andreasoningis 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 inreasoning, as "duplicate field reasoning" (ArvinCharl on X, v0.1.1560), whilereasoning_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 (textPartsAsStringinchat_text_parts.go, inpassthroughbeforesilentAssistantsOut). 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 acache_controlmark stays a list, and every other byte of the body stays as sent;buildChatalready 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_contentalone included ("Invalid assistant message: content or tool_calls must be set", #2599). Every Chat upstream gets such a turn left out, translated (buildChat, beforepairToolMessages) or relayed (silentAssistantsOutinpassthrough), by one rule (withoutSilentAssistantsinchat.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 legacyfunction_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) turnsreasoning_detailsin a message away in any shape: an entry with a stream'sindex("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, withindex: 0), so a conversation routed on to Kimi was refused on every turn (#1765).passthroughsends it to Kimi asreasoning_content(reasoningDetailsAsContent, with the message'sreasoningleft out once its text is there), which Kimi takes; a message withreasoning_contentof 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
typeis required, and turns the whole request away over one schema without it, though the tool is never called: 400 "mcp__cua-driver__dragfunctionDeclarationparameters.targetschema 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'sgoogle/gemini-3.8-flash, which Command Code's gateway serves on Vertex;targetwas an anyOf of an untyped oneOf and null,scopea const). A body whosemodelnames Gemini (geminiNamed: the id's last/segment starts withgemini, whoever serves it) has each untyped schema under its tools'function.parameters,parametersorinput_schemagiven its type in place (geminiToolTypesingemini_schema.go, inforwardOnce, 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,propertiesoritems, before its values: a string enum besideitemstyped"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$refor union, and anything undernotorifare 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 sentparametersJsonSchemaand AntigravityplainSchema, so a Gemini-shaped body isn't walked (TestGeminiToolTypesCuaDriverDrag, with cua-driver's drag schema as its server listed it,TestGeminiToolTypes).plainSchemaitself 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 itsitemsorpropertiesare 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'strueorfalse) or anx-keyword such as MCP'sx-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).plainSchemais an allow-list, sox-keys never pass it; a boolean is{}for true and left out for false (a false property leavesrequiredtoo, a falseitemsisitems {}withmaxItems 0). Before typing,geminiToolTypesrunsgeminiSchemaShapes, which does the same for the relay's case: true is{}, false is left out,x-keywords go (a property namedx-…stays), andadditionalPropertiesand theunevaluated…keywords keep their booleans; a schema with neither goes byte for byte (TestAntigravityBooleanSchemaAndXKeys,TestPlainSchemaBooleansAndXKeysEverywhere,TestGeminiToolTypesDropsBooleansAndXKeys). What is left is still JSON Schema, soparametersJsonSchema(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;foldsRootsandobjectRootsBodyinobject_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'sgoanyapi_adsenseamong them) had a rootoneOf. It is now folded for every such upstream from the first ask; a server tool (noinput_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 namedopenai, and to no other provider (cyber_access_program.rs,for_auth,for_provider). InforwardOnce, relayed or built (from Chat too), it goes as it came to a ChatGPT (Codex) account, a host ending inopenai.com, another magpie (IsRemoteMagpie, whose own upstream decides) and a relay setcodexAsSentwhen 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 anaccess_programswritten 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/tagsand/api/showare answered in Ollama's shape) sends Ollama's per-requestoptionsbeside its Chat fields: Hermes Agent sees/api/tagsanswer, takes the server for Ollama (detect_local_server_type) and sends/api/show's context asoptions.num_ctx. No Chat API readsoptions, Ollama's own/v1included (itsChatCompletionRequesthas 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 422extra_forbidden(lijiho96940561 on X). So every relayed Chat body goes without its top-leveloptions(withoutOllamaOptions, the rest byte for byte, so a tool parameter or a message namingoptionsis 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(toolatool_referencenaming the tool, or atool_definition), atool_removal, and atool_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 atool_additionnaming a tool but refuses one defining it, atool_removaland a message'stool_referencewith 422 "unknown varianttool_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).withoutDeferredToolsdrops the blocks and a message they leave empty; definitions present only in atool_addition.tool.definitionjoin the request'stoolsonce by name (an existing top-level definition wins), and atool_referenceinside atool_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_resultwhose content istool_referenceblocks alone. OpenDesign's Anthropic endpoint can't read one: 422 "Failed to deserialize the JSON body into the target type: messages[4]: missing fieldcontent" (#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 instringOrText), the references and thetool_use/tool_resultpairing kept, and is sent it that way while magpie runs (refuseShapes,shapeRefsOnly,withRefsSaid). This is inforward, so/v1/messages,count_tokensand 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). - An endpoint that reads only text and images in a
tool_resultrefuses the references themselves: "DeepSeek V4.1 supports text and image content only; got 'tool_reference'" (emilochen on X, an Anthropic-compatible URL). A 400 or 422 that refusestool_referencein words (refsRefused: a refusal word within the same clause, no brace between, so a request echoed back doesn't count, and "expectedtool_reference" doesn't either) while the request as sent holds one in atool_resultis asked again at once with each reference as the texttoolLoadedTextgives, the tools they name sent withoutdefer_loading(the rest stay deferred), and is sent it that way while magpie runs (shapeRefs,withRefsAsText;deferredOutUpFrontis the same up-front stripforwardOncemakes for Kimi, DeepSeek's own API and OpenCode's DeepSeek). A refusal a deferred block's refusal explains, while such blocks are still sent, is that one's. Chat, Responses and Gemini upstreams already get the references as that text (stringOrText). (TestToolReferenceRefusedGoesAsText,TestToolReferenceNamedOtherwiseLearnsNothing,TestRefsAsTextLeavesOthers) - A tool Claude Code's ToolSearch loads, translated to a Responses API, used to join the top-level
toolson 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 atool_result'stool_referencenames (toolRefs,Part.Loads) now goes, whereRequest.LoadedInPlaceis set, in an{"type":"additional_tools","role":"developer","tools":[…]}item right after the run of tool outputs that loaded it, once, and not intools(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 intools, a new prefix, as is expected.LoadedInPlaceis set (loadsInPlace, inforwardTranslated) for OpenAI's own API with a key (api.openai.com,*.api.openai.com), for a ChatGPT (Codex) account, and for a provider setadditionalTools(magpie provider set <id> additional-tools=on);additional-tools=off(additionalToolsOff) turns it off even where it is the default, anddefaultgoes 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 intotools, 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 namingadditional_toolsis asked again with every tool intools, 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 atool_additionblock loads (an MCP server's late tool, the advisor) stays intools.TestLoadedToolsKeepThePrefix,TestLoadedToolsInOneItem,TestLoadedToolsWhereNotTaken,TestLoadsInPlaceScope,TestLoadedToolsThroughTheGateway,TestCodexAccountLoadsInPlace. - Where a loaded tool can't go in place, Claude Code's deferred tools are turned away (
refusesDeferredindeferred_route.go), since every load changed the prompt from its first bytes and the conversation was read again uncached (Seapawn1 on X: GPT in Claude Code loses its cache with tool search on; 2.1.327 defers WebFetch, WebSearch, Monitor and the other built-ins too, so loads are frequent). A request from Anthropic's Messages with Claude Code'sDeferredToolPlaceholder(Request.DeferredNamed), asked on Chat, Gemini or a Responses upstream withoutLoadedInPlace, is answered 400invalid_request_errornamingtools.defer_loading(deferredRefusal), without reaching the upstream. Claude Code (2.1.327, tried with the real binary) takes a 400 that namesdefer_loadingas the endpoint not taking deferred tools: after its own beta-strip retries it asks again with every tool declared in full, and keeps that for the rest of the conversation,--continueincluded, so the tools are those of its first request and the prefix holds. A new conversation tries tool search again, so one on a Claude model on Anthropic's API, or on a Responses upstream that loads in place, keeps it. The message doesn't name the tool search beta, which Claude Code would remember for every conversation. Only while the tools its reminder names ("The following deferred tools are now available via ToolSearch", one a line,deferredCount) are 50 or fewer (maxDeferredDeclared, about the tenth of a 200K context Claude Code's own auto mode allows tool definitions): a longer list, an MCP router's hundreds, keeps tool search and loses the cache at a load as before, and so does a request whose reminder can't be found. The refusal is about the request, so a group doesn't fall to its next member for it, and nothing rests. A user's ownENABLE_TOOL_SEARCHcan't be told apart on the wire;additional-tools=onkeeps tool search on a Responses relay that takes the item.TestDeferredToolsTurnedAwayWhereTheyLoseTheCache,TestDeferredToolsKeptWhereLoadedInPlace,TestDeferredToolsKeptOnAnthropic,TestDeferredCount. - A Responses upstream that wants a turn's reasoning back (
replaysReasoninginresponses.go: a model withdeepseekin its name, on any host but OpenAI's, xAI's, Copilot's and Azure's) gets every reasoning item with areasoning_textand every tool call after one, relayed (withReasoningTextinpassthrough) or translated (buildResponses). DeepSeek's/v1/responsesturns the whole request away ("Thereasoning_textin the thinking mode must be passed back to the API") over a reasoning item without text, one with an empty text, and afunction_callwhose step (since the last user message or tool output) has no reasoning item. Codex sends all three in a routing group that falls to DeepSeek after ChatGPT: the backend's sealed items (encrypted_contentonly), magpie's summary-only items, and another member's calls with none (#1104, #1592). 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 andencrypted_content; a body already in that shape goes byte for byte. A channel that turns a reasoning item without an id away (a DeepSeek channel's 422 "Input tag 'reasoning' found using 'type' does not match any of the expected tags: 'message', 'tool_result'",idlessReasoningRefusal) is asked once more without such items, relayed or translated, and not sent one again (idlessReasoningRefused,withoutIDlessReasoning); items with an id still go. The refusal is a shape (shapeWords), so a group's next member, DeepSeek's own API among them, is asked and the member doesn't rest (TestIdlessReasoningRefusedByChannel,TestGroupFailsOverIdlessReasoningRefusal). - A Messages upstream that wants a turn's thinking back (
anthropicReplaysThinkinginanthropic.go: a host or a model withdeepseekin it, neverapi.anthropic.comor a Claude model) gets a thinking block on every assistant message with atool_useor right after tool results alone (refused the same way, checked 2026-10-12, #1822), relayed (withThinkingOnToolTurnsinpassthrough) or translated (build, which also keeps unsigned thinking as its text there). DeepSeek's/anthropic/v1/messages, thinking (its default, or asked for), turns the whole request away with 400 "Thecontent[].thinkingin the thinking mode must be passed back to the API" when such a message has none, and answers anyredacted_thinkingwith 422, a block it can't read. Claude Code sends both in a routing group that falls to DeepSeek after Claude (#1611). A message with no thinking gets one holding a space (noReasoning) first; Claude'sredacted_thinkingbecomes that block, or is left out beside thinking of the message's own. Signed thinking, DeepSeek's own and every other message go as they came. Checked against the real endpoint on 2026-10-11: it takes Claude's signed thinking, unsigned thinking and a space, anywhere in the message. A thinking block magpie sends unsigned (the space, or a turn's reasoning kept as its text) says"signature": "", asaBlockwritesthinkingeven when empty: OpenRouter's/api/v1/messagesholds 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(orreasoning_content) in the thinking mode must be passed back to the API" (thinkingBackRefusalinthinking_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 (thinkingBackNeededinunfit, filled inforwardOnce), 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 readsContentBlock::Thinkingas{thinking, signature}, both required, and turned a whole reply away, "missing fieldsignature" (uk.jent on Discord, on the MiniMax Code plugin). The encoder starts a thinking block signed empty (anthropicEncoder.thinking),renderAnthropicandwhole_stream.gowrite the field too, and a reply relayed from a Messages endpoint that wrote none, streamed or whole, gets an empty one (sigFieldTidyinthinking_signature.go, inpassthrough); a block already signed goes byte for byte, andredacted_thinkingis untouched. magpie never makes a signature up: an empty one is none to every path that sends history on (anthropicBodyleaves 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'slimit: 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 saynumber, 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.0becomes2500,-3.00becomes-3. Strings, keys, other fractions (2.5,2.50) and exponents (1.0e3) stay as written. No tool schema is consulted, since JSON has one number type and one that took2500.0takes2500. The rule runs over the arguments as a stream of text (wholeNums), holding back only a fraction of zeros until the next byte. This gives the same arguments whether they come whole or in deltas cut anywhere, so what a call's deltas add up to is what its done events say. Relayed replies are rewritten inpassthroughbyintTidy: Responses' function_call items, argument deltas and done events and the completed response; Chat'stool_callsdeltas and messages; Messages'tool_useinput andinput_json_delta, streamed or whole; 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 beforeintTidysees the reply, sinceintTidyholds a whole one to its flush (TestStitchedCRAndWholeFloatsBothGo). Translated replies are rewritten at the encoder (wholeEncoder, outsideusageEncoder) and atrender(wholeResult). Grok's schema quirks staygrokModel'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, bydsmlMark, 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 byparseTextCalls. 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_reasontool_calls,stop_reasontool_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 undertext/plainor no type (chatWholewithwholeTextCalls, #1845: astream:falserequest kept the markup andfinish_reasonstop), 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 becometool_useblocks 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 (responsesTextCallsintextcalls_relay.go, #4743, from v0.1.2652): the held text'soutput_text.done,content_part.doneandoutput_item.donewait with it, and the calls becomefunction_callitems after it, in the events and inresponse.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 byTestTextWritten*,TestInvokeReported*,TestDSMLAlma*(a group of Responses members and a plugin's DeepSeek, from a Responses client, one character to a delta),TestDSMLClose*,TestDSMLBlockClosedWithCalls,TestGLMTextCall*,TestPluginTextWrittenCallandTestQuietWholeReplyStreamed. Relayed Messages streams buffer complete SSE events withtidyEvents(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.TestAnthropicTextCallsSSEChunksKeepFramingandTestAnthropicMessagesSSEChunksKeepFramingcover 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'sresponse_format, Anthropic'soutput_config.formatand Gemini'sresponseMimeTypewithresponseJsonSchema/responseSchema:json_schemawith its name, description, schema and strict, orjson_object. Each upstream is asked in its own field:text.formaton Responses,response_formaton Chat,output_config.formaton Messages, andgenerationConfig.responseMimeType/responseJsonSchemaon Gemini and Code Assist. An API with no name for it getsresponse. Messages and the Claude subscription's--json-schematake a schema only, sojson_objectis told in the system prompt there (inSystem). 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), informat_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 (
toolOutputinir.goreads them from Anthropic'stool_result, Responses'function_call_output, such as Codex'sview_imageoutput[{"type":"input_image","image_url":"data:…"}], and a Chat tool message). Anthropic's Messages keeps them in thetool_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).TestCodexToolImageReachesAnthropicPluginand the Kiro plugin'stool-images.test.mjs. - An image's
detail(Part.Detail, read from a Responsesinput_imageand a Chatimage_url, in a message or a tool's output) is carried on a translation to Chat and Responses (chatImage,chatDetail,responsesDetailinchat.go). Chat takeslow,highandautoas they came, and Responses'original, which Chat lacks, ashigh; an image without one goes without. Responses takes the four as they came, and anything else, none included, asauto(#1474). Messages and Gemini have no such field, so it isn't sent there (mysterious_dove on Discord, Codex:highandoriginalwere 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, inforwardOnceafter the thinking is put back and before the byte cap, finds each base64data:image a Chat, Responses or Anthropic body holds (walkImages: messages and tool outputs) for a model withflashin 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 setimageFilesOff(magpie provider set <id> image-files=off, or the editor's Images tick under Advanced, offered only whereprovider.TakesImageFilesholds: the one host rule,ImageFilesAt, thatdsFilesOnasks; matrix0487 on Discord;TestProviderSaveImageFiles,provider-image-files.test.cjs). An image asked atdetail: lowstays inline, as a file is read at full size. Each image not held yet goes up once throughPOST /fileson the provider's host (multipart,purpose=user_data,expires_aftera day from creation), signed as a Chat request with the candidate's own key; the swap is per key (dsKeyHashbeside the image's sha256), so an id never goes with another key. The block becomes Chat's flat{"type":"file","file_id":…}, a Responsesinput_imagewithfile_idin place ofimage_url, or an Anthropic image whosesourceis{"type":"file","file_id":…}withanthropic-beta: files-api-2025-04-14added, as DeepSeek's files_api, vision, responses_api and anthropic_api guides give them (the Anthropic guide names thefilesource type and the beta; its field namefile_idis Anthropic's Files API's, which DeepSeek says it follows). The ids are kept indeepseek-files.jsonbeside 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 fordsWaitMaxat most and sends what isn't up yet inline. A 4xx whose body names afile-api-id or says a file is gone (dsFileGone) lets the ids go and asks once more with new uploads (dsRetryGoneinforward); refused so again, it goes inline. Uploaded bytes count in the request's upstream bytes (#4456). Not covered: acustom_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,buildCodeAssistSentincodeassist.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:imageSize4K 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 (
unpickedingroup.go, inmembersOff; #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 (resolveIntakes anyprovider/modelof 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.MemberLevelssplits it intoMember.Levelsand leavesEffortempty, 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 (groupLevelsreturns the candidate'slevelsfirst), 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, jsoneffortMaps;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.SaveGroupkeeps a map only for a plain member of the group (not one fixed at an effort or with several levels, not agroup/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, andnonefor an Anthropic request with thinking disabled); the map's target (mappedLevel,ultraread asmax) is sent withwithFixedEffort, fitted to the model's levels unless it isnone, and the trace's try keeps the level asked (mappedFrom). A member's fixed effort and a rule'sUseEffortstill 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 (mappedLevelsinbuildGroupEntries). 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 (
groupEntriesingroup.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 nosupported_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:effortsuffix, then the turn's pick (a routing rule's), then the agent's pick, then the request's own. A model that doesn't reason is sent as asked; the default (none picked) leaves every request as it came. The pick beats the request's own because Cursor sends its own default as often as a real choice. Picking Default hands the choice back to Cursor. - In models.dev, entries from
deepseek,kimi-code-plan-cnandkimi-code-plan-globalgainnoneonly when they have both atoggleand effort levels; the DeepSeek and Kimi APIs accepted that value in #1098. Other providers keep their listed levels because their APIs may rejectnone; 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 inextra_body.google.thinking_config. A 400 or 422 whose error namesextra_body,include_thoughtsor thinking at all (refusesThinkingConfig) marks the provider unfit for the field (thinking_config), and it is asked again withreasoning_effortalone. Gemini 3 can't stop thinking, so reasoning turned off goes atminimal, its least, or at the model's lowest level where it has nominimal(geminiLevels: those of the model's levels it hasn't turned away, or of Gemini 3's where its own aren't known or none is left). Gemini 3 turns away a level the model hasn't with a 400 that names the level (geminiRefusedLevel): AI Studio's "Thinking level MINIMAL is not supported for this model. Please retry with other thinking level." for gemini-3.8-flash, Vertex AI's "Thinking level is unsupported: THINKING_LEVEL_MINIMAL". It names thinking too, but isn't the field turned away. The level is marked refused for that model (levelRefused), and the model is asked again at the nearest level it has left, still for its thoughts, and at that level from then on. A level turned away again, with none left, is the client's 400. Passed through, a Chat client's ownnoneorminimalthat Gemini turns away this way is asked again at the model's lowest level (onEffort), and that level goes at the lowest from then on (turnedAway); the other still goes as sent, as AI Studio takesnonefrom gemini-3.8-flash. A refusal that names the levels the model takes (effortLevelsNamed, Command Code's for Qoder'snone) marks reasoning off as a whole (offRefused): both go at the lowest from then on; one that lists the other among the levels taken (otherOffNamed, quoted, OpenAI's for gpt-5.1'sminimal) marks only the level turned away. Both routes read and write the same marks. Vertex AI's OpenAI-compatible API marks each streamed chunk of thoughts in the delta'sextra_content.google.thought, and such a chunk is read as thinking. - A Gemini 3 or later model (by its id,
geminiGeneration) on an Anthropic or Chat upstream that isn't Gemini's own API (a relay serving Gemini under a host of its own) is asked a thinking level, never a budget, as Gemini 4 turns everythinkingBudgetaway (#2083) and such a relay makes one from what it is sent (geminiLevelBodyingemini_level_body.go, run inpassthroughandforwardTranslatedafterxaiBody; Mamba_asr on X). Anthropic: thinkingenabledwithbudget_tokensgoes as thinkingadaptivewithoutput_config.effort, the budget bucketed byeffortOfBudgetunless the request names an effort. Chat:extra_body.google.thinking_config's budget goes as itsthinking_level(-1 as none, 0 aslow). Either way the level is fitted to the model's (geminiLevelForEfforts: the provider's levels when known, else the catalog's levels, else nothing abovehigh, andmediumashighon a Gemini 3 Pro). Another vendor's model and a Gemini 2.x keep the body as sent (TestGeminiRelayAskedALevel). A relay that doesn't knowadaptiveuses the model's default thinking. - A Claude that thinks only adaptively (
adaptiveOnlyinanthropic.go: Opus, Sonnet and Haiku from 4.6 on, Fable and Mythos 5 and 5.1, read byclaudeVersionhowever a relay spells them) is never sent a thinking budget, which they answer with 400. magpie's own request from a Chat or Responses client (buildAnthropic) goes asthinking: {type: "adaptive", display: "summarized"}with the effort inoutput_config.effort, so the client sees the reasoning Opus 4.7 and later otherwise leave out (displayomittedby default), and a relay that refusesdisplayis asked again without it (refuseShapes), 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'ssafeguards(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'sthinking: {type: "enabled", budget_tokens}is turned into the same inforwardOnce(adaptiveThinking), the budget as its nearest effort, abovehighasmax, anddisplay: "summarized"unless the client named its own display, so the thinking that enabled shows stays shown (the refused shapes are taken out after it, andrefuseShapesreads the display as it is sent); and Pi, dsh and omp are written to ask it adaptively (AdaptiveThinking:forceAdaptiveThinking, omp'santhropic-adaptive; #1470). Pi and dsh, whose pi-ai clamps a budget's xhigh and max to high, are written so for GLM-5.2/5.3 and Gemini 3 or later on Messages too (AsksAdaptively, #6778).thinking.displayis Claude's: a model not read as a Claude (noclaudeVersionmatch and no "claude" in its name) is sent its thinking without it (withoutForeignDisplayinanthropic_shapes.go), since pi-ai, dsh's client, asksdisplay: "summarized"beside every reasoning model's budget and Alibaba Cloud's Anthropic endpoint answered a Qwen model with 400 (StudyingPython on X;TestDisplayGoesToClaudeOnly); a display forced in the provider's own fields still goes. A client'sxhighgoes asxhigh, except to Opus and Sonnet 4.6, which have noxhighand are askedmax(noXhigh, #1471). - A vendor's model that takes its level in
output_config.effortbeside thinking on (effortInOutputConfiginanthropic.go: Z.ai's GLM-5.2 and GLM-5.3, MiniMax's MiniMax-M3.1-Flash and its -Preview, and anygpt-<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, inpassthrough). 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 inoutput_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,forceAdaptiveThinkingindshKindConfig; 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, inforwardOnce, so relayed requests, count_tokens, magpie's own thinking-off and retries all get it; the model is read as the vendor names it, from the body, or from the path for Bedrock and Vertex). Claude Sonnet 5.5 refusesthinking: {type: "disabled"}and is sent{type: "between_tools"}alone, at efforthighat most. Opus 5.5, Fable 5 and Mythos 5 refuse it at every effort and are sent no thinking, at effortlowunless one was asked, withclassifierRoomadded to a reply limit below it, as Claude Code does. Opus 5 and Haiku 5.5 take it only up tohigh, soxhighandmaxare asked ashigh.between_toolssent to any other Claude goes asdisabled, or as none where that is refused too. Other vendors' models, older Claudes and later lines than these go as they came (#1454). A Sonnet 5.5 by a name these rules can't read, answering 400 that asks forbetween_tools(asksBetweenTools), is asked again with it, once; a refusal ofdisabledat any effort (thinkingOffRefused) is asked again with thinking left to the model, asalwaysThinksis. So is a relay that readsdisabledas reasoning effortnoneand 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);refusesThinkingOffis 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 asthinking: {type: "disabled"}; it went as thinking at a 4096-token budget before (#1636). A model that refuses it (refusesThinkingOff:alwaysThinks,mandatoryReasoning,thinkingOffRefused, ornoneturned away naming the levels taken) is asked again at its least (thinkingBackOn), andmarkUnfit(offRefused)sends it so at once until magpie restarts. A translated request's level can differ from the one asked:noneandminimalgo aslowwhere the model's levels don't say it stops (effortOf). The route keeps the level asked; the try, the usage log and Routing's "went" say the one built (noteWireEffort,wireEffortinwire_effort.go). Gemini's builders say theirs their own way and are logged as asked. - Tencent Cloud (TokenHub and Token Plan) runs DeepSeek's thinking by default and counts it in
max_tokens, so a Chat or Responses request naming a reply limit of 16384 or less and no reasoning of its own (and no Max output set by the user) is sent that limit plus a high effort's room (withThinkingRoom); a reply cut at its length with nothing said fails with the request's own limit named (cutVoidFailed).TestTencentDeepSeekCapGetsThinkingRoom. - An upstream that takes a model only with thinking enabled answers a request sent none, or sent it off (
thinkingOffUnlessAskedfor a vendor's model), with a 400 sayingthinking.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, withmax_tokensraised past it by what was asked andtemperature,top_pandtop_kleft out (withThinkingEnabled), andmarkUnfit(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).forwardOncedoesn't make such a model'senabledadaptive (adaptiveThinking),enabledbeing 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 (
ModelReasonlessin settings,SetModelReasonless; the provider editor's Model settings, ormagpie model efforts <provider/model> off) is sent no reasoning field on any route, whatever the agent asks: the candidate loop strips the body withwithoutAnyReasoning(quiet.go: Chat'sreasoning_effort,reasoning,thinking,enable_thinkingandinclude'sreasoning.encrypted_content, Responses'reasoning, Anthropic'sthinkingof any type andoutput_config.effort, Gemini'sthinkingConfig), the Anthropic relay doesn't addthinking:{type:disabled}for it, andforwardTranslatedclearsEffort,ThinkOffandThinkingfor its other callers. It offers no levels (Efforts,entryFor), isQuiet, 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 plainreasoning_effortwith 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.Effortsreturns the vendor's list's or models.dev's levels, andfitEffortfits 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).AutoVisionhonours the user'sModelImagesover the model's own (seesAt).TestModelSpecReachesTheGateway,TestNarrowedVendorLevelsAskAsBefore,TestAutoVisionTakesTheUsersVision. - A request to an Anthropic endpoint with
temperature,top_portop_kreaches a model that refuses them without them (samplingAsTaken, besidethinkingOffAsTakeninforwardOnce): Opus 4.7, 4.8, 5 and 5.5, Fable 5, Mythos 5, Sonnet 5 and 5.5, and Haiku 5.5, whose 400 is "temperatureis deprecated for this model" (Claude Code's auto mode classifier and magpie's own classifiers ask at temperature 0). Older Claudes, Haiku 4.5 among them, other vendors' models and later lines go as they came (#1454). A Claude by a name these rules can't read, answering that a sampling parameter is deprecated (samplingDeprecated), is asked again without them, once — a Chat or Responses client's request translated to Messages (forwardTranslated) as much as a relayed one. A model whose own list refuses them (RejectsTemperature, from the catalog'stemperature, or a plugin'stemperature: falsecarried by the plugin host, #2492) is asked withouttemperatureandtop_pwhatever 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): thedangerous-tool-use-…beta, asafeguardsfield, andsafeguard_resultsin the reply (a stream's in itsmessage_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 onapi.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 turnssafeguardsaway (#1756), the others translate the request, so neither the beta norsafeguardsis sent there (TestAutoModeReviewedRoutes,TestAutoModeReviewLeftOffOtherSubscriptions). There the beta,safeguardsand the results pass as sent, a whole reply's results moved into a stream'smessage_delta(anthropicWholeEvents), tool-use ids unchanged. A relayed reply carryingsafeguard_resultshas 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 orapi.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 meansAutoModeReviewable: 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 smallmax_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 withclassifierRoom(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 inunfituntil magpie restarts (TestAutoModeClassifierReasonsLeastOnAnUnknownModel,TestAutoModeClassifierEffortRefusedGoesWithout). - Claude Code's billing line (
x-anthropic-billing-header: cc_version=…; cc_entrypoint=…; cch=…;, its own first system block,cchchanging every turn) goes on only to a Claude model asked on Anthropic's Messages API (keepsBillingLineinbilling_line.go: Anthropic's, a relay's, Bedrock's), as Claude Code sent it. Anywhere else it is left out, the rest of the system as sent (withoutBillingLine): a vendor's model relayed on Messages (passthrough), every translation to Chat, Responses or Gemini (forwardTranslated, Claude models too). 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. On Code Assist only Gemini CLI's sign-in goes without it (dropsBillingLine, andcodeAssistBodyis built from the request that goes): kept, it was Gemini's first system words and the implicit cache read nothing on any turn (niyezaimenglima on X,TestBillingLineLeftOutForCodeAssist). The built-in Antigravity account is sent it as before, which its cloak leaves out andantigravityTurnsAwayreads (#666), and so is a plugin on Code Assist: the antigravity, agy-cli and Zed plugins' cloaks take the line to its end, Claude Code's identity sentence with it, and cut here that sentence reached Antigravity's plugin alone and a real account answered the 429 (TestBillingLineCodeAssistOthers). Once Antigravity has turned such a request away, foragForeseeing(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 inFallbackwith 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 -mor 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 byantigravityHint. Codex sends itsweb_searchtool every turn, so an Antigravity model's Codex turn goes through magpie's own search (searchReply); its rounds are wrapped inantigravityRound, 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_keyof 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,cacheKeyOfingateway.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 namesprompt_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;desktopProbeindesktop.go) goes to the model the user chose in one of Desktop's own model menus that magpie still serves (desktopChosen:__model_selector_statein Claude-3p'slocal-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 fortokenFloorto ask again at. A relay that needsprompt_cache_keygets one (above). It is recorded with kindconnection_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.TestClaudeDesktopProbeAsksNoClassifierchecks the kind. - Claude Desktop's
/v1/modelstags a model withanthropic_family_tieronly 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 aclaude-haiku-…: a chat on AgentRouter's gpt-6.1-sol sent them to Leee'sclaude-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:servedBesidegives 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'sclaude-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(DesktopInferenceModelsindesktop_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 CodebehavesAsonly from that list (z3t in its app.asar, 4.4212:modelPicker.optionswith each entry'sbehavesAs); the gateway'sbehaves_asrow field feeds Desktop's own effort profile only. A non-empty list replaces/v1/modelsin Desktop's menus (pzn: a discovered row gives only its name and description, by id), so the list is every row/v1/modelsgives Desktop, by its id and in its order, each with what Desktop would have read off the row:supports1mfor a window of 1M and up,prefer1m(and the row'sdisplay_nameaslabelOverride, where Desktop names the row by display_name) for a model listed by its[1m]id, and a pick'santhropicFamilyTierwithisFamilyDefault. 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 itsANTHROPIC_DEFAULT_<TIER>_MODEL), so a model picked for two tiers is tagged with the first (desktopTierOf). Each later tier (desktopSharedTiers) gets the model's id form under a number of its own (desktopTierAlias: magpie-.anthropic., mythos-magpie- or anthropic/magpie-), whichaliasedreads back to the model, so the gateway serves it as the pick (desktopTierAsked). That id is a row of Desktop's/v1/modelsonly (DesktopTierRows, a copy of the model's row taggedanthropic_family_tierandis_family_default), never a list entry: the list is Desktop's model menu, and an entry there showed as a model of its own, "Gemini 4 Hydrogen · haiku" beside "Gemini 4 Hydrogen" (yanghonghang on X, v0.1.3997). Desktop's discovery pins a tier the list leaves out from a tagged row (shortnameIdentityOverridesin its app.asar, 4.23118, under the list's own pins), and with a list it reads/v1/modelsonly when the profile saysmodelDiscoveryEnabled, which magpie's profile carries while a tier is shared (DesktopDiscovers). The later tier has nobehavesAs, which Desktop takes only from the list, so a model that isn't Claude runs there on Claude Code's generic prompt. Before, the later tier had no model: copilot/claude-sonnet-5.5 picked for sonnet and haiku gave Claude Code an emptyANTHROPIC_DEFAULT_HAIKU_MODEL, and its small tasks, WebFetch's page summaries among them, ran on the session's model. 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, unless two rows are named after one Claude model of Desktop's catalog, when the list is written for itslabelOverrides alone (desktopNamesClash, onkashiko on X). 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 (AppBehindreads the profile).TestDesktopInferenceModels. - Claude Code's WebSearch subrequest in Desktop's gateway mode goes to
DesktopTiers()["haiku"]when that pick is set and served (desktopSearchCall,desktopSearchTier,movedSearchindesktop.go: exactly oneweb_search_*server tool, forced bytool_choicetoweb_search); without a usable pick the existing routing stays as it was, since Desktop disables GrowthBook and Claude Code 2.1.321's small-model search flag defaults off. A moved search never changesdesktopPicked, and a subagent's search is a helper call exempt from its model, effort and turn tag only when a served haiku pick takes it, even when it already asked for that model; without one its existing subagent routing stays as it was, and terminal Claude Code is unchanged (desktopSearchHelper;TestDesktopWebSearchHaiku,TestDesktopWebSearchKeepsSessionPick,TestDesktopSubagentWebSearchIsHelper,TestDesktopWebSearchLeavesTerminalSubagent). - A request naming magpie's own id for a model it listed Claude Desktop (
claudeLooking:magpie-<n>.anthropic.<model>,mythos-magpie-<n>,anthropic/magpie-<n>, or a later tier'sdesktopTierAlias) is served by the model whose id gives<n>(aliased): the catalog's first, then the models picked for Desktop's tiers (DesktopTiers, a routing group's id left out). A pick the catalog leaves out for now, its provider's list having come back without it, refused a while (copilotRefuses) or its picks waiting for it, is still the session's model and goes to its provider as asked. Before, the id was taken for a model magpie doesn't serve, and the session's turns went to the model the last turn of any Desktop session ran on (desktop-gone,desktopPicked): Copilot's/modelsanswered without its Claude models for an hour, and a chat on Copilot's Opus 5.5 was answered by another provider's model, the one another chat ran on, with Desktop still saying Opus (mdwsk88). An id that names no model still, but names a Claude model (magpie-<n>.anthropic.claude-opus-5-5,aliasClaude), goes to the model picked for that model's tier (desktopTierTurn,desktop-tier), as Claude Code's own id of one does; any other, or one whose tier has no pick, goes as before (TestDesktopAliasOfTierPickLeftOutOfCatalog,TestDesktopAliasSkipsGroupPick,TestDesktopClaudeAliasGoneTakesItsTier,TestDesktopAliasLeftOutRoute). - 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 (
agTurnedAwayincodeassist.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), Hermes Agent's earlier default persona, and oh-my-pi's RFC 2119 line; since the evening of 11-14 also "You are Hermes Agent" (Hermes' current persona), "You are OpenCode", Codex CLI's "You are a coding agent running in the Codex CLI" (its prompt for models it has none of its own for) and pi's "a coding assistant running inside pi". Codex's GPT-6 prompt, Claude Code's own line, Gemini CLI, Qwen Code, Cline, Kilo, goose, Amp, Droid, Kimi, Aider and Cursor pass as written (real account, 11-14). An Antigravity account's system instruction goes with each such line reworded with the same meaning (antigravityCloak,agSaidAs, incodeAssistBody): the billing line left out, "built on the Claude Agent SDK by Anthropic", Codex's "built on GPT-5", Hermes' "built by Nous Research", oh-my-pi's "RFC 2119 key words", "You're" for Hermes', OpenCode's and Codex CLI's "You are", and pi's "running within pi". The refusal's hint names the agent (antigravityHint: Codex, Codex CLI, Hermes, OpenCode, pi, RFC), word for word as the antigravity and agy-cli plugins and the Routing page'sHINTShave it. Until 11-14 they went broken up by zero-width spaces; since then Google's check reads past invisible characters and turned every broken-up line away 5 of 5 on a real account, so a line is also matched with invisible characters inside it and a copy an older magpie or middleware broke up is reworded too. Every other provider, Gemini CLI's sign-in on the same envelope included, is sent the prompt as written (Gemini CLI's without the billing line, above).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 tooladvisor_20260301, itsmodelnamed as Claude Code names its own: on magpie, by magpie's id (the tier an alias likeopusis 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 (advisorToolsinadvisor.go). The model Claude Code names is first taken to the id magpie serves, as a request's own model is (advisorID): a dotted Claude id is given to Claude Code with dashes, and the advisor came back so, sorelay/claude-fable-5-2on a provider listingclaude-fable-5.2went upstream asclaude-fable-5-2, a name the relay doesn't know (Refeccd on Discord); one it can't run there (another provider's, a group, not Claude's) is run by magpie when magpie serves it (below) and otherwise 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 atool_additionnaming it. Where the advisor is left out, thattool_additiongoes 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." (withoutAdvisoron Messages,advisorGoneIninparseAnthropicfor a translation): left there, the model calledadvisor()as one of the agent's tools and Claude Code answered "No such tool available: advisor" (JackChou on Discord). The Claude subscription's bridge runs it as magpie does on a translation (below, and claude-subscription-bridge.md).TestAdvisorModelAsTheUpstreamNamesIt,TestAdvisorLeftOutOnTranslation. - magpie runs Claude Code's advisor itself where the upstream can't and the advisor's model is one magpie serves (
provider.Resolvetakes it;advisedHereinadvisor_serve.go, Awad_Yoo on X). Claude Code sends the advisor for any model only withCLAUDE_CODE_ENABLE_EXPERIMENTAL_ADVISOR_TOOLset (2.1.316), which the Claude Code advisor field writes (agent-wiring.md). Such a request is translated, a relay on Messages too (ownAPI): the server tool becomesRequest.Advisor, and the model is offered a function tooladvisorwith no parameters (advisorToolDef, a neutral description naming neither magpie nor a vendor), Claude Code's instructions andtool_additionkept as written. A call of it is answered inside the reply's rounds, beside web search's (searchRounds,adviceRound): the advisor model is asked through the gateway (advise, User-Agentmagpie-advisor/1, the executor's system prompt and conversation, what the model said before the call, its tools offered withtool_choicenone, no reasoning, and a short ask appended to the last user message,adviceFor; Claude Code's advisor instructions are cut from its system prompt and messages,advisorCut, since with them, oradvisorGonein their place, the advisor answered as the executor that it had no advisor, #6804), and the reply goes on with the advice as the call's result. Claude Code is told as Anthropic's server tells it: aserver_tool_use(srvtoolu_…, empty input) and anadvisor_tool_resultwith{type: advisor_result, text}, or{type: advisor_tool_result_error, error_code}(unavailable,too_many_requests,overloaded,prompt_too_long,execution_time_exceeded, ormax_uses_exceededpast three calls a reply). Claude Code echoes both blocks in the next turn's assistant message;readAdvisedreads them back as the model's call and its result, splitting the message around them (adviceApart). Not handled: a round that calls the advisor beside an agent tool keeps the agent's tool call only, as with web search.TestAdvisorServedForAVendorModel,TestAdvisorHistoryGoesBackAsACall,TestAdvisorFailureIsAnErrorCode,TestAdvisedHere. - An advisor Anthropic's server runs (the request relayed on Messages,
advisorToolsabove) bills apart from the request's model: the reply's top-levelusageis the executor's alone, and each call is anadvisor_messageentry ofusage.iterations, with itsmodeland token counts, billed at the advisor model's rates and in no top-level total (Anthropic's advisor tool page, "Usage and billing"). The ledger had the executor's row only, so an Opus advisor beside a Sonnet executor was in no row (#6977, Refeccd on Discord).aUsage.Iterationsis read (whole, and from a stream'smessage_delta, whose list holds every call so far and replaces the one before:Usage.advised), and each advisor call is a usage row of its own (advisorRowsinadvisor_usage.go, written byappendAdvisedbeside every row of a try that reached a provider, and on the native route): under the advisor's model by magpie's id (advisorKeyModelof the request's advisor tool,advisedAsinpassthrough; else the vendor's name), itsServedthe vendor's,Kindadvisor(usage.KindAdvisor, named Advisor on Usage's Requests and filters), the request's route, agent, account and session, status 200, no timing. It counts as a request of its own, as an advisor call magpie runs itself does (below). The executor's row is as the reply said; nothing is taken from it. Routing prices the calls too, before the request's own usage (advisorRouteUsage), so the prompt is still read from the last. Not captured from a real reply: the fixture is Anthropic's documented example word for word.TestAdvisorIterationsRead,TestAdvisorCallHasItsOwnRow. - 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 auserInputMessage, anassistantResponseMessageor as a tool entry. The built-in (buildKiroinkiro.go) marks the first message when there is a system prompt, which it folds into that message, and the current message, asbuildAnthropicmarks Anthropic's. A moved Kiro's plugin (opencode-kiro-auth 0.1.10, the mover'smin) turns eachcache_controlin the Anthropic body it is handed into one, at most 4, the last kept. - The cache marks
buildAnthropicadds 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'sprompt_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 namingcache_controlandttl(a relay that knows no ttl) is asked again at 5m and remembered inunfit(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, orcompactLastTextwhen an agent is compacting with its ask in the system prompt (modelLastAsk), as one goes before a history that opens with the model's. Nor does it send a user turn that mixes a tool'sfunctionResponsewith text, which Vertex AI answers with the same "ending with a model turn" (#1533: Codex's compaction prompt after a tool's output): what the user said goes in a user turn of its own after the tools' responses (hasResponse), except for a Claude model on Antigravity, whose tool_result turn holds both. - A tool's
strictthat an upstream turns away (toolStrictRefusalinstrict_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'stools[].functionand Responses'tools[]alike, and marked for that provider and API (toolStrictRefused): its next requests go without it at once. OpenCode 2 sends"strict": falseon 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'stools, 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 includetool_useortool_resultblocks must define tools"), soanthropicBodydeclares 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) withtool_choicenone, 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 andtoolslacks (withHistoryTools, Chat, Responses and Messages bodies, relayed or translated),tool_choicenoneonly 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 (
customToolRefusalincustom_tool.go: DeepSeek's 400 "Unsupported custom tool: 'exec'. Only 'apply_patch' is supported.", #2656; xAI's 422 "tools[N].type: unknown variantcustom, expected one of …", Rust's own wording of the type, #3392) ends the relay:passthroughmarks the model (customToolRefused) and returns not done, andattempttranslates the request on the same API (ownAPI), where each custom tool is offered as a function taking itsinputand a call comes back as thecustom_tool_callCodex 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. - An input item a Responses upstream has no type for (
inputKindWords: a local Qwen server's 400 "Unsupported input item: agent_message" for the item a Codex subagent's task comes in, cyberestro on X; Command Code'sunsupported_input_item; xAI's "unknown item type") ends the relay the same way, when the request carries an item other than a message, a function call, its output or reasoning (hasOtherItemininput_kinds.go):passthroughmarks the model (inputKindsRefused), andattempttranslates the request on the same API, where anagent_messageis the user's turn and a custom tool call a function call. A marked model's next such requests are translated at once. A native compaction or a sealed task isn't translated and gets the refusal, and magpie's own summary ask (inCompaction) keeps its own way on, the conversation as text (inputKindRefusedabove).TestUnsupportedInputItemTranslated,TestInputItemRefusalWordings,TestCodexCompactQwenInputItemAsksAgainAsText. - 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 (xaiBodyinxai_body.go, shaped inpassthroughand on the built body inforwardTranslatedalike, 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": nullbeside itsencrypted_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-levelsystem, its text and blocks (acache_controlkept) as they came, the only place that API takes the role; and a tool's schema can say"required": nullwhere 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,parametersandfunction'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.deltaandcustom_tool_call_input.deltaon as aKToolArgsdelta (argsDelta), holding back only the one that would make the JSON whole until.done, whichendCallchecks against the final arguments; the Responses encoder streams a custom tool's input ascustom_tool_call_input.delta(customStreamincustom_tool.go) before its.done. A Copilot account's Responses request is relayed with aweb_searchtool 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'sspawn_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.addedgave it, in every event after that carries anitem_idor anitem, and in theoutputofresponse.completed,response.incompleteorresponse.failed(idTidyinitemids.go, applied inpassthroughbeforephaseTidy). GitHub Copilot's/responsesgives 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 (
responsesEnumTidyinresponses_enum.go, last inpassthrough's chain, aftersniffandcodexLimitsTaphave read the upstream bytes). The ChatGPT backend speaks part of the Codex protocol:codex.rate_limits,codex.response.metadata,response.metadataand akeepaliveevent, and a typed client (Grok Build through async-openai'sResponseStreamEvent) read one as an unknown variant and lost the whole turn (#4482, crayonlu). Every event whoseevent:name, or datatypewhere it names none, is outside the enum goes; akeepalivegoes on as an SSE comment, so a quiet upstream still keeps the client's idle timer from running out. Codex itself, byUser-Agent/originatoror a key of its own (fromCodex,agentOf, ascodex_own_v1.gotells 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'scapabilities.max_output_tokens(cursorLocalModel), Muse Code'slimit.output(museModels), the GUI's model and group rows (providerInfo,providersState),magpie model output, and every agent's file (agent.maxTokens, #338). The window and the output can come from different sources: Grok's backend lists grok-4.7's 256000 window, and models.dev fills its 500000 output (catalog.DecorateandProvider.replyLimitfill an output only where the vendor gives none). An unknown window or output is published as it is. The catalog keeps the unclampedEntry.Output, and a group's member is still asked for no more than that (outputLimit,withMaxOutput), so a request isn't lowered by the clamp. A limit the user set stays in their settings as they set it (TestModelListsKeepOutputWithinTheWindow). 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/modelsand/v1/models/{id}give each model magpie knows a price of itspricingin OpenRouter's shape, USD a token as decimal strings:promptandcompletionalways (a price set at 0 included),input_cache_readandinput_cache_writeonly when that part has a price (catalog.OpenRouterPricing,catalog.PerTokeninopenrouter.go, which an agent plugin'sconnectis 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, asEntryPriceIn: 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 (noTiers, no 1-hour write). A model no price is known for has nopricingkey, never a 0. It is told to the callersmagpie_priceis (localorsharedWith), whether they ask or not. The list reads the settings, groups and providers once (EntryPricer), andcatalog.PricedByandAtEndpointlook 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 nopricing: their clients read a shape of their own, and an image's price isn't a token's./v1/modelsand/v1/models/{id}say each chat model takes tools, a routing group included (toolsTold): models.dev'stool_call: true, beside itsreasoning, and OpenRouter'ssupported_parameters(tools,tool_choice, andreasoningwhen 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. Nocapabilitieskey 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 (askedOutputinmaxoutput.go): the user's Max output, else the vendor's list or models.dev, within the window.anthropicBody'sdefaultMaxTokens(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_tokensreaches a Responses client asincomplete_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,retryTokenFieldintoken_field.go, on every request throughforwardOnce):max_completion_tokenson 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_tokenson DeepSeek (deepseekTokenField); as the client sent it elsewhere, since Zhipu and most relays readmax_tokensalone. 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 inunfit, 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).Inheritgives the new process'sListenAndServea socket to serve when the address is the same (sameAddr), and calls back once it serves;HandOffhas 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 tohandedOffDrain(15 minutes) for its requests in flight instead ofshortDrain(2s). Before that shutdown, each connection it took sends its first request (unreadConns,unreadWait5s at most):http.Server.Shutdowncloses 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,TestToolCallOfTheMagpieBeforeGoesToItinhandover_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 incounted(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). AfterunroutedShow(15s) a route of providermagpieshows 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 isredact(phaseRedact,noteRedactinginredact_phase.go, around everyredactedHitsandmaskTextHits), on/v1/magpie/concurrencyand 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.Maskingand the usage record'smasking_ms, shown as Masking in the Routing page's time and the Usage page's detail. It holds no text.TestMaskingIsAPhaseWithItsTime,TestNoMaskingNoMaskingTimeinredact_phase_test.go,routing-masking.test.cjs. It is answered 504 afterunroutedUnknown(30s) held in no wait magpie knows of, or afterunroutedMost(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 (TestUnroutedChunkedBodyReadWholeHeld504holds the other side). While an upload earns as fast as it is read, its charged time stands still, socheckMostlooks again no sooner thanunroutedRecheck(1s) rather than every sliver left (TestUnroutedMostRecheckIsNoSpin).TestUnroutedProgressingUploadOutlastsMostcovers TLS throughFrontwith declared, chunked, gzip and zstd bodies;TestUnroutedUploadCreditKeepsIdleDeadline,TestUnroutedUploadTimeIsBounded,TestUnroutedUploadAllowanceHasCeiling,TestUnroutedFastUploadBanksNothing,TestUnroutedEmptyEncodedStreamIsBounded(empty gzip members, zstd skippable frames) andTestUnroutedTrickledBodyAnswered408cover 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 ofr.Body), masking (noteMasking, fromnoteRedacting), 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 everynotePhase(slot, rpm, upstream, redact), and the body room's queue (bodyRoom.take, at mostbodyRoomWait, 100s). Each is named (itskind), 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 witherrUnrouted, its route ends with the error before the answer goes (heldWriter.claimtakes the reply, the route is marked done with its status, error and report, thensendwrites it, all underf.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 throughheldWriter, 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 saysConnection: close, and a client that closes on it ends the request's context and lets its wait go, #4300), outsidef.mu, inHeldDir(<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 newestheldKept(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, where the request itself stood (stood at:, the first of magpie's own functions on its handler's stack and what it waited in, and that stack in full under "where this request stood", ahead of the rest:watchUnroutedkeeps the handler's goroutine id,heldOwnfinds it in a dump of every goroutine and strips the argument words and pc offsets; the log line says it as "standing at", wilsonxuuuu on X: a report pasted cut before the stacks said 30s in no known wait and nothing more) 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 isRoute.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,TestHeldReportSaysWhereItStood,TestHeldOfFindsItsGoroutine,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 (
heldByGroupinkey_models.go, byaccess.Identity.HeldToGroup): the strict intersection with the key's own list,<provider>/\x00(heldToNone) when the two share none of a provider, andIdentity.Groupset 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'sholdandMember.Via(groupHeld): its candidates on an account it leaves out are Held rows withWeighed.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.SaveGroupresolves 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,replaceingroups/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 (
drawAccountsin the routing plugin'sclient.js) has a row for each member's provider with more than one account (/api/groups'accounts,groupAccountsingroups.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) andmembersFound'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. SaveGroupkeeps 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, asGroup.Accountskeeps its own.- The gateway holds such a member to that account alone:
planLevel'skeysleaves the provider's other candidates out as Held rows (memberHeld,Weighed.HeldOwnwithHeldBythe group), and fallback goes to the next member, never to another account of the same model. Withrouting: orderthe members are tried top first. The member's account is narrowed further byGroup.Accountsand a key's accounts, never widened. - Shared and imported groups drop a member's account (
withoutMemberAccountsinShareGroupandimportGroup); two members left the same are one. - The editor's model row has an account chip (
rt-macctin the routing plugin'sclient.js, for a provider/api/groups'accountslists, 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.Accountcarries the member's account. The CLI takes#<account>inmodels=(memberResolver), and the TUI's effort key keeps it. - Image and video groups go the same way:
drawingTrieskeeps the same model on two accounts as two tries, matched to the chat plan's candidates bymemberHeld, and each try is drawn on a request held to its member's account alone (memberOn, beforedrawOnAccountsandstartVideo).count_tokenscounts 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.
groupBarredinkey_models.gobars 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 ingroupGiven(serve,countHeld,keyGroupFor, embeddings, images, videos, decision groups) and, for the model lists, inkeyAllowedandkeyListed(/v1/models,/v1/models/{id}, Ollama's tags, the Codex catalog), gated onprovider.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.SaveGroupkeeps 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 (cleanGroupKeystrims 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 (
drawKeysin the routing plugin'sclient.js) offers/api/groups'gatewayKeys(groupKeysingroups.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). A limit's period total (@Cyrus_4433 on X) never resets by the clock: access.Limit.Window counts it from its Since (when it was set, or last reset; the epoch if hand-written without one) to a reset a hundred years off, so only the key's Reset moves it; its 429 says it stays refused until reset or raised. TestTotalLimit* in internal/budget. A limit's period account (ljayic on X) follows one subscription account's window (Account "/", AccountWindow its name): access.Limit.Window asks provider.AccountWindow, which reads the account's last good reading (quotas.json, never the vendor on the request's path) for that window's start and reset. When it isn't known (no reading, no such window, or the reset passed with no reading since) the reset is zero and the start is the latest time the window can't have begun before (the reset that passed, else Since), so the limit counts at least the window's calls and is never lifted on a guess; budget then says resetUnknown, its 429 retries after 5 minutes, and the accounts are read again in the background at most once a minute. TestAccountWindowLimit in internal/budget, TestAccountWindowFromLastReading in internal/provider. 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 (only when the user set a usage limit on the account, or there is another candidate to go to: a sole account held only by Codex credits being off, with no limit of the user's, is sent at once, userCapped): 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.
A key's ServiceTier (JackyFill on X; access.Key, set by the tier-key
action, the key row's service-tier badge or magpie gateway-key tier <id> follow|standard|fast|ultrafast; stored as "", "default", "priority" or
"ultrafast") sends its Responses and Chat requests at that tier whatever the
client asked, and over Codex's own setting (keyTiered in codex_tier.go,
after codexTiered in handle and in codexBackend): standard takes the
tier off, and Ultrafast on a bare model no account lists it on goes as
priority, as codexTiered does. Unset follows the request. It only sets the
request's service_tier: what is then sent upstream is the providers' own
rule (fits, takesTier, the ultrafast to priority fallback), so a vendor
that honours no service tier is sent none, and Anthropic-protocol requests
(Claude's speed) are left alone. Tests: TestGatewayKeyServiceTier,
TestKeyTieredChat, TestKeyServiceTier in internal/access,
TestGatewayKeyTierCLI, gateway-key-tier.test.cjs.
A key's Routing (justforlxz on X; access.Key, set by the routing-key
action, the key row's routing badge or magpie gateway-key routing <id> follow|smart|order|drain|rotate|usage|pace|weight|free|fast|cheap|expiring|fit|<plugin>/<name>; stored as
"", "smart", a built-in routing or a plugin's) is how a routing group its
requests ask for picks among its members' keys and accounts: the group is
planned with that routing in place of its own (keyRouted in
key_routing.go, applied where the request's group is resolved: handle for
Chat, Messages and Responses, the masked-route move there too, embeddings
and rerank, drawing, video, a System One group and a relayed search's
order). Unset follows the group. A Manual group still sends to its pick, and
a group in the group or a provider in it routed its own way keeps its own
routing (#576), as under the group's own; a member left on the default is
weighed with the key's routing, as with the group's. The plan carries the
routing it was made by (planned.routing), so leastHeld judges the
members the same way, and the trace's group shows it. count_tokens plans no
group, so it is untouched. An issued key that sets none follows its
issuer's (Identity.Routing). Tests: TestKeyGroupRouting,
TestKeyRouting in internal/access, TestGatewayKeyRoutingCLI,
gateway-key-routing.test.cjs.
A key's Redact (y0ngb1n on X; access.Key, set by the redact-key action,
the key row's masking badge or magpie gateway-key redact <id> follow|on|off; stored as "", "on" or "off") decides whether Settings ›
Privacy's masking applies to its requests. Unset follows the settings, as a
request with no key (this computer's own) always does. Off sends the key's
requests as written, for a device the user trusts; on masks them where the
settings mask nothing too, with the default rules for secrets and personal
data (masking.WithForced). Every place that masks what goes to a vendor
asks maskingFor (redactedHits, maskTextHits, so chat, count_tokens,
searches, drawing, video, speech and embeddings alike), and a native call
asks redactionWantedFor; a masker that doesn't read the request's context
can't be held to a forced pass, so that is an error, not a request sent as
it is. A request with the key's own setting is never reported to a Remote
magpie as masked (ownMaskedAs), whichever way it was set, so the remote
masks by its own settings. An issued key keeps its own setting, and its
issuer's on holds for it (Identity.Redact). Records of requests kept
locally (maskedCopy) stay masked by the settings. InUse of the redact
plugin counts a key set on. Tests: TestKeyRedactSetting,
TestKeyRedactEveryRoute, TestKeyRedact in internal/access,
TestGatewayKeyRedactCLI, gateway-key-redact.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
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 (Quota first,
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 | a Token Plan's Wan 3.0 and HappyHorse at /api/v1/services/aigc/video-generation/video-synthesis (below); none for ModelScope |
| 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: noAccount, aKey, 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%2eand across%2Ftoo), 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 andX-Magpie-*are dropped (nativeHeaderDropped), the gateway key's?key=too (nativeQuery); the rest go as they came. What a proxy says of the caller isproxyIdentity: every name lanGuard reads as forwarded (forwardHeaders:Forwarded,X-Forwarded-For,X-Real-IP,Cf-Connecting-IP,True-Client-IP,Tailscale-User-Login), anyX-Forwarded-*,Cf-*,Tailscale-*(Tailscale Serve's user login, name and picture) andX-HC-*(a LazyCat box's ingress: the box account signed in, its role and device),Via,X-Client-IPandX-Original-Forwarded-For. The Codex passthrough and relay to the ChatGPT backend (copyHeaders) and the MCP proxy drop the same; seeTestNativeAnyDropsProxyIdentityandTestPassthroughDropsProxyIdentity. A provider'sPassHeadersstill passes on the names it lists, these too: the user chose them.Signputs 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-Svcand 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,
Locationincluded, 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,
nulland*.localhostwithout 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'smodel, 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 throughrestoring, 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.
Alibaba's Token Plans (qwen-token-plan, bailian-token-plan,
alibaba-token-plan, qwencloud-token-plan) name every kind of model the
plan serves, each in its own list on the preset (PresetDef.Drawers,
Videos, Speakers, Transcribers, read by PlanDrawers, PlanVideos,
PlanSpeakers, PlanTranscribers): Qwen-Image and Wan 2.7 images
(drawn as above), Wan 3.0 and HappyHorse 1.1 videos, qwen-audio TTS and
ASR, beside the chat models (@gaubeebangeel on X). A key of such a plan
(no account, not a plugin or another magpie, dashScope) is asked on
DashScope's own APIs at its host's root (dashScopeRoot), since the
plan's host has no OpenAI-style videos or audio API:
- Video (
video_dashscope.go,filmsDashScope,makesDashScopeVideo):POST <root>/api/v1/services/aigc/video-generation/video-synthesiswithX-DashScope-Async: enable, polled atGET <root>/api/v1/tasks/<id>, its MP4output.video_urlfetched throughvendorClient.dashScopeVideoBodyputs the prompt andnegative_promptininput,input_reference,last_frameandreference_imagesasmediaitems of typefirst_frame,last_frameandreference_image(at most 10),sizeasresolution(1080P/720P/480P by its shorter side) and the nearestratio,secondsas a wholeduration,watermark: falseunless sent, and the caller's other fields inparametersas sent. The task answer names no model, so the vendor id is the model and task in base64url (dashScopeStarted,dashScopeTask). PENDING, RUNNING, SUCCEEDED, FAILED/UNKNOWN and CANCELED are read as queued, in_progress, completed and failed (dashScopeVideoStatus). Ids carry the key's mark and polls go on that key, as MiniMax's do. - Text to speech (
speech_dashscope.go,dashScopeAudio,speechRequest.dashScopeSpeech, anativeRetrievalas Gemini's speech is):/v1/audio/speechgoes toPOST <root>/api/v1/services/audio/tts/SpeechSynthesizerwithinput.text,voice(an OpenAI name, or none, is the model's own first voice:longanlingxinfor -plus,longanhuan_v3.6for -flash),format(mp3 by default, wav, pcm, opus; aac, flac andstream_format: sseare 400s before DashScope is asked),instructionsasinstructionandspeedasrate(0.5 to 2). The answer'soutput.audio.urlis fetched (fetchVendorFile), oroutput.audio.datadecoded, and served with the format's type;usage.charactersis the input counted. - Speech to text (
audioForm.nativeAt,dashScopeTranscription):/v1/audio/transcriptionsgoes toPOST <root>/api/v1/services/aigc/multimodal-generation/generation, the form's file as aninput_audiodata URI, itsformatfrom the file's name or type,languageaslanguage_hints; the prompt has no field there and isn't sent.output.textis answered as OpenAI's json, text or verbose_json; srt, vtt and/v1/audio/translationsare 400s.
The plan's Qwen-Omni realtime (wss://<root>/api-ws/v1/realtime) is
served by the realtime route as other DashScope hosts are. Covered by
TestTokenPlansNameEveryKind, TestTokenPlanSpeaks,
TestTokenPlanTranscribes, TestTokenPlanMakesVideos and
TestDashScopeVideoBody.
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).
Claude Code's Gateway Model Discovery
Claude Code with CLAUDE_CODE_ENABLE_GATEWAY_MODEL_DISCOVERY set asks GET /v1/models?limit=1000 of its ANTHROPIC_BASE_URL (User-Agent claude-code/<version>, anthropic-version: 2023-06-01) and puts in /model only the ids matching /(claude|anthropic)/i (2.1.316's bundle), so a remote magpie's Kimi, GLM or DeepSeek were left out (zent00 on X). For that request alone (claudeCodeDiscovers in claude_discovery.go: the User-Agent and the header; never another magpie), a chat model whose id says neither is listed by Claude Desktop's alias anthropic/magpie-<n> (aliasFor), which unprefixed serves as the model for every client before any provider's model of that spelling, and every row's display_name is the agents' list name (provider.LabelsFor), which /model shows. An id Claude Code keeps stays as it is; a name the calling key gives a model stays the user's; a bare-id row (BareModelIDs) it wouldn't keep is left out, its full id's row being listed already (with Only, BareModelIDsOnly, there is no full row, so it is listed by the alias). anthropic/<magpie id> is not used: a provider named anthropic (the Anthropic preset's id) serves any model asked of it by that spelling. Every other client sees the ids unchanged (TestClaudeCodeDiscoveryKeepsEveryModel).
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/keyswith{"ttl": "1h" | 3600, "name", "models", "accounts", "tokens", "cost", "readOnly"}answers 201 with the key'sid,name,key(the secret, told once,Cache-Control: no-store),expiresand what it is held to.GET /v1/magpie/keyslists the keys the caller issued, masked;DELETE /v1/magpie/keys/{id}revokes one. Seeissue_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|offlets a key issue;gateway-key listshowsuntil <time>,expired,issued by <id>andissues 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.Matchglob. A GitHub rule namesrepository,repository_owneror 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,MinTTLtoMaxTTL).
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/usage/requests?cursor=start|now|<next_cursor>&limit= |
the same requests as changes (#6060): rows to upsert by stable id with original_ids, deleted ids, next_cursor, has_more; a cursor it can't resume from is a 400/410 with a code, never a gap (see the request feed) |
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 |
/v1/magpie/admin/… |
the management API: the app's provider, account, gateway-key, account-group and routing-group handlers for a key with Key.Admin, below |
The management API
/v1/magpie/admin/ (ljayic on X) serves the GUI's own /api handlers to a
script. admin.go is the guard and
internal/gui/admin.go the route list
(adminRoutes: what is served, to which /api route; anything else is a
404, and TestAdminRoutesEveryAPIRoute fails when a listed route is not the
app's). The guard, in order: a request carrying Origin or Sec-Fetch-Site
or -Mode is refused with a key or without (a page can't leave them off, so
Origin: null, a foreign or listed page and *.localhost need no case of
their own); no key is 401; Identity.Admin == "" is 403; from loopback the
Host must be ownHost (a rebound page's GET has no Origin), and from
anywhere else the key must be AdminAny. Key.Admin is set only by
magpie gateway-key admin and the app, never through the API, and
adminOf drops it for a read-only, Browser, issued, expiring or default
key. A key action through the API on another key that has Admin
(adminMayChangeKey) is 403: rotating it would hand the caller its new
secret, or set one the caller chose, so a local key would get an any
one or take over a peer's. The caller's own key is its to change. The route is in readOnlyRefused, so a read-only key never reaches
it. The handlers are built with no window, so a sign-in opens no browser.
Routing Groups go to /api/groups (adminGroupActions; found and skip
are left out, as they set this computer's agents), with
routing-groups/{id...} (an id may be group/<id>), create and update
of the API's own in front: update reads the stored group, lays the body's
fields over it and hands that to the same save (adminGroupWrite), so
provider.SaveGroup checks every write the page's does
(TestAdminAPIRoutingGroups, TestAdminAPIRoutingGroupsGuarded). The app
sets Key.Admin from a key's menu, Advanced (gatewayAdminPick,
gateway-key-admin.test.cjs). Sign-in export is left out (#6307).
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,activeandroutes, every request the trace has that is still going, read together with the cursor undertrace.mu.GET /v1/magpie/route-events?after=<cursor>(orLast-Event-ID, which wins): SSE. Eachrouteevent has anidequal to its JSONcursor, akind, theactivecount after the change and oneroute, which replaces the display's route of thatid. A display removes it when itsphaseisdoneordropped.
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.
DeepSeek's chat page
/deepseek-chat/ is DeepSeek's open-source web chat page
(deepseek-ai/chat-demo, MIT,
release v0.1.1) served by the gateway, so any of magpie's models chats in
it and its search and link reading are magpie's (@yanghonghang on X). The
release zip is embedded as published (chatDemoZip, its LICENSE served at
/deepseek-chat/LICENSE; TestChatPageIsTheRelease holds it to the
release's sha256). Nothing is built: the one place the bundle names
https://api.deepseek.com is served as location.origin+"/deepseek-chat",
so the page calls the routes below at whatever address it was opened at.
chatpage/magpie.js, added to its index.html, gives the page the key
magpie-deepseek-chat on this computer (an agent key, counted as
deepseek-chat) and draws a model picker in its top bar, read from
GET /deepseek-chat/models (the caller's models, a DeepSeek flash model
first as the page's default) and sent as the magpie_chat_model cookie.
- Files: the page's own files (GET and HEAD) are the only keyless routes,
in
readOnlyRoutesand, while shared,lanGuard'schatPageOpen, the same bytes for everyone like the key page. A strict CSP keeps it to its own origin and scripts. Every call it makes needs a key, which another computer's user types into the page. POST /deepseek-chat/anthropic/v1/messages(chatMessages): the page's toolsdeepseek_web_searchanddeepseek_read_urlbecome Anthropic'sweb_search_20250305(magpie's own search for a model that can't search, with its citations) and aread_urlfunction tool, which magpie runs withfetchPagebetween rounds, all said to the page as one reply in its own shapes (chatTurn). Each round goes through the gateway's own Messages route, so routing, masking, limits and usage apply as to any agent. A gateway key's MaxConcurrency holds a turn as it holds an agent's request (keySlotRoutes, lazy: the rounds' tries take the slot, whichchatInner's copy of the context carries), and the speech routes eagerly; the file routes are free. The page shows sources only from text blocks'citations; a model that names URLs in its text without citing gets no source chips.- Files the page uploads (
/anthropic/v1/files) are kept in memory for the key that uploaded them until magpie restarts: images, PDFs and text; Word, PowerPoint and EPUB files are refused. - Voice input and read-aloud (
/v1/tools/asr,/v1/tools/tts) use the first speech-to-text or text-to-speech model a provider serves, and say so when there is none. - A LazyCat box's manifest makes
/deepseek-chatpublic, as it does the key page, for a key's holder who isn't signed in to the box (docs/reference.md).
Tests: TestChatPageOpensWithoutAKey, TestChatPageConversation,
TestChatPageSearchesAndReadsLinks, TestChatPageFiles,
TestTextCallsCitationAfterItsBlock, TestKeyConcurrencyChatPage,
gateway-chat-page.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 › Models › 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).
Gemini's other tools of its own a client offers (urlContext,
codeExecution, googleMaps and the rest, Request.GoogleTools, from a
Gemini client's tools or the same objects among a Chat request's,
chatGoogleTool) go on as sent to a Gemini model on Code Assist, the
Gemini API and Vertex (buildCodeAssistSent), beside googleSearch and,
like it, only when no function is declared; Claude on Antigravity gets
none. A plugin whose provider is at *.googleapis.com on Code Assist
(Antigravity's, googlePlugin) searches by googleSearch as a Google
sign-in does. Code Gemini ran comes back as text in fences (ranCode),
and a search reaches a Gemini client as groundingMetadata (grounding).
Before, all three were dropped on every translated route (daoche_wuzui on
X, TestGeminiClientKeepsGoogleTools).
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.
Codex's web.run on any other model (its POST /v1/alpha/search, or under
CodexPath) is searched by magpie (alphaSearchHere), unless the provider
the turn would go to is a key+URL relay with a Responses base set to search
by itself (Searches, "Searches the web by itself"; upstreamSearches).
Then relaySearchers sends the
body as Codex sent it, with the bare model, to <Responses base>/alpha/search
with the relay's key, Codex's turn headers, its originator and the agent's
User-Agent, and its 2xx reply goes back as it came (YIXIE233 on X: a relay
in front of a ChatGPT pool that serves /v1/alpha/search). A group goes by
its plan: the leading member decides, and later members that search are
tried after it; one that doesn't is skipped. Accounts and models a key may
not use are left out. When every try fails, magpie searches and the output
starts with why. magpieSearches (Settings' searchAll) keeps magpie's
search, as for the Responses web_search tool, which a relay set so was
already sent as is (searchedForIt). A plugin's provider is not sent
web.run: its fetch serves turns, not this route. Covered by
TestCodexWebRunGoesToRelayThatSearches and
TestCodexWebRunInGroupFollowsLeadingMember (both red on the old code),
and TestResponsesWebSearchToolToRelayThatSearches.
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 › Models › 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 › Models › 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):
askVisionWithsends Chat'sreasoning_effort; the image cache key (sightKey) has the level picked in it, so a new pick reads the image again.searchBodysends the searcher's Anthropic bodythinking(disabledfornone, else enabled withbudgetOf's budget, 1024 forminimal) andoutput_config.effortunless the vendor model is a Claude older than adaptive thinking. The gateway's translation then fits it to the vendor: adaptive thinking orbetween_toolsfor new Claude,reasoning.effortfor Responses,thinkingLevelfor Gemini 3 on Code Assist and Antigravity.- A picked level raises the call's
max_tokensby 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.
What the web-search MCP server's web_search narrows by
Beside query and count, web_search takes allowed_domains,
blocked_domains, recency_days, images and search_context_size
(search_mcp.go,
searchopts.go). They travel in
ctx (withScope), never in a request body. The ChatGPT backend's search
(codexSearch) takes them as the fields Codex's web.run has (codex-rs
codex-api search.rs): a query's domains and recency, image_query
instead of search_query for images, settings.filters,
settings.search_context_size and settings.image_settings. Every other
searcher is asked the sites as site: and -site: operators in the query
(searchScoped, at the top of webSearch) and ignores the rest. Image
results come back as pages whose text starts "Image: " (imageSaid).
The output is cut into pages at each line of 80 dashes (codexBlocks),
which often follows a page's last word with no line break: an image
search always does. TestImageSearchGivesTheCount.
TestSearchScopeReachesCodexSearch, TestSearchScopeOperatorsForOtherSearchers.
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. In Settings › Models › Web search, Advanced (shown
with two or more search APIs on, open while some are mixed) has "Ask the
search APIs": In order, or All at once, which marks every API on
(POST /api/settings/search-api with mix, the vendors, or [] for none;
heyiwei5 on X). A mix of only some of them has neither choice on, and its
line names them.
Covered by TestSearchAPIsMixedAskedTogether, TestSearchAPIsMixedOneDown,
TestSearchAPIsMixedAllDownAsksTheRest, TestSearchAPIsMixedCapped,
TestMixSearchAPIs, TestSearchCLIMix, TestSearchAPIsMixedFromSettings
and search-mix.test.cjs.
Checking every searcher (Quick check)
Settings › Models › Quick check's Web search row (POST /api/pipelines/check
with search, CheckPipeline) asks every searcher a search can go to
once, at the same time (checkSearch): the provider that searches
(searcher, through searchBy), unless provider search is off, and each
search API on (provider.SearchAPIs, through askSearchAPIKeys), in the
order a search asks them. A search stops at the first that answers, so a
check made as one search never reached a second API (heyiwei5 on X). No
searcher stands in for another, and a mixed API is asked alone, so each
line under the row is that searcher's own: its name and how long it took,
or its error. The check is ok only when every one is. Nothing set up, or
the Web search plugin off, says so as before. Each line costs one search
of that searcher, made only on a press of Test or Test all. Covered by
TestCheckSearchAsksEveryAPI, TestCheckSearchAsksOnce and
pipeline-check.test.cjs.
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).
A video the client gives the model
A video is a File part whose media type is video/* (isVideo in
video_input.go). It is read from
Messages' video block (MiniMax's Anthropic endpoint takes one), Chat's
video_url, a Chat file of a video (the nested form, or the AI SDK's flat
{type, data, mediaType}), a Responses input_file of one, and Gemini's
inlineData/fileData. It is built in each API's own shape: a video
block on Messages (videoBlock), video_url on Chat (chatVideo),
inlineData on Gemini's API. Responses has none, so a video in the latest
user message translated there is a 400 that says so (unportableVideo, in
translate). Before, Messages' block and Chat's video_url had no case in
the parsers: the request was answered 200 and billed, and the model never
saw the video (#6135, #4101). A relayed body keeps its video as it came.
Whether a model takes video is its source's list of kinds
(Entry.Inputs: a plugin's capabilities, a list's input_modalities,
models.dev); nil is unknown (videoInput). A latest-turn video for a
model known to take none is a 400 before any upstream is asked
(videoRefused, in serve after the image gate). A video of an earlier
turn to such a model is told of in words (Request.videoOff, set in
buildFor, attachmentText). A routing group takes the union of its
members' kinds (unionKinds in buildGroupEntries, so /v1/models lists
video for a group with a member that takes it, #2898), and a video goes
only to the members that take one, else those nothing is known of, else a
400 naming the group. Audio (input_audio, #4101) and PDFs (#5452) are not
handled here.
Covered by TestPluginGetsTheVideoBlock (the reporter's body to a plugin),
TestVideoReachesEveryAPI, TestVideoForAModelThatTakesNone,
TestGroupVideoGoesToMembersThatTakeIt and TestGroupInputsAreItsMembers.
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) andPicked(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). sightskeeps 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 (seenBodydedupes by the key too). A failure is still not kept.- Completed descriptions of inline images are also appended to
vision-cache.jsonlin magpie's config directory before their waiters are released (saveSight), and restored byNew. 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 byvision-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 to allowance this way.
Covered by TestAutoVisionPassesOverOneOut,
TestAutoVisionTierAmongThoseWithAllowance, TestSpentModelAcrossAccounts,
TestVisionDoesNotAskSpentDescriber and TestSearcherPassesOverOneOut.
Automatic picks are held to the provider that serves them
A slot Settings › Models leaves on Automatic (Image recognition, Web
search, Image generation, Video generation) is held to the provider
magpie first picked for it, in auto-picks.json beside providers.json
(auto_picks.go: heldPick, settlePick). seersRankedHeld and
autoSearcherReady put the held provider before every other of its
readiness; AutoDrawer and AutoVideomaker pick among its models while it
has one. A provider added later never takes a slot over: a Claude account
ranks first for images and search, and one added for account switching
alone took every agent's images and searches (hxy920830 on X). A default
fills only a slot nothing serves: nothing held yet, or the held provider
removed, turned off or left with no model for it; the next pick is then
held. Allowance still comes first for the moment (above), and the hold
stays. A model picked in Settings is the user's and no hold touches it;
the picker shows Automatic's pick as Automatic · <model>.
Holds begin once, when the gateway first serves (KeepAutoPicksHeld,
seedAutoPicks, Seeded); until then each pick is made as before, and a
file that can't be read holds nothing and is not written over. The seed
reads the last 30 days of the ledger: Image description calls (vision)
and the searcher's Web search calls (web_search, not SourceSearch). A
slot taken over by a provider added later (pickBefore: the one that
served the call just before the current pick's first) is given back while
that provider can still serve it; one the current pick served from the
first row is kept. Image and video generation have no Automatic call in
the ledger and are held to the pick at the seed.
Covered by TestAddedProviderTakesNoAutomaticPick,
TestAutoPicksSeededFromTheLedger and TestClaudeAccountAddedTakesNoImages.
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 andDecidersas a decision model.codexModelsdrops a disabled one of Codex's own, andcodexListTagchanges 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'sFallback),countTokensand Gemini's:countTokens(countOff),serveSystemOne,serveDecisionGroupandpostDecide(every decision call), draw, video and embeddings, andcodexBackendfor 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);SetDisabledModelswrites 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*ininternal/gateway,internal/provider,TestModelDisableCmd,TestDisabledModelsSetting, andinternal/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, asGroupFor) gives the group's row; elseresolveIn(asResolve) 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.
- A routing group the user made is listed by its own id too,
fastbesidegroup/fast(groupBare; 小八 on Discord), after the models' bare ids, and under Only ingroup/fast's place. Only where a request for that id reaches the group: not when it is listed already, whenGroupForof it reaches another group, or for a group magpie found (itsauto/<model>row is listed under the model's bare id already). A group a model's bare id already reaches adds nothing: a group named for a model a provider serves,glm-5.2, is listed through that model's row while the row is shown, and by its own row when it isn't (the group lists its members alone, a provider kept for routing groups, the agent's hidden models), sinceGroupFortakesglm-5.2to the group beforeResolveeither way. Before, such a group stayedgroup/glm-5.2under Only (小八 on Discord, v0.1.4377). - 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 seeglm-5.3that would go toa. - 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/modelids (magpieModels), andgroup/<id>for a group, so turning it on or off rewrites nothing; the gateway takes either id. - Only (
{"on":true,"only":true},settings.BareModelIDsOnly,provider.SetBareIDs,provider.BareOnly): the bare ids in place of the rows they stand for, not beside them (qQianye on X: a Docker magpie's client listed every model twice, and gateway mode has no Agents page to pick an agent's models on).provider.OnlyBareputs each bare id where the first row it stands for was and leaves the others out: the row it reaches (a found group,auto/glm-5.3, included), and every provider's row of that model when it reaches that model (by its group, or the first provider serving it). A row it doesn't reach (b/vendor/m9, whose bare id names the providervendor), a held key's row whose bare id isn't listed for it, and any other group's row keep their ids, so no model leaves the list. Aprovider/modelrequest is still served as before; only the list changes. For Claude Code's discovery a bare row is then the model's only row, so one it wouldn't keep is listed by its alias, not left out. Off clears Only too. - Tests:
TestBareModelIDsReporterCase(Codexgpt-5.6-sollisted 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),TestBareModelIDsOnly(Only: the rows in place, found groups on and off,provider/modelstill served, Claude Code's discovery, a held key, another magpie) inbare_ids_test.go,TestBareIDsListUserGroups(a user's group by its own id, on and Only, a group named like a model, a found group, a held key) inbare_group_ids_test.go,TestBareModelIDsSettingandTestBareModelIDsOnlySettingininternal/gui, andinternal/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/editsor/v1/images/generationsreference image, for an images API that takes files, Gemini's own API or Code Assist:fetchPictureindraw.go,publicClient), a pageweb_fetchreads (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 ab64_jsoncaller indraw.goand/v1/videos/{id}/contentinvideo.go,vendorClient; generate_image's own download ininternal/imagemcp,PublicClient). Every address the host resolves to must be public (publicAddr, which isinternal/netguard'sPublic, 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::/96with 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 (anhttps://CONNECT or SOCKS keeps the name for TLS and Host; a plainhttp://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 orlocalhost,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 plainhttp://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'sfake-ip-range6, which Clash Verge Rev turns on by default asfdfe:dcba:9876::1/64or fills in as2001:2::/64; jiezhengj, whose everyweb_fetchwas refused) is left out bydropLoonand 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 (publicIPininternal/provider/icon.go, #252), and shares the rule.TestFakeIPNameGoesToALocalProxyByName,TestFakeIPNameDialledThroughTheTUN,TestFakeIPWithItsIPv6Answer,TestFakeIPRefusesTheRestinfakeip_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'sfetchPrivate(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 thehost:portof 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.createtext 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 andOpenAI-Beta: responses_websockets) with the frame as its body,type,previous_response_idandgeneratetaken out, andstream: trueset on the internal HTTP request. OpenAI's WebSocket mode does not use the HTTPstreamfield: a client omitting it still gets incremental events before the reply completes (TestResponsesSocketStreamsWithoutStreamField).client_metadata's turn state and responses-lite flag become theX-Codex-Turn-StateandX-OpenAI-Internal-Codex-Responses-Liteheaders Codex sends over HTTP; the turn state goes as the header only, taken out of the body'sclient_metadata. Codex continues a turn on a socket byprevious_response_idand sends no turn state, so the socket keeps the state the last reply of a turn gave and sends it with that turn's next request (client_metadata.turn_idthe same), as Codex over HTTP does (TestCodexSocketKeepsTurnState). The pooled Codex route does the same per account and turn (codex_turnstate.go): a state goes back only to the account that issued it, never to the next account after a failover (TestCodexPoolTurnStateStaysWithItsAccount). It goes through the whole handler the upgrade came in on (socketEntry, outsideFrontandHandler), 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'sAcceptrefuses a browser Origin whose host isn't theHost.holdCatalogholds 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.metadatawithx-codex-turn-state,openai-modelandx-reasoning-included;codex.response.metadatawithx-models-etag, the backend's own event given magpie's tag asmodelsEtaggives it;codex.rate_limitsfrom thex-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 anerrorframe 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 answeredprevious_response_not_found, on which Codex opens a new socket and sends everything.prevResponsesisn't used: Codex saysstore: false. generate: false(Codex's warmup) is answered locally with aresponse.createdandresponse.completedof its own id; nothing is sent upstream.response.interruptnaming the reply in flight cancels its request and is answeredresponse.interrupt.accepted, then an interruptedresponse.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.failedgoes 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, throughclientSockets.drainbesidesrv.Shutdown(a hijacked connection isn't the server's), and refuses new ones 503.- The leg to the vendor cuts its own delta where the vendor keeps a
turn for the next: the ChatGPT backend and a Responses provider that
speaks the socket (
Socket; unset, OpenAI's own API does, as Codex's built-in OpenAI provider does, KawaiiZapic on X) take a turn as its new input afterprevious_response_idon a kept socket (see Providers and accounts); OpenAI's API, Azure and Ark over HTTP take the client's ownprevious_response_id(prevKeeps, below), which Codex never sends (store: false); another magpie takes the delta between the two (below). Everything else (Chat Completions, Messages, Gemini, a Responses provider over HTTP) is sent the whole conversation each turn, since those protocols keep nothing between requests. A socket's conversation doesn't outlive the socket or the gateway.
A Realtime session
GET /v1/realtime?model=… (and /realtime) with a WebSocket upgrade is the
Realtime API, as OpenAI's and DashScope's realtime models take it
(realtime in realtime.go;
gaubeebangeel on X: a Qwen Token Plan's realtime voice). A request without
the upgrade is answered 426. The model is resolved as a chat's (idOff,
modelOff, a key's models and accounts, onKeys, probeOne); a bare id
no provider lists goes to the one DashScope provider turned on
(resolveRealtimeModel), and a routing group is a 400, since a session
goes to one model. The session opens at the provider's realtime address
(realtimeURL): a DashScope base (…/compatible-mode/v1, Qwen's,
Bailian's and both Token Plans') at /api-ws/v1/realtime on the same host,
as Alibaba gives the Token Plan's qwen-audio-3.0-realtime-plus
(https://platform.qianwenai.com/docs/token-plan/best-practices/realtime-voice),
any other at base + /realtime. It is signed as the provider's requests
are (Sign, stampUA, the provider's proxy and RPM through metered),
each try in turn until one opens, and a vendor's refusal is answered with
its status and message before the client is upgraded. The client's
subprotocols go on less openai-insecure-api-key.*,
openai-organization.* and openai-project.*, and OpenAI-Beta too.
The upgrade passes the whole handler, so the allow list, lanGuard's key
and rebound, and corsGuard judge it as any request; past them an
Origin must be the address the upgrade was sent to (sameOriginSocket,
as coder/websocket's own Accept checks), since a browser's WebSocket
isn't held by CORS (TestRealtimeGuards: a foreign page, null, a
localhost subdomain and a rebound name are refused before any vendor is
dialled). A session opened with a gateway key is closed once the key is no
longer on (realtimeKeyCheck). Frames go both ways as they came; a
client's text frame is masked as the settings say (failing closed: the
session ends with a policy-violation close), the vendor's get the values
back, and audio frames (input_audio_buffer.append, *audio.delta) are
neither (TestRealtimeMasked). Each response.done with usage is a row
in the usage ledger, operation realtime, its cached input as
CacheRead; the session is one call on the Routing page with the sum.
Either side's close is given to the other with its code and reason. When
the gateway ends, every session is closed going away (realtimeSessions),
since its connection was taken from the server.
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 withstore: falsekeeps nothing. Codex over HTTP sendsstore: falsewith 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_idtaken 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/v3pay-as-you-go Responses) and it answered the previous turn on the same key (prevRoute), withstorenot 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 itsencrypted_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. A conversation the client replayed whole itself (Codex's store-off history, noprevious_response_id) goes the same way: the ids it echoes, of the kinds that may go without one and reasonings with theirencrypted_content, are taken out on that one more ask, the turns and the calls' pairing kept; an input that is one id'd item of the client's own is not a replay, and goes as it came. Only a request whose conversation magpie holds, or one that brought a whole replayed conversation, is asked again, and only with a body that differs: an id magpie doesn't hold, or a refusal with nothing 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 inpassOnCaller. - The other magpie honours the header only from a request shaped as a
magpie's hop (
keepTurnAsks): the value startsmagpie/, 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 inprevResponseswhateverstoresays, under the caller'sprevScopeand the same caps, and answersX-Magpie-Kept-Turn: 1. An id such a request names that it doesn't hold getsprevious_response_not_foundbefore anything is sent, never relayed to a vendor that might ignore it (keptTurnLostinserveAgent). - The header comes off every request as it arrives (
withCaller), andX-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, asstore: truewould 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 forprevTTL. - 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.
Bodies to another magpie, against the one before
Every request an agent makes is its whole conversation, and the hop to a
remote magpie (a cloud or Docker deploy, a shared gateway) carried it
uncompressed each turn (gaubeebangeel on X, after jixoai/reply9842).
remote_dict.go sends it as RFC
9842's Dictionary-Compressed Zstandard turned round for a request, on
every protocol, in forwardOnce (sendDict, dictSend.after) and, on
the other magpie, keptBodyRequests, between withCaller and
keyLimited.
- A request of 16 KB or more to a remote magpie offers its body
(
X-Magpie-Keep-Body: dcz). A magpie keeps it only from a magpie's request (magpieAsks), under the caller's key id and connection address (dictScope: a LAN key is every LAN computer's), and answersX-Magpie-Kept-Body: :<sha-256>:. This side then keeps the body it sent per route (prevRoute). - The next request to a route whose magpie said it keeps bodies goes as
Content-Encoding: dczagainst the kept body sharing the most content anchors with it (anchorsOf: content-defined, so moved content still counts), withAvailable-Dictionarynaming it andX-Magpie-Body-Digestthe SHA-256 of the body itself; with no kept body to share, as plainzstd. The "dcz" body is RFC 9842's: the magic, the dictionary's SHA-256, a zstd frame with its checksum and a window of at least 8 MB or 1.25 times the dictionary. - A dictionary the other magpie doesn't hold in that scope (restart,
evicted, another key or computer), a header that names another, a body
that doesn't decode or whose digest differs: 400 with
X-Magpie-Dictionary-Missbefore the body reaches the key limit or a route, and this side sends it again whole and drops the route's kept bodies. A 415 (a magpie gone back to a version from before) does the same, and the route goes uncompressed until it says it keeps bodies again. A magpie from before this never answers the header, so it is sent every body as before. - Bounds: bodies up to 48 MB are kept, each for 30 minutes. The other
magpie keeps 8 per scope, 96 MB per scope and 256 MB in all, the least
lately used going first; this side 8 per route and 128 MB in all. The
headers come off every request as it arrives, so no vendor is sent
them, and the reply's
X-Magpie-Kept-Bodycomes off before it is relayed. - Measured (
TestDictSavingOnALongConversation): two interleaved agent conversations, 80 requests growing to 1.1 MB with a 300 KB screenshot, 44.6 MB as they were, 26.4 MB as zstd, 0.64 MB as dcz; the last request 1,368 bytes. - Not covered: the kept bodies are in memory only on both sides, so the first request after either restarts goes as zstd or whole. Responses on a socket and replies are not compressed.
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(andcountTokens) puts what it masked by on the request's context (withMaskedAs,ownMaskedAs: this build's version andmasking.Fingerprint, a hash of every setting that changes what is masked, the local model and its threshold among them, never the words themselves), andpassOnCallersends it asX-Magpie-Masked-As. The other magpie skips its own pass when the settings fingerprint is its own and the sender's build is no older thanmaskerSince(sameMasking), whichever of the two builds is newer; raisemaskerSincewith a change that makes the masker find more. It passes the header on to a further magpie as it came (maskedBefore). Other settings, a build older thanmaskerSince, 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 asansweredThereHeaderbykeepRetry).passingdoesn'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,TestRemoteMagpieMasksWhatItIsNotToldWasMaskedandTestRemoteMagpieRoutedFailureNotAskedAgaininremote_magpie_once_test.go,TestFingerprintinfingerprint_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
systemgets it after a blank line; a block array gets one more text block; none getssystem. - 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,
instructionsuntouched; a stringinputbecomes that message and the user's. A request that namesprevious_response_idgets none, since the turn it follows had it. - Gemini:
systemInstruction(orsystem_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 'TestBare(ModelIDs|IDsList)'
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.