Files
magpie/docs/subsystems/gateway-routing.md
T
yetone ac79966a6d agent, gateway: Claude Code knows a relay's claude-opus-4.6 as Opus 4.6, not the retired Opus 4 (misteer_ti.)
Claude Code 2.1.296 parses a Claude model id whose version has a dot
(relay/claude-opus-4.6-us[1m], as many relays name them) as Claude Opus
4: it warns the model is retired, asks with max_tokens 32000 and offers
no effort. The same id with dashes (relay/claude-opus-4-6-us) is Opus
4.6 to it: max_tokens 64000, adaptive thinking, effort.

What changed:
- provider/claudedash.go: ClaudeDashed (a Claude-family version's dots
  to dashes; other vendors' ids untouched), ClaudeSpelled (dashed only
  when that spelling comes back to exactly this served id), and
  ClaudeUndashed/ClaudeRead (a dashed spelling back to the one served
  id; an id served as spelled always wins, two ids dashing alike are
  neither; :level and [1m] kept). ClaudeRead also knows a switched-off
  provider's models, so Reseat still moves Claude Code off one
  (TestReseatOff went red without it: opus read "", not
  cop/claude-sonnet-4.5).
- agent/claude.go: every model magpie writes into Claude Code's
  settings is spelled so: model, the ANTHROPIC_DEFAULT_*_MODEL tiers,
  ANTHROPIC_SMALL_FAST_MODEL, CLAUDE_CODE_SUBAGENT_MODEL, modelPicker.
  Every read of them (env, claudeMain, claudeStandInAt) takes the
  spelling back, so fields, applied state and Drift keep the dotted id.
  The user's own values are stashed and given back raw. A Sync rewrites
  what an older magpie wrote dotted. claudeName, the capabilities env
  and the compact-window lookup see the dashed spelling.
- agent/t3code.go and gateway/desktop.go (claudeLooking): T3 Code's
  Claude slugs and Claude Desktop's Code-tab ids without efforts are
  spelled dashed too. Desktop entries with efforts still use the mythos
  alias, which Claude Code doesn't misparse.
- gateway.go: validateModel and unprefixed take the dashed spelling
  back to the served dotted id, before key limits, middleware and
  usage see it.
- docs/subsystems agent-wiring and gateway-routing say so.

What was run:
- New tests: TestClaudeDashedIDsReachTheDottedModel (gateway),
  TestClaudeDottedVersionsGoInDashed, TestClaudeDottedServedDashedToo
  (agent), TestClaudeDashedOnlyClaudeVersions, TestUndashInExactWins,
  TestClaudeSplitKeepsEffortAndMark (provider).
- Break-it checks:
  - With ClaudeSpelled/ClaudeUndashed made identity:
    TestClaudeDottedVersionsGoInDashed fails ("the main model and its
    followers": model relay/claude-opus-4.6-us).
    TestClaudeDashedIDsReachTheDottedModel fails (sent
    "claude-opus-4-6-us", want "claude-opus-4.6-us").
  - With ClaudeRead alone made identity, the agent test fails at
    "read back" (model:relay/claude-opus-4-6-us).
- Real use: the installed claude 2.1.296 in a sandbox HOME and
  CLAUDE_CONFIG_DIR, against an in-process gateway on a free port and
  a fake Anthropic upstream. The settings.json was written by
  agent.Find("claude").Apply("model", "relay/claude-opus-4.6-us").
  - Dashed (magpie's write): the upstream got model claude-opus-4.6-us,
    max_tokens 64000, thinking adaptive, effort high. Claude Code
    reported canonicalModel claude-opus-4-6, maxOutputTokens 64000.
  - The same config with the dotted id by hand: max_tokens 32000,
    canonicalModel claude-opus-4-0.
- Full go test -tags nogui ./... (TestReseatOff red on the first
  run, fixed as above; agent, provider, gateway and main rerun green),
  gofmt -l, go vet, and GOOS=linux and
  GOOS=windows go vet -tags nogui on the touched packages.
2026-10-10 19:44:26 +08:00

62 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} and the /v1/magpie/* status endpoints. A GET on /v1/responses (a client opening Responses over a WebSocket) is answered 426, a plain one 405: Responses is relayed over HTTP only. Every route is wrapped in counted, corsGuard, callerGuard, withCaller and keyLimited; /v1/messages, /messages and /v1/messages/count_tokens in keepsSignIn too. corsGuard (#1051) serves CORS only to the origins listed in Settings › Network › Web pages (settings.CORSOrigins, cleaned to scheme://host[:port] by settings.CleanOrigins, which refuses a wildcard). For a listed origin it answers the preflight (204) and adds Access-Control-Allow-Origin, and every other request from it needs an enabled gateway key (access.Authenticate), even on loopback, or gets a 401. It takes the key from the caller lanGuard recorded too, since on the running server lanGuard has already put magpie's own token in the key's place. Any other web page is refused 403 on every route (foreignPage): on loopback a call needs no key and the body's Content-Type isn't checked, so a page the user visits could otherwise send a "simple" text/plain POST and spend their subscriptions blind. Only an http/https Origin is judged, and one on this computer (localhost, *.localhost, 127.0.0.0/8, [::1], any port) or the request's own origin (its host and port equal to Host, such as a page on the gateway's LAN address) passes, as does usemagpie.ai on /v1/magpie/omarchy. null and other schemes (app://, file://, tauri://, vscode-webview://, chrome-extension://) come from desktop apps, webviews and extensions that don't enforce CORS, and pass. A request with no Origin (every agent's) passes through with no CORS headers, as before. A page whose own name resolves to 127.0.0.1 (DNS rebinding) would count as same-origin here, so lanGuard refuses it first (rebound, 403): a loopback request carrying a browser's marks (Origin, Sec-Fetch-Site/Sec-Fetch-Mode, a Mozilla/ user agent) whose Host isn't this computer's (an IP, localhost, *.localhost, a container runtime's name for the host such as host.docker.internal, MAGPIE_PUBLIC_URL's or MAGPIE_ADDR's host, the machine's own name) needs an enabled gateway key. Agents send none of those marks and pass under any name. gateway.go, cors.go, codex_catalog.go, internal/settings/origins.go
Model resolution serve resolves the model the agent asked for: Claude tier stand-ins, a routing group (provider.GroupFor: its id, the model's id however a vendor spells it, else the one group whose name it is, unless a provider serves a model by that id), auto stand-ins, then provider.Resolve. 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). A member's own fallbacks are not the group's. fallback.go
Order of keys and accounts Routing: smart (""), order, rotate, usage (least used, with an usageHalfLife of 1h), pace or weight (weightedFirst). Smart, usage and pace weigh a subscription by its allowance (allowances), and a key by its own usage windows when magpie reads them (keyAllowance: a sub2api key given a 5-hour, day or 7-day limit, or a key bought as a plan, such as Kimi Code's or a GLM Coding Plan's); any other key has none. A lone key or account is weighed against nobody, but what it has left is still read into the trace (weighRouted), so the Routing page shows it as it does for several (#1016); all but used up, it keeps its conversation rather than being said to move (affine). A failure rests a candidate (failure, failureOf). routing.go, weighted.go, internal/provider/routing.go
Limits Each key or account (a candidate's who()) has at most MaxConcurrency requests out at once (its own AccountConcurrency over it); one more waits in its lane's queue, bounded by QueueLimit and QueueWait and turned away with a 429 past either (lanes.take). MaxRPM (coeo91 on Discord: OpenRouter's free models take 20 a minute) bounds how many requests it sends the vendor in any rolling 60 seconds (rpms): one more waits for room in the minute, in the order they came, after it has its slot and right before it is sent. A wait that would be longer than 2 minutes (or the provider's QueueWait, when shorter: rpmWait) is turned away at once with a 429 whose Retry-After is when the minute has room; nothing rests for it. An agent gone while it waits gives its place back. Every request that reaches the vendor counts: each try of the candidate loop (a retry, the next key, a fallback) waits in serve, and the requests a try makes on the way and the gateway's own asks (count_tokens, System One's decisions, embeddings, drawing, Kimi's search) are counted by rpmTransport on s.client (metered, paidFor). count_tokens never waits: a candidate with no room is skipped, and the local estimate answers. A full lane or a minute with no room gives way to a ready key or account of the provider or the group (laneMate, ready); a fallback is never asked for want of either. A plugin's account sends through its own transport, so only its tries are counted, not a plugin's own extra requests. Set in the provider editor (Concurrency, Requests per minute, Queue size, Queue wait) or with magpie provider account-concurrency, queue and rpm; a subscription's are kept with its picks. concurrency.go, rpm.go, internal/provider/concurrency.go
Sink With Sink on, a key or account that answers 429 while it still has quota goes to the back, behind every one not rate limited since. Held in memory until restart. sink.go
Affinity A conversation stays with the key or account that answered it, so the vendor's prompt cache is read again. Modes: auto (""), session, turn, off. Stored in affinity.json next to providers.json. affinity.go
One try attempt sends one candidate the request. It goes through the proxy of the account or key it uses, else the provider's (p.Via, ProxyChoice: AccountProxies holds an account's by its name, a key's by its KeyID). A 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), 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) 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. 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. Only names are kept, never the text. It goes on the trace as Route.Prompt, with Route.Conv naming a conversation that has no session id. The GUI's /api/context scores each agent from it (internal/gui/context.go). prompt.go
Vertex AI A Google Vertex AI provider speaks Gemini alone. A request goes to <base>/publishers/google/models/<model>:streamGenerateContent?alt=sse (provider.VertexPath, upstreamPath), the model named as the user's upstream name for it says (UpstreamNameIn, which the usage log's endpoint names too), with no model or stream field in its body (passthrough, forwardOnce, geminiRequest). A Gemini client's request is relayed as it came, its own thinkingConfig, safetySettings and the rest kept: streamed there, asked whole to :generateContent (provider.VertexWholePath), which answers one JSON body (Factory's rule of translating a whole request, as its route only streams, isn't Vertex AI's). Every other API's is translated (buildFor, buildVertex) and its stream read by codeAssistDecoder, which gives thought parts as reasoning, never as the answer's text. Effort: vertexEffort fits it to the model's levels, reasoning turned off going as minimal fitted the same way, and holds a model whose levels aren't known to low…high. vertexThinking sends Gemini 3 a thinkingLevel (includeThoughts false with reasoning off) and 2.5 a thinkingBudget in the model's range (vertexBudgets): turned off, the budget that stops its thinking, or Pro's least, as Pro can't stop. Thought signatures are every Gemini path's (#1445): a call's signature reaches the client in its id (signedID) and goes back on the call it came on, while a call with none in a step Vertex AI signed goes without; a step with nothing to give back has every call sent skip_thought_signature_validator. A 400 Invalid thought signature. is asked again with every call sent so (withoutSignatures), for that request only. A 400 refusing minimal (geminiRefusedLevel) is asked again at the model's lowest other level (onEffort), and markUnfit(offRefused) keeps that level until magpie restarts. Both retries are the translated path's. Vertex AI's own Google Search grounding isn't used: searchHosts names only generativelanguage.googleapis.com for Gemini, so magpie searches for it (search.go). vertex.go, gateway.go, codeassist.go, gemini.go, gemini_signature.go, search.go

Runtime path

  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. The size limit holds for the decoded bytes (413), and any other encoding is refused 415. 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, 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.
    • DecidesModel gives a 400.
    • A gateway key held to some models (keyHolds, #882) gets a 403 for any other model.
    • Sealed tasks (#619) are checked here. A Codex subagent's task its lead's spawn_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). 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.
    • 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. Only a ChatGPT account's model can be set (provider.SetCodexSubagentModel), as nothing else reads the sealed task. When no ChatGPT account on in magpie serves it now, or a gateway key held to some models may not use it, the subagent goes on the model asked for. 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 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 and agents 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. rules_pause_test.go.
  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). 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 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. The vendor's safety filter refusing a reply rests nobody, whether it refuses the turn before any of the reply is said or once some of it has been said (refused, refusedAfter). The ChatGPT backend's 502 "response protection is unavailable" is about the request's content, not the account: the same history fails the same on each of its accounts and models. It rests nobody, isn't tried again after a moment, and isn't asked of the provider's other accounts or models; another provider left in a group is asked once (protectionRefused, elsewhere). One cause is known (#1270): a history that replays the backend's 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 (30s), and never shorter than the soonest Retry-After; a member whose Retry-After ends past the pause is asked after the others. This goes on for at most replanRounds (6) rounds and only while the group's Patience lasts, 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. 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 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 stream under a type that says neither JSON nor a stream goes through as it comes (sseStart reads its first bytes); a 200 that is no reply of the protocol's fails as a translated reply that didn't stream does (502, "… did not stream"), for the next candidate to answer, and the last one's reaches the agent as the stream's error. A held stream that has sent nothing but the frames before a reply (response.created, response.in_progress, codex.rate_limits, pings, an empty part begun: eventLead) stays held as long as its agent is kept alive, up 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").
  • 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. 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.
  • 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. 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 resting candidate is tried last, never dropped (restLast). A lone candidate is tried even while it rests, because there is no other.
  • Routing decides who goes first only when nobody has answered the conversation yet. Affinity keeps the answerer while its cache is worth it. Auto mode keeps it across turns while at least cacheWorth (1024) tokens were read from the cache and the cache isn't cold (cacheCold, 5 minutes).
  • In turn (rotate), a conversation nobody has answered yet goes to the key, account or model the fewest other conversations of the provider's model or the group answered in the 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 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.
  • 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).
  • 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).
  • 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, 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), and 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 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). A reply without tool calls, any other model and Mistral (#494) are sent as before.
  • 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).
  • 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.
  • 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); 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.
  • 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 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") 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 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).

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.

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. embeddings.go relays retrieval bodies and options, draw.go sends images to the remote's images API, and video.go wraps remote task ids for later polls and downloads. passOnCaller in remote_magpie.go supplies caller/session headers without replacing the outgoing User-Agent. Conversation forwarding preserves Claude Code and Codex client headers (including Codex's originator) so relays behind the remote can recognize them. Decision, retrieval and media requests set magpie's User-Agent at their own call sites, so the remote accepts their attribution. Vendors receive no caller labels.

A custom provider (no account, no preset plan's videos) makes videos the same OpenAI way (#1446, customVideomakers), but only with the models its own fetched list marks "kind": "video" (catalog.LiveVideomakers); a name alone never makes a model a video maker. Start, poll and content go to videoBase (its Chat base, else its Responses base) + /videos, with the vendor's own User-Agent and no caller headers. Its ids end with the key's fingerprint (customVideoID, markedKey), so a poll and its download go on the key that started the video. A gateway key's account and model holds apply to all three routes (videoAsker, videoModelHeld), and to Grok's and Volcengine's polls and downloads as well.

Turning provider search off

Settings' searcher: "off" disables magpie's provider-assisted search, including Kimi Code's search service and Google sign-ins' separate search requests. Configured Search APIs still run in their saved order; failures never fall back to a provider while this setting is off. Without a ready Search API, canSearchFor does not offer magpie's replacement search tool. searchesOwn is the one check for a provider searching for its own models (Kimi Code, a Google sign-in), so ownSearcher and the model list another magpie reads (webSearchOf, which then says no search) follow it too. A provider's native search on the client's protocol remains unchanged. An empty searcher still selects a provider automatically; an unavailable named provider still falls back to that selection.

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

Verification

go test -tags nogui ./internal/gateway -run 'TestLoop|TestLongReplyThatDoesNotLoop|TestQuiet|TestSilentHeld|TestRotateSpreadsSessions|TestRouting|TestSmartRouting|TestFallback|TestNoFallbackForOtherErrors|TestLastFallbackErrorReachesTheAgent|TestRateLimitedSinksToTheBack|TestGroupRateLimitedSinks|TestAffinity|TestSeveralKeysOnTakeOverFromEachOther|TestModelNotInPlanRestsTheModelNotTheKey|TestSubscriptionAccountsTakeOver|TestGroup|TestTrace|TestImageTool|TestCodexNoCredits|TestWindowCapsHoldTheAccount|TestAccountCap|TestClaudeGoesOnMessagesWhereTheRelayHasThem|TestAutoRelaysOnTheClientsOwnAPI|TestSearchOfferedStaysOnTheClientsAPI|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|TestClaudeFiveFiveThinkingOffOnTheWire|TestSamplingAsTheModelTakesIt|TestHaikuFiveFiveSamplingOnTheWire|TestGeminiThoughtsMarkedInExtraContent|TestGeminiThinkingLevelRefused|TestGeminiMinimalRefusedTwiceAtOnce|TestPassthroughGeminiMinimalRefused|TestPassthroughEffortNoneRefused|TestPassthroughMinimalRefusedNoneTaken|TestOtherOffNamed|TestClaudeSignInNotToldItsSignInFailed|TestSignInWriterReleasesA403|TestSignInBetaStaysWithMagpie|TestStructuredOutput|TestResponsesTextKeepsVerbosityBesideFormat|TestRefusedFormatToldInWords|RPM|TestQueued|TestCustomGeminiUpstream|TestWholeNums|TestGrokCalls|TestOnlyGrokCalls|TestGrokModel|TestGrokPluginCalls'
go test -tags nogui ./internal/gateway -run 'TestVertex'
go test -tags nogui ./internal/gateway -run 'TestRemoteMagpie|TestRedactedKinds'
go test -tags nogui ./internal/redact ./internal/gui -run 'TestMoreKinds|TestCategoryDefaults|TestRedactKindsAreRedacts'
go test -tags nogui ./internal/gateway -run 'TestCodexModelList|TestCodexModelsEtag'
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.