MOMO's {"model":"glm-5.3"} was answered by opencode-go though a6api
serves glm-5.3 too, and they asked for a 409 or for the response to say
which provider was used. The pick was already deterministic, but
Resolve's comment said "exactly one provider" and no doc said what
happens.
Decision: keep serving bare ids, no 409. magpie writes only
provider/model ids into agents' configs (agent/route.go magpieModels),
so a bare id comes from a user's own config, and a 409 would break every
such client the day a second provider adds the model. The rule is now
written down and pinned:
- found groups on (the default): GroupFor takes the bare id to its found
group auto-<slug>, members in the Providers order, smart routing and
fail-over to the next provider; a conversation stays with the member
that answered it while its cache is worth it (affinity).
- found groups off: Resolve takes the first provider in the Providers
order that exposes it, alone.
- every reply already carries X-Magpie-Provider / X-Magpie-Model
(member.go), and the usage log has the provider.
What changed: Resolve's comment; gateway-routing.md model resolution
row; reference.md, the ways a model is named and the headers;
bare_slug_test.go: two providers serving glm-5.3, both modes: the first
in the Providers order answers every new conversation, reordering moves
new ones, an answered one stays in the found group, and a 503 from the
first falls over only in the found group. It passes on the old code
too: it pins behaviour that was already there, now documented.
Run: gofmt -l; go vet -tags nogui on darwin, linux, windows for provider
and gateway; go test -tags nogui ./internal/gateway ./internal/provider
in a sandbox HOME.
45 KiB
Gateway routing and fallback
The gateway is magpie's local LLM endpoint (127.0.0.1:3425 by default). It
serves Chat Completions, Responses, Anthropic Messages and Gemini. It finds
the provider, key or account and model for each request. When the upstream
doesn't speak the agent's API, the gateway translates. When an upstream
fails before any of the reply is sent, the gateway moves to the next
candidate.
This page covers how a request is routed. Plugins that change requests and replies are in Gateway middleware. Subscriptions served by a plugin are in Provider and plugin ownership.
Responsibilities and sources of truth
| Part | Responsibility | Source |
|---|---|---|
| Address and caller | DefaultAddr. The local token magpie and the per-agent magpie-<agent> (TokenFor). agentOf tells which agent asked, first by token, then by User-Agent. |
gateway.go |
| 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. There is no Host check, so a page whose own name resolves to 127.0.0.1 (DNS rebinding) counts as same-origin. |
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. 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 |
| 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 |
Runtime path
handle(proto)reads the body and the model (requestBody,requestModel), then callsserveAgent. Every route that reads an agent's body (each API, count_tokens, Gemini's, embeddings, images, videos, System One, the Codex backend path) reads it throughreadBoundedRequestBodyinrequest_bounds.go. It decodes aContent-Encodingofgziporzstd(decodedBody; Codex sends zstd to a custom provider's/v1/responsestoo, #1223) and drops the header, so the provider is sent plain JSON. The size limit holds for the decoded bytes (413), and any other encoding is refused 415.keyLimitedreads a limited key's compressed body the same way, so its reservation is the decoded size.serveAgentruns the middleware chain, thenserve.serveredacts secrets in the request (redacted;redact.MaskJSONleaves ids alone, 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.DecidesModelgives 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_agentsealed goes only to a ChatGPT account, or back to the Responses provider that answered the lead (leadProvider, a relay of the ChatGPT backend such as Sub2API, #1109), relayed as it came even when web search is offered. A lead's turn carrying its subagent's sealed reply (send_message) goes back to the Responses provider that answered the lead's own conversation (leadProviderof the request'sconversationID, #1237); otherwise it is refused before anyone is asked (sealedReader,sealedTaskError). Who answered is first what affinity remembers; when affinity has let it go (a day since, a restart past the 512 conversationsaffinity.jsonkeeps, or the lead's last reply broken off,unanswered), the usage log's answers to the lead's thread and the request's own conversation in the last 30 days count too (loggedAnswers, #1367), andleadFirstreads the lead's key or account from them. A refused or failed call and a title answer nothing, and Codex's own sign-in is told of as the ChatGPT backend. The refusal names who sealed the task when it is known, and says how to go on with it. - A model set for Codex's subagents (
settings.CodexSubagentModel, the Agents page's Codex "subagent model", willz on Discord) is put on a Codex subagent's request (x-openai-subagentread askind:collab_spawn) before this check, whatever model its lead'sspawn_agentasked for (codexSubagentPickincodex_subagent.go): incodexBackendfor one of Codex's own bare models, which then goes throughserveAgent, and inservefor any other. 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'skindWhysays it. The lead's turns, titles and every other kind are never moved. - Rules and image inputs are handled here too.
- Candidates come from
planGroupfor a group orplanfor a provider. They are filtered bysealedReadersandallowedCandidates. An account past its share is held out of the candidates (capHeld): a usage cap's share, each window at its own where the account gives it one (AccountWindowCaps, willz on Discord: 50% of the five hours, 40% of the week) and at the account's cap otherwise, or 100% of a window for a Codex account set not to spend its credits (provider.HoldCaps,WindowCaps.Of,CodexNoCredits). The account is held while any window is past its own share, andcappedErrorand the trace name the fullest such window's share and cap. When every candidate is held and one held for its credits spends its resets by itself,autoResetspends a reset on it and it is tried (planned.held); otherwise a capped or barred set returnscappedErrororbarredError. Thenaffinemoves the conversation's last answerer first, unless it is resting or nearly used up. AnX-Magpie-Accountheader (AccountHeader) pins the request to one account: only that account is tried, and when it can't answer the caller is told why. - The candidate loop calls
attempton each candidate in turn, through aholdWriter. The writer holds the reply until it is clearly passing. A candidate that fails before anything is sent rests (failure): out of credit for 30 minutes, out of quota until reset, rate limited until retry-after, otherwise a minute and longer on repeats. A 400, 403, 404 or 422 that says the model isn't served (unservedWords) and says nothing of quota, credit or a rate limit rests only that key's or account's model (modelRefused, keyed byrestID, its backoff counted apart): its other models are still served first in order (#1235, SenseNova's 403 "model is not available in the current token plan"). A 400, 404, 410 or 422 that says the model is retired (retiredWords: OpenCode Zen's 410ModelDeprecated"Model exo-free has been deprecated.", whose own model list still names it; MOMO on Discord) rests only that model the same way, is retryable so a group's next member or another provider of it is asked, and is remembered (provider.Retire,retired.jsonbesideproviders.json): the model leaves that provider's entries in the catalog (buildEntries), so /v1/models, every agent's model list and the found groups go without it, until a request on it is answered again (UnretireinservedCandidate) or a week has passed. A refresh of the vendor's list doesn't bring it back early, since that list is where it still is. Aprovider/modelrequest for it is still sent. A subscription account that fails any other way with a window full, by magpie's latest reading of its windows, rests until that window renews. Both quota rests and window rests are held tolongestQuota(8 days), so a reset time read wrong (a year off) doesn't bench the account for that long. The next candidate is then tried. A failed provider waitsfallbackCooldown(1 minute) at the back. 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 ownweb_search_callin a request that doesn't declare theweb_searchtool is refused so, whatever the account, model or turn (a plain turn, a thread's description, a compaction, Codex's own text compaction for a custom provider withtools: []). Every request to the ChatGPT backend with such a history therefore declares cached-only search ({"type":"web_search","external_web_access":false},provider.DeclareSearch): an account's incodexBody, Codex's own sign-in relayed incodexUpstreamOn. It goes in the tools, or for Responses Lite (its header,reasoning.contextall_turns, or anadditional_toolsitem already there), which refuses a top-levelweb_search, in theadditional_toolsitem. A request that offered no tools getstool_choicenoneso the model can't search; one with a forced choice keeps it. A history without a search, or a request that declares search already, is relayed unchanged. siwc, API-key requests to openai.com and the legacy/responses/compactare left as they were. - The last candidate's error reaches the agent. 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, anapi_errorsaying " refused magpie's credential (HTTP 401): …" with x-api-key said as "API key", and any other error such a request is told keeps its status with x-api-key said as "API key", as does a stream's error after its 200 (keepsSignIn,claude_signin.go). Recent calls and the usage log keep the provider's status and message. Any other 403, and a request with magpie's key or an API key, is answered as before. The sign-in's beta (oauth-…inanthropic-beta) isn't passed on either (askedBetas), so a provider gets the request as Claude Code with magpie's key sends it; a provider's ownheader.anthropic-betastill goes. - A 2xx that can't be an API's answer is the 502 it stands for (
notAnAPIReply, #1012): a web page (text/html, or a body that begins as one: a sign-in page, Cloudflare's challenge), a body with nothing in it, or one sent as JSON that doesn't begin as JSON. Every upstream request goes through it (forwardOnce, and the built-in clients' own: the ChatGPT backend's/responses, Kiro, Zed, Qoder, Devin, Cursor, Command Code), so it fails over, rests and is logged as a 502 does, its reason naming the page's title. Only the first bytes are peeked, which a stream waits for anyway, and a compressed body is left as it came. - A streamed request is never left silent while its vendor says nothing.
holdWriter.watchruns beside each try: pastkeepHeldAfter(15s) it sends a held try's agent the stream's 200 and SSE comments (keepAlive), none of the try, so another candidate may still answer in the same stream; once the reply passes, it puts a comment between two of its lines afterkeepaliveEveryof quiet. It stops afterkeepaliveLongest(5 minutes) with nothing from the vendor. A try waiting for its key's or account's slot or for room in its minute (lanes.take,rpms.wait) is kept alive the same way (keepQueued), for as long as it waits; once the 200 is out, the try is held, and its failure or its queue turning it away reaches the agent as the stream's error (failTo), not a status (coeo91 on Discord). A wait shorter thankeepHeldAftersends nothing, so its 429 keeps itsRetry-After. A proxy in front such as Cloudflare (125s) otherwise ends the request (#947). Gemini streams get no comments (#934). A vendor that then ignoresstream:trueand answers 200 with its reply whole has it sent as the agent's stream (wholeAsStream: Chat, Responses, Anthropic), not as the stream's error, while a stream under a type that says neither JSON nor a stream goes through as it comes (sseStartreads 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. - Claude's, GPT's and Gemini's reasoning is held (
refusesAfterThinking, up toholdThinking, 4 minutes) so that a refusal after it goes to the next candidate unseen (#248). It is held only while one could: on the last candidate a refusal isn't asked again, so Claude's and GPT's reasoning streams as it comes there, and a refusal after it reaches the agent as the vendor's own. Held there, a lone relay's Claude or GPT showed Claude Code its thinking all at once with the text, and Codex none until then (iTianbao on X). Gemini's stays held on the last candidate too, for a reply that only reasoned to be asked again (#667). Any other model's reasoning is never held. - A streamed reply stuck in a loop is ended, not let run to its output limit (#1359, Moody-Sin: WorkBuddy's DeepSeek v4.1 flash reasoned round "Now." "Writing." "Go." "Let me write." "OK." until max tokens while dsh and Pi waited).
holdWriter.Writefeeds every streamed try, passed through or translated, a key's, a built-in subscription's or a plugin's (a moved WorkBuddy's fetch in the plugin host,TestLoopEndsWorkBuddysReply), in each of the agent's protocols, to aloopGuard(loop_guard.go). It cuts the reasoning and the text, each apart, into units, its lines and sentences (a list's1.or a decimal is no sentence's end), compared without case or a closing stop. A unit with no word in it (a letter run with no digit: not a brace, a rule,0x00, a hash or a row of numbers) isn't counted. When the lastloopWindow(256) counted units of either are among no more thanloopDistinct(24) different ones, the try is cut (cutLoop): what came with that write goes out, then the protocol's stream error (streamError, 502) naming the loop and quoting its units, and the vendor's request is cancelled. It falls back to nobody and rests nobody (failLoop); its usage record's error type isreply_loop. A cycle need not be exact. Code, tables, lists, logs, CSV and base64 differ line to line or have no words, and don't trip it (TestLoopGuardLeavesOrdinaryRepliesAlonefeeds magpie's own sources and docs through it). A reply sent whole (no stream, or Gemini withoutalt=sse) isn't read. Settings › Models › Replies › Stop looping replies (noLoopGuard) turns it off. - 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%: onlySpentShareOf(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 lastheldFor(30 minutes) are on (leastHeld, #946). Ties, resting ones and a group with a group in it keep routing's order. With session affinity, two sessions of one group so stay on different models. - A ChatGPT account that holds credits answers past its windows on them; the vendor spends them. That is the default. Set not to spend them (Usage card's Use credits,
magpie quota credits <account> off), the account is held at 100% of a window till it renews, by magpie's latest reading of its windows (provider.Allowances, refreshed about every minute), so the other accounts, groups and fallbacks take the request. A cap set on the account (1–99%) takes precedence. Unlike a cap, the hold is at the vendor's own 100%, so an account allowed to spend its resets spends one there, both when every candidate is held and after the last one is refused. A reset made forgets the account's cached allowance (renewedNow), so neither hold outlives the windows it started again. - Different failures are classified separately: out of credit, out of quota, rate limit and other errors rest for different lengths. A fix must not merge them into one bucket (see #873).
- A sub2api key out of its own limit answers 429
api key 7天限额已用完(or日限额,5小时限额) asrate_limit_exceeded. It is out of quota (plannedWords), not rate limited: it rests till the window it filled renews when its windows as last read say so, elsequotaRest, and its windows are read again (staleKeyAllowance). A reading that finds that window full no more (the limit raised in the relay's panel, or the key's usage reset) lifts the rest (renewed, told throughprovider.OnRenewed), as a Codex reset spent does an account's; the key's other rests stay. While it rests out of its windows, they are read again each time it is planned (restingOf, once a minute at most), so this holds where nothing weighs it by them: an ordered group. The relay out of accounts for everyone (503No available accounts, or a later version's 429All available accounts are currently rate-limited) says nothing of the key's windows: it backs off as any failure or rate limit does, never to the window. A key's windows count only its own spend, so other users draining the relay's accounts show up as those errors, not in the windows. - An account resting out of its window (a Claude account by the time Claude Code's refusal named,
resets, or any bywindow) is back once magpie's reading of its windows (provider.Allowances) finds it full till sooner: the window used belowSpentShareOf, or its reset passed, with no other window over the same models still full. The reading tellsprovider.OnRenewedas the account'sUsageAgentand user, andrenewedlifts that account's rests out of quota or bywindow; its rests for a rate limit, its credit, a verification or a failure stay, as a key's do, and so does every rest of other accounts still out of their windows. Planning reads every account candidate's allowance, ordered groups included, so this needs no step of its own inrestingOf. - Only an account is held at a usage cap (
capHeld) or rested out of one model's pool (pooled); a key's windows order it and rest it, nothing more. - Codex offers its image tool (the
image_gennamespace, #870) to every magpie provider. When a provider other than a ChatGPT sign-in or openai.com answers a bare 400,attemptasks it once more without the tool (image_tool.go). This happens both passed through and translated. If that works, the provider is marked unfit for the tool (tool:image_gen) and isn't offered it again. If it doesn't, the tool is restored and the 400 stands (#949). - Codex's model list from the backend path (
codexModels) is the ChatGPT backend's for its sign-in and then magpie's (provider.CodexListed), its ETag and every reply'sX-Models-Etagtagged withprovider.CodexListTagso a change has Codex ask again. A Codex there only for account failover, not connected (CodexOwnOnly,agent.CodexOwnOnly; #1385), gets the backend's alone, tagged withprovider.CodexOwnListTag; neither tag contains the other, so connecting or disconnecting has Codex fetch the list again. - A translated Responses reply gives Codex reasoning items magpie made: an
rs_id and a summary, nothing sealed. Codex hands them back on every turn. A request relayed as is to OpenAI's API or Azure OpenAI goes without them (withoutBareReasoning) unlessstoreis true, because both look the id up among stored items and answer 400 "Item with id 'rs_…' not found" (#1008). Any other Responses upstream gets them, because a DeepSeek model wants its reasoning back (#388). When one answers 400 naming the input (refusesInput:paramisinput, or the error names an item by id), as a relay in front of OpenAI does with a message of its own,passthroughasks once more without them and, once that works, leaves them out for that provider and model from then on (bareReasoningRefused, #1044). Codex's compaction offers no tools, so it is relayed even when its turns were translated. When a provider answers its summary request 404, or 400 for an item it didn't find (itemNotFound, a relay in front of either),codexCompactasks once more with the conversation as text (plainCompact), then compacts locally (#866, #1008). So does the ChatGPT backend's 502 "response protection is unavailable" (protectionRefused): a long history refused so was answered as text. Codex also compacts remotely, acompaction_triggeron/responsesthat wants exactly one compaction item back, on any provider table named "OpenAI", as CC Switch names its relay tables. magpie points those at/v1while a magpie model is on, sohandlemakes the summary there too (codexInput,codexCompact), and magpie's summaries go back to the model as text (#1301). - A Grok model writes a whole number in a call's arguments with a fraction of zeros (
2500.0,17277.0), whoever serves it: the Grok subscription or its plugin, xAI, OpenRouter or a relay. Codex reads its integer fields as u64, usize or i32 even though their schemas saynumber, so serde turns away the whole call (#1431). In a reply to a request whose model, as magpie names it or as it is sent upstream, has a last/segment beginning withgrok(grokModel,grokServed), every number in a call's arguments written with a fraction of zeros and no exponent loses the fraction:2500.0becomes2500,-3.00becomes-3. Strings, keys, other fractions (2.5,2.50) and exponents (1.0e3) stay as written. No tool schema is consulted, since JSON has one number type. The rule runs over the arguments as a stream of text (wholeNums), holding back only a fraction of zeros until the next byte. This gives the same arguments whether they come whole or in deltas cut anywhere, so what a call's deltas add up to is what its done events say. Relayed replies are rewritten inpassthroughbyintTidy: Responses' function_call items, argument deltas and done events and the completed response; Chat'stool_callsdeltas and messages; Messages'tool_useinput andinput_json_delta, streamed or whole. Translated replies are rewritten at the encoder (wholeEncoder, outsideusageEncoder) and atrender(wholeResult) whenRequest.Grokis set. Any other model's reply is relayed byte for byte (grok_integral.go). - Structured output is carried across every translation (
Format,format.go). It is read from Responses'text.format, Chat'sresponse_format, Anthropic'soutput_config.formatand Gemini'sresponseMimeTypewithresponseJsonSchema/responseSchema:json_schemawith its name, description, schema and strict, orjson_object. Each upstream is asked in its own field:text.formaton Responses,response_formaton Chat,output_config.formaton Messages, andgenerationConfig.responseMimeType/responseJsonSchemaon Gemini and Code Assist. An API with no name for it getsresponse. Messages and the Claude subscription's--json-schematake a schema only, sojson_objectis told in the system prompt there (inSystem). The bridges to a vendor's own API (Cursor, Devin, Kiro, Qoder, Command Code, Zed) are always told in the system prompt. A 400 or 422 that names the field (refusesFormat: DeepSeek's "This response_format type is unavailable now", a schema Anthropic can't hold) marks the provider and model (formatRefused), and the request is asked again with the format told in the system prompt, as are later requests to that provider and model. A relayed request keeps its format as sent. A Gemini client's format is also still told in its system prompt, as before. - Group members are
provider/model[:effort]. A member with a fixed effort is asked for that effort, bounded by the group's levels (#671). - An agent whose config can't carry an effort has one picked in magpie (
provider.AgentEffort, settings'agentEfforts; Cursor Private Inference's row, #1003). It is asked for on that agent's requests to a model that reasons (Provider.Thinks), in place of the level the request sent, fitted to the model's levels and bounded by the group's. Order: a member's fixed effort, then a model's:effortsuffix, then the turn's pick (a routing rule's), then the agent's pick, then the request's own. A model that doesn't reason is sent as asked; the default (none picked) leaves every request as it came. The pick beats the request's own because Cursor sends its own default as often as a real choice. Picking Default hands the choice back to Cursor. - Gemini's OpenAI-compatible API (AI Studio's, or a proxy in front of Gemini on this computer or the LAN:
geminiCompat) is asked for the model's thoughts inextra_body.google.thinking_config. A 400 naming it (refusesThinkingConfig) marks the provider unfit for the field (thinking_config), and it is asked again withreasoning_effortalone. Gemini 3 can't stop thinking, so reasoning turned off goes atminimal, or at the model's lowest level where its levels are known and have nominimal(geminiOffLevel). Google's 400 forminimal(geminiMinimalRefused; gemini-3.8-flash's "Thinking level is unsupported: THINKING_LEVEL_MINIMAL") names thinking too, but isn't the field turned away: the model is marked as refusing reasoning off (offRefused) and asked again at its lowest level, and so from then on, still asked for its thoughts. Vertex AI's OpenAI-compatible API marks each streamed chunk of thoughts in the delta'sextra_content.google.thought, and such a chunk is read as thinking. - A 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'scapabilities.max_output_tokens(cursorLocalModel), Muse Code'slimit.output(museModels), the GUI's model and group rows (providerInfo,providersState),magpie model output, and every agent's file (agent.maxTokens, #338). The window and the output can come from different sources: Grok's backend lists grok-4.7's 256000 window, and models.dev fills its 500000 output (catalog.DecorateandProvider.replyLimitfill an output only where the vendor gives none). An unknown window or output is published as it is. The catalog keeps the unclampedEntry.Output, and a group's member is still asked for no more than that (outputLimit,withMaxOutput), so a request isn't lowered by the clamp. A limit the user set stays in their settings as they set it (TestModelListsKeepOutputWithinTheWindow).
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.
Verification
go test -tags nogui ./internal/gateway -run 'TestRemoteMagpie'
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|TestRefusalAfterThinkingFailsOver|TestGeminiEmptyRepliesAskedAgain|TestLocalUnredacted|TestCORS|TestForeignPagesRefused|TestGeminiThinkingOffAtItsLowest|TestGeminiThoughtsMarkedInExtraContent|TestClaudeSignInNotToldItsSignInFailed|TestSignInWriterReleasesA403|TestSignInBetaStaysWithMagpie|TestStructuredOutput|TestResponsesTextKeepsVerbosityBesideFormat|TestRefusedFormatToldInWords|RPM|TestQueued|TestCustomGeminiUpstream|TestWholeNums|TestGrokCalls|TestOnlyGrokCalls|TestGrokModel|TestGrokPluginCalls'
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.