Routes now carry Folder: the last two levels of the working directory the agent states (Claude Code's "Primary working directory", Codex's <cwd>, Pi, OpenCode), cut by shortFolder before the route is stored, so no full path reaches the routing history, /api, or the GUI. It is kept in the routing history for as long as the history itself (30 days / 200 MB). A request that states no folder (title, side calls) takes the folder its session (or parent session) last stated; the per-session map is capped at 512 entries. GUI: By session headings read "Agent · folder · title", their tooltip and every request row's tooltip (page and tray panel) name the folder, the stage's agent subtitle lists the last level of each folder when an agent works in more than one, and the panel's agent node tooltip lists them. Run: - TestShortFolder (unix, trailing slash, C:\, D:\, UNC, CJK with spaces) and TestRouteKeepsItsFolderShort (real Handler, fake upstream: session inheritance, a moved Windows path, nothing of the full path in the marshalled routes, saveRoute -> History round trip), TestTurnDone. Broke it by hand: without the session lookup the title request has no folder; with the folder unshortened the full path shows. Both go red. - routing-session-folder.test.cjs: chromium + webkit x en, zh, zh-TW, ja, de x 1100 and 420 px, 20/20. Red on the old routing.js and with the stage's live routes left out. - GUI suites routing-*, panel-routing*, purpose-filter, reasoning-speed, gui-de/ja/zh-tw, click-scroll, number-units: 951/951. - gofmt -l clean; go vet darwin, linux (nogui), windows; builds for all three. go test -tags nogui ./...: all ok except internal/gateway, which hit go test's default 10m timeout at 611s on a loaded machine (#2108); alone with -timeout 30m it passes in 356s. - Real use: nogui build in a sandbox HOME, fake upstream, real Claude Code 2.1.299 (claude -p) run from .../workspace/magpie and .../src/dial: the day's routing jsonl has folder "workspace/magpie" and "src/dial" and no part of the sandbox path above them. Not tried: title/side requests' inheritance end to end with a real agent (claude -p made none), Codex, OpenCode and Pi with real binaries, Windows.
155 KiB
Gateway routing and fallback
The gateway is magpie's local LLM endpoint (127.0.0.1:3425 by default). It
serves Chat Completions, Responses, Anthropic Messages and Gemini. It finds
the provider, key or account and model for each request. When the upstream
doesn't speak the agent's API, the gateway translates. When an upstream
fails before any of the reply is sent, the gateway moves to the next
candidate.
This page covers how a request is routed. Plugins that change requests and replies are in Gateway middleware. Subscriptions served by a plugin are in Provider and plugin ownership.
Responsibilities and sources of truth
| Part | Responsibility | Source |
|---|---|---|
| Address and caller | DefaultAddr. The local token magpie and the per-agent magpie-<agent> (TokenFor). agentOf tells which agent asked, first by token, then by User-Agent. |
gateway.go |
| 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 |
| HTTP surface | Handler routes /v1/chat/completions, /v1/responses, /v1/messages (each also without /v1), /v1/models, Gemini's /v1beta/models/…, the Codex backend path, /v1/codex/models (Codex's catalog shape for a Codex elsewhere with a gateway key, codexCatalog, kept to the key's models by keyAllowed; #1281), /mcp/{name}, /mcp/magpie/web-search and /mcp/magpie/vision (magpie's own web search and image recognition as MCP servers, below) and the /v1/magpie/* status endpoints. /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, 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 GET on /v1/responses (a client opening Responses over a WebSocket) is answered 426, a plain one 405: Responses is relayed over HTTP only. Every route is wrapped in counted, corsGuard, callerGuard, withCaller and keyLimited; /v1/messages, /messages and /v1/messages/count_tokens in keepsSignIn too. corsGuard (#1051) serves CORS only to the origins listed in Settings › Network › Web pages (settings.CORSOrigins, cleaned to scheme://host[:port] by settings.CleanOrigins, which refuses a wildcard). 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. It takes the key from the caller lanGuard recorded too, since on the running server lanGuard has already put magpie's own token in the key's place. Any other web page is refused 403 on every route (foreignPage): on loopback a call needs no key and the body's Content-Type isn't checked, so a page the user visits could otherwise send a "simple" text/plain POST and spend their subscriptions blind. Only an http/https Origin is judged, and one on this computer (localhost, *.localhost, 127.0.0.0/8, [::1], any port) or the request's own origin (its host and port equal to Host, such as a page on the gateway's LAN address) passes, as does usemagpie.ai on /v1/magpie/omarchy. null and other schemes (app://, file://, tauri://, vscode-webview://, chrome-extension://) come from desktop apps, webviews and extensions that don't enforce CORS, and pass. A request with no Origin (every agent's) passes through with no CORS headers, as before. A page whose own name resolves to 127.0.0.1 (DNS rebinding) would count as same-origin here, so lanGuard refuses it first (rebound, 403): a loopback request carrying a browser's marks (Origin, Sec-Fetch-Site/Sec-Fetch-Mode, a Mozilla/ user agent) whose Host isn't this computer's (an IP, localhost, *.localhost, a container runtime's name for the host such as host.docker.internal, MAGPIE_PUBLIC_URL's or MAGPIE_ADDR's host, the machine's own name) needs an enabled gateway key. Agents send none of those marks and pass under any name. Before any of that, lanGuard lets in one request without a key from anywhere: POST /_magpie/claude-mcp/<token> with the token of a Claude subscription run now live (ownCallback, see the Claude subscription bridge), the run's MCP helper calling back to a MAGPIE_ADDR that isn't loopback (#1546). 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; 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). 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, internal/settings/origins.go |
| Model resolution | serve resolves the model the agent asked for: Claude tier stand-ins, a routing group (provider.GroupFor: its id, the model's id however a vendor spells it, else the one group whose name it is, unless a provider serves a model by that id), auto stand-ins, the agent's own stand-in (StandIn: Codex's config.toml model when magpie is its provider, for a name it sends that magpie doesn't serve, such as its auto-review's codex-auto-review), itself taken through GroupFor and auto stand-ins so a config naming a group bare reaches it, then provider.Resolve. A Codex memory call or auto-review (x-openai-subagent: guardian, or codex-auto-review) that still names no served model goes to the model Codex's last turn was answered on (codexMemoryStandIn, per agent and gateway key), so a Codex on magpie through another provider table, a profile or another computer isn't answered 404 (Adam on Discord, TestCodexAutoReviewReachesItsTurnsModel). A bare model id several providers serve (MOMO on Discord: glm-5.3 under opencode-go and a6api) is never refused: with found groups on (the default) GroupFor takes it to the group magpie found for it (auto-<slug>), its members in the Providers order, routed and failed over as any group, a conversation staying with the member that answered it while its cache is worth it (affinity); with them off, Resolve takes the first provider in the Providers order that exposes it, with no fallback. magpie writes only provider/model ids into agents' configs (magpieModels), so a bare id is one the user wrote. /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 |
| Candidates | plan lists one provider's candidates: one per key or account on, then each Fallback model, with resting ones last (restLast). planGroup and planLevel weigh a group's members together. A nested group plans by its own routing (#576). So does a member whose provider routes other than Smart (ownRouting): weighed as one by its first not resting (firstAwake), tried whole in its own order; leastHeld leaves such a group's order alone too. A provider on Smart, or routed as the group is, is pooled with the group's other keys and accounts. group_own_routing_test.go. A member's own fallbacks are not the group's. |
fallback.go |
| Order of keys and accounts | Routing: smart (""), order, rotate, usage (least used, with an usageHalfLife of 1h), pace or weight (weightedFirst). Smart, usage and pace weigh a subscription by its allowance (allowances), and a key by its own usage windows when magpie reads them (keyAllowance: a sub2api key given a 5-hour, day or 7-day limit, or a key bought as a plan, such as Kimi Code's or a GLM Coding Plan's); any other key has none. A 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 (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, and a kept conversation moves the round's charge to the member that kept it (wrrSeat, wrrMove). A lone key or account is weighed against nobody, but what it has left is still read into the trace (weighRouted), so the Routing page shows it as it does for several (#1016); all but used up, it keeps its conversation rather than being said to move (affine). A failure rests a candidate (failure, failureOf). A lone key or account is weighed against nobody, but what it has left is still read into the trace (weighRouted), so the Routing page shows it as it does for several (#1016); all but used up, it keeps its conversation rather than being said to move (affine). A failure rests a candidate (failure, failureOf). |
routing.go, weighted.go, internal/provider/routing.go |
| Limits | Each key or account (a candidate's who()) has at most MaxConcurrency requests out at once (its own AccountConcurrency over it); one more waits in its lane's queue, bounded by QueueLimit and QueueWait and turned away with a 429 past either (lanes.take). MaxRPM (coeo91 on Discord: OpenRouter's free models take 20 a minute) bounds how many requests it sends the vendor in any rolling 60 seconds (rpms), counting each for a second more (rpmSlack), since the vendor counts a request when it arrives and the first on a new connection arrives later by its dial: one more waits for room in the minute, in the order they came, after it has its slot and right before it is sent. A wait that would be longer than 2 minutes (or the provider's QueueWait, when shorter: rpmWait) is turned away at once with a 429 whose Retry-After is when the minute has room; nothing rests for it. An agent gone while it waits gives its place back. Every request that reaches the vendor counts: each try of the candidate loop (a retry, the next key, a fallback) waits in serve, and the requests a try makes on the way and the gateway's own asks (count_tokens, System One's decisions, embeddings, drawing, Kimi's search) are counted by rpmTransport on s.client (metered, paidFor). count_tokens never waits: a candidate with no room is skipped, and the local estimate answers. A full lane or a minute with no room gives way to a ready key or account of the provider or the group (laneMate, ready); a fallback is never asked for want of either. A plugin's account sends through its own transport, so only its tries are counted, not a plugin's own extra requests. Set in the provider editor (Concurrency, Requests per minute, Queue size, Queue wait) or with magpie provider account-concurrency, queue and rpm; a subscription's are kept with its picks, 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 |
| Sink | With Sink on, a key or account that answers 429 while it still has quota goes to the back, behind every one not rate limited since. Held in memory until restart. |
sink.go |
| 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. 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). Pause rules and a gateway key's group hold apply as for a chat. Nothing rests for a failed drawing. TestImageGroupMovesOnToTheNextMember, TestVideoGroupMovesOnToTheNextMember. |
draw.go, video.go, catalog.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. |
affinity.go |
| One try | attempt sends one candidate the request. It goes through the proxy of the account or key it uses, else the provider's (p.Via, ProxyChoice: AccountProxies holds an account's by its name, a key's by its KeyID). A request magpie makes for one provider while serving another's (a web search, an image description, a classifier call) takes its own provider's proxy or the global one, never the outer one: netproxy.With replaces a choice the context already names, "" too, and webSearch starts from none, so the search APIs follow the global proxy (#1522). A subscription with its own client is served specially, such as Claude through the genuine Claude Code. The request is relayed as is (passthrough) when the model is usable on the agent's API, except that a Claude model where the provider has an Anthropic URL is translated to Messages from Chat or Responses too (OnMessages: OpenCode speaks Chat for every model, and a relay drops cache_control there), unless the user set the model's API or the vendor's list names its APIs. A request offering web search to a provider that doesn't search by itself is translated too, so magpie can search for it (search.go; a provider that searches for some of its models only, Command Code's Provider API, lists them in searchModels by API, and none count under its x-cmd-zdr header, #1590), but on the agent's own API where the provider serves it and no ResponsesFirst/MessagesFirst rule prefers another: Codex offers web_search on every turn, and each went out as Chat (#997). Otherwise it is translated (translate) to the first API usable gives: Chat, except Responses for OpenAI's models where their maker serves them (ResponsesFirst), Responses for every model at ModelScope, whose Chat API reports neither the tokens its cache answered nor reasoning while its Responses API reports both (ResponsesTellsCache, #1578; a 404 there sends the model to Chat, and only there), and Anthropic's Messages for a Claude model where the provider has an Anthropic URL (MessagesFirst, which keeps its cache breakpoints, #997). An API that answers the model is not served there (wrongEndpoint) is remembered in unfit until magpie restarts. When every API has turned the model away, the API the user picked for it (ModelAPI) is asked again, and without a pick each API the provider has a URL for (Speaks), Chat first. Provider.Native, the API agents with a per-model API (Pi, omp, droid) are wired to ask on, follows the same order. A custom provider with a Gemini URL (#1346) has Gemini last among the APIs it speaks: a Gemini client's request is relayed there, and any other is translated to it when it has no other, or when the user set Gemini as the model's API (SetModelAPI takes chat, responses, anthropic or gemini, each only where the provider has its URL; a model set to Gemini has no Native, so those agents ask it on their own API and it is translated). Upstream it is always asked models/{model}:streamGenerateContent?alt=sse under the base (upstreamPath), the model only in the path (forwardOnce drops the body's), so a Gemini client that asked for one JSON body is translated, as for Factory's generate route. |
gateway.go |
| Trace | The Routing view's record of each decision, written where the decision is made: candidates, rests, which try answered. Route.Folder is the folder the agent says it works in (workDir), its last two levels only (shortFolder, e.g. workspace/magpie), never the full path; a request that says none (a title, a topic check) takes its session's as said last (trace.sessionFolder), one without a session id has none (#1068). It is kept in the routing history on disk for as long as the route is (history.go: 30 days, 200 MB). The GUI shows it in By session's headings, a request row's tooltip, the stage's agent working in more than one folder, and the tray panel's agent tooltip. |
trace.go |
| Prompt | What each request's prompt held, part by part: the agent's system prompt, tool definitions (an MCP server's tools as one item), instruction files and skills, files its tools read, their other output, and the conversation. inspectPrompt reads it from the body as the agent sent it, before translation; calibrated scales the estimate to the prompt the vendor counted and sets the window of the model that answered. The route keeps names and sizes only, never the text, so the routing history on disk holds none. For the card's text (masaka on Discord), the trace keeps the last promptBodies (10) request bodies in memory only (at most 32 MiB each, 64 MiB together), masked as the vendor got them; for a model let have it unmasked, the masked copy is kept all the same. PromptText reads a part's items and their text from that body again (prompt_text.go), served to the GUI as /api/context/text; once a body is dropped, or magpie quits, its text is gone. It goes on the trace as Route.Prompt, with Route.Conv naming a conversation that has no session id. The GUI's /api/context scores each agent from it (internal/gui/context.go). |
prompt.go |
| Vertex AI | A Google Vertex AI provider speaks Gemini alone. A request goes to <base>/publishers/google/models/<model>:streamGenerateContent?alt=sse (provider.VertexPath, upstreamPath), the model named as the user's upstream name for it says (UpstreamNameIn, which the usage log's endpoint names too), with no model or stream field in its body (passthrough, forwardOnce, geminiRequest). A Gemini client's request is relayed as it came, its own thinkingConfig, safetySettings and the rest kept: streamed there, asked whole to :generateContent (provider.VertexWholePath), which answers one JSON body (Factory's rule of translating a whole request, as its route only streams, isn't Vertex AI's). Every other API's is translated (buildFor, buildVertex) and its stream read by codeAssistDecoder, which gives thought parts as reasoning, never as the answer's text. Effort: vertexEffort fits it to the model's levels, reasoning turned off going as minimal fitted the same way, and holds a model whose levels aren't known to low…high. vertexThinking sends Gemini 3 a thinkingLevel (includeThoughts false with reasoning off) and 2.5 a thinkingBudget in the model's range (vertexBudgets): turned off, the budget that stops its thinking, or Pro's least, as Pro can't stop. Thought signatures are every Gemini path's (#1445): a call's signature reaches the client in its id (signedID) and goes back on the call it came on, while a call with none in a step Vertex AI signed goes without; a step with nothing to give back has every call sent skip_thought_signature_validator. A 400 Invalid thought signature. is asked again with every call sent so (withoutSignatures), for that request only. A 400 refusing minimal (geminiRefusedLevel) is asked again at the model's lowest other level (onEffort), and markUnfit(offRefused) keeps that level until magpie restarts. Both retries are the translated path's. Vertex AI's own Google Search grounding isn't used: searchHosts names only generativelanguage.googleapis.com for Gemini, so magpie searches for it (search.go). |
vertex.go, gateway.go, codeassist.go, gemini.go, gemini_signature.go, search.go |
Codex titles, descriptions 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. Title Off mode does not disable descriptions.
codexTitlesTo, codexDescriptionsTo, codexTitle and codexDescription in
codex_titles.go own this selection
and response wrapping. Both the Responses API and Codex backend entrypoints
use it. Usage and Routing retain the original purpose; unusable description
answers are recorded as description failures. These helpers do not decrypt
foreign sealed history or repair ChatGPT's response protection.
Codex's composer predictions (#1970), its guess at the user's next message,
are another hidden turn on a fork of the thread, sent only through the
ChatGPT sign-in, with thread_source composer_predictions. Each one reads
the whole conversation again. CodexPredictions selects where they go: empty
sends them as Codex asked, off answers {"suggestion":null} from magpie
and sends nothing (sentNowhere, as title Off mode), and a model id sends
them to that model. codexPredictionsTo and codexPrediction own this, at
the same two entrypoints. A model's answer reaches Codex only as the
{"suggestion": string|null} object it asked for (predictionJSON): plain
text is never taken as a suggestion, as Codex would put it in the user's
composer as their next message, so it gives no prediction and the call is
recorded as a prediction failure (noPrediction).
Runtime path
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, as Codex's own client sends it (provider.CodexCompressed; openai/codexresponses_request_compression). 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). 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).keyLimitedreads a limited key's compressed body the same way, so its reservation is the decoded size.serveAgentruns the middleware chain, thenserve.serveredacts secrets in the request (redacted;redact.MaskJSONleaves ids alone; the request's tool definitions and output schemas, found by their place in each protocol (top-leveltools,tool_choice,response_format,text,generationConfigand 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), 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): 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). A request whose provider and fallbacks, or whose group's models, all skip redaction (unredactedRoute,provider.SkipsRedaction: set Send requests unmasked,Unredacted, with every address on this machine or the local network) goes to them as the agent wrote it; the log and recent calls keep the masked body. count_tokens and embeddings follow the same rule.- With Mask personal data on, each kind in
redact.Categories(internal/redact/more.go) is masked unless the user turned it off (redactKindsin settings,Options.Kinds). On by default: US SSNs, passport numbers, IBANs that pass mod 97, birthdays next to a word that says so, MAC addresses, and serial numbers next to S/N or the like. Off by default: the user name in a home folder, user@host in a prompt or ssh command, public IPv4 and IPv6 addresses (never private, loopback, link-local, CGNAT or documentation ranges) and cloud bucket names, since agents send them in nearly every request and the model must copy the placeholder exactly inside a path or URL. Context rules run only near their words (rule.matches). The Settings rows come fromREDACT_KINDSin app.js, whichTestRedactKindsAreRedactsholds to the same ids and defaults. - With Mask secrets on, the user's own masking rules (
redactRules,redact.Rule: a placeholder name and a prefix or an RE2 pattern,internal/redact/rules.go) run before magpie's. Settings → Privacy adds them, removes them, and edits one in place (POST /api/settings/redact-rulewith the rule's index and its current value,editRedactRuleininternal/gui/api.go). Every rule is checked byredact.CheckRuleswhen settings are saved; an edit that doesn't compile, matches the empty string, repeats another rule or names a rule no longer at that index is refused with the rules left as they were. The gateway reads the rules from settings on each request (redactionOptions), so a change applies to the next request. DecidesModelgives a 400.- A gateway key held to some models (
keyHolds, #882) gets a 403 for any other model. - 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 (a day since, a restart past the 512 conversationsaffinity.jsonkeeps, or the lead's last reply broken off,unanswered), the usage log's answers to the lead's thread and the request's own conversation in the last 30 days count too (loggedAnswers, #1367), andleadFirstreads the lead's key or account from them. A refused or failed call and a title answer nothing, and Codex's own sign-in is told of as the ChatGPT backend. The refusal names who sealed the task when it is known, and says how to go on with it. 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. A request carrying a task the ChatGPT backend sealed (sealedTaskIn: a sealed agent message that isn't aMESSAGE, whichwithoutSealedMessagesleaves out) is put only on a ChatGPT account's model; set to another, the subagent stays on the model asked for, which the sealed gate below handles as with nothing set. When magpie doesn't serve the model set now, or a gateway key held to some models may not use it, the subagent goes on the model asked for too. The route trace keeps both models and the reason it stayed (Route.Subagent), and the Routing page'skindWhysays it. The lead's turns, titles and every other kind are never moved. - Rules and image inputs are handled here too.
- A rule 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), 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 …>. 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.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 member it names, then those the matching rules after it name (ruleOrder), each not resting, then the group's others to fail over to. 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. - 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. - 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 (classifierSubinrouting.js).TestIntentRoutesATurn,TestJevPicksTheIntent,TestSummaryCountsMagpiesOwnCallsApart,TestByMagpie,TestServedRefSaysASubscription,own-requests.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>in the system prompt, and OpenCode'sWorking directory:inside its<env>block. Only the system prompt and the user's and system messages' text count, never the model's words or a tool's result, and the last said wins. An agent that says none has no folder, and nofolders=rule matches it (unknown, never empty). The same reading tells a plugin's fetch where its agent works (provider-plugins). A pause rule may hold by folder too (below). The trace'sRuleHit.Folderis the folder read, and the Routing page tells it beside the rule'sfolder …condition.TestFolderUnder,TestRuleMatchesByFolder,TestParseRuleFolders,TestWorkDirOfEachAgent,TestRuleByFolder,TestRuleMatchesExceptFolders,routing-folder.test.cjs. Rules by folder are never in a shared group (ShareGroupdrops everyByFolderrule). - A pause rule (
Rule.Pause,pause=<model>; John on Discord: a model of the group paused in its vendor's peak hours) leaves the model it names out of the group while it holds (provider.PausedOut, onruleClock): the group's own rules and each nested group's on the way down to a member, a group named taking all its models, and a model named taking it wherever a group in the group has it (#625). It runs before planning, on every request rather than once a turn, so the model is not first, not a failover, and not kept by affinity, and comes back as soon as the hours end. It holds by hours, days, agents and folders only (cleanRulesrefuses another condition), and is not a send-to rule:Matches,MatchRule,ThenUses,Ruledand the compaction rules leave it out. A send-to rule naming a paused model finds it unready and the group routes as without it. The trace keeps what was paused (GroupRef.Paused), and the Routing page says so. Every model paused answers 503 (pausedError) naming each rule. Embeddings go by the same pauses; manual groups have no rules (Live), so none pause there. A pause by folder (#1606, Ti800: a subscription's quota kept for the long task in one folder,pause=<model> except-folders=~/big-task) reads the folder only when such a pause is on the way (provider.PausesByFolder, thenworkDir): outside its except-folders, which includes a request that says no folder (a subagent's or a small model's that doesn't), the model is left out; withfolders=, only requests known to be in them. Embeddings and System One's decision calls have no folder.Paused.Folder/ByFoldercarry what was read, and the Routing page says the folder or that none was said.rules_pause_test.go,TestPauseByFolder,TestPauseByFolderRule,TestParsePauseByFolder,routing-pause-folder.test.cjs.
- With Mask personal data on, each kind in
- Candidates come from
planGroupfor a group orplanfor a provider. They are filtered bysealedReadersandallowedCandidates. An account past its share is held out of the candidates (capHeld): a usage cap's share, each window at its own where the account gives it one (AccountWindowCaps, willz on Discord: 50% of the five hours, 40% of the week) and at the account's cap otherwise, or 100% of a window for a Codex account set not to spend its credits (provider.HoldCaps,WindowCaps.Of,CodexNoCredits). A ChatGPT account's call oncodex-auto-review, which OpenAI counts in no window, is held by no usage cap, only by credits it may not spend (freeOnChatGPT, #1593,TestAccountCapLetsAutoReviewThrough). The account is held while any window is past its own share, andcappedErrorand the trace name the fullest such window's share and cap. When every candidate is held and one held for its credits spends its resets by itself,autoResetspends a reset on it and it is tried (planned.held); otherwise a capped or barred set returnscappedErrororbarredError. Thenaffinemoves the conversation's last answerer first, unless it is resting or nearly used up. AnX-Magpie-Accountheader (AccountHeader) pins the request to one account: only that account is tried, and when it can't answer the caller is told why. - The candidate loop calls
attempton each candidate in turn, through aholdWriter. The writer holds the reply until it is clearly passing. A candidate that fails before anything is sent rests (failure): out of credit for 30 minutes, out of quota until reset, rate limited until retry-after, otherwise a minute and longer on repeats: 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). A 400, 403, 404 or 422 that says the model isn't served (unservedWords) and says nothing of quota, credit or a rate limit rests only that key's or account's model (modelRefused, keyed byrestID, its backoff counted apart): its other models are still served first in order (#1235, SenseNova's 403 "model is not available in the current token plan"). A 400, 404, 410 or 422 that says the model is retired (retiredWords: OpenCode Zen's 410ModelDeprecated"Model exo-free has been deprecated.", whose own model list still names it; MOMO on Discord) rests only that model the same way, is retryable so a group's next member or another provider of it is asked, and is remembered (provider.Retire,retired.jsonbesideproviders.json): the model leaves that provider's entries in the catalog (buildEntries), so /v1/models, every agent's model list and the found groups go without it, until a request on it is answered again (UnretireinservedCandidate) or a week has passed. A refresh of the vendor's list doesn't bring it back early, since that list is where it still is. Aprovider/modelrequest for it is still sent. A 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) 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 subscription account that fails any other way with a window full, by magpie's latest reading of its windows, rests until that window renews. Both quota rests and window rests are held tolongestQuota(8 days), so a reset time read wrong (a year off) doesn't bench the account for that long. The next candidate is then tried. A failed provider waitsfallbackCooldown(1 minute) at the back. 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. 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 only: the backoff count stays, and a refusal after it rests the key again the usual way. 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). 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). 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. siwc, API-key requests to openai.com and the legacy/responses/compactare left as they were. - The last candidate's error reaches the agent, with one exception for a group (#1418,
patience.go). When every member has failed in a way that passes (busy: 408, 500, 502, 503, 504 or 529 that isn't a proxy, a quota or response protection, or a 429 that is a short rate limit, not a plan or credit), and nothing of the reply has been sent, the members that failed so are asked again in turn after a pause (replan). The pause isretryPausedoubled each round up toreplanLongest()(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.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 isPatienceDefault, 60s; -1,PatienceOff, turns it off; at mostPatienceLongest, 240s). A pause that would end past the budget isn't taken, and the agent gets the error. While another member is busy too, the last one isn't first tried again alone (passing): the members take turns, and once the budget has begun, the same-one retries aren't taken either. While the budget lasts, the last candidate's failure is held (newHoldWriter), and a streaming agent is kept alive through the pause with SSE comments (pauseAlive). The try is traced withAgain(the pause),Replan(how many are asked again) andPatience(the budget in seconds). The group editor's "Every member busy" row sets it. A plain provider keeps only the same-one retriespassinggives the last one left. 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 try that answered is recorded (served,answered) for routing, affinity and usage.
Constraints and failure behavior
- A fallback happens only while none of the reply has been sent. An agent never gets half a reply from one upstream and the rest from another.
- A request is one usage record, counted once by how it ended (小一 on Discord: Codex on credits showed "5,482 · 1,094 failed" while rows said "2 tries/3 tries" and had been answered). The final record carries
trieswhen the route took more than one (rec.Tries, from the trace'sTries). A try a vendor refused or turned away (hw.refused,hw.turnedAway) still writes its own record, for what it billed and why it failed, markedhanded_on;usage.Totals.countskips such a record for calls and failures. A request failed only when the agent got an error (LostRequest); one answered after a failed try is counted beside it as answered on a retry (Totals.Retried,RetriedRequest, theretriedfilter). Logs written beforehanded_onare read the same way: the log index marks a failed, non-rejected record followed by another of the same route id as handed on (routeRowsinlog_index.go). Counts by account or route (vias, window holds) still count every try. - 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. The route's tries carrytierandtier_servedthe same way. A bridge that doesn't go throughforwardOnce(the Claude subscription, Cursor's built-in) leavestier_sentempty. Code:tier_record.go. - 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), 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. - A request whose key is a Claude sign-in (
claudeSignIn:Authorization: Bearer sk-ant-oat…, Claude Code signed in to claude.ai with magpie as its base URL) is never told a 401, nor a 403 saying "OAuth token has been revoked". magpie never passes that sign-in on, so such an answer is a provider refusing magpie's credential, or one of magpie's own Claude accounts lapsing; told it, Claude Code renews its own sign-in before each of its retries (ten for one request) and then asks to/login. Any error whose message mentions x-api-key, whatever its status, Claude Code tells as "Not logged in · Please run /login" too. It is told as a 502 in magpie's words, anapi_errorsaying " refused magpie's credential (HTTP 401): …" with x-api-key said as "API key", and any other error such a request is told keeps its status with x-api-key said as "API key", as does a stream's error after its 200 (keepsSignIn,claude_signin.go). Recent calls and the usage log keep the provider's status and message. Any other 403, and a request with magpie's key or an API key, is answered as before. The sign-in's beta (oauth-…inanthropic-beta) isn't passed on either (askedBetas), so a provider gets the request as Claude Code with magpie's key sends it; a provider's ownheader.anthropic-betastill goes. - A 2xx that can't be an API's answer is the 502 it stands for (
notAnAPIReply, #1012): a web page (text/html, or a body that begins as one: a sign-in page, Cloudflare's challenge), a body with nothing in it, or one sent as JSON that doesn't begin as JSON. Every upstream request goes through it (forwardOnce, and the built-in clients' own: the ChatGPT backend's/responses, Kiro, Zed, Qoder, Devin, Cursor, Command Code), so it fails over, rests and is logged as a 502 does, its reason naming the page's title. Only the first bytes are peeked, which a stream waits for anyway, and a compressed body is left as it came. - A streamed request is never left silent while its vendor says nothing.
holdWriter.watchruns beside each try: pastkeepHeldAfter(15s) it sends a held try's agent the stream's 200 and SSE comments (keepAlive), none of the try, so another candidate may still answer in the same stream; once the reply passes, it puts a comment between two of its lines afterkeepaliveEveryof quiet. It stops afterkeepaliveLongest(5 minutes) with nothing from the vendor. A try waiting for its key's or account's slot or for room in its minute (lanes.take,rpms.wait) is kept alive the same way (keepQueued), for as long as it waits; once the 200 is out, the try is held, and its failure or its queue turning it away reaches the agent as the stream's error (failTo), not a status (coeo91 on Discord). A wait shorter thankeepHeldAftersends nothing, so its 429 keeps itsRetry-After. A proxy in front such as Cloudflare (125s) otherwise ends the request (#947). Gemini streams get no comments (#934). A vendor that then ignoresstream:trueand answers 200 with its reply whole has it sent as the agent's stream (wholeAsStream: Chat, Responses, Anthropic), not as the stream's error, while a 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 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) — 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. 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 reply passed through in its own protocol isn't read this way. - Claude's, GPT's and Gemini's reasoning is held (
refusesAfterThinking, up toholdThinking, 4 minutes) so that a refusal after it goes to the next candidate unseen (#248). It is held only while one could: on the last candidate a refusal isn't asked again, so Claude's and GPT's reasoning streams as it comes there, and a refusal after it reaches the agent as the vendor's own. Held there, a lone relay's Claude or GPT showed Claude Code its thinking all at once with the text, and Codex none until then (iTianbao on X). Gemini's stays held on the last candidate too, for a reply that only reasoned to be asked again (#667). Any other model's reasoning is never held. - A streamed reply stuck in a loop is ended, not let run to its output limit (#1359, Moody-Sin: WorkBuddy's DeepSeek v4.1 flash reasoned round "Now." "Writing." "Go." "Let me write." "OK." until max tokens while dsh and Pi waited).
holdWriter.Writefeeds every streamed try, passed through or translated, a key's, a built-in subscription's or a plugin's (a moved WorkBuddy's fetch in the plugin host,TestLoopEndsWorkBuddysReply), in each of the agent's protocols, to aloopGuard(loop_guard.go). It cuts the reasoning and the text, each apart, into units, its lines and sentences (a list's1.or a decimal is no sentence's end), compared without case or a closing stop. A unit with no word in it (a letter run with no digit: not a brace, a rule,0x00, a hash or a row of numbers) isn't counted. When the lastloopWindow(256) counted units of either are among no more thanloopDistinct(24) different ones, the try is cut (cutLoop): what came with that write goes out, then the protocol's stream error (streamError, 502) naming the loop and quoting its units, and the vendor's request is cancelled. It falls back to nobody and rests nobody (failLoop); its usage record's error type isreply_loop(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 loop in the text, or after a text or call, is ended at once (TestLoopAfterTextIsNotAskedAgain), and so is a Chat stream passed through as it comes, whose bytes aren't magpie's to splice. A cycle need not be exact. Code, tables, lists, logs, CSV and base64 differ line to line or have no words, and don't trip it (TestLoopGuardLeavesOrdinaryRepliesAlonefeeds magpie's own sources and docs through it). A reply sent whole (no stream, or Gemini withoutalt=sse) isn't read. Settings › Models › Replies › Stop looping replies (noLoopGuard) turns it off. - 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. 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. Smart compares renewals window by window, biggest first, each truncated to the hour (
weighRouted), so the order decides only when every window falls in the same hour. A window's renewal is its reset, or, when what it has left runs out sooner or it has no reset, that moment (Limit.RunsOut, fromQuotaWindow.RunsOutAt;Allowance.Renewal): the WorkBuddy plugin (0.1.14) sends it on its Credits window as the soonest end of a package with credits left (cdredfox on X). Only Smart reads it; Weekly pace, the 90%/98% tiers and rests go by the window's share and reset as before. 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 Smart 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 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). 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. The last key left rests too when it is refused so, as the keys before it do. 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 back (soonestBack). 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 listed inkeysas well as inkeyis one candidate (KeysOn), not asked twice.TestAllRestingAnswersFromRest,TestOwnQuotaRest,TestQuotaHeldOnlyForKeysOutOfAllowance,TestFirstKeyListedTwiceAskedOnce. - Routing decides who goes first only when nobody has answered the conversation yet. Affinity keeps the answerer while its cache is worth it. Auto mode keeps it across turns while at least
cacheWorth(1024) tokens were read from the cache and the cache isn't cold (cacheCold, 5 minutes). - 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. 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. - In turn (
rotate), a conversation nobody has answered yet goes to the key, account or model the fewest other conversations of the provider's model or the group answered in the lastheldFor(30 minutes) are on (leastHeld, #946). Ties, resting ones and a group with a group in it keep routing's order. With session affinity, two sessions of one group so stay on different models. - A ChatGPT account that holds credits answers past its windows on them; the vendor spends them. That is the default. Set not to spend them (Usage card's Use credits,
magpie quota credits <account> off), the account is held at 100% of a window till it renews, by magpie's latest reading of its windows (provider.Allowances, refreshed about every minute), so the other accounts, groups and fallbacks take the request. A cap set on the account (1–99%) takes precedence. Unlike a cap, the hold is at the vendor's own 100%, so an account allowed to spend its resets spends one there, both when every candidate is held and after the last one is refused. A reset made forgets the account's cached allowance (renewedNow), so neither hold outlives the windows it started again. - Different failures are classified separately: out of credit, out of quota, rate limit and other errors rest for different lengths. A fix must not merge them into one bucket (see #873).
- A 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 sub2api key out of its own limit answers 429
api key 7天限额已用完(or日限额,5小时限额) asrate_limit_exceeded. It is out of quota (plannedWords), not rate limited: it rests till the window it filled renews when its windows as last read say so, elsequotaRest, and its windows are read again (staleKeyAllowance). A reading that finds that window full no more (the limit raised in the relay's panel, or the key's usage reset) lifts the rest (renewed, told throughprovider.OnRenewed), as a Codex reset spent does an account's; the key's other rests stay. While it rests out of its windows, they are read again each time it is planned (restingOf, once a minute at most), so this holds where nothing weighs it by them: an ordered group. The relay out of accounts for everyone (503No available accounts, or a later version's 429All available accounts are currently rate-limited) says nothing of the key's windows: it backs off as any failure or rate limit does, never to the window. A key's windows count only its own spend, so other users draining the relay's accounts show up as those errors, not in the windows. - A 5xx is a server error, not quota, unless the vendor's own quota code says so (
quotaCodes:usage_limit_reached,RESOURCE_EXHAUSTED, Claude Code'susage limit reached|<unix>). A relay's 500 "当前模型 gpt-5.5 负载已经达到上限,请稍后重试" names its load, not the key's allowance: it was read as out of quota byusedUpWords(上限), which rested the key till a reset and kept a group's Patience from waiting it out (#1418). The quota words (usedUpWords) still apply to a 4xx. - 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) 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, 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 more thanlongestWritten(7 days) off isn't read. 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 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. 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. - An account resting out of its window (a Claude account by the time Claude Code's refusal named,
resets, or any bywindow) is back once magpie's reading of its windows (provider.Allowances) finds it full till sooner: the window used belowSpentShareOf, or its reset passed, with no other window over the same models still full. The reading tellsprovider.OnRenewedas the account'sUsageAgentand user, andrenewedlifts that account's rests out of quota or bywindow; its rests for a rate limit, its credit, a verification or a failure stay, as a key's do, and so does every rest of other accounts still out of their windows. Planning reads every account candidate's allowance, ordered groups included, so this needs no step of its own inrestingOf. - Only an account is held at a usage cap (
capHeld) or rested out of one model's pool (pooled); a key's windows order it and rest it, nothing more. - 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 (restModelinrouting.js, #1960,routing-model-rest.test.cjs). - 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) can't tell the model's pool from the account's, so it rests whole, andnarrowWhenReadwaits 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); 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 request built for a Messages upstream (
buildAnthropic: a Chat, Responses or Gemini client translated, and Zed's bridge) 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 relayed to a Messages upstream isn't mended.anthropic_tool_pairing_test.go. - A Responses request bound for anything but a ChatGPT sign-in has its tool exchanges mended in
attempt, before it is relayed or translated, plugins included (responses.go). An item inside a run of calls and results (after one of the run's results and before the last, or before any result when the model didn't write it) moves to the end of that run (joinToolRuns, #1752, Edward4226): Codex writes its<image_resize_notice>right after each result whose image it resized, so a batch of two calls had it between their results, and a strict upstream answered 400 (OpenCode Go/DeepSeek "No tool output found for tool call …", Volcengine's "must be followed by tool messages", #1822); a Chat translation answered the second call with a synthetic result. An item carrying acall_idnever moves, the model's own reasoning and text between its calls stay, and 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. - Codex's model list from the backend path (
codexModels) is the ChatGPT backend's for its sign-in and then magpie's (provider.CodexListed), its ETag and every reply'sX-Models-Etagtagged withprovider.CodexListTagso a change has Codex ask again. A Codex there only for account failover, not connected (CodexOwnOnly,agent.CodexOwnOnly; #1385), gets the backend's alone, tagged withprovider.CodexOwnListTag; neither tag contains the other, so connecting or disconnecting has Codex fetch the list again. The user's picks on the codex provider (provider.CodexNativePicked) narrow the backend's listed models. They keep its hidden ones (visibility: "hide"), which no picker shows. One of those iscodex-auto-review: when the list lacks it and no reviewer is set, Codex's auto-review runs on the conversation's model at low effort (#1460,TestCodexModelListPicksKeepHidden). The account's own models kept out of agents' lists for routing groups (provider.CodexNativeUnlisted) are dropped from it too, hidden ones kept: every one when the codex provider is "Only through routing groups" (Provider.Unlisted), and those a group that unlists its members names (Group.Unlists). A Codex there only for failover keeps them, as it is handed no groups;spawnChoicesdrops the same ones (#1602,TestCodexModelListUnlistedForGroups). - Reasoning state goes through magpie's translation as the vendor wrote it when the agent and the upstream speak the same API (#1445, XYenon): a non-streaming request to a stream-only account, web search on the agent's own API, a plugin, failover. The IR carries it sealed (
Part.Sealed,SealedBy; eventsKThinkStart,KSealed,KTextSiginir.go), so each thinking block or reasoning item stays apart, whole or streamed, and a seal is written only for its own API (sealedBy). Anthropic'sredacted_thinkinggoes back raw (to DeepSeek as a thinking block, below), and a thinking block signed with no text keeps its signature (aBlockstill writes"thinking": "", #1447), on Claude's subscription too. A Responses reasoning item keeps its id, summary andencrypted_content, and goes back to a Responses upstream as it came when it has no reasoning text (sealedReasoning; text, another vendor's, is still left out for OpenAI, #1411). Gemini'sthoughtSignaturestays on the call it signed and on text; a later call of a signed step goes without one, and only an unsigned step or Claude on Antigravity getsskip_thought_signature_validator. Another API's agent gets the call's signature in its id, as on chat (#687), with its length in the mark (__ts<n>__), so an id a client shortened carries no signature and the call goes as unsigned (#1536); it gets no one else's seal. Carrying reasoning across APIs (an envelope) isn't done. - A translated Responses reply gives Codex the reasoning items a Responses upstream sent, as it sent them; any other upstream's reasoning becomes items magpie made: an
rs_id and a summary, nothing sealed. Codex hands them back on every turn. A request relayed as is to OpenAI's API or Azure OpenAI goes without them (withoutBareReasoning) unlessstoreis true, because both look the id up among stored items and answer 400 "Item with id 'rs_…' not found" (#1008). Any other Responses upstream gets them, because a DeepSeek model wants its reasoning back (#388). When one answers 400 naming the input (refusesInput:paramisinput, or the error names an item by id), as a relay in front of OpenAI does with a message of its own,passthroughasks once more without them and, once that works, leaves them out for that provider and model from then on (bareReasoningRefused, #1044). Codex's compaction offers no tools, so it is relayed even when its turns were translated. When a provider answers its summary request 404, or 400 for an item it didn't find (itemNotFound, a relay in front of either),codexCompactasks once more with the conversation as text (plainCompact), then compacts locally (#866, #1008). So does the ChatGPT backend's 502 "response protection is unavailable" (protectionRefused): a long history refused so was answered as text. Codex also compacts remotely, acompaction_triggeron/responsesthat wants exactly one compaction item back, on any provider table named "OpenAI", as CC Switch names its relay tables. magpie points those at/v1while a magpie model is on, sohandlemakes the summary there too (codexInput,codexCompact), and magpie's summaries go back to the model as text (#1301). - A Responses request Codex sends a Responses provider is fitted for a backend that isn't OpenAI's before it goes (
passthrough): Responses Lite'sadditional_toolsitem lifted intotools(liftAdditionalTools, #350), 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). Off is the default, and a subscription account is never sent so.TestCodexAsSent. - Every request to a key+URL provider goes with magpie's User-Agent (
magpie/<Version>,userAgentForinuser_agent.go), except a provider setpassUserAgent(#1851,magpie provider set <id> user-agent=agent, the editor's "Send the agent's own User-Agent"): it gets the User-Agent the inbound request carried, unchanged, for a coding plan that serves only the agents it names. 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, not a 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, 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.TestUserAgentPassedOn,TestUserAgentAccountUntouched,TestUserAgentFor,TestPassesUserAgent,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; 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. - 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), 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). - 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). Kimi is never sent them (forwardOnce,isKimi); 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; the tools stay in the request'stools, 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). - 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 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 Grok model writes a whole number in a call's arguments with a fraction of zeros (
2500.0,17277.0), whoever serves it: the Grok subscription or its plugin, xAI, OpenRouter or a relay. Codex reads its integer fields as u64, usize or i32 even though their schemas saynumber, so serde turns away the whole call (#1431). In a reply to a request whose model, as magpie names it or as it is sent upstream, has a last/segment beginning withgrok(grokModel,grokServed), every number in a call's arguments written with a fraction of zeros and no exponent loses the fraction:2500.0becomes2500,-3.00becomes-3. Strings, keys, other fractions (2.5,2.50) and exponents (1.0e3) stay as written. No tool schema is consulted, since JSON has one number type. The rule runs over the arguments as a stream of text (wholeNums), holding back only a fraction of zeros until the next byte. This gives the same arguments whether they come whole or in deltas cut anywhere, so what a call's deltas add up to is what its done events say. Relayed replies are rewritten inpassthroughbyintTidy: Responses' function_call items, argument deltas and done events and the completed response; Chat'stool_callsdeltas and messages; Messages'tool_useinput andinput_json_delta, streamed or whole. Translated replies are rewritten at the encoder (wholeEncoder, outsideusageEncoder) and atrender(wholeResult) whenRequest.Grokis set. Any other model's reply is relayed byte for byte (grok_integral.go). - 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), DeepSeek's half-Hermes<parameter>form (#917) and GLM's<arg_key>/<arg_value>(#906), read byparseTextCalls. 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 reply whose model made a call itself is left alone. 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), and every translation, which magpie always asks streamed, a plugin's included, whatever the client asked (textCallSee). A relayed Responses or Messages upstream's text is not read for calls. Covered byTestTextWritten*,TestGLMTextCall*,TestPluginTextWrittenCallandTestQuietWholeReplyStreamed. - Structured output is carried across every translation (
Format,format.go). It is read from Responses'text.format, Chat'sresponse_format, Anthropic'soutput_config.formatand Gemini'sresponseMimeTypewithresponseJsonSchema/responseSchema:json_schemawith its name, description, schema and strict, orjson_object. Each upstream is asked in its own field:text.formaton Responses,response_formaton Chat,output_config.formaton Messages, andgenerationConfig.responseMimeType/responseJsonSchemaon Gemini and Code Assist. An API with no name for it getsresponse. Messages and the Claude subscription's--json-schematake a schema only, sojson_objectis told in the system prompt there (inSystem). The bridges to a vendor's own API (Cursor, Devin, Kiro, Qoder, Command Code, Zed) are always told in the system prompt. A 400 or 422 that names the field (refusesFormat: DeepSeek's "This response_format type is unavailable now", a schema Anthropic can't hold) marks the provider and model (formatRefused), and the request is asked again with the format told in the system prompt, as are later requests to that provider and model. A relayed request keeps its format as sent. A Gemini client's format is also still told in its system prompt, as before. - 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, Qoder and Cursor (cursorImage) put them in a user message right after the results, and the result says they follow. Command Code puts them in the user's turn after the results, Gemini and Code Assist after the function's response, and Devin in its tool message. Kiro's results hold text alone, so Kiro (the built-in, and its plugin from 0.1.9 on) sends them with the message that answers the call, and only the latest images go again (#369, #1861).TestCodexToolImageReachesAnthropicPlugin,TestCodexToolImageKiro,TestCodexToolImageCursor, and the plugin'stool-images.test.mjs. - Group members are
provider/model[:effort]. A member with a fixed effort is asked for that effort, bounded by the group's levels (#671). - An agent whose config can't carry an effort has one picked in magpie (
provider.AgentEffort, settings'agentEfforts; Cursor Private Inference's row, #1003). It is asked for on that agent's requests to a model that reasons (Provider.Thinks), in place of the level the request sent, fitted to the model's levels and bounded by the group's. Order: a member's fixed effort, then a model's:effortsuffix, then the turn's pick (a routing rule's), then the agent's pick, then the request's own. A model that doesn't reason is sent as asked; the default (none picked) leaves every request as it came. The pick beats the request's own because Cursor sends its own default as often as a real choice. Picking Default hands the choice back to Cursor. - Gemini's OpenAI-compatible API (AI Studio's, or a proxy in front of Gemini on this computer or the LAN:
geminiCompat) is asked for the model's thoughts inextra_body.google.thinking_config. A 400 or 422 whose error namesextra_body,include_thoughtsor thinking at all (refusesThinkingConfig) marks the provider unfit for the field (thinking_config), and it is asked again withreasoning_effortalone. Gemini 3 can't stop thinking, so reasoning turned off goes atminimal, its least, or at the model's lowest level where it has nominimal(geminiLevels: those of the model's levels it hasn't turned away, or of Gemini 3's where its own aren't known or none is left). Gemini 3 turns away a level the model hasn't with a 400 that names the level (geminiRefusedLevel): AI Studio's "Thinking level MINIMAL is not supported for this model. Please retry with other thinking level." for gemini-3.8-flash, Vertex AI's "Thinking level is unsupported: THINKING_LEVEL_MINIMAL". It names thinking too, but isn't the field turned away. The level is marked refused for that model (levelRefused), and the model is asked again at the nearest level it has left, still for its thoughts, and at that level from then on. A level turned away again, with none left, is the client's 400. Passed through, a Chat client's ownnoneorminimalthat Gemini turns away this way is asked again at the model's lowest level (onEffort), and that level goes at the lowest from then on (turnedAway); the other still goes as sent, as AI Studio takesnonefrom gemini-3.8-flash. A refusal that names the levels the model takes (effortLevelsNamed, Command Code's for Qoder'snone) marks reasoning off as a whole (offRefused): both go at the lowest from then on; one that lists the other among the levels taken (otherOffNamed, quoted, OpenAI's for gpt-5.1'sminimal) marks only the level turned away. Both routes read and write the same marks. Vertex AI's OpenAI-compatible API marks each streamed chunk of thoughts in the delta'sextra_content.google.thought, and such a chunk is read as thinking. - A Claude that thinks only adaptively (
adaptiveOnlyinanthropic.go: Opus, Sonnet and Haiku from 4.6 on, Fable and Mythos 5 and 5.1, read byclaudeVersionhowever a relay spells them) is never sent a thinking budget, which they answer with 400. magpie's own request from a Chat or Responses client (buildAnthropic) goes asthinking: {type: "adaptive", display: "summarized"}with the effort inoutput_config.effort, so the client sees the reasoning Opus 4.7 and later otherwise leave out (displayomittedby default), and a relay that refusesdisplayis asked again without it (refuseShapes), 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). A client'sxhighgoes asxhigh, except to Opus and Sonnet 4.6, which have noxhighand are askedmax(noXhigh, #1471). - A request to an Anthropic endpoint that turns thinking off is sent as the model takes it (
thinkingOffAsTaken, inforwardOnce, so relayed requests, count_tokens, magpie's own thinking-off and retries all get it; the model is read as the vendor names it, from the body, or from the path for Bedrock and Vertex). Claude Sonnet 5.5 refusesthinking: {type: "disabled"}and is sent{type: "between_tools"}alone, at efforthighat most. Opus 5.5, Fable 5 and Mythos 5 refuse it at every effort and are sent no thinking, at effortlowunless one was asked, withclassifierRoomadded to a reply limit below it, as Claude Code does. Opus 5 and Haiku 5.5 take it only up tohigh, soxhighandmaxare asked ashigh.between_toolssent to any other Claude goes asdisabled, or as none where that is refused too. Other vendors' models, older Claudes and later lines than these go as they came (#1454). A Sonnet 5.5 by a name these rules can't read, answering 400 that asks forbetween_tools(asksBetweenTools), is asked again with it, once; a refusal ofdisabledat any effort (thinkingOffRefused) is asked again with thinking left to the model, asalwaysThinksis. 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. - A model the user ticked no levels of (
ModelReasonlessin settings,SetModelReasonless; the provider editor's Names & levels, 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. - A request to an Anthropic endpoint with
temperature,top_portop_kreaches a model that refuses them without them (samplingAsTaken, besidethinkingOffAsTakeninforwardOnce): Opus 4.7, 4.8, 5 and 5.5, Fable 5, Mythos 5, Sonnet 5 and 5.5, and Haiku 5.5, whose 400 is "temperatureis deprecated for this model" (Claude Code's auto mode classifier and magpie's own classifiers ask at temperature 0). Older Claudes, Haiku 4.5 among them, other vendors' models and later lines go as they came (#1454). A Claude by a name these rules can't read, answering that a sampling parameter is deprecated (samplingDeprecated), is asked again without them, once — a Chat or Responses client's request translated to Messages (forwardTranslated) as much as a relayed one. - Claude Code's 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 (Anthropic's API, a relay, Bedrock, Vertex), and anything onapi.anthropic.com. 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. 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; the wiring turns the review off in its settings while no model it can reach through magpie is reviewed (claudeReviewEnv, agent wiring), which is the page's remedy for a gateway that can't run the checks (1EFLOPS on X: Codex's model behind magpie). - Claude Code's billing line (
x-anthropic-billing-header: cc_version=…; cc_entrypoint=…; cch=…;, its own first system block,cchchanging every turn) goes on only to a Claude model asked on Anthropic's Messages API (keepsBillingLineinbilling_line.go: Anthropic's, a relay's, Bedrock's), as Claude Code sent it. Anywhere else it is left out, the rest of the system as sent (withoutBillingLine): a vendor's model relayed on Messages (passthrough), every translation to Chat, Responses or Gemini (forwardTranslated, Claude models too), and the subscriptions asked through their own clients' APIs (Cursor, Devin, Kiro, Qoder, Zed, Command Code's Go plan, inattempt). Kept, a vendor read it as the prompt's first words and its prefix cache missed from byte 0 every turn (#1600, justrun1983: 4% read from DeepSeek's cache behind Command Code's plan). The Claude subscription's run sends its own (withoutBillingHeader), another magpie decides for the provider it picks, and Code Assist (Antigravity, Gemini CLI) is sent it as before, whichantigravityTurnsAwayreads (#666). - 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. - 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 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). - A request that names no reply limit, translated to Anthropic's Messages API, which needs
max_tokens(forwardTranslated; a Zed subscription's Claude inserveZed), 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).
Remote magpie APIs
A remote provider serves the conversation, token-counting, System One,
embeddings, rerank, 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 uses HTTP/SSE;
its WebSocket route still answers 426. Discovery and older-peer behavior
are described in Providers and accounts.
GET /v1/magpie/limit (keyLimit in
key_limit.go) answers the limit of
the gateway key the request carries (access.Caller) and of no other: it
reads nothing from the request but its key. A local magpie asks it with
each of its remote-magpie keys for that key's card on its Usage page
(#1547).
System One uses RouteDecider and postDecide in
decide.go, taking one provider prefix
off at each hop and preserving the state, questions and vendor errors.
A model naming a group of decision models (provider.Group.Decides: every
member a decision model; cleanDecisionGroup in
decide_group.go refuses a mixed
one, one inside a chat group, and patterns, rules, effort or fast mode on
it) goes to serveDecisionGroup in
decide_group.go instead
(decisionGroupOf: group/<id>, or a group's id or name by GroupFor). It
plans the members' keys and accounts with planGroup (perKeyBarred keeps
a decision-only provider's keys: DecidesModel), applies a gateway key's
model and account limits and pause rules as for a chat, and tries each
candidate in turn: a retryable failure that is not the request's own
(shapeRefused, promptRefused, protectionRefused) rests it
(decideFailed → restAfter) and the next is asked; the last one's answer
is passed on. Every try is a Try of one route; one usage row is written
for the answer. A group classifier of decision models fails over the same
way (askDecisionGroup, decideRefused carrying the vendor's status). A
decision group is kept out of the agents' catalog (groupEntries), and a
conversation asked of it is refused 400 pointing at /v1/systemone.
embeddings.go relays retrieval
bodies and options (serveRetrieval), 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), draw.go sends images
to the remote's images API, and video.go
wraps remote task ids for later polls and downloads. passOnCaller in
remote_magpie.go supplies
caller/session headers without replacing the outgoing User-Agent.
Conversation forwarding preserves Claude Code and Codex client headers
(including Codex's originator) so relays behind the remote can recognize
them. Decision, retrieval and media requests set magpie's User-Agent at
their own call sites, so the remote accepts their attribution. Vendors
receive no caller labels.
A custom provider (no account, no preset plan's videos) makes videos the
same OpenAI way (#1446, customVideomakers), but only with the models its
own fetched list marks "kind": "video" (catalog.LiveVideomakers) 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 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
magpie's User-Agent (or the agent's, passUserAgent) and no caller headers. Its ids end with the key's
fingerprint (customVideoID, markedKey), so a poll and its download go
on the key that started the video. A gateway key's account and model holds
apply to all three routes (videoAsker, videoModelHeld), and to Grok's
and Volcengine's polls and downloads as well.
Turning provider search off
Settings' searcher: "off" disables magpie's provider-assisted search,
including Kimi Code's 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, 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.
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.
WorkBuddy's search service
A WorkBuddy plan's models (the China build's and WorkBuddy AI's, built-in
or moved onto the plugin) 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 TestWorkBuddySearchesForItsModels (Claude Code's
literal WebSearch request, the real service's reply bytes) and
TestWorkBuddyPluginSearches.
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
that sends the item back in its next input (Codex replays its output) loses
nothing: parseResponses has no case for web_search_call and leaves it
out, as before.
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.
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 to no other provider. Its error goes
back to the model, and webSearch then asks the search APIs, when any are
set up. namedFailed keeps the last search it didn't make, cleared when it
next searches. Settings › Web search shows that (SearcherFailed,
searchFailed) at the start of the row's help, ahead of its ellipsis.
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 (describe) has the level in it, so a new level 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.
A search API's base URL
Each search API (provider.SearchAPI)
has an optional url, its base URL: an endpoint of the user's own that
answers as that API does (#1580). Empty is the vendor's own
(SearchVendor.Base); SearXNG has none, so its URL is required. check
takes only an http:// or https:// URL with a host and no ?query or
#fragment, since askSearchAPI puts the vendor's path after it
(/search, /res/v1/web/search, /v2/search) with the slash at its end
trimmed. The request goes through the gateway's client, so it follows
magpie's proxy settings as the vendor's own address does
(TestSearchFollowsTheSearchersProxy).
The key is sent only to that URL. Go keeps Brave's X-Subscription-Token
and Exa's x-api-key across a redirect to another host, so askSearchAPI
doesn't follow one. The 3xx is the error, and it names where the search
was sent. magpie ships and lists no third-party search endpoint; the URL
is only ever the user's.
A value the user set is never replaced by the vendor's default. In
Settings › Models › Web search the field sits under the key for every API,
with the vendor's own address as its placeholder. Picking an API that is
already added fills in its saved URL, so Add with a new key alone keeps
the URL, and Add with no key changes only the URL. On the CLI,
magpie search add <api> <key> keeps the URL set before, and url= with
nothing after it puts the vendor's own back. Backup and sync carry url
with the rest of the entry.
Covered by TestSearchAPIAtItsOwnBaseURL, TestSearchKeyStaysAtItsBaseURL,
TestSearchAPIBaseURLFromSettings, TestSearchCLI and
search-api.test.cjs.
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. 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.
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. Settings › Models › Web search shows a row
of the keys under an API with several or with Tavily's (In turn / In order,
each key masked with what it has used, Check again), and magpie search
lists the same, read fresh.
Covered by TestReadTavilyUsage, TestSearchKeysTakeTurnsRoundRobin,
TestSearchKeyRefusedRests, TestSearchRestFor, TestSearchQuotas,
TestSearchKeyNeverInFull, TestSearchAPIKeysTakeTurns and
search-keys.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).
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 and search-mcp.test.cjs.
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, askVisionWith asks the prompt beside it under
visionAskSystem. 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.
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, and a searcher named there is not handed on
to another provider when it fails (see "A searcher that fails or finds
nothing"). Image and video generation (AutoDrawer,
AutoVideomaker) are not held this way.
Covered by TestAutoVisionPassesOverOneOut,
TestAutoVisionTierAmongThoseWithAllowance, TestSpentModelAcrossAccounts,
TestVisionDoesNotAskSpentDescriber and TestSearcherPassesOverOneOut.
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. - An id already in the catalog as is (a group's or a provider's own id) is not listed twice. Group rows themselves add nothing.
- The target must be in the list shown: a gateway key held to some models
sees only the bare ids that reach one of its models, so a key held to
b/*doesn't 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), so turning it on or off rewrites nothing. - 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) inbare_ids_test.go,TestBareModelIDsSettingininternal/gui, andinternal/gui/tests/bare-ids.test.cjs. - An image a caller names by URL that magpie downloads itself (an
/v1/images/editsor/v1/images/generationsreference image, for an images API that takes files, Gemini's own API or Code Assist:fetchPictureindraw.go) is downloaded from public addresses only (publicClientinimage_fetch_guard.go). Every address the host resolves to must be public (publicAddr: not loopback, RFC 1918, fc00::/7, link-local with 169.254.169.254, CGNAT 100.64/10, unspecified, multicast, documentation, reserved, Teredo, nor an IPv4-mapped, NAT64 or 6to4 form of one), 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 (privateDialer). 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). Each redirect, up to 5, is checked the same, and what comes must sniff as an image. A request from this computer (local: loopback, not through a proxy or tunnel, and not from a web page,fromBrowser) may name a private address, since its sender reaches it already and a local agent may serve its images on localhost; one with a gateway key from elsewhere may not. A URL left for the vendor to fetch (a chat model's message) is the vendor's to fetch, and an image the vendor itself answers by URL is downloaded as before (FetchImagewith the gateway's client).
Verification
go test -tags nogui ./internal/gateway -run 'TestGroupAsksOneRestingMemberNotEach|TestLoneRestingMemberStillAsked|TestRetrievalGroupAsksOneRestingMember|TestProbeOne|TestLoop|TestLongReplyThatDoesNotLoop|TestQuiet|TestSilentHeld|TestRotateSpreadsSessions|TestRouting|TestSmartRouting|TestFallback|TestNoFallbackForOtherErrors|TestLastFallbackErrorReachesTheAgent|TestRateLimitedSinksToTheBack|TestGroupRateLimitedSinks|TestAffinity|TestSeveralKeysOnTakeOverFromEachOther|TestModelNotInPlanRestsTheModelNotTheKey|TestSubscriptionAccountsTakeOver|TestGroup|TestTrace|TestImageTool|TestCodexNoCredits|TestWindowCapsHoldTheAccount|TestAccountCap|TestClaudeGoesOnMessagesWhereTheRelayHasThem|TestAutoRelaysOnTheClientsOwnAPI|TestSearchOfferedStaysOnTheClientsAPI|TestSearchFollowsTheSearchersProxy|TestCodexSearchAnsweredOnResponses|TestAgentEffortOnCursorLocal|TestAzureCompactionWithoutMagpiesReasoning|TestCodexCompact|TestProtection|TestSearchedConversation|TestUnsearchedConversationUnchanged|TestNotAnAPIReply|TestAPIReplyUntouched|TestCodexBackendWebPage|TestSub2APIKeyLimitIsQuota|TestKeysWeighedByTheirWindows|TestGroupWeighsKeyWindows|TestKeyOutOfItsWindowRestsUntilReset|TestKeyPoolErrorDoesNotRestForWindow|TestKeyBackOnceItsWindowIsNotFull|TestRestingKeyReadAgainInAnOrderedGroup|TestClaudeAccountBackOnceItsWindowRenews|TestThinkingStreams|TestHeldThinkingKeepsTheAgentAlive|TestCodexHeardWithinItsIdleTimeout|TestRefusalAfterThinkingFailsOver|TestGeminiEmptyRepliesAskedAgain|TestLocalUnredacted|TestCORS|TestForeignPagesRefused|TestAIStudioThinking|TestGeminiThoughtsThroughLocalProxy|TestGeminiRefusedLevel|TestGeminiThinkingOffAtItsLowest|TestThinkingOff|TestTranslatedEffortLoggedAsSent|TestTranslatedThinkingOffRefused|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 'TestVertex'
go test -tags nogui ./internal/gateway -run 'TestPublicAddr|TestEditImageURL|TestPrivateDialer'
go test -tags nogui ./internal/gateway ./internal/provider ./internal/cli ./internal/gui -run 'TestDisabled|TestModelDisableCmd'
node --test internal/gui/tests/disabled-models.test.cjs
go test -tags nogui ./internal/gateway ./internal/gui -run 'TestBareModelIDs'
node --test internal/gui/tests/bare-ids.test.cjs
go test -tags nogui ./internal/gateway -run 'TestTextWritten|TestGLMTextCall|TestPluginTextWrittenCall|TestQuietWholeReplyStreamed'
go test -tags nogui ./internal/gateway -run 'TestAutoMode|TestClaudeBridgeSafeguard'
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/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.