Files
magpie/docs/subsystems/gateway-routing.md
T
yetone 30869e35a7 usage, gateway: each request's log row says the service tier asked, the one each try was sent at, and the one the vendor said it ran at (#1784, zhenghaowen0967)
What changed
- usage.Record has tier_asked, tier_sent and tier_served, and the CSV gets
  them as its last three columns.
  - tier_asked is the client body's service_tier (Claude's speed fast reads
    "fast").
  - tier_sent is the tier the try's last request actually went out at. It
    is noted in forwardOnce after every rewrite (a fast pick's priority,
    Ultrafast turned to priority on a plan without it, buildResponses
    dropping a tier the host can't take) onto the per-attempt wireAt. So a
    handed-on try's own row has its own tier.
  - tier_served is only what the reply said: service_tier at the top level,
    in response.service_tier, or in an Anthropic usage. It is read by the
    relay sniffer and by both translated readers, and is empty when the
    reply says nothing. It is never filled in from the ask.
- Codex's own relayed sign-in (codex_backend) records the same three.
- /v1/magpie/route: Route.tier (asked), and each Try has tier and
  tierServed. The session route has asked_tier, tier, tier_served and each
  try's tier and tier_served.
- docs/reference.md (CSV columns) and gateway-routing.md describe them.

Why
zhenghaowen0967 asked that a request whose Ultrafast was sent as priority
to an account without it show that in usage, per try, without calling
the served tier confirmed unless the reply says so.

What was run
- TestTierRecordedPerTry. With Pro out, the first try is recorded
  ultrafast, the second priority, and the final record has asked=ultrafast,
  sent=priority and served empty while the fake doesn't echo. With an
  echoing fake, served is what it said ("ultrafast", and "default" when
  none was asked). It also checks the CSV columns, and the Codex relay path
  with priority.
- TestUpstreamTierShapes covers the Chat chunk, Responses
  response.completed, a Responses body, an Anthropic message_start and
  message_delta usage, null, an over-long tier and non-JSON, as well as
  bodyTier per protocol.
- Broke it by hand:
  - with forwardOnce's noteWireTier removed, TestTierRecordedPerTry goes
    red (route tries' tier empty, TierSent empty);
  - with the sniffer's Tier line removed, TestUpstreamTierShapes goes red,
    and so does the Codex relay case of TestTierRecordedPerTry.
- go test -tags nogui ./internal/gateway ./internal/usage ./internal/cli;
  ledger_test's CSV expectations gain the three empty columns.
- gofmt -l; go vet on darwin; GOOS=linux and GOOS=windows go vet -tags
  nogui.

Not done
- The served-tier fixtures are built from the shapes OpenAI and Anthropic
  document, not from saved replies. Whether chatgpt.com's Codex backend
  echoes service_tier wasn't tried against a real account.
- Bridges that don't go through forwardOnce (the Claude subscription,
  Cursor's built-in) leave tier_sent empty.
- There is no price multiplier for priority/ultrafast and no GUI column.
2026-10-13 14:22:53 +08:00

130 KiB
Raw Blame History

Gateway routing and fallback

The gateway is magpie's local LLM endpoint (127.0.0.1:3425 by default). It serves Chat Completions, Responses, Anthropic Messages and Gemini. It finds the provider, key or account and model for each request. When the upstream doesn't speak the agent's API, the gateway translates. When an upstream fails before any of the reply is sent, the gateway moves to the next candidate.

This page covers how a request is routed. Plugins that change requests and replies are in Gateway middleware. Subscriptions served by a plugin are in Provider and plugin ownership.

Responsibilities and sources of truth

Part Responsibility Source
Address and caller DefaultAddr. The local token magpie and the per-agent magpie-<agent> (TokenFor). agentOf tells which agent asked, first by token, then by User-Agent. gateway.go
HTTP surface Handler routes /v1/chat/completions, /v1/responses, /v1/messages (each also without /v1), /v1/models, Gemini's /v1beta/models/…, the Codex backend path, /v1/codex/models (Codex's catalog shape for a Codex elsewhere with a gateway key, codexCatalog, kept to the key's models by keyAllowed; #1281), /mcp/{name}, /mcp/magpie/web-search and /mcp/magpie/vision (magpie's own web search and image recognition as MCP servers, below) and the /v1/magpie/* status endpoints. A GET on /v1/responses (a client opening Responses over a WebSocket) is answered 426, a plain one 405: Responses is relayed over HTTP only. Every route is wrapped in counted, corsGuard, callerGuard, withCaller and keyLimited; /v1/messages, /messages and /v1/messages/count_tokens in keepsSignIn too. corsGuard (#1051) serves CORS only to the origins listed in Settings › Network › Web pages (settings.CORSOrigins, cleaned to scheme://host[:port] by settings.CleanOrigins, which refuses a wildcard). 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). 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. 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
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. 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 and descriptions

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.

Runtime path

  1. handle(proto) reads the body and the model (requestBody, requestModel), then calls serveAgent. Every route that reads an agent's body (each API, count_tokens, Gemini's, embeddings, images, videos, System One, the Codex backend path) reads it through readBoundedRequestBody in request_bounds.go. It decodes a Content-Encoding of gzip or zstd (decodedBody; Codex sends zstd to a custom provider's /v1/responses too, #1223) and drops the header, so the provider is sent plain JSON, with one exception: a ChatGPT account's turn (POST CodexBase/responses, from the accounts loop in forwardOnce or relayed by codexUpstreamOn) is compressed again with zstd, as Codex's own client sends it (provider.CodexCompressed; openai/codex responses_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, and codexDropped judges a reset by the bytes that went on the wire. 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); writeError adds to any 413 it isn't holding that this is a byte limit, not the model's context, and to /compact or start a new conversation (TestOverLimitSaysWhoseAndWhatToDo). keyLimited reads a limited key's compressed body the same way, so its reservation is the decoded size. serveAgent runs the middleware chain, then serve.
  2. serve redacts secrets in the request (redacted; redact.MaskJSON leaves ids alone; the request's tool definitions and output schemas, found by their place in each protocol (top-level tools, tool_choice, response_format, text, generationConfig and the like, and the tools of a Responses additional_tools or tool_search_output item), go as written save their descriptions, so a word the user masks can't break a grammar or an enum (#1911); and what the vendor sealed with a signature, a thinking block, Gemini's thoughts or Responses' encrypted reasoning, goes back as the vendor wrote it: only the values masked elsewhere in the request, and secrets masked before, are put back as their placeholders; a value masked once, at least 8 characters long, is masked again wherever a request has it, as an exact match whatever words are around it, so what the vendor wrote about a placeholder doesn't go back with the value in it, redact/known.go), resolves the model to a provider or a group, and refuses what can't be served. A request whose provider and fallbacks, or whose group's models, all skip redaction (unredactedRoute, provider.SkipsRedaction: set Send requests unmasked, Unredacted, with every address on this machine or the local network) goes to them as the agent wrote it; the log and recent calls keep the masked body. count_tokens and embeddings follow the same rule.
    • With Mask personal data on, each kind in redact.Categories (internal/redact/more.go) is masked unless the user turned it off (redactKinds in settings, Options.Kinds). On by default: US SSNs, passport numbers, IBANs that pass mod 97, birthdays next to a word that says so, 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 from REDACT_KINDS in app.js, which TestRedactKindsAreRedacts holds 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-rule with the rule's index and its current value, editRedactRule in internal/gui/api.go). Every rule is checked by redact.CheckRules when settings are saved; an edit that doesn't compile, matches the empty string, repeats another rule or names a rule no longer at that index is refused with the rules left as they were. The gateway reads the rules from settings on each request (redactionOptions), so a change applies to the next request.
    • DecidesModel gives 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_agent sealed goes only to a ChatGPT account, or back to the Responses provider that answered the lead (leadProvider, a relay of the ChatGPT backend such as Sub2API, #1109), relayed as it came even when web search is offered. A lead's turn carrying its subagent's sealed reply (send_message) goes back to the Responses provider that answered the lead's own conversation (leadProvider of the request's conversationID, #1237); otherwise it is refused before anyone is asked (sealedReader, sealedTaskError). A sealed message (Message Type: MESSAGE, not a task) that nobody asked can open is left out instead, an input_text note naming its sender in its place (withoutSealedMessages, #1613): a lead on a chat provider whose subagent is on one of Codex's own models goes on, as the subagent's final result still reaches it as text. Only a sealed task (NEW_TASK, or an item with neither header) is refused. Who answered is first what affinity remembers; when affinity has let it go (a day since, a restart past the 512 conversations affinity.json keeps, or the lead's last reply broken off, unanswered), the usage log's answers to the lead's thread and the request's own conversation in the last 30 days count too (loggedAnswers, #1367), and leadFirst reads the lead's key or account from them. A refused or failed call and a title answer nothing, and Codex's own sign-in is told of as the ChatGPT backend. The refusal names who sealed the task when it is known, and says how to go on with it. It also says what is sealed (sealedTaskItself, #1855): the task itself, spawn_agent's message, which the backend returns sealed (encrypted_function_args) and Codex hands the subagent as it came, so fork_turns="none", which only leaves the lead's turns out, doesn't help; nothing in it can be left out for the subagent to go on.
    • A model set for Codex's subagents (settings.CodexSubagentModel, the Agents page's Codex "subagent model", willz on Discord) is put on a Codex subagent's request (x-openai-subagent read as kind:collab_spawn) before this check, whatever model its lead's spawn_agent asked for (codexSubagentPick in codex_subagent.go): in codexBackend for one of Codex's own bare models, which then goes through serveAgent, and in serve for any other. Any model magpie serves can be set (provider.SetCodexSubagentModel, #1633): a task handed as text (a lead magpie served on a chat provider, or multi-agent V1) is read by any model. A request carrying a task the ChatGPT backend sealed (sealedTaskIn: a sealed agent message that isn't a MESSAGE, which withoutSealedMessages leaves out) is put only on a ChatGPT account's model; set to another, the subagent stays on the model asked for, which the sealed gate below handles as with nothing set. When magpie doesn't serve the model set now, or a gateway key held to some models may not use it, the subagent goes on the model asked for too. The route trace keeps both models and the reason it stayed (Route.Subagent), and the Routing page's kindWhy says it. 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/userSaid in prompt.go, which the turn count (turnIn), the classifier's question (userText), the conversation's key (firstWords, in ruleKey and the affinity scope), Copilot's Auto (lastUserText) and the prompt breakdown's turns (userSays) all go by. It drops <system-reminder …> blocks (a source= attribute too) and any text that begins as an agent writes for the model alone: Codex's <environment_context>, <user_instructions>, <turn_aborted>, <user_shell_command>, <subagent_notification> and # AGENTS.md instructions for …; Claude Code's and ZCode's <task-notification>, <subagent-notification>, agent lists ("Available agent types …", "New agent types are now available …"), TodoWrite and task-tool nudges and rewind notices; ZCode's <plugin_reference>; the Codex app's <in-app-browser-context …>. The Codex app's context before ## My request (for Codex): is dropped and what follows it kept (the injected list beside agentsFor). A user message with nothing of the user's in it (and no image or file) begins no turn: after an answer or a tool round it carries the turn on (within), so the turn's rule and stick hold and the classifier isn't asked; right after the user's words it leaves their turn as it began. The classifier is asked about the last user message that has words of the user's, only those words. firstWords hashes the words of the first user message that has any, so an instruction file or notice the agent changes beside them doesn't move the conversation to a new key and lose its stick mid-turn (#1826: ZCode's TodoWrite nudge classified as a new, harder turn, and three keys for one ZCode session). TestTurnInSkipsWhatTheAgentPutIn, TestUserTextSkipsWhatTheAgentPutIn, TestFirstWordsAreWhatTheUserSaid, TestIntentHoldsPastWhatTheAgentPutIn.
    • A classifier that can't say which kind a turn is (an error, no answer within classifyTimeout, an answer that isn't a number, or resting classifyRest after a failure) leaves a turn whose conversation had an intent, still one of this turn's, with that intent (Classified.Fallback is previous, its Error kept), so the turn goes where the turn before went rather than to the group's first member; with no intent before, no rule with an intent matches, as before. The Routing page says the turn kept it (classWhy). The turn's decision itself (turnRules) is kept in memory only: after a restart a turn under way waits for the next one and the stick holds it meanwhile. TestIntentClassifierFailsKeepsThePreviousIntent, routing-intent-fallback.test.cjs.
    • The classifier's requests are magpie's own (#1839). Asked in words, they go out with RouterAgent's User-Agent (magpie-router/1), so their records' agent is magpie and callKind marks them routing; a decision model's (Jev, System One) record is written with Kind: "routing" too. They go to the same key or account as any other request and count in its totals, while usage.Group.Own (Record.ByMagpie: agent magpie or one of its magpie- User-Agents, with search's and image description's) says how many of an account's, key's or model's calls, tokens and cost were magpie's own. A classifier set to a subscription's model (modelRef.Sub, or a group whose first member is one) asks that subscription as every turn begins, twice when it picks both intent and effort in words; the Routing page says so beside it (classifierSub in routing.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/b is not under /a/bc; ~ is the home folder; a Windows drive is one with its WSL mount (C:\work is /mnt/c/work) and a \\wsl$\<distro> or \\wsl.localhost\<distro> share is the distro's own path; case doesn't count on macOS and Windows, nor ever for a drive. A rule outside folders (Rule.ExceptFolders, except-folders=~/big-task; #1606, Ti800) matches when the folder is in none of them, and an agent that says none isn't known to be in one, so it matches; a rule may have both (Rule.ByFolder, inFolders). The folder is read from the request only when a rule of the group has folders or except-folders (workDir in workdir.go), in each agent's own words, taken from captured requests: Claude Code's - Primary working directory: <path> (its </> as entities; (was <old>) after a change dropped), Codex's <environment_context> <cwd>, Pi's <cwd> in the system prompt, and OpenCode's Working 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 no folders= rule matches it (unknown, never empty). The same reading tells a plugin's fetch where its agent works (provider-plugins). A pause rule may hold by folder too (below). The trace's RuleHit.Folder is the folder read, and the Routing page tells it beside the rule's folder … condition. TestFolderUnder, TestRuleMatchesByFolder, TestParseRuleFolders, TestWorkDirOfEachAgent, TestRuleByFolder, TestRuleMatchesExceptFolders, routing-folder.test.cjs. Rules by folder are never in a shared group (ShareGroup drops every ByFolder rule).
    • A pause rule (Rule.Pause, pause=<model>; John on Discord: a model of the group paused in its vendor's peak hours) leaves the model it names out of the group while it holds (provider.PausedOut, on ruleClock): the group's own rules and each nested group's on the way down to a member, a group named taking all its models, and a model named taking it wherever a group in the group has it (#625). It runs before planning, on every request rather than once a turn, so the model is not first, not a failover, and not kept by affinity, and comes back as soon as the hours end. It holds by hours, days, agents and folders only (cleanRules refuses another condition), and is not a send-to rule: Matches, MatchRule, ThenUses, Ruled and the compaction rules leave it out. A send-to rule naming a paused model finds it unready and the group routes as without it. The trace keeps what was paused (GroupRef.Paused), and the Routing page says so. Every model paused answers 503 (pausedError) naming each rule. Embeddings go by the same pauses; manual groups have no rules (Live), so none pause there. A pause by folder (#1606, Ti800: a subscription's quota kept for the long task in one folder, pause=<model> except-folders=~/big-task) reads the folder only when such a pause is on the way (provider.PausesByFolder, then workDir): outside its except-folders, which includes a request that says no folder (a subagent's or a small model's that doesn't), the model is left out; with folders=, only requests known to be in them. Embeddings and System One's decision calls have no folder. Paused.Folder/ByFolder carry what was read, and the Routing page says the folder or that none was said. rules_pause_test.go, TestPauseByFolder, TestPauseByFolderRule, TestParsePauseByFolder, routing-pause-folder.test.cjs.
  3. Candidates come from planGroup for a group or plan for a provider. They are filtered by sealedReaders and allowedCandidates. An account past its share is held out of the candidates (capHeld): a usage cap's share, each window at its own where the account gives it one (AccountWindowCaps, willz on Discord: 50% of the five hours, 40% of the week) and at the account's cap otherwise, or 100% of a window for a Codex account set not to spend its credits (provider.HoldCaps, WindowCaps.Of, CodexNoCredits). A ChatGPT account's call on codex-auto-review, which OpenAI counts in no window, is held by no usage cap, only by credits it may not spend (freeOnChatGPT, #1593, TestAccountCapLetsAutoReviewThrough). The account is held while any window is past its own share, and cappedError and the trace name the fullest such window's share and cap. When every candidate is held and one held for its credits spends its resets by itself, autoReset spends a reset on it and it is tried (planned.held); otherwise a capped or barred set returns cappedError or barredError. Then affine moves the conversation's last answerer first, unless it is resting or nearly used up. An X-Magpie-Account header (AccountHeader) pins the request to one account: only that account is tried, and when it can't answer the caller is told why.
  4. The candidate loop calls attempt on each candidate in turn, through a holdWriter. The writer holds the reply until it is clearly passing. A candidate that fails before anything is sent rests (failure): out of credit for 30 minutes, out of quota until reset, rate limited until retry-after, otherwise a minute and longer on repeats. A 400, 403, 404 or 422 that says the model isn't served (unservedWords) and says nothing of quota, credit or a rate limit rests only that key's or account's model (modelRefused, keyed by restID, its backoff counted apart): its other models are still served first in order (#1235, SenseNova's 403 "model is not available in the current token plan"). A 400, 404, 410 or 422 that says the model is retired (retiredWords: OpenCode Zen's 410 ModelDeprecated "Model exo-free has been deprecated.", whose own model list still names it; MOMO on Discord) rests only that model the same way, is retryable so a group's next member or another provider of it is asked, and is remembered (provider.Retire, retired.json beside providers.json): the model leaves that provider's entries in the catalog (buildEntries), so /v1/models, every agent's model list and the found groups go without it, until a request on it is answered again (Unretire in servedCandidate) or a week has passed. A refresh of the vendor's list doesn't bring it back early, since that list is where it still is. A provider/model request for it is still sent. A 400 or 422 that says this upstream's API can't take the request's shape (shapeWords: xAI's 422 "unknown item type" (#350), OpenAI's "Unknown parameter", and a limit of a model's own on tool schemas, OpenCode Go's 400 "JSON schema exceeds the maximum nesting depth of 10 levels" on muse-spark-1.3-contributor, #1870) 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 to longestQuota (8 days), so a reset time read wrong (a year off) doesn't bench the account for that long. The next candidate is then tried. A failed provider waits fallbackCooldown (1 minute) at the back. A WorkBuddy account the vendor restricted (#1849: 403 {"code":11140,"msg":"request illegal","displayMsg":{"en":"Your account has been restricted due to unusual activity",…}}) rests restrictedRest (2 hours) as restricted (failRestricted), not the minutes of an unknown failure: only WorkBuddy lifting the restriction, after the user's appeal, brings it back. Both shapes are known: the built-in's wbExplain and the plugin's explained() (0.1.17, the mover's min) end the error with provider.WBRestrictedHint (restrictedSaid), and the vendor's own body, its code 11140 or its words (provider.WBRestricted), counts only from a WorkBuddy candidate (restrictedRefused, isWorkBuddy), as another vendor's 11140 is its own. Bare "request illegal" isn't matched. WorkBuddy's 11128 channel refusal stays promptRefused and rests nobody. The Routing page names it "account restricted by the vendor", says the appeal is the way back, and gives the account's row a button that lifts the rest (/api/gateway/unrest) once the vendor has. Every other rest a key or account takes (quota, rate limit, retry-after, a failure's backoff) can be lifted by hand the same way (#1869): "Try now" on its row on the Routing page and beside its rest note in the provider's key list. It ends the rest 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's stop_details category and explanation when it gave them (refusedDetail, #1768: "safety filter: refusal (category cyber)"); none is made up when it gave none. stop_details is carried through the IR (Event.StopDetails), so a Claude subscription run through the claude CLI and a translated Anthropic route keep it for an Anthropic client too. The ChatGPT backend's 502 "response protection is unavailable" is about the request's content, not the account: the same history fails the same on each of its accounts and models. It rests nobody, isn't tried again after a moment, and isn't asked of the provider's other accounts or models; another provider left in a group is asked once (protectionRefused, elsewhere). One cause is known (#1270): a history that replays the backend's own web_search_call in a request that doesn't declare the web_search tool is refused so, whatever the account, model or turn (a plain turn, a thread's description, a compaction, Codex's own text compaction for a custom provider with tools: []). Every request to the ChatGPT backend with such a history therefore declares cached-only search ({"type":"web_search","external_web_access":false}, provider.DeclareSearch): an account's in codexBody, Codex's own sign-in relayed in codexUpstreamOn. It goes in the tools, or for Responses Lite (its header, reasoning.context all_turns, or an additional_tools item already there), which refuses a top-level web_search, in the additional_tools item. A request that offered no tools gets tool_choice none so the model can't search; one with a forced choice keeps it. A history without a search, or a request that declares search already, is relayed unchanged. siwc, API-key requests to openai.com and the legacy /responses/compact are left as they were.
  5. 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 is retryPause doubled each round up to replanLongest() (30 times retryPause, 30s), and never shorter than the soonest Retry-After; a member whose Retry-After ends past the pause is asked after the others. This goes on while the group's Patience lasts. replanRounds (12) is only a backstop that never comes first: the pauses alone add up to PatienceLongest in 11 rounds (with 6, a group set to 240s gave up after 90s of pauses, real-jacket on #1418; TestPatienceIsUsedUp). The budget is the group's Patience, counted from the first time every member had failed, when the agent would have had the error (waitFrom; Group.Waits: 0 is PatienceDefault, 60s; -1, PatienceOff, turns it off; at most PatienceLongest, 240s). A pause that would end past the budget isn't taken, and the agent gets the error. While another member is busy too, the last one isn't first tried again alone (passing): the members take turns, and once the budget has begun, the same-one retries aren't taken either. While the budget lasts, the last candidate's failure is held (newHoldWriter), and a streaming agent is kept alive through the pause with SSE comments (pauseAlive). The try is traced with Again (the pause), Replan (how many are asked again) and Patience (the budget in seconds). The group editor's "Every member busy" row sets it. A plain provider keeps only the same-one retries passing gives 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 marked Gone (#1894, heng91: a relay down while its proxy was off, the agent's window closed). The Routing page says the agent canceled the request before the retry and lists it as canceled, rather than ending its story on "tried again in 2s", a retry that never came (TestAgentGoneInTheRetryPause, routing-agent-gone.test.cjs). A 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 tries when the route took more than one (rec.Tries, from the trace's Tries). A try a vendor refused or turned away (hw.refused, hw.turnedAway) still writes its own record, for what it billed and why it failed, marked handed_on; usage.Totals.count skips such a record for calls and failures. A request failed only when the agent got an error (LostRequest); one answered after a failed try is counted beside it as answered on a retry (Totals.Retried, RetriedRequest, the retried filter). Logs written before handed_on are read the same way: the log index marks a failed, non-rejected record followed by another of the same route id as handed on (routeRows in log_index.go). Counts by account or route (vias, window holds) still count every try.
  • Each record keeps the service tier three ways (#1784): tier_asked is what the client's body asked (bodyTier; Claude's speed fast reads fast), tier_sent is what that try's last request went out with, noted in forwardOnce after every rewrite (fast picks, Ultrafast to priority on a plan without it) onto the per-attempt wireAt, and tier_served is only what the reply said it ran at (upstreamTier, read by the sniffer and the translated readers), empty when it says nothing. The route's tries carry tier and tier_served the same way. A bridge that doesn't go through forwardOnce (the Claude subscription, Cursor's built-in) leaves tier_sent empty. Code: tier_record.go.
  • A usage record carries its prompt's cache beside in and out (#1839): cache_read (tokens read from the vendor's cache) and cache_write (cache creation, Anthropic's cache_creation_input_tokens; cache_write_1h the part written for an hour). in holds neither. Both are written on every record, 0 too, so a prompt that missed the cache reads as that. A record from before then has neither and reads as 0. Every route fills them: Anthropic's messages, Chat (OpenAI's prompt_tokens_details.cached_tokens, DeepSeek's prompt_cache_hit_tokens), Responses (input_tokens_details.cached_tokens) and Gemini (cachedContentTokenCount), passed through or translated, whole or streamed, a plugin's fetch, and the Claude subscription bridge. System One's decision calls report no cache. TestUsageRecordsCacheTokensOnEveryRoute, TestPluginUsageRecordsCacheTokens, TestClaudeSubscriptionUsageKeepsCacheTokens, TestRecordAlwaysCarriesCacheTokens.
  • A request whose key is a Claude sign-in (claudeSignIn: Authorization: Bearer sk-ant-oat…, Claude Code signed in to claude.ai with magpie as its base URL) is never told a 401, nor a 403 saying "OAuth token has been revoked". magpie never passes that sign-in on, so such an answer is a provider refusing magpie's credential, or one of magpie's own Claude accounts lapsing; told it, Claude Code renews its own sign-in before each of its retries (ten for one request) and then asks to /login. Any error whose message mentions x-api-key, whatever its status, Claude Code tells as "Not logged in · Please run /login" too. It is told as a 502 in magpie's words, an api_error saying " refused magpie's credential (HTTP 401): …" with x-api-key said as "API key", and any other error such a request is told keeps its status with x-api-key said as "API key", as does a stream's error after its 200 (keepsSignIn, claude_signin.go). Recent calls and the usage log keep the provider's status and message. Any other 403, and a request with magpie's key or an API key, is answered as before. The sign-in's beta (oauth-… in anthropic-beta) isn't passed on either (askedBetas), so a provider gets the request as Claude Code with magpie's key sends it; a provider's own header.anthropic-beta still goes.
  • A 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.watch runs beside each try: past keepHeldAfter (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 after keepaliveEvery of quiet. It stops after keepaliveLongest (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 than keepHeldAfter sends nothing, so its 429 keeps its Retry-After. A proxy in front such as Cloudflare (125s) otherwise ends the request (#947). Gemini streams get no comments (#934). A vendor that then ignores stream:true and answers 200 with its reply whole has it sent as the agent's stream (wholeAsStream: Chat, Responses, Anthropic), not as the stream's error, while a reply under a type that says neither JSON nor a stream is held as a stream when its first bytes are one (sseStart), read event by event like one that says so, so an error among its frames still goes to the next candidate (#1418: it went through at once); a 200 that is no reply of the protocol's fails as a translated reply that didn't stream does (502, "… did not stream"), for the next candidate to answer, and the last one's reaches the agent as the stream's error. A held stream that has sent nothing but the frames before a reply (response.created, response.in_progress, codex.rate_limits, pings, an empty part begun, and any event streamEvent doesn't know to carry text, reasoning, a call or a reply's end (replyEvent), or an item not known that isn't a call or a tool's (streamPart.said): eventLead; Aliceonly on #1418: an unknown event was taken for content and let a frames-only 200 through, and its server_is_overloaded reached Codex with five candidates left) stays held as long as its agent is kept alive, up to holdLead (4 minutes, under the 300s Codex waits for an event; keptQuiet), so a server_is_overloaded that comes after it is a failure the next candidate answers (#1418: let through at 15s, the ChatGPT backend's failure 36s in ended Codex's turn with sub2api, next in the group, never asked). A stream whose agent can't be kept alive (Gemini's) is let through after holdLongest (15s), as before. Codex counts only events toward that 300s, not comments, so the bound is the request's, not each try's: once Codex on Responses has heard no event for agentQuietMost (4 minutes) since the request began or its last event (keptAlive.tooQuiet), the try in hand is let through (scan, keepQuiet), and no group replan or same-one retry is taken whose pause would end past it (fadenoob on Discord: held tries and replan pauses added up past 300s and Codex reconnected on "idle timeout waiting for SSE"). A translated reply whose upstream stream stops before it said its reply had — an Anthropic one with no stop_reason and no message_stop, a Responses one with no response.completed, the same two a relayed one is told by (sniff.whole; a Chat stream may end without [DONE] and be whole), a Gemini or Code Assist one whose last chunk has no candidate's finishReason (geminiEnds, #1643: usageMetadata is no end, Vertex AI sends it on every chunk; a chunk with no candidate at all is the empty reply's to answer, #667), and a relayed Gemini one told the same way (#1644; it ends in Gemini's own {"error":{"code":502,…,"status":"UNAVAILABLE"}} data line from streamFailure, TestGeminiRelayEndedShort) — ends the turn with "the reply ended before it was complete" (errEndedShort, TestResponsesUpstreamEndedShort, TestGeminiUpstreamEndedShort), asked again in place where the upstream goes on from a prefill (continuation.go). A client that asked for no stream is told the same 502 of such a cut (translate, TestNonStreamEndedShort, TestGeminiNonStreamEndedShort), rather than handed what came as its whole reply.
  • Claude's, GPT's and Gemini's reasoning is held (refusesAfterThinking, up to holdThinking, 4 minutes) so that a refusal after it goes to the next candidate unseen (#248). It is held only while one could: on the last candidate a refusal isn't asked again, so 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.Write feeds every streamed try, passed through or translated, a key's, a built-in subscription's or a plugin's (a moved WorkBuddy's fetch in the plugin host, TestLoopEndsWorkBuddysReply), in each of the agent's protocols, to a loopGuard (loop_guard.go). It cuts the reasoning and the text, each apart, into units, its lines and sentences (a list's 1. or a decimal is no sentence's end), compared without case or a closing stop. A unit with no word in it (a letter run with no digit: not a brace, a rule, 0x00, a hash or a row of numbers) isn't counted. When the last loopWindow (256) counted units of either are among no more than loopDistinct (24) different ones, the try is cut (cutLoop): what came with that write goes out, then the protocol's stream error (streamError, 502) naming the loop and quoting its units, and the vendor's request is cancelled. It falls back to nobody and rests nobody (failLoop); its usage record's error type is reply_loop (usage.LoopErrType), and Usage counts them per model (Totals.Loops), as "{n} looped" beside the model's failures in the Overview's rows and the Requests ranking (#1858, TestLoopsCountedPerModel, usage-loops.test.cjs). A reply magpie translates into the agent's protocol (streamTranslated) whose reasoning loops before it has said a text or a call, and isn't a continuation, is asked again once in place instead (loopReasks, through holdWriter.onLoop; cdredfox on X, WorkBuddy AI's DeepSeek v4 flash): the agent keeps the reasoning it has, the next try's follows it in the same stream, as an empty reply's re-ask does (#667), and only a loop on that try ends the reply with the error (TestReasoningLoopIsAskedAgain). A 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 (TestLoopGuardLeavesOrdinaryRepliesAlone feeds magpie's own sources and docs through it). A reply sent whole (no stream, or Gemini without alt=sse) isn't read. Settings › Models › Replies › Stop looping replies (noLoopGuard) turns it off.
  • A Chat request's earlier turns carry the assistant's thinking back in the spelling its own client used: reasoning_content (DeepSeek's, which OpenCode and most clients send), reasoning (OpenRouter's) or reasoning_details (OpenRouter's structured one). A request translated to a non-Chat upstream reads whichever of the three the turn has, in that order, as the turn's thinking (messageReasoning, reasoningText, read by parseChat in chat.go); the passthrough has read all three since mistralThinking (#494), which was the one place that did. Before that the parse layer read reasoning_content alone, so a tool-calling session whose client spelled it another way went on from its second turn without the model's own reasoning.
  • The order of the steps a request's accounts go through, how much the accounts' own order (Make first) counts under each routing, and how often an allowance is read are described for users in How magpie picks an account. Smart compares renewals window by window, biggest first, each truncated to the hour (weighRouted), so the order decides only when every window falls in the same hour. A window's renewal is its reset, or, when what it has left runs out sooner or it has no reset, that moment (Limit.RunsOut, from QuotaWindow.RunsOutAt; Allowance.Renewal): the WorkBuddy plugin (0.1.14) sends it on its Credits window as the soonest end of a package with credits left (cdredfox on X). 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's usedRenews), not the biggest window's: a Factory account 32% into its week and 16% into its month reads "32% used · renews in 3 days" while Smart still ranks it by its month (#1778). A route from before usedRenews says when only for an account of one window. Affinity keeps a conversation on an account at 90–97%: only SpentShareOf (98%, 100% In order) stops it (affine), while the 90% tier (lowShare) orders only conversations nobody has answered.
  • A turn's end is told to the app for the "Task done alert" notification (itieniu on X, turndone.go). The trace follows each agent session's turn (turns, keyed by agent and session): a request is of the turn unless it has a Kind or is a Claude Code subagent's (agentTurnOf), and its reply is scanned on the way to the agent for a tool call in any wire format (toolScan, a JSON value such as "type":"tool_use" or "finish_reason":"tool_calls", never a key or text). The turn is done when no request of it is going, the last reply was whole, under 400 and called no tool, and nothing more came for turnQuiet (4s); a session idle past turnStale (30m) starts over. Only a turn that ran at least settings.TurnDoneAlert seconds is told (TurnDone, set by the GUI; nil under magpie serve, so nothing is followed). The ChatGPT backend path (codexBackend) is followed the same way. TestTurnDoneSaidAtTheTurnsEnd, TestTurnDoneCodexBackend, TestToolScan, turn-done.test.cjs.
  • A resting candidate is tried last (restLast). Of the resting candidates, a request asks only the one whose rest ends soonest, the first in order on a tie (probeOne, #1799). The others aren't asked by that request, so a member that is down isn't asked by every request its rest was meant to spare it from, and a group that is down whole takes one upstream request per request, not one per member. Every ready candidate is still asked in its order. A lone candidate is tried even while it rests, because there is no other. The trace still lists every member, the resting ones with their rest. Only rests are read, and a failure about the request's content or its model rests no member (a model refusal rests only restID), so neither leaves a member out. The same applies in count_tokens, embeddings and rerank, image accounts and a group's System One decision models. A Codex reset (autoReset) still looks over every candidate. This is like AxonHub's error-aware load balancing: the rest and its backoff are the penalty that decays, and the member back soonest is the one asked to show it is back. Keys out of their allowance aren't asked even so, not even the one back soonest or a lone one (#1772: four Ollama Cloud keys out for the week, each asked again and refused on every request). When every candidate left is a key (not a subscription account, whose resets autoReset may spend) resting out of quota or credit after a 429 or 402, none is asked. The first one's refusal is given again (quotaHeld, its words kept in the rest's said), saying when it is asked again. 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 vendor Retry-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 rests quotaRest (15 minutes), or the provider's own quotaRest in minutes (Provider.QuotaRestFor, at most MaxQuotaRest, 8 days; magpie provider quota-rest <id> 7d). A time the vendor names stands over it. A key listed in keys as well as in key is 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 fresh affine keeps only the candidates of that who (strictOnly): its other models stay, so a group's rules still pick among them, but no other account, key or provider is asked, and a resting or spent one is asked anyway. A failure there reaches the agent and rests the account as a non-lone candidate's would (strictAlone), so new conversations go elsewhere. Before planning, strictKeep takes the stuck account back from what holds new conversations off it: a usage cap (pl.capped, capHeldOnly), so the conversation goes on past it. An account held for credits it may not spend is answered 429 naming the account and Strict, and nothing reaches the vendor, rather than moved. An account removed, switched off, barred, or not allowed for the calling key is gone, and the conversation moves as under session. The trace says strict even with one candidate. strict_affinity_test.go, stays-strict.test.cjs.
  • In turn (rotate), a conversation nobody has answered yet goes to the key, account or model the fewest other conversations of the provider's model or the group answered in the last heldFor (30 minutes) are on (leastHeld, #946). Ties, resting ones 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: 401 token_revoked and the like, #1793) fails as failAuth: the next member is asked at once, nothing rests, and the account is marked (noteSignIn in signin_revoked.go). Its later requests aren't sent while it has that credential: forwardOnce answers them with a 401 of magpie's own (revokedReply), so they too pass on. Compaction on an account of magpie's (compactOn) picks a marked one last. A key's provider answering the same words rests as before.
  • A sub2api key out of its own limit answers 429 api key 7天限额已用完 (or 日限额, 5小时限额) as rate_limit_exceeded. It is out of quota (plannedWords), not rate limited: it rests till the window it filled renews when its windows as last read say so, else quotaRest, and its windows are read again (staleKeyAllowance). A reading that finds that window full no more (the limit raised in the relay's panel, or the key's usage reset) lifts the rest (renewed, told through provider.OnRenewed), as a Codex reset spent does an account's; the key's other rests stay. While it rests out of its windows, they are read again each time it is planned (restingOf, once a minute at most), so this holds where nothing weighs it by them: an ordered group. The relay out of accounts for everyone (503 No available accounts, or a later version's 429 All available accounts are currently rate-limited) says nothing of the key's windows: it backs off as any failure or rate limit does, never to the window. A key's windows count only its own spend, so other users draining the relay's accounts show up as those errors, not in the windows.
  • A 5xx is a server error, not quota, unless the vendor's own quota code says so (quotaCodes: usage_limit_reached, RESOURCE_EXHAUSTED, Claude Code's usage limit reached|<unix>). A relay's 500 "当前模型 gpt-5.5 负载已经达到上限,请稍后重试" names its load, not the key's allowance: it was read as out of quota by usedUpWords (上限), which rested the key till a reset and kept a group's Patience from waiting it out (#1418). The quota words (usedUpWords) still apply to a 4xx.
  • A 429 that names in words when the account is back (WorkBuddy's "将在 2026-10-11 20:16:02 UTC+8重置" and "your usage will reset at 2026-10-11 12:37:53 UTC+8, …", #1669) 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 than longestWritten (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's insufficient_quota alike (TestCreditsExhaustedIsOutOfCredit). On the rate-limit branch, a reset time the refusal names (resetsAt, or resetsHeader as keepRetry noted it) is believed up to longestQuota, as out of quota believes it, and the Routing page says it rests until then (resets); a Retry-After or a rate-limit reset header is still held to longestWait (an hour) (rateRest). The same rest runs for a plugin's requests: the WorkBuddy plugin passes these 429s on as they come (TestPluginWrittenResetRests). A JSON error body that escapes what isn't ASCII as \uXXXX (Python's json.dumps does by default) has its strings decoded before any word list (creditWords, rateWords, plannedWords, usedUpWords, resetsWhen, …) is matched (wordsOf), so an escaped 余额不足 or 用量 reads as an unescaped one does.
  • An account resting out of its window (a Claude account by the time Claude Code's refusal named, resets, or any by window) is back once magpie's reading of its windows (provider.Allowances) finds it full till sooner: the window used below SpentShareOf, or its reset passed, with no other window over the same models still full. The reading tells provider.OnRenewed as the account's UsageAgent and user, and renewed lifts that account's rests out of quota or by window; its rests for a rate limit, its credit, a verification or a failure stay, as a key's do, and so does every rest of other accounts still out of their windows. Planning reads every account candidate's allowance, ordered groups included, so this needs no step of its own in restingOf.
  • Only an account is held at a usage cap (capHeld) or rested out of one model's pool (pooled); a key's windows order it and rest it, nothing more.
  • Codex offers its image tool (the image_gen namespace, #870) to every magpie provider. When a provider other than a ChatGPT sign-in or openai.com answers a bare 400, attempt asks it once more without the tool (image_tool.go). This happens both passed through and translated. If that works, the provider is marked unfit for the tool (tool:image_gen) and isn't offered it again. If it doesn't, the tool is restored and the 400 stands (#949).
  • A turn the agent stopped with its tool call still out is replayed by the client with the call and no result, and Google's APIs turn a history whose call turn goes unanswered away with 400, every later turn of the conversation with it. The Gemini build (buildCodeAssistSent, which serves a Google sign-in, Vertex AI and a custom provider's Gemini API alike) answers such a call with the synthetic result the chat build pairs an interrupted turn's call with (pairToolMessages, #1275), right after the calls (pairFunctionTurns, #1560): beside the answers the client sent there, or in a user turn of its own before what the user said, since a turn mixing a functionResponse with text is turned away too (#1533); a Claude model on Antigravity gets it in the one tool_result turn. A call with no id counts as answered by a response of its name.
  • A 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 a tool_use the next message doesn't answer and for a tool_result naming no call of the message before it. A call left unanswered gets the synthetic interrupted result, is_error set, first in the user message after it or in one of its own; a result that answers no call goes as a text block with what it said (its images as they came); a second answer to one call is dropped. A well-formed exchange goes as it was built. An Anthropic client relayed to a Messages upstream isn't mended. anthropic_tool_pairing_test.go.
  • A Responses request bound for anything but a ChatGPT sign-in has its tool exchanges mended in attempt, before it is relayed or translated, plugins included (responses.go). An item inside a run of calls and results (after one of the run's results and before the last, or before any result when the model didn't write it) moves to the end of that run (joinToolRuns, #1752, Edward4226): Codex writes its <image_resize_notice> right after each result whose image it resized, so a batch of two calls had it between their results, and a strict upstream answered 400 (OpenCode Go/DeepSeek "No tool output found for tool call …", Volcengine's "must be followed by tool messages", #1822); a Chat translation answered the second call with a synthetic result. An item carrying a call_id never moves, the model's own reasoning 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's X-Models-Etag tagged with provider.CodexListTag so a change has Codex ask again. A Codex there only for account failover, not connected (CodexOwnOnly, agent.CodexOwnOnly; #1385), gets the backend's alone, tagged with provider.CodexOwnListTag; neither tag contains the other, so connecting or disconnecting has Codex fetch the list again. The user's picks on the codex provider (provider.CodexNativePicked) narrow the backend's listed models. They keep its hidden ones (visibility: "hide"), which no picker shows. One of those is codex-auto-review: when the list lacks it and no reviewer is set, Codex's auto-review runs on the conversation's model at low effort (#1460, TestCodexModelListPicksKeepHidden). The account's own models 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; spawnChoices drops 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; events KThinkStart, KSealed, KTextSig in ir.go), so each thinking block or reasoning item stays apart, whole or streamed, and a seal is written only for its own API (sealedBy). Anthropic's redacted_thinking goes back raw (to DeepSeek as a thinking block, below), and a thinking block signed with no text keeps its signature (aBlock still writes "thinking": "", #1447), on Claude's subscription too. A Responses reasoning item keeps its id, summary and encrypted_content, and goes back to a Responses upstream as it came when it has no reasoning text (sealedReasoning; text, another vendor's, is still left out for OpenAI, #1411). Gemini's thoughtSignature stays on the call it signed and on text; a later call of a signed step goes without one, and only an unsigned step or Claude on Antigravity gets skip_thought_signature_validator. Another API's agent gets the call's signature in its id, as on chat (#687), with its length in the mark (__ts<n>__), so an id a client shortened carries no signature and the call goes as unsigned (#1536); it gets no one else's seal. 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) unless store is true, because both look the id up among stored items and answer 400 "Item with id 'rs_…' not found" (#1008). Any other Responses upstream gets them, because a DeepSeek model wants its reasoning back (#388). When one answers 400 naming the input (refusesInput: param is input, or the error names an item by id), as a relay in front of OpenAI does with a message of its own, passthrough asks once more without them and, once that works, leaves them out for that provider and model from then on (bareReasoningRefused, #1044). Codex's compaction offers no tools, so it is relayed even when its turns were translated. When a provider answers its summary request 404, or 400 for an item it didn't find (itemNotFound, a relay in front of either), codexCompact asks 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, a compaction_trigger on /responses that wants exactly one compaction item back, on any provider table named "OpenAI", as CC Switch names its relay tables. magpie points those at /v1 while a magpie model is on, so handle makes the summary there too (codexInput, codexCompact), and magpie's summaries go back to the model as text (#1301).
  • A Responses request Codex sends a Responses provider is fitted for a backend that isn't OpenAI's before it goes (passthrough): Responses Lite's additional_tools item lifted into tools (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 set codexAsSent (magpie provider set <id> codex=as-sent) gets a request from Codex (fromCodex) as Codex sent it, its model name alone swapped, with Codex's own headers (codexClientHeader). 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>, userAgentFor in user_agent.go), except a provider set passUserAgent (#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's magpie/…, magpie-router/1, magpie-vision/1, magpie-search/1, and the image tool's <client> magpie-image/1, built from MCP's clientInfo, not a User-Agent), go as magpie; magpie never makes up another client's. forwardOnce sets it for chat, Anthropic, Responses, Gemini and count_tokens; embeddings, images and videos (retrieveFrom, sendWith, remoteVideoContent) set it with stampUA from the caller the request came with (caller.ua, withCaller), and before #1851 went with Go's default. Claude Code's and Codex's own headers are copied after, as before, and the user's header.User-Agent is put on when the request is signed, so it wins. provider.PassesUserAgent refuses it for a signed-in account, a plugin's, and a vendor whose own client magpie goes as (OwnClient: OpenCode, Cline, Kilo, another magpie); their signing sets their own. TestUserAgentPassedOn, TestUserAgentAccountUntouched, TestUserAgentFor, TestPassesUserAgent, provider-user-agent.test.cjs.
  • A Chat upstream that wants a turn's reasoning back (chatReplaysReasoning in chat.go: a host or a model, as magpie or the provider names it, with deepseek in it, such as OpenCode Go's deepseek-v4.1-flash, or Command Code's plugin) gets every assistant tool call with reasoning_content, relayed (withReasoningOnToolTurns in passthrough) or translated (buildChat). DeepSeek turns the whole request away ("The reasoning_content in the thinking mode must be passed back to the API") when a tool call made since the user's last message has none, which a client sends for a turn it saw no thinking on: another model's, a translated one (#1462). The turn's own thinking goes back as it came; one sent in reasoning or reasoning_details is copied in; 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) turns reasoning_details in a message away in any shape: an entry with a stream's index ("the reasoning_details at position 1 entry 0 must not contain streaming index") and any other entry ("… has an invalid type"), checked against api.kimi.com/coding on 2026-10-12. pi keeps another vendor's thinking there (MiMo's, through Command Code, with index: 0), so a conversation routed on to Kimi was refused on every turn (#1765). passthrough sends it to Kimi as reasoning_content (reasoningDetailsAsContent), which Kimi takes; a message with reasoning_content of its own keeps that. Another upstream that refuses a thinking field "at position N", as Kimi words it (a relay in front of it), is asked once more the same way and marked (refusedInMessages, withoutMessageReasoning).
  • A Responses upstream that wants a turn's reasoning back (replaysReasoning in responses.go: a model with deepseek in its name, on any host but OpenAI's, xAI's, Copilot's and Azure's) gets every reasoning item with a reasoning_text and every tool call after one, relayed (withReasoningText in passthrough) or translated (buildResponses). DeepSeek's /v1/responses turns the whole request away ("The reasoning_text in the thinking mode must be passed back to the API") over a reasoning item without text, one with an empty text, and a function_call whose step (since the last user message or tool output) has no reasoning item. Codex sends all three in a routing group that falls to DeepSeek after ChatGPT: the backend's sealed items (encrypted_content only), magpie's summary-only items, and another member's calls with none (#1104, #1592). DeepSeek reads a step (a run of reasoning, assistant messages and calls) as one assistant message whose thinking is the item it starts with: in the current turn, a step with a call or after a tool output must lead with a reasoning item, so [message, reasoning, call] and [output, message] are refused while [reasoning, message, call] and [output, reasoning, message] are taken (checked against api.deepseek.com on 2026-10-12). Codex sends a step that said something before its call with no reasoning for another model's turn, which magpie used to send [message, reasoning " ", call] and DeepSeek refused intermittently, only while the turn lasted (#1822, through OpenCode Go). An item's own text is kept; one without gets its summary, else a space (noReasoning); each such step leads with its reasoning (reasonFirst): its own first reasoning item moved ahead, else one holding a space. A sealed item keeps its id and encrypted_content; a body already in that shape goes byte for byte.
  • A Messages upstream that wants a turn's thinking back (anthropicReplaysThinking in anthropic.go: a host or a model with deepseek in it, never api.anthropic.com or a Claude model) gets a thinking block on every assistant message with a tool_use or right after tool results alone (refused the same way, checked 2026-10-12, #1822), relayed (withThinkingOnToolTurns in passthrough) or translated (build, which also keeps unsigned thinking as its text there). DeepSeek's /anthropic/v1/messages, thinking (its default, or asked for), turns the whole request away with 400 "The content[].thinking in the thinking mode must be passed back to the API" when such a message has none, and answers any redacted_thinking with 422, a block it can't read. Claude Code sends both in a routing group that falls to DeepSeek after Claude (#1611). A message with no thinking gets one holding a space (noReasoning) first; Claude's redacted_thinking becomes that block, or is left out beside thinking of the message's own. Signed thinking, DeepSeek's own and every other message go as they came. Checked against the real endpoint on 2026-10-11: it takes Claude's signed thinking, unsigned thinking and a space, anywhere in the message.
  • A 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 say number, 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 with grok (grokModel, grokServed), every number in a call's arguments written with a fraction of zeros and no exponent loses the fraction: 2500.0 becomes 2500, -3.00 becomes -3. Strings, keys, other fractions (2.5, 2.50) and exponents (1.0e3) stay as written. No tool schema is consulted, since JSON has one number type. The rule runs over the arguments as a stream of text (wholeNums), holding back only a fraction of zeros until the next byte. This gives the same arguments whether they come whole or in deltas cut anywhere, so what a call's deltas add up to is what its done events say. Relayed replies are rewritten in passthrough by intTidy: Responses' function_call items, argument deltas and done events and the completed response; Chat's tool_calls deltas and messages; Messages' tool_use input and input_json_delta, streamed or whole. Translated replies are rewritten at the encoder (wholeEncoder, outside usageEncoder) and at render (wholeResult) when Request.Grok is 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 by parseTextCalls. Each block must name an offered tool and have arguments that can be read; else the text goes on as it came. The text before the first block is kept, what is left of the tags goes, and the reply ends as one that called tools (finish_reason tool_calls, stop_reason tool_use). A 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 under text/plain or no type (chatWhole with wholeTextCalls, #1845: a stream:false request kept the markup and finish_reason stop), which also covers a vendor that answered a streamed request whole (wholeAsStream), 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 by TestTextWritten*, TestGLMTextCall*, TestPluginTextWrittenCall and TestQuietWholeReplyStreamed.
  • Structured output is carried across every translation (Format, format.go). It is read from Responses' text.format, Chat's response_format, Anthropic's output_config.format and Gemini's responseMimeType with responseJsonSchema/responseSchema: json_schema with its name, description, schema and strict, or json_object. Each upstream is asked in its own field: text.format on Responses, response_format on Chat, output_config.format on Messages, and generationConfig.responseMimeType/responseJsonSchema on Gemini and Code Assist. An API with no name for it gets response. Messages and the Claude subscription's --json-schema take a schema only, so json_object is told in the system prompt there (inSystem). 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 (toolOutput in ir.go reads them from Anthropic's tool_result, Responses' function_call_output, such as Codex's view_image output [{"type":"input_image","image_url":"data:…"}], and a Chat tool message). Anthropic's Messages keeps them in the tool_result. Chat, 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's tool-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 :effort suffix, then the turn's pick (a routing rule's), then the agent's pick, then the request's own. A model that doesn't reason is sent as asked; the default (none picked) leaves every request as it came. The pick beats the request's own because Cursor sends its own default as often as a real choice. Picking Default hands the choice back to Cursor.
  • Gemini's OpenAI-compatible API (AI Studio's, or a proxy in front of Gemini on this computer or the LAN: geminiCompat) is asked for the model's thoughts in extra_body.google.thinking_config. A 400 or 422 whose error names extra_body, include_thoughts or thinking at all (refusesThinkingConfig) marks the provider unfit for the field (thinking_config), and it is asked again with reasoning_effort alone. Gemini 3 can't stop thinking, so reasoning turned off goes at minimal, its least, or at the model's lowest level where it has no minimal (geminiLevels: those of the model's levels it hasn't turned away, or of Gemini 3's where its own aren't known or none is left). Gemini 3 turns away a level the model hasn't with a 400 that names the level (geminiRefusedLevel): AI Studio's "Thinking level MINIMAL is not supported for this model. Please retry with other thinking level." for gemini-3.8-flash, Vertex AI's "Thinking level is unsupported: THINKING_LEVEL_MINIMAL". It names thinking too, but isn't the field turned away. The level is marked refused for that model (levelRefused), and the model is asked again at the nearest level it has left, still for its thoughts, and at that level from then on. A level turned away again, with none left, is the client's 400. Passed through, a Chat client's own none or minimal that Gemini turns away this way is asked again at the model's lowest level (onEffort), and that level goes at the lowest from then on (turnedAway); the other still goes as sent, as AI Studio takes none from gemini-3.8-flash. A refusal that names the levels the model takes (effortLevelsNamed, Command Code's for Qoder's none) marks reasoning off as a whole (offRefused): both go at the lowest from then on; one that lists the other among the levels taken (otherOffNamed, quoted, OpenAI's for gpt-5.1's minimal) marks only the level turned away. Both routes read and write the same marks. Vertex AI's OpenAI-compatible API marks each streamed chunk of thoughts in the delta's extra_content.google.thought, and such a chunk is read as thinking.
  • A Claude that thinks only adaptively (adaptiveOnly in anthropic.go: Opus, Sonnet and Haiku from 4.6 on, Fable and Mythos 5 and 5.1, read by claudeVersion however a relay spells them) is never sent a thinking budget, which they answer with 400. magpie's own request from a Chat or Responses client (buildAnthropic) goes as thinking: {type: "adaptive", display: "summarized"} with the effort in output_config.effort, so the client sees the reasoning Opus 4.7 and later otherwise leave out (display omitted by default), and a relay that refuses display is asked again without it (refuseShapes), as is one that refuses auto mode's safeguards (Copilot's Messages API: 400 "safeguards: Extra inputs are not permitted" on claude-opus-5.5, #1756; shapeSafeguards, TestSafeguardsRefusedLeftOut), and neither is sent it again while magpie runs; a client's thinking: {type: "enabled", budget_tokens} is turned into the same in forwardOnce (adaptiveThinking), the budget as its nearest effort, above high as max, and display: "summarized" unless the client named its own display, so the thinking that enabled shows stays shown (the refused shapes are taken out after it, and refuseShapes reads the display as it is sent); and Pi, dsh and omp are written to ask it adaptively (AdaptiveThinking: forceAdaptiveThinking, omp's anthropic-adaptive; #1470). A client's xhigh goes as xhigh, except to Opus and Sonnet 4.6, which have no xhigh and are asked max (noXhigh, #1471).
  • A request to an Anthropic endpoint that turns thinking off is sent as the model takes it (thinkingOffAsTaken, in forwardOnce, so relayed requests, count_tokens, magpie's own thinking-off and retries all get it; the model is read as the vendor names it, from the body, or from the path for Bedrock and Vertex). Claude Sonnet 5.5 refuses thinking: {type: "disabled"} and is sent {type: "between_tools"} alone, at effort high at most. Opus 5.5, Fable 5 and Mythos 5 refuse it at every effort and are sent no thinking, at effort low unless one was asked, with classifierRoom added to a reply limit below it, as Claude Code does. Opus 5 and Haiku 5.5 take it only up to high, so xhigh and max are asked as high. between_tools sent to any other Claude goes as disabled, or as none where that is refused too. Other vendors' models, older Claudes and later lines than these go as they came (#1454). A Sonnet 5.5 by a name these rules can't read, answering 400 that asks for between_tools (asksBetweenTools), is asked again with it, once; a refusal of disabled at any effort (thinkingOffRefused) is asked again with thinking left to the model, as alwaysThinks is. So is a relay that reads disabled as reasoning effort none and turns that level away naming the ones it takes (Sub2API's gpt-6.1-sol, "does not support reasoning effort "none"; use low, medium, high, xhigh or max", #1465); refusesThinkingOff is the one list of these refusals for both routes. A relayed request refused so marks the model (markUnfit(offRefused)), and its later requests go with thinking left to the model at once until magpie restarts, as auto mode's classifier asks on every action.
  • A Chat or Responses client's reasoning turned off (none, ThinkOff), translated to an Anthropic endpoint (buildAnthropic), goes as thinking: {type: "disabled"}; it went as thinking at a 4096-token budget before (#1636). A model that refuses it (refusesThinkingOff: alwaysThinks, mandatoryReasoning, thinkingOffRefused, or none turned away naming the levels taken) is asked again at its least (thinkingBackOn), and markUnfit(offRefused) sends it so at once until magpie restarts. A translated request's level can differ from the one asked: none and minimal go as low where the model's levels don't say it stops (effortOf). The route keeps the level asked; the try, the usage log and Routing's "went" say the one built (noteWireEffort, wireEffort in wire_effort.go). Gemini's builders say theirs their own way and are logged as asked.
  • A request to an Anthropic endpoint with temperature, top_p or top_k reaches a model that refuses them without them (samplingAsTaken, beside thinkingOffAsTaken in forwardOnce): Opus 4.7, 4.8, 5 and 5.5, Fable 5, Mythos 5, Sonnet 5 and 5.5, and Haiku 5.5, whose 400 is "temperature is deprecated for this model" (Claude Code's auto mode classifier and magpie's own classifiers ask at temperature 0). Older Claudes, Haiku 4.5 among them, other vendors' models and later lines go as they came (#1454). A Claude by a name these rules can't read, answering that a sampling parameter is deprecated (samplingDeprecated), is asked again without them, once — a Chat or Responses client's request translated to Messages (forwardTranslated) as much as a relayed one.
  • Claude Code's auto mode asks the API to review each action (automode.go, Anthropic's auto-mode-classifier-billing): the dangerous-tool-use-… beta, a safeguards field, and safeguard_results in the reply (a stream's in its message_delta). Only Anthropic runs that classifier, so they reach only a route it answers on (AutoModeReviewed): the Claude subscription (the bridge hands them to Claude Code's own binary), a Claude model under any vendor's spelling (Anthropic's API, a relay, Bedrock, Vertex), and anything on api.anthropic.com. There the beta, safeguards and the results pass as sent, a whole reply's results moved into a stream's message_delta (anthropicWholeEvents), tool-use ids unchanged. 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, cch changing every turn) goes on only to a Claude model asked on Anthropic's Messages API (keepsBillingLine in billing_line.go: Anthropic's, a relay's, Bedrock's), as Claude Code sent it. Anywhere else it is left out, the rest of the system as sent (withoutBillingLine): a vendor's model relayed on Messages (passthrough), every translation to Chat, Responses or Gemini (forwardTranslated, Claude models too), and the subscriptions asked through their own clients' APIs (Cursor, Devin, Kiro, Qoder, Zed, Command Code's Go plan, in attempt). Kept, a vendor read it as the prompt's first words and its prefix cache missed from byte 0 every turn (#1600, justrun1983: 4% read from DeepSeek's cache behind Command Code's plan). The Claude subscription's run sends its own (withoutBillingHeader), another magpie decides for the provider it picks, and Code Assist (Antigravity, Gemini CLI) is sent it as before, which antigravityTurnsAway reads (#666).
  • A model that refuses a conversation ending with the assistant's message (refusesPrefill: OpenCode Go's Claude models over Messages, "This model does not support assistant message prefill"; Volcengine's Agent Plan, "…for a model that does not support prefill"; Gemini's, "Requests ending with a model turn are not supported") is marked for that provider, model and API (prefillRefused, #1447); the provider's other models keep their prefill (prefill.go). A Chat or Responses client's conversation ending with the assistant's message, which those APIs read as a turn already said (Request.LastIsTurn), is asked again with a user turn after it (continueText), translated (forwardTranslated) or relayed (passthrough, userLastBody), and so from then on. An Anthropic client's prefill is its own ask and gets the refusal as sent. magpie's own continuation of a cut reply (continuation.go) isn't asked of that model again; the try the model refused ends the reply with what cut it, not with the refusal. A request magpie builds in Gemini's own shape (buildCodeAssistSent: Vertex AI, Gemini CLI's and Antigravity's Code Assist, Factory) never ends with the model's turn, which all of them turn away: a user turn goes after it, continueText, or compactLastText when an agent is compacting with its ask in the system prompt (modelLastAsk), as one goes before a history that opens with the model's. Nor does it send a user turn that mixes a tool's functionResponse with text, which Vertex AI answers with the same "ending with a model turn" (#1533: Codex's compaction prompt after a tool's output): what the user said goes in a user turn of its own after the tools' responses (hasResponse), except for a Claude model on Antigravity, whose tool_result turn holds both.
  • A model's reply limit is published within the window beside it (#1438, provider.OutputWithin, Entry.PublishedOutput): /v1/models' max_output_tokens (modelObject), Cursor Private Inference's capabilities.max_output_tokens (cursorLocalModel), Muse Code's limit.output (museModels), the GUI's model and group rows (providerInfo, providersState), magpie model output, and every agent's file (agent.maxTokens, #338). The window and the output can come from different sources: Grok's backend lists grok-4.7's 256000 window, and models.dev fills its 500000 output (catalog.Decorate and Provider.replyLimit fill an output only where the vendor gives none). An unknown window or output is published as it is. The catalog keeps the unclamped Entry.Output, and a group's member is still asked for no more than that (outputLimit, withMaxOutput), so a request isn't lowered by the clamp. A limit the user set stays in their settings as they set it (TestModelListsKeepOutputWithinTheWindow).
  • A request that names no reply limit, translated to Anthropic's Messages API, which needs max_tokens (forwardTranslated; a Zed subscription's Claude in serveZed), is sent the model's published limit (askedOutput in maxoutput.go): the user's Max output, else the vendor's list or models.dev, within the window. anthropicBody's defaultMaxTokens (16384) is left only for a model whose limit isn't known. Every Codex turn on a Claude went at 16384 before, and a long thinking and tool turn ran out of it: stop_reason: max_tokens reaches a Responses client as incomplete_details.reason: "max_output_tokens" (#1792, tensornull). A limit the client names goes as it is. The thinking budget fits under the filled limit as under one the client named (TestAnthropicMaxTokensIsTheModels).

Remote magpie APIs

A remote provider serves the conversation, token-counting, System One, embeddings, rerank, image generation/edit and video creation/status/content APIs. Gemini clients enter through the local Gemini adapter and follow the same model routing as other conversation clients. Responses uses HTTP/SSE; its WebSocket route still answers 426. Discovery and older-peer behavior are described in Providers and accounts. GET /v1/magpie/limit (keyLimit in key_limit.go) answers the limit of the gateway key the request carries (access.Caller) and of no other: it reads nothing from the request but its key. A local magpie asks it with each of its remote-magpie keys for that key's card on its Usage page (#1547).

System One uses RouteDecider and postDecide in decide.go, taking one provider prefix off at each hop and preserving the state, questions and vendor errors. A model naming a group of decision models (provider.Group.Decides: every member a decision model; cleanDecisionGroup in decide_group.go refuses a mixed one, one inside a chat group, and patterns, rules, effort or fast mode on it) goes to serveDecisionGroup in decide_group.go instead (decisionGroupOf: group/<id>, or a group's id or name by GroupFor). It plans the members' keys and accounts with planGroup (perKeyBarred keeps a decision-only provider's keys: DecidesModel), applies a gateway key's model and account limits and pause rules as for a chat, and tries each candidate in turn: a retryable failure that is not the request's own (shapeRefused, promptRefused, protectionRefused) rests it (decideFailed → restAfter) and the next is asked; the last one's answer is passed on. Every try is a Try of one route; one usage row is written for the answer. A group classifier of decision models fails over the same way (askDecisionGroup, decideRefused carrying the vendor's status). A decision group is kept out of the agents' catalog (groupEntries), and a conversation asked of it is refused 400 pointing at /v1/systemone. embeddings.go relays retrieval bodies and options, draw.go sends images to the remote's images API, and video.go wraps remote task ids for later polls and downloads. passOnCaller in remote_magpie.go supplies caller/session headers without replacing the outgoing User-Agent. Conversation forwarding preserves Claude Code and Codex client headers (including Codex's originator) so relays behind the remote can recognize them. Decision, retrieval and media requests set magpie's User-Agent at their own call sites, so the remote accepts their attribution. Vendors receive no caller labels.

A custom provider (no account, no preset plan's videos) makes videos the same OpenAI way (#1446, customVideomakers), but only with the models its own fetched list marks "kind": "video" (catalog.LiveVideomakers); a name alone never makes a model a video maker. Start, poll and content go to videoBase (its Chat base, else its Responses base) + /videos, with 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.

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.

A search API's base URL

Each search API (provider.SearchAPI) has an optional url, its base URL: an endpoint of the user's own that answers as that API does (#1580). Empty is the vendor's own (SearchVendor.Base); SearXNG has none, so its URL is required. check takes only an http:// or https:// URL with a host and no ?query or #fragment, since askSearchAPI puts the vendor's path after it (/search, /res/v1/web/search, /v2/search) with the slash at its end trimmed. The request goes through the gateway's client, so it follows magpie's proxy settings as the vendor's own address does (TestSearchFollowsTheSearchersProxy).

The key is sent only to that URL. Go keeps Brave's X-Subscription-Token and Exa's x-api-key across a redirect to another host, so askSearchAPI doesn't follow one. The 3xx is the error, and it names where the search was sent. magpie ships and lists no third-party search endpoint; the URL is only ever the user's.

A value the user set is never replaced by the vendor's default. In Settings › Models › Web search the field sits under the key for every API, with the vendor's own address as its placeholder. Picking an API that is already added fills in its saved URL, so Add with a new key alone keeps the URL, and Add with no key changes only the URL. On the CLI, magpie search add <api> <key> keeps the URL set before, and url= with nothing after it puts the vendor's own back. Backup and sync carry url with the rest of the entry.

Covered by TestSearchAPIAtItsOwnBaseURL, TestSearchKeyStaysAtItsBaseURL, TestSearchAPIBaseURLFromSettings, TestSearchCLI and search-api.test.cjs.

Web search as an MCP server

SearchMCPPath, /mcp/magpie/web-search, serves the same webSearch a model that can't search is given (the searcher's model, a Kimi Code plan's service, the search APIs, as Settings › Models › Web search orders them) as an MCP server of its own, so Cursor, Claude Desktop or any agent can mount it as a web_search tool (Kayphoon on Discord). It speaks Streamable HTTP only: each POST of a JSON-RPC message or batch is answered with JSON (initialize, ping, tools/list, tools/call), notifications get 202, and GET and DELETE get 405, since the server has no stream or session of its own. Legacy SSE isn't served; a client that only speaks stdio mounts it through mcp-remote. The path has two segments under /mcp/, so it can't hide a signed-in server's /mcp/{name}.

It is a gateway route like the others. lanGuard takes a gateway key from another machine (only while magpie is shared) and refuses a rebound browser host, and the handler checks local/sharedWith again as a backstop when Handler is served without lanGuard. Unlike other routes, a web page on this computer (a localhost Origin, which corsGuard lets through) is refused too: only an origin listed in Settings, which corsGuard already held to a gateway key, may call it, as the MCP spec has a server check Origin. keyLimited passes /mcp/ by, so each tools/call reserves the calling key's limit itself (budget.Reserve), and a spent key's call is a tool error with no search made. The search is marked CallFor{Agent, MCP: true}, so Routing says the agent called magpie's web_search MCP tool rather than that magpie searched for one of its models. With nothing that can search, the tool error says where to add a search API. Settings › Models › Web search shows the address (#searchMcpRow, from the Settings page's own gateway address).

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

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 ./internal/provider ./internal/cli ./internal/gui -run 'TestDisabled|TestModelDisableCmd'
node --test internal/gui/tests/disabled-models.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.