@laiuuui on X (tweet 2122704105005314155) was told to put Gemini behind
a proxy in a supported region. Their VPSes give only SSH (address, port,
password or key), and every http:// proxy they added failed with Go's
words alone.
A saved proxy can now be an SSH server. Settings > Network > Add proxy
has Proxy | SSH; SSH asks for the server, the user and the password, and
Advanced (closed) holds a private key and the trusted host key. magpie
logs in itself with golang.org/x/crypto/ssh (no ssh command) and resolves
the @id to a SOCKS5 server of its own on loopback, which takes only its
own random login and carries each CONNECT as a direct-tcpip channel, as
ssh -D does: lazy login, keepalive@openssh.com every 20s, one re-login
when a channel finds the connection dead.
- Save logs in first: a refused login is said there and nothing is kept.
- The host key is trusted on first use, kept in authorized_keys form and
shown as its SHA256 fingerprint; another key is refused
(HostKeyChangedError, both fingerprints said) until Trust a new key.
- The key is a secret like the password: left out of backups and
syncs without keys, kept on a sync that has none.
- ssh:// typed as a plain address is refused: its login goes with a
saved proxy.
A failed proxy says why (netproxy.Why: an English template the page
translates in all five languages, Go's words after it): an SSH server
typed as http:// or socks5:// ("is an SSH server, not a proxy: add it as
SSH"), a refused login, keyboard-interactive refused (OpenSSH without
PAM, "unexpected message type 51"), nothing listening, not SSH, TLS on a
plain proxy, 407, timeouts, hangups, and a server that logs in but won't
forward (AllowTcpForwarding no, or macOS 27's sshd, which hangs up on
every forward, OpenSSH's own ssh -W too). A check the user asks for
reads the server's first bytes when Go's text can't tell: Go reads a
real OpenSSH banner ("SSH-2.0-OpenSSH_9.6p1 Ubuntu-3ubuntu13.20") as an
HTTP status line with a malformed code, and an SSH server's banner can
reach Go's transport before its request goes out
("readLoopPeekFailLocked", found red 1 of 20 on mica, then 40 of 40
green). Each save is tested at once.
app.js keeps one line (api() hands a proxy_why reply to proxies.js,
where proxyWhy now lives); both script budgets are raised by that line's
52/54 bytes, with the reason in core_budget_test.go.
Run (mica, at this head on origin/main 81c666e1c):
- go test -tags nogui ./internal/netproxy/... ./internal/settings/
./internal/davsync/ ./internal/gui/ ./internal/provider/
./internal/backup/...: ok
- GOOS=linux and GOOS=windows go vet of netproxy, settings, gui; gofmt -l
internal: clean
- GUI, chromium and webkit, en/zh/zh-TW/ja/de, 1100 and 420px:
saved-ssh-proxy, saved-proxies, i18n-keys, provider-proxy-missing:
64/64
- Tests use netproxy/sshtest, an SSH server on loopback that answers
channels itself; nothing reaches the network.
Broken by hand, each red: accepting any host key
(TestSSHProxyRefusesAChangedHostKey); no login check on the SOCKS end
(TestSSHProxyLocalEndNeedsItsLogin); no SSH banner case and no banner
probe (TestProxyFailureNamesAnSSHServer, its OpenSSH-banner case); no
type-51 case (TestSSHProxySaysWhyItFailed, keyboard-interactive); no
code 2 for a hangup (TestSavedSSHProxyThatWontForward, both cases);
api() not handing proxy_why to proxies.js (saved-ssh-proxy, 20 of 20
cases red: err.why is already a failed move's reason).
Real use: Ubuntu 24.04 OpenSSH_9.6p1 (WSL magpie-desktop, a user sshd
on loopback, key login): the host key was learned, a Cloudflare trace
through the tunnel came back ip=104.194.93.45 loc=US, a wrong password
said "turned the login away", a changed host key said both
fingerprints, and http:// and socks5:// pointed at the sshd both said
"is an SSH server". mote's and mica's sshd (macOS 27, OpenSSH 10.5 and
10.3) log in and refuse every forward, now said as "won't forward
connections".
Not tried: a password login against a real sshd (the user sshd had no
shadow access), a real VPS, and the full go test ./... and full GUI
suite: both mote and mica were running other sessions' GUI suites the
whole time.
286 KiB
Providers and accounts
The gateway can send a request to three kinds of upstream:
- A provider in
providers.json: an endpoint with one or more API keys. Google Vertex AI's is signed with the user's Google credentials, or with one API key (express mode). - A subscription account: an agent's own sign-in (Codex, Claude Code, Copilot and others) that magpie reads from the agent's store, or an account signed in from magpie.
- A plugin's account: a subscription served by an OpenCode plugin.
Package internal/provider holds all three, the routing groups built over
them, and what is left of each one's allowance.
Plugin ownership of the deprecated built-in subscriptions is in Provider and plugin ownership. How the gateway orders keys and accounts per request is in Gateway routing and fallback.
Responsibilities and sources of truth
| Part | Responsibility | Source |
|---|---|---|
| Provider | Provider holds the endpoint bases for each Protocol (Chat, Responses, Anthropic, Gemini), the keys, Fallback, Routing, Sink, UseFirst (Smart puts it ahead of the other providers it weighs it with, gateway routing), NoStandIn (never a fallback for another model, gateway routing), Affinity, concurrency and queue limits, MaxImages (the most images one request to it may carry, the user's word: by model id, "*" for all, ImageCapOf; set in the editor's Advanced › Images per request or with magpie provider set <id> max-images=<n> max-images.<model>=<n>, renamed with a model's local id; past it the gateway leaves the oldest images out before sending, image_cap.go, #6849), Headers, Proxy, models, and balance settings. BaseAPI is the API a custom provider's editor shows its Base URL as: the one the user picked and saved, while it has a URL, so a provider with a chat URL beside its Responses one isn't shown as OpenAI compatible after Responses was picked. Requests go by which URLs are set; Native, the API agents' model files ask a model on, takes BaseAPI where it serves the model, after the OpenAI-model and Claude-on-Messages rules (nb5p on Discord: dsh asked a Responses relay's GPTs on Chat). A custom provider's Gemini URL is the base of Google's Gemini API, or of one that answers as it does (#1346): GeminiBase keeps it as the base, as typed (a pasted endpoint or model list cut back; only Google's own bare host is given /v1beta, JNDliuliuM on X), and Base(Gemini) asks it at GeminiAsked's base: a bare host at its /v1beta, as Google's SDKs ask one, any base with a path as typed (equinox0253 on X, TestGeminiAsked, TestGeminiBareHostAskedAtV1beta). Requests, a model's test and the model list go there: requests to models/{model}:streamGenerateContent?alt=sse under it (GeminiPath), a namespaced id's slashes kept and each segment escaped (GeminiModelPath, which Vertex AI's, a plugin's Code Assist and Gemini image generation (draw.go) share; an id with an empty, . or .. segment goes as one escaped segment, #6695) signed with x-goog-api-key (AuthHeaders), and its models are listed by catalog.FetchGemini (paged, only those serving generateContent). Factory's sign-in alone keeps its own /generate route and token (FactoryGemini). Account is set only for a subscription and is never saved (json:"-"). |
provider.go |
| Rate windows | A provider bills the hours it says at its own rate (#2463): RateWindows, each a span HH:MM–HH:MM on this computer's clock whose end may pass its start over midnight, the days it is on (Days, time.Weekday's numbers, none for every day), and a rate from just over 0 to 1000 at three decimals. The first window that holds a call's time multiplies the price again, on top of PriceRate — a price the user set for a model included, which the price rate alone leaves as set — and outside every window the price rate alone counts. A call is priced at its own time wherever a cost is counted call by call — the Usage page and its CSV, a gateway key's cost limit, the gateway's sessions in Usage — by EffectivePriceAt, which EffectivePriceIn is at time.Now(), and its record's time is read on this computer's clock whatever zone it was written in (a call reported as …Z); the Sessions page sums a session's calls by model, not by time, so it prices them without any window (BasePriceIn in sessions.priceOf), the same at every hour it is read; the ledger's Pricer holds each provider's base price and windows once and reads each record's rate at the record's own time, so a window that opens mid-page prices only the calls inside it; a gateway block's rows (blockPricer, the Requests tab) take their price from a memo asked with no time, which RateAt reads as no window, and each row is put at its own window's rate there (atWindow before Price.In). A list price billed double at peak (Peak, DeepSeek's, Ollama Cloud's two DeepSeek models' and the relays PeakOf names) is part of the base: the final price is that base, peak included, times the window's rate, so a provider with a Peak needs no window for the same hours: the order is the spec (the author, YangHonghang), so a 0.8 window on a shared DeepSeek key takes 0.8 off the peak price at peak, and a window set over the official peak hours would double them twice, which the editor's hint says under the windows. /v1/models prices its list at now (EntryPricer); the model list magpie writes into an agent's own config (AgentPricer, Pi's and omp's cost) leaves every window out, since nothing rewrites that file as a window opens or closes. CheckRateWindows says what is wrong with a set; the editor keeps the windows under Advanced, drawn by ratewindows.js, which app.js imports when an editor draws the field (rateWindowsField) so it adds nothing to the core's scripts — until it has loaded, a save leaves rateWindows out, which keeps them. A provider with windows shows what it bills at now on its row (rateNow in /api/providers, rateNowOf in the GUI's providers.go: RateAt on the server's clock, which calls are counted on, never the browser's); one with a price rate alone shows nothing new. Windows are kept with the provider: a save that leaves them out keeps them, null or an empty list clears them, and a signed-in account's survive its Save — the account branch and withPicks both go through one list, accountSettings, beside its PriceRate, or the editor's Save would quietly drop what it shows (#4738: two lists drifted, and additionalTools, extraBody, reply headers, its rests, limitRestOff and patience were each lost one way; TestAccountSettingsKept). |
ratewindow.go, models.go, ledger.go (Pricer), app.js (rateWindowsField), ratewindows.js, gui/providers.go (rateNowOf) |
| Key price rates | A provider of API keys can bill each key at a price rate of its own (KeyPriceRates, by the key's fingerprint in lower case, above 0 up to 1000 at three decimals; @tnt12231 on X: a relay sells keys in groups at 0.5× and 1.2× under one endpoint). A key without one bills at the provider's PriceRate (KeyPriceRate). The ledger's Pricer memoizes by the record's ProviderKeyID too and prices through BaseKeyPriceIn, so the Usage page, its CSV, a key's spend cap and a typed balance (usage.KeySpent) count each key's calls at its rate; PriceAt prices a routing candidate at the rate of the key it holds (By price). A call with no key recorded, the Sessions page and the budget's estimate before a key is picked use the provider's rate. A price the user set for a model stands as set, as under the provider's rate, and rate windows multiply on top. SetKeyPriceRate refuses a subscription, a rate of 0 or out of range and a key the provider hasn't; nil takes it off. ReplaceKey carries it to the new value. Set under the editor's Advanced, a line per key under Price rate once there are two keys or more (folded past eight as the per-key proxies are; an empty line shows the provider's rate as its placeholder), saved as keyPriceRates on provider/save ({} takes them off, left out keeps them), or `magpie provider key-rate [key [rate |
default]]`, which also lists each key's rate. |
| Billing | Whether a provider is on a plan or paid as used, marked by a grey badge on its Providers row and summed up as a tag on a routing group's card (EV_John_Liu on X). BillingKind (billing.go) is the user's word (Billing: the editor's Billing under Advanced, Auto/Plan/Pay as you go; magpie provider set <id> billing=plan|payg|auto), else a signed-in account (a plan), a plan's own preset (planPresets: Kimi Code, the Token Plans, OpenCode Go, ClinePass), else the name of the preset region it sits at (regionOf: "Pay as you go…" or "…Plan…"; one named by place, or a preset with no regions, is the vendor's API, pay as you go), and mixed when a key of it is on a plan of the other kind (KeyAccount.Plan). It is "", and nothing is shown, for a provider added by its address, a local server, another magpie, a decision model, or a preset whose one endpoint takes both (unsaidPresets: MiniMax, ModelScope and the like). /api/providers gives billing and billingKind, a group's memberInfo[].billing; the card's tag is shown only when every member's is known. It marks only: routing and prices don't read it. TestBillingKind, TestBillingEveryRegion, TestProviderBilling, TestProviderSetBilling, provider-billing.test.cjs. |
billing.go, providers.go |
| Anthropic key header | A provider of the user's own on a third-party Anthropic API is sent its key as both x-api-key and Authorization: Bearer (AuthHeaders); Anthropic's own API, Bedrock, Azure, Vertex and every subscription account have their own and never this choice (BothAuth is false). Some services refuse the two together with a 401 (Aloha on Discord: "鉴权 header, x-api-key 和 Authorization 不可以同时存在"), so Provider.AuthHeader (authHeader: empty for both, x-api-key or bearer; anything else is read as empty) sends one alone, picked in the editor's Key header row (shown while bothAuth is true, or a custom provider's Anthropic URL is a third party's). Left at both, a 401 whose body catalog.BothAuthRefused tells as that refusal (it names both headers and says they can't be together, in Chinese or English) is asked once more with x-api-key alone, then Bearer alone (RetryOneAuth, in the gateway's forwardOnce and the provider test's probe; catalog.fetchOne for the model list through listAuth); the first not answered 401 or 403 is kept with LearnAuthHeader, which never changes a pick the user made. A request carrying the user's own Authorization or x-api-key header is never retried. |
authheader.go, test.go, catalog/authheader.go, catalog/live.go |
| GLM Coding Plan key at pay as you go | Zhipu's and Z.ai's presets offer Pay as you go first (/api/paas/v4) and the Coding Plan (/api/coding/paas/v4, Responses at /api/v1); both share /api/anthropic, which bills the plan, so a plan's key left at Pay as you go worked in Claude Code and was refused 429 code 1113 "余额不足或无可用资源包" in Codex (@cleverpigo on X). Nothing in the key tells the two apart, so a Chat request to open.bigmodel.cn or api.z.ai at /api/paas/v4 refused 1113 is asked once more at /api/coding/paas/v4 (RetryZhipuCoding, in the gateway's forwardOnce and the provider test's probe). Served there, LearnZhipuCoding moves a saved provider with that one key, still at that URL, to the plan's OpenAI URL (and the preset's plan Responses URL when it has none); one with other keys stays and is asked again each time. Refused there too, the 1113 body keeps its code and gets both URLs and what to change in its message (ZhipuNoBalanceHint). A pay-as-you-go key with a balance is never answered 1113 and never sent to the plan's endpoint. |
zhipu_coding.go, test.go |
| A Zen free model on OpenCode Go | OpenCode's two gateways serve different free models: Zen's free tier (/zen, asked with the public key OpenCodeAnonymousKey) serves its -free models and big-pickle, Go (/zen/go, a Go key) only a few of its own (beam-free, iceman-contributor-free on 2026-11-02). Go answers a model it doesn't serve 400 "Upstream request failed: Model is unavailable." before it reads the key, so Claude Code asking one of Zen's free models on an OpenCode Go provider failed on every request (51bit.eth on Discord). Such a request, a free model by OpenCodeFree, is asked once more at Zen's free tier on the same API (openCodeGoToZenFree, OpenCodeFreeURL), with the public key and never the user's Go key (RetryOpenCodeFreeOnZen, in the gateway's forwardOnce); a model that isn't free isn't. Refused there too, or not free, the 400 keeps Go's words and says where the model is served. Not changed: when Go's /models refuses the key, the provider lists models.dev's opencode-go, which names free models Go doesn't serve (#4900). |
opencode_go_free.go |
| OpenCode Go endpoints | Go's docs name one URL per API under /inference/go: /openai/v1 (chat, Responses), /anthropic (Messages), /google/v1beta (Gemini, models/{id}:streamGenerateContent). The preset gives them (OpenCodeGoChat, OpenCodeGoAnthropic, OpenCodeGoGemini); a provider of the preset saved with the older /zen/go or /inference/go/v1 URLs is moved on load, and one added by hand with a single Go URL gets the rest filled beside it (openCodeEndpoints). A URL the user gave another API stays. |
opencode_endpoints.go |
| Zhipu's 200 refusals | Zhipu's and Z.ai's /api/v1 (the GLM Coding Plan's Responses API, from their Codex pages) and /api/monitor answer a refusal 200 in the platform's envelope, {"code":1000,"msg":"身份验证失败。","success":false}, where their OpenAI and Anthropic endpoints answer the same key 401 (@xanahopper on X: a refused key tested green on the Responses row only). ZhipuEnveloped turns a 2xx JSON body from open.bigmodel.cn or api.z.ai with success: false into {"error":{"code","message"}} at the status Zhipu's error-code table gives (1000–1005 → 401, 1113 and 1302–1399 → 429, 1220 → 403, 1210–1229, 1261 and 1301 → 400, anything else → 502), in the provider test's probe (endpoint tests, model tests, Detect APIs) and the gateway's forwardOnce. A stream, a compressed body, a body over 64 KB and every other host pass as they came. The plan's quota card for a key refused there (1000–1005, or a 401) says <Zhipu or Z.ai> didn't take this key (<their words>): … with the vendor's API-keys page (zhipuRefused), not asked again as a team's key, and the GUI shows it as that (quotaError) rather than "Allowance unavailable". |
zhipu_envelope.go, planquota.go, test.go |
| Extra body | ExtraBody (extraBody in providers.json, the editor's Extra body, #1604) is a JSON object whose fields WithExtraBody adds at the top level of every JSON body sent to the provider: Messages, Chat, Responses and Gemini, relayed as they came or translated, in the gateway's forwardOnce and in Test and Detect (tested). A field the body has already is kept; a name written "!name" replaces it. A service_tier of ultrafast there is kept by a group member or fast pick sent Fast, which would otherwise have written priority first (gateway routing, KoiLx0 on X). Values are put in as written, objects whole, not merged. ${sessionId} in any string, at any depth, becomes the request's session: the agent's session header (sessionOf), else the id conversationID derives from how the conversation opens (magpie- and its hash, Gateway routing's Affinity), so it stays the same through one conversation; Test and Detect send magpie-test- and 12 random letters, a new one each time. ${threadId} is the thread the agent names within that session: Codex's thread_id (its turn metadata or thread-id header, threadOf), which a subagent has of its own while it shares its lead's session; read only when the provider's headers or extraBody name it (AsksThread). No other agent names a thread, and there ${threadId} is the session's id. ${subagentId} becomes the Claude Code subagent the request is of (x-claude-code-agent-id, subOf), "" on the conversation's own turns, which never send the header, so ${sessionId}:${subagentId} keeps one prompt_cache_key per subagent where ${sessionId} alone carries every subagent's turns on one key (#2937). model, stream and the conversation (messages, input, contents, system, systemInstruction, system_instruction, instructions, tools, ExtraBodyReserved) are magpie's: Save refuses them with or without ! (ExtraBodyOK), the editor says so as they are typed, and one written into providers.json by hand is dropped on read (cleanExtraBody). Not sent with it: count_tokens, embeddings, images, video and System One's decision model (other APIs), and a signed-in account's requests, except a ChatGPT (Codex) account's (magpie-releases#18): its requests are built as Codex CLI's (codexBody) and take the fields Codex CLI adds by choice, such as access_programs (OpenAI's Daybreak), while store, tool_choice and include, which the backend needs as codexBody sets them, can't be set (codexOwned). Its extraBody is written into providers.json by hand under the account's entry and kept onto the account by withPicks, and kept by a later Save (#4738: Save dropped it before); the editor has no box for it. A client's own top-level access_programs on Responses or Chat is carried to a Responses build as it came (Request.AccessPrograms), so a request translated (a Codex account is streamed, so a whole Responses request is made again) keeps it as a relayed one does. It reaches only the upstreams Codex itself sends it to (keepsAccessPrograms, #3172, see gateway routing); it is taken out before the extraBody merge, so an access_programs the user puts in a provider's extraBody still goes. One object goes to every API; fields for one API alone are not a thing yet. A thinking budget it puts in on an Anthropic endpoint is fitted to a Claude that thinks only adaptively after the merge, as an agent's is (adaptiveThinking, TestExtraBodyBudgetFittedToAdaptiveModel). |
extrabody.go, gateway.go |
| Headers' conversation ids | ${sessionId}, ${threadId} and ${subagentId} in a value of the provider's Headers (Axel Burks on Discord: a gateway in front of several Azure accounts routes one conversation to one account by a session header) are the ids extraBody gets, on every request Sign signs: the gateway carries the conversation to it in the request's context (WithConversation), on every API and count_tokens too. A request that is no turn of a conversation (a model list, a balance, an embedding, image or video, System One's decision model, a search) gets an id of its own, magpie- and 12 random letters, new each time (OwnConversation); Test and Detect's is their magpie-test- id, the same in headers and body. A literal placeholder is never sent. In a header the ids go without control characters (headerSafe): an agent's session id with CR or LF in it would split the header, or Go would fail the request. A value with neither placeholder goes as written (SentHeaders). |
conversation.go, account.go, gateway.go, codex_resume.go |
| A remote magpie's headers | Every request magpie makes to a Remote magpie carries the provider's Headers (Yirasumi on Discord: the Usage page's read went without the header a proxy in front of the remote asks for): its API requests and model list as any provider's (Sign, listHeaders), and its cards, a card's refresh, its quota history and each gateway key's limit (signRemote), the last four as no turn of a conversation (${sessionId} an id of its own). The key always reaches the remote as x-api-key (remoteKey), which a gateway reads beside Authorization: a user's Authorization (a proxy's own scheme) goes in place of magpie's Bearer copy without taking the key away, and a user's x-api-key is never sent to a remote magpie, so a key's limit is read with that key. A user's Authorization that is itself another gateway key of that magpie is read first there, as on any request. |
remote_quotas.go, remote_key_limits.go, remote_magpie.go, account.go |
| A model's own headers | ModelHeaders in settings ("pid/model", SetModelHeaders, at most 32, names checked as Headers' are; the editor's Model settings, + Add header; axelburks on Discord: Volcengine Ark routes an endpoint by a header) go on a key's provider's requests for that model alone, after the provider's Headers: a name both have is sent once, as the model's, over the provider's and over the key's Authorization or x-api-key (headersFor, in SentHeaders(ctx) and AsksThread(ctx)). The gateway names the model in the request's context (WithModel) on every API, streamed or not, count_tokens, images, video, embeddings and System One's decision model; modelOf reads it only for the provider it was set for, so a fallback serving the same id is sent its own headers alone. A native route (Gemini's, Copilot's) names the model by the body's vendor id. Headers the agent passes (PassHeaders) still stand over both. A signed-in account and a plugin get none (takesModelHeaders). TestModelHeadersReachTheirModelOnEveryRoute, TestModelHeadersStayWithTheirProvider, TestModelHeadersReachSystemOne, model-headers.test.cjs. |
|
| A model's own system prompt | ModelSystemPrompts in settings ("pid/model", SetModelSystemPrompt in modelsystem.go: trimmed, at most 64KB, no NUL, a model the provider serves; empty takes it away; the editor's Model settings, System prompt, staged as modelPrefs[id].system by modellimits.js; liucl on X) is added after the agent's own system prompt on every request for that model, whatever agent sends it: see gateway routing. Any provider takes one, a signed-in account and a plugin too. Renaming the provider or the model carries it (perModelFields). TestProviderSaveModelPrefs, model-system-prompt.test.cjs. |
|
| A model's own speed | ModelTiers in settings ("pid/model" to priority or ultrafast; CleanModelTier, SetModelTier in modeltier.go, refused where CanFast / CanUltra say the model or account has no such mode). It rides ModelPref.Tier with the other Model settings, magpie model tier sets it, and the gateway sends it on a direct pick for an agent with no fast pick of its own (kdajenks on X). |
modeltier.go, modelprefs.go, gateway.go |
| Reply headers | ReplyHeaders (replyHeaders in providers.json, the editor's Reply headers under Advanced, a comma-separated list, #4145) names headers of the vendor's reply the gateway passes on to the agent, matched whatever their case and saved canonical (cleanReplyHeaders). DefaultReplyHeaders (Request-Id, X-Request-Id, X-Oneapi-Request-Id) go from every provider without being listed: opaque request ids, under names magpie sets nothing of its own. Never passed on, listed or not (ReplyHeaderPassable): the reply's framing (Content-*, Transfer-Encoding, hop-by-hop), cookies and sign-ins (Set-Cookie, Authorization, WWW-Authenticate, Proxy-*), CORS (Access-Control-*), Sec-*, redirects and browser policy (Location, Strict-Transport-Security, Content-Security-Policy…), Retry-After/Cache-Control/Date/Server/Vary (magpie writes those) and X-Magpie-* (the gateway reads them as notes of the try). Save refuses such a name (ReplyHeadersOK), the editor says so before the save (replyHeadersOf, its list held to Go's by TestReplyHeadersNeverAsTheProvidersAre), and one written into providers.json by hand is dropped on read. A preset's provider and a signed-in account's requests take it too (withPicks). How the gateway carries them is in gateway routing. |
replyheaders.go, reply_headers.go |
| Request headers to pass | PassHeaders (passHeaders in providers.json, the editor's Request headers to pass right after Reply headers under Advanced, a comma-separated list; 3jRzfF52Qx on X) names headers of the agent's request passed on to this provider as the agent sent them, matched whatever their case and saved canonical (cleanRequestHeaders). The agent's value stands over a fixed Headers value of the same name; when the agent sends none, the fixed one goes. Sign puts them first (passClientHeaders), so an account's own signing still has the last word. Never passed on, listed or not (RequestHeaderPassable): magpie's own key as an agent sends it (Authorization, X-Api-Key, X-Goog-Api-Key, Api-Key), cookies and sign-ins (Cookie, Set-Cookie, WWW-Authenticate, Proxy-*), the connection's fields (Host, hop-by-hop, Expect), what magpie writes for the body it sends (Content-*, Accept, Accept-Encoding), Origin, Sec-* and X-Magpie-*. Save refuses such a name (RequestHeadersOK), the editor says so before the save (replyHeadersOf(…, true), its list held to Go's by TestReplyHeadersNeverAsTheProvidersAre), and one written by hand is dropped on read. Only the provider that lists them gets them: the agent's headers ride the request's context under that provider's id (WithClientHeaders), so a fallback, a group's other members, a side model or a searcher get none. A preset's provider, a signed-in account's requests and a plugin's fetch take it too. Wire headers are masked when read, so a passed one shows in a call's log as any header does. |
requestheaders.go, gateway.go |
| Native compaction | NativeCompaction (nativeCompaction in providers.json, the editor's Compaction row, magpie provider set <id> compaction=native|magpie; #1099) has Codex's compaction asked of the provider as Codex sent it and its sealed item returned unchanged. Off by default. Only a provider whose wire carries it can be set so (CarriesCompaction: a Responses API, a ChatGPT account, GitHub Copilot; not another agent's sign-in or a plugin's), and CompactsOn(model) also needs the model asked on Responses. SetNativeCompaction, the CLI and the GUI's save refuse it elsewhere. An account keeps it through Save's picks (withPicks), and AddCopy carries it. The gateway's half is in gateway-routing. |
native_compaction.go |
| providers.json | Path is providers.json in magpie's config folder. A read that fails returns ErrUnreadable and is never treated as empty. store writes atomically through a rename and drops the cached catalog (catalog.Touched). |
provider.go |
| A provider renamed | Rename (the editor's id field, magpie provider set <id> id=<new>) keeps the old id in Was, so a model still picked by it reaches the provider. Usage is recorded under the id a call went out by and never rewritten; whatever reads it names the provider by its id now through UsageRenames().Of(id, time): the summary, the Requests page (its blocks, the probe rows, other computers' days), the Sessions tab's vias, window holds, NewPricer/NewCoster and the gateway's loggedAnswers (cybercaius on Discord: a renamed provider was listed under both ids). Visit hands records out as recorded, so Of is taken once. An id another provider takes later (a rename onto it, or Save of a new provider under it) moves from the first one's Was to its Gave with the time (giveID): calls recorded under it before then stay the first one's, later ones are the new one's. An id held by a provider or a subscription now is never renamed (Renamed), and freeID doesn't hand out an id in any Was, so adding a vendor again gets -2. Ids reused before Gave existed have no time and go to whoever holds the id now. A provider deleted (Delete) is kept in providers.json's deleted with its name, Was, Gave and when (provider.Deleted): its calls stay under its id while no provider has that id, and once one is added under it (or a later deleted one had it) they go to Deleted.UsageID, <id>~<when, UTC>, so the new provider has only its own (cybercaius on Discord). The Usage page names either by the deleted provider's name and marks it with when it was deleted (Renames.Gone, Named.Deleted). Deletes before this was kept have no record and go to whoever holds the id now. A deleted provider's calls can be merged into a provider there is now, or named by the user, from a "…" beside the Requests page's Provider filter while it is picked (ledProviderMore in plugins/usage/page.js, POST /api/usage/deleted, GET /api/usage/deleted/into; CyberCaius on Discord, who had renamed a provider onto the old id to do it). Both are kept on its Deleted record, not in settings and never in the log: MergeDeleted sets Into and MergedAt, NameDeleted sets Label (Deleted.Shown), so a provider added later under the old id inherits neither. Renames.Both(id, time) gives the id a call is shown under (Of, merges followed) and the one it was made to (Own): a merged call is listed, filtered and summed under the target, but priced, held and answered by its own (Record.priceID, block_price.go's as, window holds, loggedAnswers), so a merge moves no cost or token. The target's face lists what is merged into it (Named.Merged), and the same "…" parts each again (into ""). Renaming the target carries the merge; deleting it ends it (a merge older than the target's deletion is not followed). A providers.json that can't be read keeps the last renames read, not none. The summary and Requests caches key on Renames.Key, the vias cache too. |
rename.go, block_price.go |
| The list | All merges stored providers with Accounts(). An entry with no URL stores the user's picks for an account. The order is file.Order. Reads within one request share one build (Hold, #746). Requests that miss a build together (a write drops what is held) wait for the first one's build and take it, unless a write came while it was built; a wait is bounded (heldWait), so a caller never waits for good. Before, each built again behind logins.json's lock, and requests sat past the 30s unrouted deadline (#5104: TestLoginsMissedTogetherListedOnce, TestHeldWaiterBuildsAgainAfterAWrite, TestHeldWaiterNeverStuck). OwnPaused is held the same way, once a request. |
provider.go |
| Model picks | Models are the models the user picked for agents; none means the vendor's list, up to 24 (Exposed), unless the user chose Select none (NoModels, magpie provider models <id> none): then none of its models is served, not to agents, not to any routing group (auto groups included), not by a provider/model id, not as a classifier, while its balance and usage are still read (ServesNone, #1818). Codex's own list at /backend-api/codex/models drops the ChatGPT account's visible models too, as spawn_agent's list of them does, and the list's ETag changes so a running Codex asks again (CodexNativePicked in codex_models.go, #2530); the hidden ones Codex runs jobs of its own on (codex-auto-review, gpt-reserve) and other providers' models stay. The editor's serves control names it Usage only, beside Vendor's list and Picked only, and the card says "usage only" (#2068); Picked only from there picks the models the vendor's list serves, to unpick from. A file without noModels reads as before, and a pick clears it. With nothing picked and Select none off, Best in family (BestInFamily, magpie provider models <id> best, the editor's fourth option, Steven on Discord) serves only the newest model of each family the vendor lists, up to 24: the family is the id with its version numbers taken out, a dated snapshot counts as its alias, and sizes and suffixes (-mini, -pro, -8b) stay in the name (FamilyOf, BestInFamily in family.go). A newer one the vendor lists later takes the old one's place with nothing saved. Codex's own list narrows the same way (CodexNativePicked). An older one named by its provider/model id is still served, as an unpicked one is under Picked only. A pick or Select none clears it, and a file without bestInFamily reads as before. Save keeps beside new picks the models listed then (PickedFrom, listedWith), and the same picks saved again keep it. When the picks held every model listed then, one the vendor lists since is served first beside them (withNewlyListed, Picks); one listed then and left unpicked stays out. A remote magpie's routing group listed since is served beside any picks, ones that left models out too, so a group made there shows in the agents' pickers with no tick (KoiLx0 on X, TestRemoteMagpieNewGroupServedBesidePicks); one listed at Save and left unpicked stays out. Picks saved before PickedFrom was kept are taken to hold every model when they hold every one released up to the newest of them (models.dev's release_date), so a Claude account whose user picked them all is served Haiku 5.5 (wakaka). The editor and the TUI start from Picks, so a later Save keeps the new model. While some picks are set aside (the list is known to be short), a save with new picks keeps the models the earlier PickedFrom had beside those listed now, so a model the user saw and left unpicked isn't new when that list has it again; a list short of no pick is taken as it is. A pick a list fetched again stops listing (Refetch, KeepListsFresh, and a plugin's hourly KeepPluginsListed) leaves Models for Delisted (dropGonePicks), not served, and goes back among the picks when a later list has it (relistPicks): Our Free Model's plugin lists its account channels' models only once its service has read them after a restart, and its free pools only while they answer, so each magpie update had its user pick every model again (多喝热水 on Discord). Every save keeps Delisted but for what it picks again (delistedWith); Select none clears it. A provider whose every pick is in Delisted serves none of its models for pickWait (an hour) from when the last one left (DelistedAt, waitsForPicks), not the vendor's list; after that, or for picks set aside before DelistedAt was kept, the picks are taken as gone for good and the list is served as if none were picked, while they still come back with a list that has them. WorkBuddy AI took its Free plan's deepseek-v4.1-flash off its list for hy3, and an account whose one pick it was got no model in the agents' picker, its row reading "1 image model" (maxleebeta on Discord). KeepPluginsListed asks again after relistSoon (5 minutes) when a list left a pick out. Devin's picks and set-aside picks are read without Adaptive and Fusion, in any case (withoutDevinRouters in normalize): the built-in listed them before it served Devin's chat API (ce8d0e065), which answers either with 502 "no API providers are available", and picks saved then were served as the user's own models after the move to the plugin, which lists neither (TestDevinRouterPicksNotServed). TestPluginPicksComeBackWithTheirList, TestEveryPickDelistedServesNone, TestPicksGoneForGoodServeTheList and TestRelayPicksComeBackWithTheirList cover it. |
models.go, provider.go |
| List schedule and rules | A provider of the user's own (not an account, a plugin's or a decision-only one) can set RefreshEvery (magpie provider refresh-every <id> 6h, or 1d, or off, at least 10m) and AutoInclude (magpie provider auto-include <id> 'gpt-*' 're:claude-.*', or none; a glob with *, or re: matching the whole id, both in any case (compilePattern; (?-i) inside a re: makes case matter); a plain id is refused) (#2135). The gateway (magpie serve or the app) looks each minute and fetches a list once Fetched is that old, through the same Refetch as Fetch models (KeepListsFresh); a failed fetch waits min(every, 15m). RefetchTaking adds to the picks a model the fetch newly lists that a rule matches (takeMatching), starting from what is served now (Exposed), so nothing served is taken away and a model the user unticks stays out (it is not new to the next fetch). Setting the rules takes the current list's matches. Every save that doesn't set them keeps them, the window's editor among them; the editor has no fields for them yet. A Remote magpie with no RefreshEvery is fetched every 10m (RemoteMagpieEvery, RefreshSchedule), so a model the other magpie lists later (ZCode's GLM-5.3-Trial once its plugin read the gift, 6igsteven on Discord) is served without Fetch models; off set on it is kept as "off" and asks it only when told (TestRemoteMagpieListFollowsTheOtherMagpie). The gateway also follows each Remote magpie's list as it changes there (KaCli on Discord: a route or group changed on the server reached the agents on the computer using it only on the next 10m): KeepRemoteListsFollowed keeps one long-poll per Remote magpie, a GET /v1/models with X-Magpie-List-Wait and the If-None-Match of its last answer, and on a new ETag fetches the list through the same RefetchTaking, so catalog.Touched rewrites the agents' configs within a second or two. A magpie from before answers at once with no ETag; it is left to the schedule and asked to wait again after an hour. One set to off is not followed (TestRemoteMagpieListFollowed, TestRemoteMagpieOldListNotFollowed, TestRemoteMagpieOffNotFollowed in remote_follow_test.go). |
autolist.go, models.go, remote_follow.go, providers_cli.go |
| Keys | Several keys per provider. Requests go to the first key that is on; the gateway moves on when it is out or rate limited. Key stays the first, so other code reads it as before. A key can be made for one protocol (KeyProtocol): Anthropic, Chat, Responses or a custom provider's Gemini API (corddis_114 on Discord). WithKey leaves it that protocol's URL only, and the gateway puts the key that suits the model first (keyFit: Claude to the Anthropic key, GPT to a Chat or Responses one, Gemini to the Gemini one; TestKeyMadeForGemini, TestKeyProtocolGemini, key-gemini.test.cjs). A key made for a protocol its provider has no URL for is skipped (perKeyBarred); when every key is, the provider is still tried whole on the URLs it has, and the candidate carries noURL so it isn't quiet: Routing's row (Weighed.NoURL) says "key set to {api} only, no {api} URL · sent on the others", and the editor's key row shows a "No {api} URL" chip (keyLacksURL; #1702, TestKeyForAProtocolWithNoURLIsSaid, key-nourl.test.cjs). A key's value can be replaced in place (ReplaceKey, #1869: a key rotated at the vendor): it keeps its name, place, protocol, weight and on or off, and what was set for it by its fingerprint (AccountModels, AccountProxies, AccountConcurrency) and the gateway keys held to it (access.ReplaceAccount) move to the new one; the GUI's keys/replace also lifts its rests (UnrestAll). Its past requests stay under the old fingerprint, by the same name. A provider may hold thousands of keys (@NetRozee on X: a thousand froze magpie). Nothing goes over its keys once for each key: KeysOn drops a repeat by a set, a row's rest keys come from RestKeys (whether several are on, found once), and whether each key serves a model from Serving, which reads the lists once and keeps each model's keys as a set until the lists are read anew (keyLists). KeysListed and ListsRead count them for the tests (TestProviderInfoListsKeysOnce, TestPerKeyReadsListsOnce). A provider's keys have their balances, plans and remote limits read keyReadsAtOnce (8) at a time (keySlots); other providers' beside them. The editor's per-key proxy lines fold as its Accounts list does (proxyLines, provider-many-keys-proxy.test.cjs). Asking a key's models (fetchPerKey) still goes one key after another. Each Fetch models carries each key's list into the models it serves (refreshKeyModels in key_models_refresh.go): a key with a list of its own gains what its list gained and loses what it lost, keeping what the user ticked or un-ticked; a key on All models (the provider's first, one added before per-key lists, one whose list wasn't read in time when added) is given its own list when that list leaves out a model the other keys list. A key the user set to All models (accountmodels with none) is marked in AccountModelsAll and stays so; the editor's save keeps it. A key set to All models before the mark was kept has none, and is narrowed once to its list on the next Fetch (young02036 on Discord, TestFetchTicksEachKeysListOnAllModels, TestFetchModelsTicksEveryKeysModels). Every key goes out at once, one a line, for another magpie to take in (@emilochen on X: one provider's keys from this computer to a magpie in the cloud): AllKeys gives the keys alone, on and off, in the list's order, each once; their names, protocols and plans stay behind. The editor's Copy all N keys (shown with more than one key, under Add another key, drawn by keyrates.js; provider/key with allKeys) copies them to the clipboard for the other magpie's Paste several, and magpie provider keys <id> prints them to stdout for magpie provider keys <id> add, which reads them from stdin or as words (a flag is never a key). Nothing logs them (TestAllKeys, TestCopyAllKeysPastesInto, TestKeysCmd, key-copy-all.test.cjs). |
keys.go, key_models_refresh.go |
| Accounts at once | MaxAccounts *int is the user's own count of keys or accounts taking requests at the same time: nil takes the plugin's (PluginAtOnce: maxAccounts on the plugin's auth hook or package.json magpie, host.js atOnceOf), 0 is no limit, saved clamped to 0..MaxLimit; a subscription's is kept with its picks (withPicks). AtOnce() answers the one in force, SetAtOnce sets it (magpie provider at-once, the editor's Accounts at once; GUI save leaves it as it was when the body has none). The gateway's use is in gateway routing (TestAtOnce, TestAtOnceSave, TestAtOnceCmd). |
concurrency.go |
| A provider with no key | A provider of the user's own saves, imports and is Ready with no key when it is a preset with NoKey or its host is on this computer or the user's own network (keyOptional, ownNetwork): localhost, a loopback, private, link-local or carrier-grade NAT (Tailscale's 100.64/10) address, or a .local name, read from the URL alone with no lookup. A company's keyless relay at a LAN address is taken as a local server is (iSnow_999 on X: a Codex relay at http://:8080 was left out of a CC Switch import as "it has no API key"); a keyless address on the internet still needs its key. With no key it is asked as one on 127.0.0.1 is: a Responses request carries no Authorization. |
provider.go, importapps.go, import_lan_test.go |
| A key a provider | One vendor's keys saved a provider each — an app that keeps an entry a key, as CC Switch does, imported (yuluo_yx on X: "NVIDIA #001" to "#600" at one address, "Mistral #0001"…) — are folded into one provider with those keys (FoldCopies at start-up, foldAdded after ImportFromApps): hundreds of copies listed every model hundreds of times in every agent's picker and found group, and 3,000 made /api/state 86 MB. At start-up only copies by name are folded: a base name and that name with a number after it (copyBase: " #12", or freeName's " 2"), one at least numbered; an import folds what it added whatever their names. Either way they must be alike in all but their key (foldShape: the provider with its id, name, keys and on/off left out), what the settings say of their models (modelPrefs) and where they are named (foldRefs: Visible, the agents' picked, hidden and ordered models, the groups, the providers falling back to them), so one key shown to one agent and another to another stays apart. Not folded: a subscription's, a hidden one, one without a key, Vertex, one with a StepFun sign-in of its own. The first on, in the providers' order, takes the rest in; its name becomes the base and its key is named its old name. Each other is a key in order, named its name, off if it was off (all off: the provider is off, its keys on); its id goes in Was, so its calls count with the provider by their key (ProviderKeyID is the key's fingerprint, unchanged) and a model picked by the old id still reaches it. Group members, rules, weights and fallbacks naming them name the provider once; their per-model settings and fetched lists go; balance and window history kept by their id moves to their key's name (foldHistories). A providers.json that doesn't parse is left alone. It runs at every start and writes nothing when there is nothing to fold. TestFoldCopies, TestFoldCopiesIntoOneOn, TestFoldCopiesUnreadable, TestImportFoldsAKeyAnEntry. |
fold.go, importapps.go, main.go |
| Antigravity CLI's own key | agy on a Gemini API key of the user's own ("modelProvider": "gemini" in ~/.gemini/antigravity-cli/settings.json, GEMINI_API_KEY in its environment) lists the Gemini API's models, Gemini 4 Carbon and Hydrogen among them, while the agy-cli subscription runs agy on its Google sign-in (shenggxhz on X: agy listed Gemini 4, magpie's refresh didn't). The Providers page finds that key as an import source ("Antigravity CLI", readAgySettings) and offers it as the Google Gemini preset, or at GOOGLE_GEMINI_BASE_URL's Gemini endpoint when it is set. The variables are magpie's environment's, else the login shell's (proc.GeminiKeyVars, read with LoginEnv and never set in magpie's environment), as a terminal's agy has them. agy on its sign-in offers nothing; with no key it is listed as not importable; at magpie itself it is refused, as every import is. The plugin's own listing reading that setting is plugins#1218. TestAgyGeminiKeyIsFound, TestAgyGeminiKeyOnlyWhenAgyUsesIt. |
import_agy.go, path_other.go |
| A key's plan | A vendor whose plans take keys of their own (PresetDef.KeyPlans: zhipu, zai, stepfun, stepfun-cn, xiaomi, baidu-qianfan, tencent-cloud, huaweicloud, volcengine, siliconflow) lets each key say which of the preset's Regions it is for (KeyAccount.Plan, Provider.KeyPlan for the first; yckonnnn on X: a Volcengine pay-as-you-go key and an Agent Plan key in one provider). No plan, or the provider's own, is the provider's plan, as every key was before, and is stored as none (SetKeyPlan, the GUI's keys/plan). WithKey moves a key's copy to its plan's endpoints (atKeyPlan: chat, Responses, Anthropic, decide, key page, docs and catalog; a provider at a host of its own, a mirror or a test's fake vendor, keeps that host) and marks it a key's view (keyView), so nothing judges plans on it again. Only when the keys in use are on more than one plan (PlansMixed) does anything differ: the model list is each key's plan's (fetch goes to fetchPerKey; a plan with no list of its own, planOnly, is its preset list without a request, so Ark's Coding and Agent Plans ask nothing while pay as you go asks /api/v3/models with its own key); plan media (planMedia) are every plan's; each key serves its plan's models alone (PlanServing, read by the gateway's perKeyBarred; a model set for the key in AccountModels it serves); plan windows (PlanQuotas), Volcengine's and Tencent Cloud's access-key windows (planViews) and balances (balance.go) are read at each key's plan. Volcengine's keys carry nothing that says their plan, so none is guessed; Xiaomi's tp-, Tencent's sk-tp-, MiniMax's sk-cp- and Bailian's sk-sp- prefixes are documented in code but not used to set a plan. The editor's key row has a plan chip (planPicker, the app's own menu) while the provider has several keys or the key has a plan. Not done: a gateway key held to some keys of a mixed provider's video (videoAsker) may pick another key's plan; a mixed provider whose own plan has no balance source while a key's plan has is not read (KeyBalances reads each key at its own plan, and a key whose plan has none, a GLM Coding Plan's, gets no balance card beside its plan windows; Zhipu/Z.ai pay-as-you-go keys read /api/biz/account/query-customer-account-report, undocumented, at their own host, and SiliconFlow's card says its query is gone with the console to open, siliconFlowRetired, nam.haid on Discord); StepFun's plan windows are a sign-in per site, unchanged. TestKeyPlanEndpoints, TestKeyPlanServing, TestKeyPlanOldConfigsUnchanged, TestSetKeyPlan, TestKeyPlanModelList, TestKeyPlanViews, key-plan.test.cjs. |
key_plans.go, keys.go, models.go |
| Google Vertex AI | google-vertex (VertexPreset, IsVertex) is a provider of the user's own, signed with Google credentials, or with one API key (express mode, below). Provider.Vertex holds project, location (global, us, eu or a region; global when empty), credentials (a file; empty for Application Default Credentials) and impersonate (a service account's email). Save refuses a list of keys (it takes one), then normalizes them (Normal) and checks each (check); normalize clears the four URLs and any key put in providers.json by hand, which stands in for neither a token nor a project and leaves the provider as found savable, so the provider's one address is vertexBase, https://<host>/v1/projects/<project>/locations/<location>, its host following the location (vertexHost). It speaks chat completions, Anthropic's Messages API and Gemini (Speaks, Base), each model one of them (ListedAPIs, which ModelAPI can't change for it): a Gemini model on generateContent at that address, a partner model (VertexPartner: a publisher/model id, as every one models.dev lists for google-vertex has, such as deepseek-ai/deepseek-v4.1-flash-maas) on Google's OpenAI-compatible chat completions at <address>/endpoints/openapi, and Claude (VertexClaude: an id starting claude- with no publisher, claude-opus-5-5 or Vertex's dated claude-sonnet-4-5@20250929) on the Messages API at that address, each request at its model's own path (VertexClaudeRequest: /publishers/anthropic/models/<model>:streamRawPredict or :rawPredict, count-tokens:rawPredict for a count, anthropic_version vertex-2023-10-16 in the body), as Anthropic's Vertex SDK in Claude Code asks it. The preset lists the current Claude models at global under the ids Claude Code gives them for Vertex. The provider's test asks Gemini alone, since a partner model or Claude answers only after the project turns it on in Model Garden. Each such model has its own test (TestModel, TestVertexPartnerModels, TestVertexClaudeModels), and a test as Codex is refused as it is for Claude Code. It is Ready once that address can be made (a project), or it has a key (express mode), never from an account; until then the app, magpie providers and the TUI say it needs a project, and magpie provider <id> says how to give it one. hasEndpoint counts it as a provider of the user's own, not a subscription's picks. Express mode (Langanpaibian on X): a Key and no project (VertexExpress) is asked at https://aiplatform.googleapis.com/v1/publishers/google/models/<model>:streamGenerateContent, the key in x-goog-api-key (Sign), no Google token read or minted. Google serves Gemini models alone there, so Base(Chat) and Base(Anthropic) are empty and the list drops partner and Claude models (vertexExpressModels). A key with a project is asked at the project's address, signed by the key. Vertex.BaseURL (any /v1 stripped, vertexRootOf) replaces Google's host for a keyed provider, such as a proxy; without a key it is refused at Save and dropped on load, so a Google token never goes to an address the user typed. An import link naming it is refused (ParseImport): its project and credentials are the user's own, which no link hands over. Sign refuses any other address and sets the bearer token before the user's Headers; AuthHeaders gives it no key header (a key is x-goog-api-key, set by Sign). Its models are its location's (vertexModels, in planModels): the preset has NoList, because Vertex AI has no list that says what a location serves. The lists are in the reference. |
vertex.go, provider.go, account.go, rename.go, models.go, importurl.go |
| Vertex AI tokens | vertexCredentialsFile finds the credentials as Google's libraries find Application Default Credentials: the provider's credentials, else the file GOOGLE_APPLICATION_CREDENTIALS names, else application_default_credentials.json in gcloud's folder (CLOUDSDK_CONFIG, else ~/.config/gcloud, %APPDATA%\gcloud on Windows); a ~/ that starts any of them is the home. mint reads three kinds: authorized_user (a refresh-token grant), service_account (an RS256 JWT, RFC 7523: signed) and gcloud's impersonated_service_account, whose source_credentials are minted and traded at IAM Credentials, along its delegates, for the account its service_account_impersonation_url names (impersonationURL: the token never goes to that URL's host). With impersonate set, the token those give is traded at IAM Credentials' generateAccessToken for a cloud-platform token of that account's, as gcloud's --impersonate-service-account does (impersonateFor); the credentials' account needs roles/iam.serviceAccountTokenCreator on it, which the 403 names. vertexTokens keeps one token per file and impersonated account, in memory only; requests made together mint it once, and those that waited through a mint that failed are given its error rather than each minting in turn (mints, failed). A mint cut short because its own request was given up on fails none of them: the next one mints. It is minted again within vertexRefreshLead (5 minutes) of expiry, or when the file's size or modification time has changed (gcloud signed in again). One mint, every exchange included, gets vertexMintWait (30 seconds). The file is only read. |
vertex.go, signin.go |
| Amazon Bedrock Mantle | bedrock-mantle ("Amazon Bedrock (Mantle)", @marktoown on X) is a vendor preset beside the runtime's bedrock, with the same Bedrock API key and seventeen regions of its own (mantleRegions: the bedrock-mantle.{region}.api.aws hosts that answered on 2026-10-16). Chat completions and Responses are at /v1, Messages at /anthropic; unlike the runtime it lists its models (GET /v1/models; NoList stays the runtime's alone). Its OpenAI APIs serve each model under one of two prefixes: OpenAI's closed GPTs and xAI's Grok under /openai/v1, the rest under /v1 (MantleBase, used by the gateway and the provider test's tinyBody). IsBedrockMantle is the preset or a provider added at a Mantle host (mantleHost), and IsBedrock includes it, so every Bedrock rule holds there too: Claude on Messages alone, the key as x-api-key alone, max_completion_tokens, no metadata, no Priority. A provider added at a Mantle address is given the APIs it wasn't (mantleEndpoints, in normalize), and a chat or Responses URL given at /openai/v1 is moved to /v1, where the list is. |
presets.go, provider.go, test.go |
| Subscription accounts | Accounts reads the credentials each agent keeps on disk or in the macOS Keychain; nothing is stored twice. With account discovery off (#1535, below) none of them is read. A built-in that has moved to its plugin is dropped (Moved), and plugin accounts are placed in its slot (placeMoved). Sign adds the account's own auth, then the user's Headers. |
account.go |
| Token refresh | Each account refreshes through its vendor. For example, codexToken refreshes within 5 minutes of expiry and writes the rotated tokens back where it read them (codexStore.write: ~/.codex/auth.json, or Codex's keychain item), every other field kept, for Codex CLI. Before refreshing a sign-in read from the keychain it asks the item again, so a rotation Codex made since isn't spent twice. A 400 or 401 from the vendor's refresh endpoint means it was refused (refreshFailed). |
account.go |
| Codex's credential store | Codex 0.162 keeps its ChatGPT sign-in where cli_auth_credentials_store in $CODEX_HOME/config.toml says (codex-rs/login/src/auth/storage.rs): file (default) is auth.json; keyring the system keychain alone; auto the keychain, else auth.json, on read and on save; ephemeral Codex's memory. Saved to the keychain, Codex removes auth.json (#2312, #2367, Dony2050). On macOS magpie reads that item through security, as it reads Claude Code's: service Codex Auth, account `cli |
+ the first 16 hex digits of SHA-256 of the canonical CODEX_HOME (codexKeychainAccount), the value auth.json's JSON on one line. readCodexLoginis the one reader:codexAccount, codexToken, liveLogin, CodexAPIKeySignedIn, codexLoginAuth, codexUntil(the usage card's and each saved account row'sUntil, from the sign-in Codex holds when it holds that one), session identities and the agent's wiring (provider.CodexSignIn: codexChatGPT, Agent.Source) go through it. keyringwith no item is signed out;autowith no item, or one the keychain wouldn't give, isauth.json, as Codex does. An item the keychain wouldn't give under keyring is not known (codexStoreError), never signed out. With [features] secret_auth_storageon (Codex's default on Windows) keyring and auto mean Codex's encrypted auth storage, which magpie doesn't read; nor does it read the Linux or Windows keychain. Therekeyringandephemeralare not known,autoisauth.jsonwhen Codex left one, and the saved accounts' reason says to setfile (codexSignedOutWhy). Requirements an admin manages (requirements.cli_auth_credentials_store) aren't read. Reading the secret can put up to two macOS prompts in front of the user, who may type their password, so one read per item is in flight at a time and waits up to 2 minutes for them (keychainAsk, askCodexKeychain), outside the cache's lock. A reader waits at most 5s from when that ask started (keychainHold) and is otherwise told magpie is waiting for an answer (errKeychainWaiting); no request or page waits out the prompt. security exit 44 is no item; 51 (errSecAuthFailed) or 128 (errSecUserCanceled) is denied or cancelled (errKeychainRefused); the 2 minutes running out is no answer (errKeychainNoAnswer); anything else is errKeychainUnread. Each says so in the saved accounts' reason, and none of them is signed out. A read the keychain gave is kept while the item is unchanged: after 10s a reader asks only the item's modification date (Stat, find-generic-passwordwithout-w, which shows no prompt) and reads the secret again only when Codex or magpie changed it (#2367: with "Allow" once, background polls asked again every ~30s). A refusal or no answer is kept 10 minutes (#2408). magpie's own writes (codexStore.write, keepCodexKeychain) keep the date of what they wrote; a switch, sign-out or refresh forgets a read (forgetCodexKeychain) so the next one checks the date, but keeps a refusal; switching and refreshing read afresh. Beside a refusal, no answer or waiting, the saved accounts' line has Try again (Exclusion.Retry, keychain-retry, RetryCodexKeychain), which reads once past the refusal, and the reason says "Always Allow" lets /usr/bin/security read the item, so macOS stops asking each time Codex changes it. A switch or a first sign-in (saveCodexLogin) writes the store Codex reads, and refuses when that store couldn't be read, when config.toml doesn't parse, or when it is one magpie doesn't read; it leaves an auth.json beside the item to Codex. Signing the last account out (deleteCodexLogin) removes the item, then auth.json, as codex logout`. Not tried against an item Codex itself wrote: macOS may ask whether magpie can read it, and Codex whether it can read one magpie rewrote. |
| Codex's other folders | Codex keeps one ChatGPT sign-in a folder (codex-rs/login/src/auth/storage.rs: $CODEX_HOME/auth.json, or the keychain item named by the folder) and writes its sessions there (rollout/src/lib.rs); --profile only lays $CODEX_HOME/<name>.config.toml over config.toml, the sign-in shared (config/src/loader/mod.rs). So a second account is Codex run with CODEX_HOME=~/.codex-work. appdir.CodexHomes finds those folders: CodexHome first, then folders in the home folder or beside CodexHome named codex* or .codex*, or one folder down in one (~/.codex-profiles/work), that hold auth.json or sessions/. Sessions and the usage ledger read every one (sessions.codexFiles, Dirs). rememberLogins saves each folder's account with Home set to it (codexHomeLogins); the one ~/.codex is signed in to is that one's. Such an account is renewed in its folder, as Codex's own (codexHeldIn in renewSaved, as heldByCodex does for ~/.codex), so the quota, the gateway and the keep-alive never spend a copy's refresh token under that folder's Codex. It isn't switched into ~/.codex (switchSavedLogin, NextLogin's spares): the error names the folder and the CODEX_HOME=… codex command. A refresh OpenAI refuses there marks the account signed out (codexHeldRefusal, codexSignInRead), so its row has Sign in again, and magpie's sign-in writes the new tokens back to that folder (codexHeldFolder in addLogin), never to ~/.codex (TestCodexHeldInOtherFolderSignedOutThenSignedInAgain). Remove forgets it and sets that folder's sign-in aside in codex-homes-removed.json (the folder to a SHA-256 of its refresh token, setCodexAside), the folder's files left as they are; codexHomeLogins passes over the folder while it holds that sign-in, and a sign-in made there again is listed again. An unreadable record reads no other folder's account that look (charliepu on Discord: a .codex-db-backup-… folder no Codex runs in, refused with "codex logout"; TestCodexHeldFolderAccountRemoved). phantom3792 on X: only the default folder's sessions counted, and an account added from another folder read no quota (TestCodexOtherHome*, TestCodexHomesIn). Not done: Codex's thread names (session_index.jsonl) and a sqlite_home are read from CodexHome only (#3530). |
codex.go, logins.go, codex_homes_test.go |
| A revoked sign-in | A 401 whose words say the sign-in itself is gone (SignInRevoked: ChatGPT's token_revoked, invalid_grant, refresh_token_reused; never token_expired, a 403, a 5xx or a network error) marks the account for the credential it was sent with (NoteRevokedSignIn, #1793). A saved ChatGPT account is refreshed first, as Codex does on a 401, and a refresh that goes through marks nothing. The mark is a hash of the header, never the credential, kept in logins.json as Refused: "revoked:<mark>" with the account's Lapsed, and read back after a restart. While the account has that credential, the gateway doesn't send its requests (RevokedSignIn); its row says Sign-in required with Sign in again. A ChatGPT account's usage read marks it too (codexSignInRead in loginQuota, charliepu on Discord: an account OpenAI signed out showed only a blank allowance): /wham/usage answering 401 with those words is refreshed once (codexWindowsRenewing), and the account is marked for the token turned away when the refreshed read is turned away the same (codexSignInGone), or, for the one Codex is signed in to, when its refresh is refused (its row used to say nothing, its allowance line "run codex login"; a saved one's refused refresh is savedRefreshFailed's). Any other 401, a 403, a 5xx or a network error is unknown and marks nothing. Each failed read says why on the account's row (codexUsageWords, codex_usage_words.go; hmy on Discord: five ChatGPT accounts each said only "Allowance unavailable", the error being Go's bare status text or decode error, which the GUI read none of): Cloudflare's challenge page in place of an answer (a proxy or VPN address, usually), HTTP <code> with the backend's own detail or error words, chatgpt.com not reached, or a reply magpie doesn't read; quotaError in app.js turns each into a line of the card's language, the raw error in the row's tooltip. The words keep what was matched before: the status text that passing (quota_last.go) reads to keep the last reading over a 429 or a 5xx, and the answer itself under Unwrap for codexExpired. An error with no words of its own says "Allowance unavailable — hover for why". A ChatGPT API account (chatgpt-api, chatgpt_api.go) has no usage read: OpenAI's API tells none, only chatgpt.com/settings/usage does. loginQuota says so (siwcNoUsage, with that page as SeeAt) and asks nothing; it used to read the account as a Codex one, so an active one read Codex's own sign-in ("Codex is signed out; run codex login", or another account's allowance under its name) and the card said only that it couldn't be read (danzi002 on Discord). Guarded by TestChatGPTAPIUsageSaysWhere. Sign in again runs magpie's own sign-in for the account (addLogin), which replaces its tokens, in Codex's auth.json too when Codex is signed in to it. Signed in anew (upsertLogin with another credential, addSideLogin), refreshed, served a request (ServedSignIn), or its usage read going through, it is clear. Claude (claude_auth.go), Copilot (copilot_lapsed.go: GitHub's 401/403 on the token exchange, the CLI's stand-in or the usage read, cleared when a token is served) and plugins keep their own marks. |
signin_revoked.go, copilot_lapsed.go |
| Sign-in alerts | A system notification tells of an account in use (On or Active) of a subscription switched on whose row says Sign in again (steven_4422 on Discord: before, only the row and its Signed out pill said so). The test is the Providers page's (renderAccounts): any Lapsed on a Claude, Copilot or plugin account, and on another built-in one a mark signInGone matches (needsSignIn); a plugin's usage read that says so marks the account too. A Claude account is told of three days before its sign-in ends as well, as Claude Code's own "Your login expires in N days" is: its credentials' refreshTokenExpiresAt (Claude Code sets it from the token reply's refresh_token_expires_in, else 30 days from the sign-in, and keeps it over a refresh that sends none; past it, Claude Code takes the sign-in for none), unless the access token outlasts it by more than the three days (claudeSignInEnds). Each is told once (dueSignIns): a lapse until the account is usable again, an end until it moves; the marks are kept in signin-alerts.json beside providers.json, so a restart doesn't tell again, and an account not listed keeps them alertKeep. An unreadable marks file tells nothing. WatchSignIns looks a minute after start and every two minutes after, reading magpie's own files only. It is always on. The GUI sends it under `magpie-signin- |
(signInKind, signInText in five languages), and a click opens that provider's editor (clickView→providers&edit=), where the account's Sign in again is; a Linux dismissal opens nothing. The magpie serving the gateway tells the same alerts to request hooks' onSignIn, with marks of their own in signin-hooks.json([gateway-request-hooks](gateway-request-hooks.md#sign-in-notification)). Guarded byTestSignInAlertClaudeSignedOut, TestSignInAlertClaudeEnding, TestDueSignIns, TestSignInAlertOpensItsProviderandTestRevokedAccountToldToHooksOnce`. |
| A token called expired | A ChatGPT 401 whose words say the access token has expired and ask for a refresh (SignInExpired: token_expired, "Provided authentication token is expired. Please try refreshing it."; never refresh_token_expired, which is revoked) while the token's own exp is still ahead (willz on Discord, #2973: two saved Team accounts) is mended by one refresh. codexToken refreshes only as exp nears, so before this the token went out as it was until the user signed in again, and the card said only Unauthorized. The usage read (codexWindowsRenewing: loginQuota, codexSubscriptionUsage, and the reset spenders through codexUserWindows) refreshes once and reads once more, never again: a refresh refused says to sign in again (a saved account is marked lapsed, savedRefreshFailed; Codex's own is marked revoked, see A revoked sign-in, through loginQuota, while codexSubscriptionUsage's card still says codex login), and a token refreshed for it and still called expired says so too (errCodexStillExpired) and is marked revoked the same. The gateway renews the account a request went with (NoteExpiredSignIn from noteSignIn, 20s at most); the request itself fails over as before, and the next goes with the new token. Each refresh is keyed on the token turned away (codexTokenRenewing, renewSavedLoginFrom), under the lock signing waits on: a sign-in holding another token by then, renewed by Codex or another reply, is used as it is, so two replies for one token spend one rotation. Codex's own sign-in is read from its store afresh for it and written back through codexStore.write (temp and rename), a saved one's through writeLogins. Not tried against the real backend. |
codex_expired.go, account.go, logins_on.go |
| Saved accounts | logins.json remembers every Codex and Claude Code account seen signed in. A switch moves the credentials into the agent's own store and saves the ones it replaces. A saved account that is on (SetLoginOn) stands behind the agent's own. Its tokens stay in logins.json. While Claude Code is signed out, a saved Claude account stands in for its own (claudeStandIn); with every saved account's sign-in gone, Claude Code is still listed, on the one seen last, signed out (claudeListed), its accounts each saying to sign in again, so it never leaves the Providers list (LeeHom on Discord). Claude Code's own account while still Held is never listed that way, since the sign-in it may have left on disk would be served. A Held account never gets a config directory of magpie's either (claudeSavedDir refuses it, errClaudeHeld): a second Claude Code there would spend the refresh token Claude Code holds and sign it out. A sign-in that can't be read whole is no sign-out: Claude Code on Windows rewrites .credentials.json and .claude.json in place while magpie has the file open (its rename gets EPERM), so a read can find either empty or cut short. Until such a read has lasted claudeUnsureGrace (2 minutes), the Held account stays active and is not marked lapsed (claudeSignInUnsure in rememberLogins, Logins and renewLogins); it is marked lapsed only when the file is gone, Claude Code emptied it, claude auth status says it is logged out, or no account is named (xbpb6 on X: the account said Sign-in required over and over on Windows; TestClaudeHalfWrittenSignInIsNoLogout). The Mac's keychain item is read whole or not at all, and there nothing changes. An account whose every login in use has lapsed is Provider.SignedOut: magpie providers and the TUI say " is signed out", as the app's row does. |
logins.go, logins_on.go, claude_dirs.go |
| Sign-in in magpie | StartSignIn runs the vendor's own browser OAuth with its client and takes the tokens at a callback on this machine. A browser that can't reach that callback (magpie on a server or in Docker) ends on a page that won't load; its address, pasted (SubmitSignInCallback), goes through the same callback handler (pastedCallback). ChatGPT's sign-in comes back only to port 1455; when that port can't be opened, the sign-in still starts and waits for the pasted address alone, and says why in CallbackBlocked with the port in CallbackPort: reserved for Windows' WSAEACCES on a port in a range it excludes for Hyper-V, WSL or Docker, busy for anything else, such as another program holding it (callbackBlocked, #1782). ChatGPT also signs in by device code, as codex login --device-auth does (CodexDeviceSite, startCodexDeviceSignIn in codex_device_signin.go): magpie asks auth.openai.com/api/accounts/deviceauth/usercode for a code, the box shows it with ChatGPT's device page, and magpie polls deviceauth/token (403 or 404 is not entered yet, up to 15 minutes), then trades the code at the token endpoint with the verifier it got and the /deviceauth/callback redirect. Nothing listens on this machine. The window starts this way when magpie web is opened from another computer (remotePage in app.js: a host other than localhost or loopback; curtinp118 on Discord, magpie on a VPS), and the box offers the other way as a link either way; a device code ChatGPT turns away (404) fails with a link to the browser's way. A plugin's browser sign-in (auto) whose page names a port on this machine to come back to takes its pasted address too: magpie opens it there on 127.0.0.1, for the plugin's own listener (pluginCallback, loopbackPorts); Command Code's page posts its key from script, so it offers the API key way instead. A Claude account is signed in by Claude Code itself. Signing in brings back an account removed from magpie (ShowAccount). A sign-in started in magpie (StartSignIn, StartPluginSignIn) reads as done (SignInStatus, WaitSignIn) only after finish has run ShowAccount for its account, so the window, which opens the account as soon as it sees done, finds it listed. If providers.json can't be written then, the account stays hidden and the sign-in still ends done. Signing in to a plugin's provider from the command line (pluginLogin, with a key or the browser) brings it back too. It also takes off the mark a sign-in its vendor turned away left on the account (Lapsed) and shows again the agent's own account removed in magpie (clearPluginLapse). The window's plugin sign-in does the same with the browser (pluginDone, then finish) or with a key (PluginAPIKey); a key and the command line share these steps in PluginSignedIn. A sign-in leaves through the proxy the account's own requests will use (#1663): ProxyOfLogin (the account's, else the subscription's, else the global one) for the account being signed in again, the subscription's for a new one. Every request of the flow goes through signInFlow.via, Claude Code's own login gets it as *_PROXY (netproxy.EnvWith), and a plugin's sign-in runs its fetch under that proxy (via in host.js; plugins_cli.go for the command line). The window's sign-in box shows it as a "Proxy: …" link (signInProxyLink, the app menu, no userinfo shown) with Global, Direct, the subscription's and each account's proxy, or a typed one; picking one starts the sign-in again through it (SignInOptions.Proxy), and when it ends the pick is kept as the account's (keepSignInProxy: the subscription's own when it is its only account, else the account's entry). Global isn't offered while the subscription has a proxy and other accounts, since nothing could keep it. The browser's own leg goes through the browser's network, not magpie's. The window or magpie web opens the sign-in page in the default browser (openSignIn in internal/gui/api.go; openSignInPage in app.js for a web tab), and the waiting box always shows the link with Copy link. With Settings › Privacy › Sign-in pages off (SignInLinkOnly, max2020 on Discord, who signs in from a separate fingerprint browser), magpie opens nothing: the reply carries linkOnly, the box says the page wasn't opened, with a Settings › link to the row, and offers Open, and magpie accounts add and a plugin's browser login from the command line (pluginLogin) print the link without opening it. A callback on this machine still comes back from another browser on it, and the pasted address covers one that can't reach it. A plugin whose own CLI opens the page (opened, Grok Build's device sign-in on macOS and Windows) still opens it. Signing out leaves through the same exit: a ChatGPT account's refresh token is revoked through its own proxy, read before the account is forgotten (forgetSIWCLogin), and Devin's CLI, asked who is signed in or for its models, runs with the account's proxy (devinCommand, devinProxy). |
signin.go, codex_device_signin.go, claude_signin.go, pluginsignin.go, pluginsignin_paste.go, proxy.go, plugins_cli.go |
| Import from files | ImportLogins (ChatGPT, Claude), ImportGoogleAccounts (Antigravity) and ImportFactoryKeys take other tools' files, from the window (signin/import) or magpie accounts import (#1453). ChatGPT reads Codex's auth.json, CLIProxyAPI's and Cockpit Tools' files, Sub2API's export (sub2apiEntry) and codexbar's ~/.codexbar/config.json (codexbarEntries: the openai_oauth provider's accounts and openAI.remoteConnectionAccounts, the workspace from openAIAccountId). Each ChatGPT and Google sign-in is refreshed before it is added, so the tool the file came from is signed out of it; both surfaces say so first, and the command imports nothing without --yes or a yes. Claude reads CLIProxyAPI's files and Sub2API's export, whose Claude account says its email as Anthropic does, email_address, in credentials or extra, and keeps its scope, account_uuid and org_uuid as Claude Code's scopes, accountUuid and organizationUuid (#1975); a file with no email is refused, as Claude Code's own .credentials.json is. Claude's are kept as the file has them. Claude also reads claude-swap's cswap export (format 1, claude-swap 0.29; cswapEntry, #4532): each account's credentials.claudeAiOauth and config.oauthAccount, with its organization name, and its alias becomes the account's name when that account has none and no other account is called or signed in as it (importNames). An encrypted export, another format, a Codex entry and an API-key entry are refused with what to do; testdata/cswap_0.29.0_export.json is claude-swap's own output. A refresh token magpie holds already is exists, never refreshed; accounts are matched by email and workspace, or for Claude organization (sameLogin). A Claude sign-in for an account magpie has, Claude Code's own or a saved one that can be used, with another refresh token is taken only when the file's expiresAt is later than the one magpie has (the account's own config directory counted, claudeNewerKept); otherwise it is exists with why, and nothing is written: an export made before Claude Code's last refresh holds a spent refresh token, and written over Claude Code's own it signed the account out (#4532, TestImportCswapKeepsNewerSignIn). A file that gives no expiresAt never replaces one. A sign-in itself imported and never run since is kept with expiresAt 1, so any dated file is taken over it. An entry with an access token and no refresh token is refused (accessOnly). A line (or a JSON string) holding a setup-token (sk-ant-oat…, as claude setup-token prints it, bare, as CLAUDE_CODE_OAUTH_TOKEN=… or export …) is added as one by AddClaudeSetupToken, never taken for a refresh token (bareImport, importSetupToken, liukaybee on X); one magpie has is exists, an API key pasted there is refused, and in the ChatGPT import it is refused as Claude's, nothing sent (TestImportClaudeSetupToken). One file of several that holds no account is a failed row with its place (ImportedAccount.File), never skipped. The files are only read. |
login_import.go, google_import.go, factory_key.go, accounts_cli.go |
| Antigravity to agy | The withdrawn Antigravity plugin (antigravity) signed in with Antigravity's own Google OAuth client, the one agy signs in with, so its accounts move to Antigravity (local agy CLI) as they are (@tongzhenbao on X). AgyMoveUsers names the plugin's sign-ins (then the built-in's never moved) whose email agy-cli doesn't have, as agyMove in /api/providers; the line over the list (agymove.js, imported only when there are any) has Move and Not now. MoveToAgy (provider/toagy) installs agy-cli at agyCLIMin (0.1.68, whose auth.import takes them; from the plugins repo's dist branch while npm has none), agy when it is missing, and hands every sign-in to its import, which writes each into an agy home of its own and keeps it only once agy models runs with it; one agy refuses is said by name (agyMoved). The token goes only where it went (Google, through agy), and the old sign-ins are left where they are. TestAgyMoveUsersAreTheOldPluginsNotInAgyCLI, TestMoveToAgyImportsTheOldSignIns, TestToAgyMovesAndSaysEachAccount, agy-move.test.cjs. |
agy_move.go, providers.go, agymove.js |
| Export to files | ExportLogins (ChatGPT, Claude) writes the saved accounts in the two formats ImportLogins reads (heyiwei5 and Rk1ngggg on X): Sub2API's sub2api-data (one file, sub2apiAccount: platform openai or anthropic, as Sub2API's account_data.go has it) or CLIProxyAPI's auth files (one an account, cliproxyAuth, named <type>-<email>[-<plan>].json), so a round trip into magpie, Sub2API or CLIProxyAPI works (TestExportClaudeRoundTrip, TestExportCodexRoundTrip). A CLIProxyAPI Claude file also carries account_uuid and org_uuid, which its own readers ignore and loginEntry keeps, so two seats of one email stay two accounts. The file holds live sign-ins: it is written 0600 and never over a file (WriteExport), no surface prints a token, and each says first (ExportRisk) that whoever has the file is signed in as the account, and that a ChatGPT refresh token renews in one place only, so the first tool to renew it signs the other out. An account with no refresh token (access-only, a setup-token) is skipped and named with why. The window's Export accounts to a file… row on a ChatGPT or Claude account list (acctexport.js, POST /api/signin/export) saves into Downloads (a folder of its own for CLIProxyAPI's) and shows the path; magpie accounts export <codex|claude> [<email>...] [--format sub2api|cliproxyapi] [--to <folder>] [--yes] asks first without --yes. |
login_export.go, accounts_cli.go, gui/providers.go, acctexport.js |
| Claude setup-token | A Claude account can be added from the long-lived token claude setup-token prints (sfss5362 on X), which Claude Code takes in CLAUDE_CODE_OAUTH_TOKEN (the window's Use a setup-token instead… and Add an account by setup-token…, POST /api/signin/claude-token). AddClaudeSetupToken keeps it in logins.json as {"setupToken":…}, named Claude setup-token <6 hex of its hash> (it tells no email), on beside the others; the same token again is the same account. Such a token has the inference scope only: Claude Code's auth status says oauth_token with no email or plan, and its /usage prints the API cost view, so /usage is never run for it and its allowance is unknown (errClaudeSetupToken, kept by passing as saying nothing about the account) until a reply's rate-limit event tells it. Its config directory (claudeTokenDir) holds no .credentials.json, which Claude Code could fall back to on a refused token. Nothing of it goes in Claude Code's keychain or .credentials.json: addLogin, putClaudeLogin, SetKeepLoginAs (errClaudeTokenSwitch), NextLogin's spares and signInToFirst pass it over. Claude Code itself is switched to it by hand only (liukaybee on X, claude_token_env.go): its row's Use (SwitchLogin) writes the token as env.CLAUDE_CODE_OAUTH_TOKEN in Claude Code's user settings.json, which Claude Code takes over its stored sign-in, and keeps the token's sha256 in claude-token-env.json; the stored sign-in is left as it is, and stays the Active account the gateway and magpie's own runs use (they read no user settings: --setting-sources ""). Login.Uses marks the token Claude Code uses; the window says In use on it, and Signed in with a Use that switches back on the account signed in to. A switch to any signed-in account takes magpie's token out first (a settings.json that can't be read refuses the switch and keeps the record), and so does removing the token's account (claudeTokenGone). A value the user set there, or changed from magpie's, is theirs: never written over (errClaudeOwnToken) nor taken out. While the token is in use NextLogin moves Claude Code nowhere, as its allowance can't be read. Claude Code reads its env as it starts, so sessions started after the switch are on the new account. Tried with Claude Code 2.1.316 in a sandbox: a token there is used over a valid stored sign-in, and with it taken out the stored sign-in is used again. TestClaudeCodeSwitchedToSetupToken, TestClaudeOwnEnvTokenLeftAlone, TestClaudeEnvTokenUnreadableSettings, TestClaudeSetupTokenRemovedLeavesSettings, TestClaudeSetupTokenInUseNotMovedOff, claude-setup-token.test.cjs. |
claude_setup_token.go, claude_token_env.go, claude_subscription.go (inClaudeDir), providers.go |
| ChatGPT access token only | A saved ChatGPT account can be kept with only the access token it has (EastonXvii on X: savedLogin.AccessOnly, codex_access_only.go), from the import (ImportCodexAccessOnly; the window's Access token only tick, magpie accounts import codex <file> --access-only) or on a saved account (SetLoginAccessOnly; POST /api/login/access-only and /renewed, the row's ⋯, `magpie accounts access-only codex on |
off). magpie never refreshes it, which would rotate its refresh token and sign out where it came from: the import sends nothing to ChatGPT's token endpoint and needs an unexpired access token and an id_token (a refresh token is optional, and the import is told apart by its access token); renewSaved hands out the token while its own exp is ahead (accessOnlyToken), refuses a forced renewal without lapsing, and lapses the account once the token has run out or the backend turned it away (accessOnlyLapse, a refreshRefused); the keep-alive passes it over. Codex itself is never signed in to it (switchable, switchSavedLogin, NextLogin's return, keep-as), and the account Codex renews itself, here or in another CODEX_HOME, can't be kept so (errAccessOnlyHeld`). Its row says magpie only, and once lapsed Access expired with Import again. Signing in to it again in magpie, or importing it without the tick, replaces the entry with one magpie renews. |
| Switch accounts only | magpie as a Claude Code (or Codex) account switcher alone, with nothing connected (the owner on X; growaiskills, Rennix7t). In the window, the Agents row of a Claude Code or Codex not connected says the account it is signed in to (switchEntry in app.js, from the providers list prefetchProviders reads at start, so /api/state reads no keychain for it), also when magpie has no models to connect (switchable, before the empty line). Its menu, headed Switch accounts only, lists the agent's saved accounts: a pick goes through POST /api/login/switch (SwitchLogin), or provider/keeplogin with keepLoginAs when the agent is kept signed in to an account of the user's choosing, as the account rows do; the button says Switched for five seconds and the status line says new sessions use the account, one already open keeps its own until started again. Only switch {agent}'s sign-in (SwitchOnly above, provider/switchonly) is a ticked item there (Codex: with more than one usable account, as under Providers), and the row then says Not connected · switching accounts only. Manage accounts…, and a pick whose sign-in lapsed, open Providers › the agent. A Codex still failing over from a magpie before (#1385, until the next Sync takes it out) has it in place of the old ChatGPT accounts button. In the tray panel (whose Quick panel shortcut opens it from any app, shuizhuyu on X) it is the account line of the agent's opened row (.ag-who), drawn from the list kept from the last read (panelAccounts, GET /api/providers?last=1, no keychain read; a fresh read only when none is kept), so opening the panel reads no sign-in. The menu waits for one fresh /api/providers read and opens on what it says; Manage accounts… and a lapsed pick open the window's Providers (window/main?view=providers). The provider and login actions keep their answer as the last list (keepProviders), so a switch made anywhere is in the panel's next line at once (TestKeptProvidersFollowActions, panel-switch-accounts.test.cjs). Not on a WSL twin's row, not on a connected agent's. |
app.js, logins.go |
| Used-up switch | When the account Codex or Claude Code is signed in to has used its allowance, the agent is signed in to the next account that is on and has room (#208). Claude Code whose requests go to magpie's gateway (ClaudeThroughMagpie: its settings' ANTHROPIC_BASE_URL is the gateway, either sign-in) is not moved: the gateway already sends its requests to an account with room, and moving the sign-in only took away what the user signed it in for, such as claude.ai connectors (oreoft on Discord set it back more than ten times; TestClaudeRoutedThroughMagpieKeepsItsSignIn). Not routed, or with Only switch Claude Code's sign-in, it still moves. Codex's sign-in goes back to the account it moved off once that has room again, as the gateway's Smart and In order give it requests again; routed Until used up it doesn't, as the gateway keeps the requests on the next (routes.Drain), so it stays with them till that one is used up too, as Claude Code's and a switch-only Codex's do unless routed In order (returnsToFirst; WalterAIBuilder on X: Codex signed back in to the first showed that one in use while the second's week was spent, TestCodexDrainSignInStaysOnTheNext). When every one is past its line too, it goes to the one with the most room left (roomLeft: the fullest stopping window's distance below the switch share, or the account's own cap when lower), when that has more than the account it is on by roomMargin (1 point), so two all but even accounts don't trade it each look; else it stays (StringKe in #4532, after cswap's best; TestNextLoginTakesTheMostRoomWhenAllArePast). A Claude account on overages (/usage's "You are currently using your overages…" line) is read with its windows and a spent Extra usage row of text (claudeOveragesWindow: Used 100, ending when the last used-up window renews, else at the next reading), so it is moved off as a used-up one; before, the line made the reading an error, and the switch, which stays on an account it can't read, left Claude Code billing overages (StringKe, #4532; TestClaudeSwitchOffOverages). The GUI says the row In use in the reader's language. Under the accounts of a Claude Code or Codex with more than one, the switch is a switch of its own, Switch {agent}'s account automatically (the auto-switch box in app.js; off is KeepLogin, posted to provider/keeplogin; before 11-11 a Keep {agent} signed in to tick that turned it off, which a user read as the switch gone). On, a line under it says what the switch does with that agent's sign-in (SignInMovesOf, signInMoves on its /api/providers row, signInMovesLine): left where the user put it while Claude Code's requests go through the gateway (gateway), else the share it moves at and whether it comes back to the first (moves), each decided as NextLogin decides it (TestSignInMovesSaysWhatSwitchDoes). Off, it names the account the agent stays on, with a pick of another (keepLoginAs). Switch-only always moves the sign-in, so the switch is held on there (sign-in-moves.test.cjs). Beside the switch, an ⓘ mark whose hover card (settingshints.js, the box a .hint-row with its .hint lines out of sight) says how the switch works and why it is the agent's own use of the account: the sign-in written where the agent keeps its own, as /login or codex login does; usage read by Claude Code's own /usage or where Codex's /status reads it; for Claude Code, every request still sent by Claude Code itself straight to Anthropic; and that sharing an account is against the vendor's terms. It promises nothing about bans (autoswitchtip.js, loaded when the switch is drawn). Only where the sign-in moves: moves, or kept without routed, which SignInMovesOf sets when Claude Code goes through the gateway, so turning the switch on would move its requests, not its sign-in. Routing (Allowances) skips Text rows, so the gateway's own choice of account doesn't count it. A model's own week (Current week (Sonnet only), (Fable)) counts for that model in routing, not for the switch, which moves the sign-in only on windows that count every model (usedPast); "Sonnet only" is read as the Sonnet week, 7 days · Sonnet counting sonnet, the window the seven_day_sonnet header keeps (#4532, TestClaudeUsageSonnetOnly). `magpie accounts switch <claude |
codex> next (NextInOrder) takes the other accounts the agent can be signed in to (switchable, not lapsed), on or off in magpie as the accounts list's *Use* does, so one the agent signed itself in to, which starts off, is in the rotation (StringKe, #4532; TestNextTakesAccountsThatAreOff), from the one after the account the agent is on, wrapping round: the first with room, else the one with the most room left, said to be past its line; with no reading of any, it refuses rather than guess (TestNextInOrder). For Codex, *Only switch Codex's sign-in* (SwitchOnly, SetSwitchOnly) keeps magpie's openai_base_url failover out of Codex's config, so the switch is all magpie does (#1907); an unreadable providers.json reads as switch-only, so the failover is not written on a guess. For Claude, the same setting keeps the accounts to Claude Code (Provider.KeptToAgent): On()is false, so the gateway, catalog and groups serve nothing on them, while switching and usage, gated byleftAloneon the rawOff, go on. No request of a saved Claude account passes magpie then, so one Claude Code wasn't signed in to since has no reading: once the account Claude Code is on is spent, NextLogin reads such a spare (readSpare, spareReadinclaudeWindows) by Claude Code's own /usagein the account's directory, in order and only till one has room; a spare read once is not read again, and one whose read failed waitsclaudeUsageWait(cn_Vincentzyx on X,TestClaudeSwitchOnlyReadsUnreadSpares). Codex's spares are read through their saved tokens and had no such gap. Claude Code on its own login is out long before a five-minute look notices (#4443: 4% left to refused in two minutes): while Claude has an account to move to, KeepOnAnAccountWithRoomlooks at its sign-in everyclaudeLookEvery(a minute) between its full looks whenclaudeLookDue, that is when the account Claude Code is on is near out (claudeNearOut, codexNearShare; its /usageis then due afterclaudeNearOutWaitrather thanclaudeUsageWait), or when Claude Code wrote a rate_limitrefusal ("You've hit your … limit") into one of its sessions since that account's last/usage (scanClaudeLimits, which reads only what was appended to each projects//.jsonlsince the last scan). The refusal names no account, so it only makes the/usageread due (and the reading stale,StaleAllowance); the read decides (TestClaudeNearOutIsReadEveryMinute, TestClaudeRefusalInSessionReadsAtOnce, TestKeepOnAnAccountWithRoomLooksAtClaudeNearOut`). |
| Removing the signed-in account | ForgetLogin signs Codex or Claude Code in to another of its accounts first (nextOnForget: the first other that is on, else one whose sign-in holds, else any, never a setup-token account or one Codex keeps in another folder: switchable), then forgets this one; a switch that fails removes nothing (StringKe, #4532: Claude's was refused while Codex's switched). Codex's only account is signed out as codex logout does. Claude Code is never signed out: its last account it can be signed in to is refused with SignedInError{Only} (GUI code signed_in_only, and that account has no Remove). Claude Code's own credential is never deleted; the forgotten account's folder (forgetClaudeDir) is its own. TestForgetLiveClaudeSwitchesFirst, TestForgetOnlyClaudeIsKept, codex-signout.test.cjs. |
|
| Claude Code's proxy | Claude Code on its own subscription asks Anthropic itself, through the proxy its env names. While any Claude account has a proxy of its own (AccountProxies), the env of Claude Code's settings.json names the proxy of the account it is signed in to (#1807): HTTPS_PROXY and HTTP_PROXY set to that account's own, else the subscription's Proxy (ProxyOfLogin), and NO_PROXY to loopback; none for direct or a SOCKS proxy, which Claude Code can't use. It is written on every switch (switchLogin, the user's or SwitchWhenSpent), when the Claude subscription is saved, and at the gateway's look every loginSwitchEvery (a sign-in made in Claude Code itself). Claude Code reads its env at start, so only sessions started after the switch take it. A proxy key the user set (in either case) is theirs: magpie then writes none and takes out none of theirs. What magpie wrote is kept in claude-proxy-env.json, and a key is magpie's only while it holds that value. A settings.json that doesn't parse is left as it is. Its log lines name the proxy through netproxy.Redact, without its user and password (#1886); the env gets it whole. |
claude_proxy_env.go |
| Routing groups | User-made groups from the Routing view, and auto-found groups of the same model across providers (derived, never stored). The same model is the same id as vendors agree on it (sameModel): lowercase, without a vendor's prefix, a version's dot as -, a run of spaces, _ and - as one - (a relay listing its display name as the id, GPT-6 Sol, joins gpt-6-sol, Chill on Discord: TestSameModelDisplayNameAsID), and without a YYYYMMDD or Ark YYMMDD snapshot date. The found groups also merge a model a plugin offers at a context window of its own, after an @ (mergeName, windowless: Cursor's claude-haiku-5-5@1m and claude-opus-5-5@300k, grok's grok-4.7@500k and grok-4.7@131072), into its model's group, listed by the model's id: the same model at the same price per token, and a group's members differ in window by provider anyway (Will on Discord: claude-haiku-5-5@1m ticked in Cursor stayed out of auto/claude-haiku-5-5). A provider is one member: its unsized model when it lists one, else the first size it lists; the editor's Same as shows the windowless name (MergeName). A Vertex @20260801 is a snapshot date, and any other @ stays (TestAutoGroupsJoinAModelAtItsWindow). Every word still counts (gpt-6, gpt-6-mini and gpt-6-sol stay apart), as do a :variant, a four-digit release and OpenAI's dashed date (gpt-4o-2024-08-06, a pinned snapshot whose group id agents may already name). A provider kept "Only through routing groups" joins them the same way. Members are provider/model[:effort]. A group can nest another (group/<id>); SaveGroup refuses loops. A group given another id (agent.RenameGroup: the Routing groups page, magpie groups rename, the TUI) moves every agent field on group/<old> to group/<new>, spelled as the agent spells it, through the same renameRefs a provider's rename uses, then SyncCatalog; before, the agents stayed on a group magpie no longer had (lucis0116 on X, TestRenameGroupMovesTheAgentsOnIt). A provider's or group's display name needs no move: store and SaveGroup drop the catalog, and SyncCatalog writes the new labels into every agent's list. Match takes a glob or re: pattern (#766), both matched in any case (compilePattern; (?-i) inside a re: makes case matter). A free: before one (FreePrefix, compileRule, #5903) keeps, of the models the rest matches, those whose catalog entry says free (Entry.Free, the vendor's or plugin's flag as last read): free:workbuddy/*. A $0 price (PricedFree), a rate, an account's name or an id with free in it never counts, and the GUI's hint says the flag is no promise of no charge. A provider's AutoInclude takes no free: (isIDPattern). What a pattern matches follows the members named, in the catalog's order, until the user drags it elsewhere (usrname1833 on Discord): Placed keeps the whole order, named and matched alike, and the group is read and routed in it (placedIn); a model matched since goes last, one no longer matched drops out, a save that sends the named members only leaves the matched where they were (placedOver), and a provider's or group's rename carries it (TestGroupPatternMembersKeepTheirPlace, group-member-drag.test.cjs; a member is dragged by its number or its row's logo and room around its words, group-member-row-drag.test.cjs). A found group follows the providers magpie has: one removed leaves it, while one switched off stays in it (foundGroups, heldOffEntries; one without a key, such as a plugin not signed in, finds no group), skipped by membersIn, left off a found group's card, logos and TUI line with a count of those switched off (XYenon on Discord: routing-provider-off.test.cjs, TestFoundGroupLineLeavesASwitchedOffProviderOut) and said as switched off in its editor and the TUI's group page, so switching one of two providers off for a while doesn't take the group away from the agents, rules and groups set to it; it is back in its place once on again (#2671: TestFoundGroupStaysWithAProviderOff, TestFoundGroupWithAProviderOff, TestReseatKeepsAFoundGroupWithAProviderOff, TestFoundGroupMemberOfASwitchedOffProvider). A found group the user changed (an auto-… id stored) is read without the members of providers magpie no longer has (withoutRemoved, not written back, so a provider back under its id is back in it), except a manual group's pick, a rule's model, or all of them when none would be left. It keeps following its model as a found group does (Kxsg79bEYFP4 on X: a third provider with the model, a plugin's, had stayed out of a group the user had changed): SaveGroup stores, for an auto-… id, what it had seen (Group.Seen: the models magpie found in it by that save, and those the user named, as provider/model), and a provider that serves the model since joins it as it is read, after the user's own members (joined, not written back), unless kept out of found groups. A model seen and not a member is one the user took out, and stays out; a provider's rename or a fold carries Seen (mapModelRefs), and a shared group leaves it behind. A found group changed before Seen was kept takes in nothing, as nothing says which of its models the user took out; its next save sees what is found then (TestChangedFoundGroupTakesInANewProvider, TestChangedFoundGroupFromBeforeKeepsItsMembers, TestChangedFoundGroupTakesInAPluginProvider). A switched-off provider's members stay in it, skipped by membersIn, and the Routing groups page says them as switched off (memberJSON.providerOff). The user's own groups keep their members. Three templates make a group in one click from the models the user has (provider.Templates, AddTemplate; the Routing groups page's cards before a first group and its Templates menu after, magpie group template [kind] [name]): smart sends a hard turn to the strongest model and an easy one or a compaction to a cheap one, asked by a classifier (the decision API when there is one, else the cheapest priced model that doesn't reason); thrifty starts on two cheap models of different providers and sends high reasoning to the strongest; steady fails over between the strongest model of up to three providers. A model is weighed by its maker's list price when known, else what its provider charges, else by its id's size words (sizeOf); one over tooDear (USD 100 a million output tokens) is never picked. A template that can't be made says what is missing (Need). It is saved under a name and id no group has (freeGroupName, shared with CopyGroup), never over one. A group is shared as text (ShareGroup, a group row's Copy to share): JSON marked "magpie": "routing-group" with a format version (ShareVersion), holding the group's members as it names them, patterns, routing, rules, classifier and settings. A group holds only provider/model ids, never a key, account or address, and the derived matches, found/hidden/off flags and the rules that hold by a folder (a path on the sharer's machine, Rule.Folders) stay behind; a pasted one is left out too. ImportGroup (the Routing groups page's Import, POST /api/groups/import) reads it with words or a code fence around it, refuses another text, a newer format or none (ShareError, said in the reader's language). A member whose provider the importer has is kept; else the same model (AutoGroupOf) under the first provider of theirs that serves it (Instead); else it is left out and named (Missing), with the rules that send to it, its place among the off and fast members, and a classifier gone takes the intent rules and auto effort with it. Nothing is added when no member is left; what is added gets a free name, never replacing a group. A group of patterns only that match nothing now (a plugin's models not listed) has no members: /api/groups says them, and an unmakeable template's, as [], never null; the Routing groups page reads the response through groupsFrom and draws a group it still can't draw as one row saying so, so one bad group never hides the rest (#1585). |
group.go, grouptemplate.go, group_share.go |
| Allowance | Quotas asks every vendor at once: subscription windows (SubscriptionUsage), key-bought plans (PlanQuotas) and key balances (KeyBalances). The Usage page, magpie quota --json and GET /v1/magpie/quotas read it, each window with its whole-window estimate (Holds/HoldsWhy, usage.WithWindowHolds, which quotaReport reaches through the ReckonHolds hook since package provider can't import usage, #2333). A Remote magpie's cards (GET /v1/magpie/quotas/cards, writeCards) carry the estimate too, for the owner or a key with no limits on what it sees, since the computer reading them has none of the remote's calls to reckon from (linkaww on Discord: a Docker magpie's ChatGPT Pro week showed no whole on the other computer; TestRemoteMagpieCardsCarryTheirWholes). A Codex card's estimate counts the calls of a ChatGPT API account (chatgpt-api) that is the same ChatGPT account, whose plan limits they share: the tokens of both must name the same chatgpt_account_id and chatgpt_user_id, never matched by name, so two Team seats of one email stay apart (SamePlanAccounts in chatgpt_same_plan.go, jctaoo on Discord, TestWindowHoldsCountsTheSameChatGPTAccountThroughTheAPI). Routing weighs such a ChatGPT API account by that Codex account's reading too: Allowances("chatgpt-api") gives it the Codex account's allowance (samePlanAllowances; tmr11235 on X, TestChatGPTAPIAllowanceIsTheSameAccountsCodexReading), so Smart no longer puts it after every known account as unknown; one with no Codex twin stays unknown. A window that has just reset, with too little used to scale (HoldsLow, HoldsNoneRouted), keeps the account's last whole for that window, marked holds.prevAt (the time it was reckoned; the GUI's tooltip says which window it came from, as a past cycle's does) until it tells its own; the last whole per account and window is kept in window-holds.json (carryHolds in window_holds_carry.go, every provider's, Musikrv77852 on X; TestWholeKeptAcrossReset, quota-holds.test.cjs). A single card can be read again on its own (#840). A remote magpie's cards come from what it has kept (CachedCards, GET /v1/magpie/quotas/cards) and are never read there for this computer except by a card's refresh (POST /v1/magpie/quotas/refresh, throttled per card). What it has kept is the Usage page's cards with the readings made behind the requests since laid over them, a later one over an earlier by readSeq (cards_kept.go): each account's LoginUsage reading (the used-up switch, the Codex warm-up, routing's Allowances), and each key's KeyAllowance windows on its plan or balance card. A Claude account's windows Claude Code told as it answered (NoteClaudeLimits, kept in claudeUsage with their own heardSeq, which drops the account's LoginUsage reading) stand on its card over any reading started before them (withHeardClaude, #2206), so a magpie only requests reach still tells them. An account or key read that way and never on the page gets a card from that reading, and after a restart, before either is read again, the cards come from quotas.json, dated (AsOf). A magpie serving only other magpies has nobody on its page (#1313). What it has kept includes its own Remote magpies' cards as it last read them (passedOnCards, no remote asked), so a chain passes every card on (yuyong_id on Discord: magpie3 → magpie2 → magpie1 showed none of magpie1's Codex at magpie3), named after each magpie (magpie2/magpie1/codex, "Codex · magpie1 · magpie2"); the card standing for a remote and its keys' limits stay the reader's own. Each card carries via, the catalog.Self of each magpie it went through, and a reader leaves out one that loops (catalog.Loops, as a model's magpie_via). A refresh of such a card is passed to the magpie it came from (quotaCardsRefresh takes a card id this magpie has from a remote); a Codex reset is offered on the magpie next door only, and quota history isn't passed on. The status line's kept report (KeptQuotaReport) has a remote's cards the same way. A ChatGPT account's card has an Image generation row (WithImageLane, image_lane.go, Lane images, Text and Aside so routing, holds and history never see it; hqqqqqqqh on X, #6160): ChatGPT's images have a quota apart from the 5-hour and weekly windows, which /wham/usage doesn't tell (additional_rate_limits is null). Every reply of the images API, a 200 too, does: x-codex-active-limit: imagegen_premium with the window in x-codex-primary-* (1440 minutes, reset-at), or in the limit's own family (x-imagegen-premium-primary-*, as Codex's parse_all_rate_limits reads it). The gateway keeps that window per account (heardCodexImage in codex_image_limits.go, from magpie's drawing and from Codex's own relayed /images/*; provider.ImageHeard), and never takes it for a chat window (codexHeaderLimits tells none when the active limit is an image one; #6412, Green14964 on X: the card said "2 minutes" of a 24-hour window). So the row says Available with the window's reset, Used up when the headers say 100% or while the image model is resting on that account after a refusal (ImageRest, the gateway's restingUntil, whose time is the refusal's resets_at, #2244, else the heard window's reset for a 429 with that window full, not quotaRest's 15 minutes), and Unknown before any drawing, never a share or a count (TestWithImageLaneOnlyReadCodexCards, TestCodexImageRowIsTheRefusalsResetTime, TestCodexImageRowFromA200sHeaders, TestCodexImageRefusalRestsUntilItsWindow, codex-image-row.test.cjs). The window heard lives in memory only, so after a restart the row is Unknown until the next drawing. Not done: the count of images made in the window. Each key of a remote-magpie provider also gets a card of its own, under <remote>/~keys, one section per key (#1547, remoteKeyCards in remote_key_limits.go): the gateway key's limit as that magpie holds it, read from GET /v1/magpie/limit asked with that key alone, so a key never sees another's numbers. It shows a window per cap (tokens, spend) named for the period, used against the cap, with its reset, plus GatewayKey (what is left, calls, a cycle of days, used up); a key held to no limit shows Unlimited. It is kept for remoteCardsFor like the remote's cards and read again by the card's refresh (?provider=<remote>/~keys&user=<key name>). A read that fails keeps the last numbers, dated (AsOf); with none the card says why, never zero or no limit. A remote from before /v1/magpie/limit (404) says it is too old to tell (errRemoteNoKeyLimit). A remote's Codex card keeps its Resets (not a GLM team's, ByWindow), and its check-ins are dropped: Use one… there goes through /api/usage/codex-reset with the card's provider, and UseRemoteCodexReset asks the remote's POST /v1/magpie/quotas/codex-reset?user= with the provider's key (#3850). The remote spends it with SpendCodexReset, the same function as the Usage page (UseCodexResetCard, then AwaitAllowance). The account is always named. A 403 gateway_key_read_only is told as a read-only key there, and a 404 as a remote too old. No answer within RemoteResetWait says the reset may have been used, and it is never asked again by itself. A remote that holds the key to a budget, models or accounts answers its cards 403 gateway_key_held (#1981, errKeyHeld): the cards kept from before are dropped, and beside the key's own card the remote's card says it tells this key no quotas, and that on that computer Quotas is turned on for the key and it is let use every model of a provider whose usage it is to see (errRemoteHeld; yi_time on Discord saw the remote's Claude vanish from every page with no word). Its owner can let the key be told the cards of what it may use (#2216, magpie gateway-key quotas <id> on); the remote then answers those, and 403 held as before when that is none (writeCards), so that key shows the same card. A remote's cards are kept by provider and key (remoteCardsID), so a changed key never shows what the old one was told, and a read is kept only over one asked before it (keepRemoteCards). Each card also carries routing, each window's span, the model it alone counts and whether it is aside (provider.ToldRouting in writeCards), which a window's own json leaves out; the magpie reading them lays them back on the windows (withRouting in keepRemoteCards), and only such a card is weighed by routing (provider.RemoteAllowance, #6708, gateway routing). Passed on, the cards keep them, so a third magpie weighs them too. A read the test hook dropped (ForgetRemoteCardsForTest moves remoteCardCache.gen on) is not kept. Cursor, Grok and a Kiro key keep the page's cards only. With Settings → Allowances → Allowance reads at When I ask (QuotaReads == "asked", #1518: magpie started at login before the proxy app read by itself, direct), only a read the user asked for goes out: the Usage page or the tray panel's Allowances opened (no more than once in 30s, quotasOpened, #1588) or refreshed (?asked=1), a card's refresh (RefreshUsage), magpie quota, magpie accounts, magpie quota wait and the TUI's quotas (Asked). Any other read (quotaReading → holdUnasked) carries netproxy.Hold, so its requests fail before they leave, and every reader gives back what it last read, dated, or "not read yet" (errNotAsked): routing, the used-up switch, the menu bar and alerts go by that. An account refused for its quota (StaleAllowance → markStaleRead) or a key refused (StaleKeyAllowance → refused) is still read, once (unheld). Warm-up and check-in are not reads and are unchanged. A plugin's window may carry a prepaid wallet's balance in its unit and no share (QuotaWindow.Balance, #3950): the card and magpie quota show the figure (BalanceText), and routing reads it through Allowance.Left. |
cards_kept.go, quotas.go, subscription_usage.go, planquota.go, balance.go, quota_refresh.go, remote_quotas.go, remote_key_limits.go, quota_asked.go |
| A remote magpie's prices | A local magpie asks a remote magpie's /v1/models with X-Magpie-Prices (PricesHeader, sent by listHeaders). The remote answers each model's magpie_price: what its own Usage page counts the model at (EntryPriceIn: the price its user set, else its provider's list price at its price rate; a routing group only when every member costs the same). It tells it only to a request from its own computer or one let in with a gateway key (local or sharedWith); a list that didn't ask gets no magpie_price (a remote request without a valid key never reaches the list: lanGuard refuses it); every list told to those callers also carries the same price as OpenRouter's pricing, for agents (gateway routing). The local keeps the price with the fetched list (catalog.Model.Price; a value that isn't a price, or has a negative part, is dropped, the model kept) and uses it as that provider's list price (ListPrice → remotePrice). A price the local user set (provider/model, provider/*, */model) still comes first, and the local provider's own price rate still applies on top. A remote from before this sends no field and the models stay priced as before; an older local sends no header and is sent nothing new. The model editor says the greyed price is the other magpie's (remoteList). |
remote_magpie.go, models.go, gateway.go (models), live.go |
| A remote magpie's service tiers | A remote magpie's /v1/models gives each model the service_tiers its own Codex is offered on it (codexTiers → codexcat.ServiceTiers, from the same CodexCatalog and codexcat.Entries as its /v1/codex/models: Fast on a ChatGPT account's GPT model, the tiers of Codex's own entry on a relay's, none on a model it offers none). The local keeps the ids (catalog.Model.Tiers → Entry.Tiers), codexListed hands them on for the remote's models, and codexcat.Entries offers them to the local Codex with Codex's own names (namedTiers). The gateway sends the tier Codex asks for to a remote magpie as it was asked (Request.OwnTier, as for a provider added by its address; dropped and not sent again if refused), and the remote serves it as its own Codex's turn (#1234). An agent's picker offers the bolt on a remote's model whose tiers hold priority (provider.CanFast reads them with RemoteTiers; Ultrafast too where they hold ultrafast, UltraOn), and a fast pick of one goes on with service_tier priority on the remote's Chat or Responses: an agent on Messages, whose fast is Claude's speed, has it turned into the tier the remote offers (forwardTranslated), so Claude Code's pick reaches the remote's vendor too (littlekk88 on Discord; TestRemoteMagpieFastPick, red without either half). A remote from before this sends no tiers, and its models are offered none, as before. The list gives every client the tiers, not only a magpie asking with X-Magpie-Drawers: Cindy shows its Fast switch on a model whose service_tiers hold priority (#1914, TestModelsListTiersForEveryClient). |
codexcat.go, codex_models.go, codex_catalog.go, gateway.go, live.go |
| Two magpies each the other's remote | The list a magpie gives another magpie (X-Magpie-Drawers) names, as magpie_via, the magpies each model passes through to its vendor, itself last (catalog.ViaHere, viaOf; a routing group's are its members' together, so a group with the other magpie's own group of the model in it is left out there too). Each process has a random id (catalog.Self). A fetched list leaves out a model whose magpie_via has this magpie and another one (it went out of here and came back), or more than MaxVia (8), so two magpies that are each other's remote no longer list each other's models back one level deeper on every 10-minute fetch, without end, each level another member of the found auto/ group and another trip round the two (cdredfox on Discord, 100-200% CPU). A remote that is this magpie itself (sync carries a Remote magpie provider to the computer it names, hanslin1666) has its models through this id alone, taken once; one through this id twice or more is left out. Such a remote is found by its own list: a fetch whose models' magpie_via ends with this magpie's own Self is kept, by provider id and the address it answered at, in remote-self.json (noteSelf; another lister, or a list with no via, takes it away; an empty list or a failed fetch changes nothing; this computer's own file, never in a backup or a sync). The provider is then left out (SelfLeftOut in On, SwitchedOff, remoteMagpies): its models are not listed beside this magpie's own nor in a found group, and a request naming one, an agent's pick sync brought from the other computer, is served here with the remote's id taken off the front (ThroughSelf in Resolve and ResolveRoute), not passed through the gateway again. The Providers row says This magpie (greyed while left out) and its editor says why, with Use it anyway (KeepSelf, provider/keepself, SetKeepSelf), the user's to set (hanslin1666): kept, it is served as any remote, each request twice through this magpie. KeepSelf is this computer's own like KeepLogin (Mirror, Restore, blanked in davsync's hashes), since the other computer's copy points at this one, which is not itself (TestRemoteMagpieThatIsThisOneIsLeftOut, TestRemoteSelfRecord, remote-self.test.cjs). Each request passed on to a Remote magpie says how many magpies it went through (X-Magpie-Hops, passOnCaller); one that arrives having passed MaxVia is answered 508 Loop Detected (withCaller), read only from a magpie's request and taken off every request as it arrives. A magpie older than the field sends none, and its models are taken as they were. The quota cards a Remote passes on follow the same ways (X on 0.1.3678: A → B → C → A told Kiro and Codex by remote-B/kiro and remote-B/remote-C/remote-A/remote-B/remote-C/kiro, hours apart, to a Remote enabled for one local model): a card's via that names any magpie twice is a loop too, so one that came round after this magpie restarted (its old Self is no longer this one's) is left out (catalog.Loops), and isn't kept in remoteCardCache (keepRemoteCards). A Remote's cards are shown, and passed on, only for the providers it is enabled for: the card's provider id must be the provider path of an exposed model there (its id less the last part, or a parent of it, whole parts only: relay/strata enabled tells relay/strata, never relay/kiro; remoteCardWanted, cardWantedFor, TestRemoteCardWantedByWholePath, 748975219 on X), unknown, so all shown, while its list isn't read, and all shown for a Remote set to Select none (it serves no model, its usage is still read; a user on X, 0.1.3929, TestRemoteSelectNoneStillShowsItsCards). One subscription account's copies (same provider, same user) are one card, the newest complete reading, then the shorter way (oneCardPerAccount, in RemoteCards and CachedCards; a key's cards, whose user is a name two keys may share, are not merged) (TestRemoteCardsFollowEnabledModelsAndDedupe, TestLoopsOnARepeatedMagpie). |
magpie_via.go, live.go, gateway.go, remote_magpie.go, remote_self.go, remote_quotas_scope.go |
| A remote magpie that moved | Computer A's router hands it a new address now and then (luckymanjc on Discord), and B's Remote magpie, saved at the old one, reached nothing. When B can't connect to it at all (a dial error, unconnected), its list fetch (fetch in models.go) and the gateway's request (forward in gateway.go) call SeekMoved (remote_moved.go): every address of the old one's /24 and of up to four of B's own private /24s is dialled at A's port (500ms each, 128 at once, lanNeighbours). Whatever takes the connection there may be anyone's (a café's network, A switched off), so it is sent neither the key nor the provider's headers until it proves it holds the key (proves): B POSTs a nonce of its own and RemoteKeyID (the key's sha256, hex) to RemoteProvePath (/v1/magpie/prove) with no key and no proxy, and checks with hmac.Equal that the answer is RemoteProof: HMAC-SHA256 under the key of the nonce and the address B dialled. A answers it (remote_prove.go) for an enabled gateway key of that id (access.ProveSecret: constant-time compares over every key, then Check) at the address the connection reached it on (http.LocalAddrContextKey), so a host passing B's nonce on to A elsewhere hands back a proof for A's address, not its own; 404 for a key it hasn't or has turned off. Only an address that proved is asked /v1/models with the key, and the first that lists 200 and whose list this magpie didn't make (magpie_via) is saved as the provider's address and asked again. A magpie from before the route, one behind a port forward or NAT (it is reached at another address than its own), or one behind a proxy that needs the provider's headers, is not found, and the user types the new address. An address saved, by that look or by the user's edit, is taken at once by a request already under way (le13ure on X: requests kept trying the old address after the edit): the gateway's try loop asks Readdressed before each try and moves the candidate onto the saved address, SeekMoved hands back the saved address when another caller's look (or the user) saved one within the minute, and a pause between tries (pauseAlive, pauseUntilReaddressed in patience.go) ends when store signals Edited and the provider's address changed. Dialling a private or link-local IP literal gives up after 5s (lanDialCap in lan.go, through Dispatch), where the OS would wait over a minute on an address no one holds (TestRemoteMagpieSavedElsewhereIsTaken, TestRemoteMagpieRetryGoesToTheSavedAddress, TestPauseEndsWhenReaddressed, TestLANDialGivesUp). A name or a public address is never looked around, an address the user changed meanwhile stands, and a provider is looked for once a minute at most, callers at once sharing the look (TestRemoteMagpieKeyGoesToNoNeighbour: an impostor that lists 200 for anything, one with a proof under another key, one with a garbled proof and one relaying to the real magpie are sent no key or header and not saved, and the real one is; TestRemoteProof, TestRemoteMagpieFoundMoved, TestRemoteMagpieNotFoundStays, TestRemoteMagpieMovedIsFound, TestRemoteProveAnswersOnlyTheKeysHolder). |
|
| A relay's Codex entries | A provider the user added by its address with a Responses URL may list its models in Codex's own shape (slug, supported_reasoning_levels, shell_type, base_instructions: catalog.CodexEntry), plainly or when asked with Codex's client_version, as sub2api does (ctopsc on Discord: GPT-6.1 Terra was handed models.dev's 922000 window where the relay said 272000). fetchOne keeps such a row whole (catalog.Model.Codex, with its window, max window and inputs read off it), and when the plain list has none it asks the same URL once more with client_version (codexEntries): only where the list is fetched (add, key change, Refresh), never per Codex poll. The answer only adds entries to models the plain list has; one that fails or can't be read keeps the last list's entries (failed read = unknown), one that answers plainly says there are none. codexcat.listedEntry hands Codex the relay's entry as given, base_instructions included, with magpie's slug, name, priority and " via magpie" description; the user's window, compaction, levels and image setting still win (levels keep the relay's descriptions). A saved list from before is enriched at its next Refresh. TestCodexListedEntry, TestCodexListedEntryInPlainList. |
codex_entries.go, live.go, codexcat.go |
| An endpoint's catalog | A key's provider with no catalog of its own (none named, none from a preset) is priced from the models.dev catalog whose api is one of its endpoints (EndpointCatalog, catalog.AtEndpoint; a trailing slash and case don't count, and an Anthropic base, kept as its root, is also matched with its /v1). Only when exactly one catalog is at that address, and it isn't a plan's (an id with -plan, or a membershipCatalogs one): a plan lists its membership's $0, and two catalogs at one address can't be told apart. A subscription's account never gets one. A provider at AMD's own endpoint is priced from amd, which lists Qwen3.8-27B at $0, a price, where its maker sells no such model and it had none (#2052); a relay's endpoint matches nothing and its model stays unpriced, never priced at a reseller's guess. magpie model price names the catalog, and says how to give a price when none is known. |
models.go, catalog.go |
| The maker's own price | A model priced at its maker (MakerPrice, a provider's ListPrice after its own catalog, PricedName; through makerListPrice) is priced at a models.dev provider that lists it as its own (catalog.MakerPriced): one whose entry's canonical_model_id names it as the maker, or whose id is the maker's with a region (alibaba-cn), never a plan's (-plan) and never at $0. A maker preset that is such an API is asked first, in preset order, then the other owners by id; only then the maker presets as before (PricedBy). A maker preset that resells another lab's model no longer prices it: Mistral's deepseek-v4-1-flash-1017 at $0.30/$1.20 gave way to DeepSeek's $0.15/$0.60, and a lab that isn't a preset (Meta's muse-spark) is priced at all. So a subscription's model (Command Code's, bestony on Discord) is estimated at what its maker charges (TestMakerPriceIsTheMakersOwn). A model no maker lists (Kimi K2.5, GLM-5.2 Fast) stays unpriced; the user gives it a price or a same-as model. |
models.go, catalog.go |
| A model at a window | A plugin offers a model at each context window it serves by <id>@<N>k or <id>@<N>m: the Cursor plugin's claude-opus-5-5@300k, claude-opus-5-5@1m and gpt-5.5@272k, one per size Cursor's picker has, and the grok plugin's grok-4.7@500k. Such an id is priced as the model it is that window of (pricedNames, modelWindow), at any provider and in MakerPrice, after its own id; a long prompt's rate is the price's tier, read from the call's tokens (Price.At), not from the window. Only Grok's ids were read this way before, so every Cursor call on a sized id had no cost (RyuJeXu on X). A window with no k or m is read off a Grok id only (grokWindow, grok-4.7@131072); an @ with a date (claude-opus-4-5@20251101) is part of the id. Guarded by TestCursorWindowIDsPricedAsTheirModel, TestWindowOnlyReadOffAnID and usage.TestCursorWindowCallIsPriced. |
models.go |
| A membership's $0 catalog | models.dev lists every model of Kimi Code's plans (kimi-code-plan-global, kimi-code-plan-cn) and of Xiaomi MiMo's Token Plans (xiaomi-token-plan-cn, -sgp, -ams) at $0: what the membership charges per token, not what the model costs. membershipCatalogs are never read for a price (priceCatalogs, makerPriceCatalogs), so a Xiaomi MiMo model is priced at xiaomi's list price at every region, and each region of the preset names its own catalog, pay as you go xiaomi alone (#1873). A Kimi Code provider's model is priced at the Kimi API model it is (kimiCodeAPI, from Kimi Code's docs: k3 and k3-256k are kimi-k3, k3.1-pro and k3.1-pro-highspeed are kimi-k3.1-pro and kimi-k3.1-pro-highspeed, kimi-for-coding-highspeed is kimi-k2.7-code-highspeed), and kimi-for-coding (K2.8 Preview, not on the API) is unpriced rather than free (#1370). The alias is Kimi Code's alone (kimiCodePlans): a relay's own k3 keeps its own price. A catalog other than these that lists a model at $0 still prices it at $0: models.dev has truly free models (nvidia, modelscope). The Requests list names the API model it was priced as (PricedNameFor). |
models.go |
| A plugin's own price | A model no catalog prices (models.dev has no vendor's own model: Devin's SWE-2 and SWE-1.7 Lightning, Cursor's auto, Qoder's efficient) is priced at what its plugin lists it at (ListPrice → pluginListPrice, plugin.Model.Cost, read by pluginPrice: an input or output above 0, OpenCode's 0 being none), else at $0 when the plugin says the plan serves it free (pluginFree, plugin.Model.Free: Devin's Free cost tier, Qoder's and WorkBuddy's x0). Both come after every catalog, so a price a catalog gives is kept over the plugin's. Devin's plugin (0.1.18) lists each paid model at the price Devin's GetCliModelConfigs gives it (input, cached input and output per 1M tokens); a moved Devin user's calls on Devin's own models had no cost on Usage before (太陽と向日葵 on Discord, TestPluginFreeModelCostsNothing). A plugin that gives no price and doesn't say free leaves the model unpriced. |
models.go, plugins.go, providers.go |
| Codex's free auto-review | OpenAI made Codex's Auto-review free for users signed in through a ChatGPT account (silverzhou on Discord), so a codex-auto-review call through the Codex subscription is priced at nothing (ListPrice → codexReviewFree, provider.ChatGPTReviewFree), not at GPT-5.6 Luna's price (pricedNames), and the Requests list names no model it is priced as (PricedNameFor). Not on a Free plan, where it spends the allowance (cybercaius), read from the plan Codex is signed in to now; a Codex signed out since counts as a paid plan, as the gateway's caps take it (freeOnChatGPT). The same model through an API key, the ChatGPT API subscription or a relay, and a review that followed the session to another model, keep their price; a price the user set wins. Every call is priced as it is read, so rows logged before are free too; the price views' cache keys on each account's plan (usagePriceCacheKey). Guarded by TestAutoReviewFreeOnChatGPTSignIn and usage.TestAutoReviewFreeOnChatGPT. |
|
| A lab's models | models.dev keeps two catalogs: api.json, each provider's models with that host's prices, and models.json, each lab's models with only what is the model's on every host (name, window, reply limit, thinking, inputs, release), no price. Sync keeps the second beside the first as labs.json (LabsPath, syncLabs: best effort, through a rename, a failed fetch keeping the last; a catalog with none beside it is Stale once a process, so it comes at the next look). A model only a lab lists, no provider (models.dev took the gated Claude Mythos 5.1 out of anthropic's list in #11327 and kept its lab file), is voted into the same tables as a listed one (loadGen, labs), so ContextOf, OutputOf, NameOf, Thinks, SeesImages and every entry built on them know it wherever a vendor's or an account's list has it; a thinking one with no levels takes the levels of the newest of its family a provider gives them (labKinEfforts: Mythos 5.1 takes Mythos 5's). A model a provider lists keeps what providers say of it. catalog.Describe builds a model from these for a list that names an id alone. TestLabOnlyModelIsKnown, TestLabsLeaveListedModels, TestSyncKeepsLabs, TestAnthropicKeyGatedModelDescribed (iebb on Discord). |
labs.go, catalog.go |
| models.dev unreachable | The catalog (CachePath, models.json) is written whole through a rename (writeWhole), so a reader never sees it half written and a fetch that fails (refused, hanging past fetchBound, a page that isn't the catalog) keeps the last good copy. loadGen reads magpie's copy, then OpenCode's, then the copy the binary ships with (bundled/api.json.gz, bundledAt), passing over one it can't parse. Seed (the app's backend, magpie serve, the plugin host) writes the shipped copy into CachePath dated bundledAt when there is no catalog file or the one there is older, so the plugin host's mdev reads it too and Stale still has the real one fetched. The app's backend fetches beside the vendors' lists rather than before them, and KeepFresh tries a failed fetch again after retryFirst (2 minutes), doubling up to the hour (nextRetry). The fetch goes through http.DefaultClient, so through the proxy in Settings, *_PROXY or the system's (netproxy.Install). A test binary has the shipped copy off (bundledOn). Refresh it with go generate ./internal/catalog and set bundledAt (creeksuen on X). TestFailedSyncKeepsLastGood, TestFirstRunOfflineAnswersFromShippedCopy, TestUnreadableCacheFallsBackToShippedCopy, TestSeed, TestSyncWritesThroughRename, TestFailedFetchRetriedSoon. |
bundled.go, fresh.go, catalog.go, backend.go |
| A Claude account's models | magpie never asks Anthropic with a Claude sign-in, so a Claude account's list is models.dev's anthropic list and what Anthropic told the account's Claude Code beyond it. Claude Code keeps that in its .claude.json from its own bootstrap: additionalModelOptionsCache (models its /model picker offers beyond its own; a null value or a disabled one is not a model), modelAccessCache (entitled per API id) and additionalModelCostsCache (Anthropic's prices). Claude Code 2.1.323 and later also keep a version-2 catalog per account, <config dir>/cache/model-catalog/<organizationUuid>-<first 12 hex of sha256(accountUuid)>-cc.json (catalog.config.models: id, name, runtime window, reply limit, effort levels, mm_images); readClaudeCodeModels adds the models of the catalog of the account its .claude.json names, from that config directory or Claude Code's own (which keeps every account's that signed in there), the one fetched last, and fills a window, limit or levels models.dev doesn't have from it. Another account's catalog in the folder is never read, a file of another version or surface is unknown, and a .claude.json or catalog that doesn't parse (halfway through a write) is what it said last (readKeepingGood; #6418, TestClaudeCodeCatalogV2Models). claudeModels reads the file of Claude Code's own sign-in (claudeProfilePath) and of each saved account's directory (claudeAccountDir), through filememo, and adds each model none of them lists, described by catalog.Describe and priced as Anthropic told it. Account.Lists for a Claude account goes by its own file (claudeLists: the saved directory's, or Claude Code's own when its oauthAccount is that account, the one Anthropic answered last): a model it isn't entitled to is out, so routing tries the accounts entitled to a gated model first; with no file, every model is taken to be in, as before. ListPrice of a provider whose catalogs include anthropic falls back to that price after every catalog (claudeCodePrice). The agent's own Claude Code model picker (claudeOwn) offers what ClaudeCodeModels gives for the account signed in here; a WSL distro's keeps the catalog's. A fetch of the list in the app or magpie serve (Fetch models, the accounts' relist) fetches models.dev's catalog first when it is older than askedAfter (10 minutes) and wasn't tried in that time (catalog.Asked), only in a process that keeps the catalog fresh: the daily sync alone left a model launched since off the list the user had just fetched, while Claude Code's own /model, built from the catalog baked into its binary (latest_per_family), had it (hhdaxia on X: Fable 5.2, TestClaudeFetchAsksModelsDevForANewModel). Not done: a Claude Code that never started on a saved account has no file, so its gated models show only once it has run there. TestClaudeAccountListsGatedModels. |
claude_code_models.go, claude_code_catalog.go, account.go, codex_models.go, claude.go, fresh.go |
| A key's own windows | A sub2api key given a spending limit per 5 hours, day or 7 days answers its /v1/usage with rate_limits and no remaining (readSub2APIKeyLimits). With the Balance URL set to it, the key's card shows them as the windows 5 hours, 1 day, 7 days, in USD, beside a balance field the user wrote; Check balance and magpie provider show give what its fullest window has left (Balance). A Balance URL at an account query left without its token (a sub2api panel's /api/v1/user/profile, new-api's /api/user/self, after the token was removed) asks the same panel's query for the key instead, the saved URL untouched (keyQueryOf, BalanceQuery), unless the user's Headers carry an Authorization or Cookie of their own. A Balance URL of the user's own is asked with GET, or with POST and no body when the provider's BalanceMethod says so (#2368: an endpoint that answers only a POST; the editor's GET/POST beside the URL, balance.method= on the command line); any other method is refused before anything is sent (balanceMethodOf). KeyAllowance gives routing the same windows: never waited for, read in the background at most once a minute, a failed read keeping the last, and seeded from the card's last reading (quotas.json) after a restart. A key bought as a plan (Kimi Code, GLM Coding Plan and Z.ai, MiniMax Coding Plan, OpenCode Go, Command Code, Ollama Cloud, Mistral: planQuotaSourceOf) gives routing its card's windows the same way (planKeyWindows, Zhipu's team quota behind a key with none of its own); the Usage page's read of its card is taken at once (noteKeyAllowance), and a key there that turns out pay-as-you-go, with no windows, is asked again only every 30 minutes (keyNoWindowsAge). Kimi Code's /usages (readKimiCode) is read as kimi-cli and kimi-code read it: the week's usage and each limits[] window as counts, and the shares in usages (limit_5h, limit_7d, and limit_month_total as a Month window renewing at its reset_time, lidazi2016 on Discord); a window told both ways is the share's, and limit_month_code, the part of the month code used, is no window. TestReadKimiCode, TestReadKimiCodeMonth. A Command Code plan's key has its month of credits as a Credits window beside the 5-hour and weekly ones, as the signed-in subscription's card has (cmdKeyWindows, #2451): billing/credits leaves the plan out, so it is the key's billing/subscriptions plan, asked at most every ten minutes and the last one kept while it can't be read; the same reply's period end is the Credits window's reset, left off once it has passed (#2454); a key whose plan was never read has its two windows alone. On Go, GOAT and Pro the month is counted in Command Code's usage-value credits, not dollars (GOAT's 70 are $100 of a model like DeepSeek V4.1 Flash, $70 of GLM-5.2), so the window says "28.80 / 70.00 credits" with bought credits as "+ $5.00 extra" beside it; Max, Ultra and Teams Pro keep the CLI's dollar pool, and Provider, pay as you go, has no month (cmdPlans, as the plugin since 0.1.20, plugins #556). Ollama Cloud's ollama.com/api/balance (#1888, readOllamaPlan) tells the plan's included allowance as one window in USD, Month when its period is a month long, renewing at period.until, and Aside while credits bought on top are left; those credits are the key's balance card (readOllamaCredits), and a reply that names none has no balance card rather than $0. A Mistral key is told its organization's month at api.mistral.ai/v1/billing/budget, as Mistral's Vibe CLI reads it (mistral_plan.go, dhanyqaz on Discord). The budget is the organization's, so every key of it gets the same vibe_budget and api_budget; which one a key spends is its kind, asked once a key of console.mistral.ai/api/vibe/whoami (plan_type). A Vibe key (chat) has vibe_budget as one Month window, a Studio key made in the console (api) has api_budget as API · Month, so the accounts' strip never adds the two; each is in the currency billing names (none when it names none), Aside while pay-as-you-go is on (the budget's own, else the subscription's vibe_payg_enabled for Vibe and payg_enabled for Studio), with the plan's name from billing/subscription (EDU is Student). A key whoami can't place (a failed read, no plan_type, Mistral Code's key) or whose budget is 0 has no card, and Le Chat's own message limits are told nowhere. ModelScope's API-Inference token is told its 魔粒 at the OpenAPI's modelscope.cn/openapi/v1/magicubes/balance (readModelScope, jiabubu on Discord): available_balance, which leaves out what running tasks have frozen, as the balance card; the page's daily list (/magicubes/transactions) isn't in the OpenAPI, so what is spent a day is the card's own trend. StepFun's Step Plan is read through a platform sign-in, not the key, and isn't one of them: the sign-in is the provider's own, kept by provider id in stepfun-auth.json (two StepFun providers on one site can be two accounts, #2384), one card per signed-in provider; a file from before that, kept by site, is given on read to the StepFun providers on that site (stepfunBySite), and copies of one sign-in are renewed together. The Qwen AI platform's Token Plan is read the same way, through a platform sign-in kept by provider id in qianwen-auth.json (qianwen_plan.go; see the Alibaba Cloud Token Plan below). Baidu Qianfan's Token Plan Personal (a provider at qianfan.baidubce.com/v2/tokenplan/personal, QianfanPlan; yuushabu_buyinn on X, #5860) is read as StepFun's is, by the same bookmarklet and paste (renderStepPlan, its field in qianfanplan.js, imported when such a provider's editor opens): the user's Baidu Cloud console cookie, checked with a real read before it is kept by provider id in qianfan-auth.json (0600; a raw Cookie: header or a copied cURL is taken too, for the HttpOnly cookies document.cookie leaves out), asks console.bce.baidu.com/api/qianfan/charge/tokenPlanPersonal/resource (qianfan_plan.go). The running plan's credits (billingMode credit) or tokens are one Month window up to its expiresAt, with its auto-renew; the per-plan apiKey in the reply is never kept. A redirect, 401, 403, an HTML page or a refusal naming the login is a signed-out session, an error card and never 0 left; the kept sign-in is then marked ended (Ended, the first time only), so the editor (stepPlanJSON.ended) says Baidu ended it and shows the bookmarklet and paste again, and a new paste or a read the console takes clears it. A cookie the console sets in a reply that read the plan (on the resource's path) is merged into the kept Cookie header as a browser would (mergeQianfanCookies), so a session Baidu renews as it is used stays the one magpie holds. There is no AccessKey/SecretKey route: Baidu's documented OpenAPI (the Qianfan API catalog, v2/charge?Action=DescribePackageResources for 量包, Finance's bill and balance APIs, the Enterprise plan's seat APIs on an API key) has no read for a Token Plan Personal. The Enterprise plan has no card: the console reads it through seat and admin APIs, not a tokenPlanTeam/resource. Built from the console's own script and field names; never read with a real account here. TestReadQianfanPlan, TestSaveQianfanPaste, TestQianfanPlanCard, TestQianfanSessionEnded, TestMergeQianfanCookies, TestQianfanSignInRoutes, qianfan-plan.test.cjs. Nor are Volcengine Ark's Coding Plan and Agent Plan (#1427): their 5-hour, weekly and monthly windows are told only to the account's access key (AccessKeyID, SecretAccessKey), asked of open.volcengineapi.com (GetCodingPlanUsage, GetAFPUsage) and signed as Volcengine's own SDK signs (volcSign), so they are cards on the Usage page (volcPlanQuotas in PlanQuotas), never routing's windows. Nor is Tencent Cloud's Token Plan 企业版 (#1574): what a team plan has used of its cycle's credits (专业套餐) or tokens (轻享套餐) is told only to the account's SecretId and SecretKey (kept as AccessKeyID, SecretAccessKey), asked of tokenhub.tencentcloudapi.com (DescribeTokenPlanList, DescribeTokenPlan, version 2026-03-22) and signed TC3-HMAC-SHA256 (tc3Sign), one card per team plan (tencentPlanQuotas). |
sub2api_usage.go, key_allowance.go, volcengine_usage.go, tencent_usage.go |
| A relay's balance found | A provider added by hand, or from a relay's preset, with a key and no Balance URL, at no host magpie knows a query for, is asked where relays tell a key its balance: the base's origin's /v1/usage (sub2api, $remaining), then /api/usage/token (new-api, $data.total_available / 500000), with the key's own auth and headers (probesBalance, probeBalance). A 200 whose field reads is the query; it is kept in memory for the origins and key for 24 hours and then looked for again, so a relay that moved to other software is not read at a query that now means something else. When the look finds nothing, the old query stays while it turns the key away (401/403, so the card says so) or the relay is down. Finding none is kept for 6 hours (5 minutes when the relay couldn't be reached). Nothing is written to the provider: the card reads the found URL, BalanceQuery names it, and the editor shows it under the Balance URL (BalanceFound, balanceFound in /api/providers and the check's reply; balfound.js), with Use to copy it into the fields so a wrong amount can be put right. None found means no card (errNoBalance) and, from the editor's check, No balance at /v1/usage or /api/usage/token. Never asked: a model vendor's or local server's preset host, this computer, OpenCode and the Cline API (noProbeHosts), a plan's windows (planQuotaSourceOf). A hand-added yylx.io relay showed no balance until its operator had the user import it again (11-05). |
balance_probe.go |
| Account names and seats | AccountNames (by the account, in lower case, like AccountCaps) are names the user gives accounts, set by SetAccountName (GUI provider/accountname, magpie accounts alias); they live in providers.json only, never in a vendor's or plugin's sign-in. A name picks its account wherever the account's own name does (AccountByName): the CLI's accountNamed (switch, forget, alias), the pool's --accounts, and accountRef (caps, models, weights, concurrency) after an exact name. It is refused when two accounts have it or it is another account's email or name, so it never picks by guess; accountRef then finds no account, as the GUI passes exact names (StringKe in #4532, TestAccountsAliasPicksTheAccount). A GLM Coding Plan read with a key (glmPlan) and a ZCode account (built-in or zcode-plugin) whose windows' resets agree are one seat (seatMatch, #90/#953), shown once, on the account's card (seatCards, used by quotas, Allotted and CachedCards). A match is remembered in seats.json beside quotas.json: a failed read or a window with no reset yet is unknown and keeps the key's card off while the account is signed in; windows that disagree forget it (#1515). Cards carry Seat (the key provider's name, and the key's when it has several) and Alias (the user's name, else the plugin's, else Seat) with Named when it is the user's own, which Hide accounts leaves in sight (#3656), as /v1/magpie/quotas, magpie quota and magpie accounts do. Records (a trace's who, usage's ProviderAccount) keep the vendor's name, the key the user's name is kept by, and every list of them looks the name up as it is shown (AccountShown, AccountShownOf, AccountRef.Shown), so a request from before a rename reads by the new name too: the Routing page's accounts and requests (userShown in plugins/routing/client.js, from /api/providers' accountNames), its Several accounts pools (onOf), the Usage page's Accounts and the request log's Account filter (usageapi), magpie usage, and a gateway key's accounts (AccountNames, /api/caller-keys). Before plugins#310 (a renamed Kiro account read by its old name on every request after) those showed the vendor's name. An account with no name of the user's own goes by the name its plugin's usage() gives it (PluginUserOf, the user of its last read: loginUsageCache, else quotas.json), else by its id: a Huawei Cloud CodeArts account kept by its IAM id iam::<domain>:user:<name> reads as the masked phone its card shows (#4416). AccountShown, AccountShownOf and AccountLabelOf (cards' Alias, magpie accounts, usageapi's Account filter, the quota alert) apply it, and the GUI has it as /api/providers' accountUsers (accountShownOf in app.js: the editor's rows, the per-account proxy lines, Routing's userShown, Hide accounts). The id stays the key everything is kept by; nothing stored changes. A read that fails keeps the last good user; nothing read yet, or a plugin whose windows are all model pools (not kept in quotas.json) after a restart, is its id until the next read. |
account_names.go, account_seats.go |
| Last served | served.json records when each account, plan or key last answered, shown as lastServedAt (#570) on /v1/magpie/quotas and on the Usage page's own cards (Quotas → cardsServed, this computer's cards only, the caches left alone). The Usage page and the tray panel show the last-answered account in full, and a menu bar card that follows the account in use (`codex |
*) takes the one that answered within the last hour, else InUseLogin's guess, else the one that answered last at all (a plugin's accounts, #1516) (trayInUseCard; okingkee on X: A spent, B answering, the menu bar stayed on A). NoteServedcallsOnServedMovedwhen a provider's answers move to another account or key, andSwitchLogin` after a switch, so the menu bar reads its cards again at once. |
| Partners | Services that pay to be listed first in the add sheet, under a heading of their own ("Partners · magpie's sponsors"). The list is site/partners.js, served at usemagpie.ai/api/partners: a change reaches users with a deploy, not a release. Partners never waits: it returns what was fetched last and fetches again behind the call on a process's first ask, whatever the kept list's age, and hourly after (10 minutes after a failure), keeping the list in partners.json in the cache folder. The magpie serving the gateway fetches it when it starts and whenever it is due, asked for or not (KeepPartnersFresh), so an app left open on another page still learns of a partner added. The file also says when the last fetch started (tried) and, when it failed, why (error, logged once until a fetch gets the list again), so a list that stops changing tells a fetch that fails from one that never came back (tried after at, no error) and from none asked (#3362). Each entry is checked again on every read (validPartners): its own id, never a built-in preset's, a name, an endpoint, https only, at most 12; what only magpie's presets may set (a decision API, no key, a user endpoint) is cleared. Its logo is fetched through FetchIcon and kept as an uploaded icon, used as it is while its iconUrl stays the same; the prune after a save of providers.json (pruneIcons) leaves the logos of the partners listed now (keptPartnerIcons), as it leaves a plugin's. A partner is a preset to the rest of magpie (Preset, FromPreset, the editor), and one no longer listed still is to the providers added from it (Seen), without the sponsored mark. The window lists a partner in the languages it names (langs) only and shows its tagline in the page's language (notes, else en). MAGPIE_PARTNERS points it elsewhere, off lists none; tests list none unless they name a list. How often each listed partner was shown, opened (its row, its key page) and added is counted per UTC day (CountPartner, capped at 20 of each and 5 adds, kept in partner-counts.json in the cache folder) and sent with the next day's stats event as magpie partner events (internal/stats); nothing is counted with the stats or their usage part off. A listed partner the add sheet (or the TUI's, or magpie providers presets) hasn't shown yet is new (NoticePartners keeps those shown, as noticed in partners.json, whatever the stats); the window's add button carries a small dot for it, with its name in the title, until the sheet shows it. |
partners.go, partner_events.go, site/partners.js |
| Local servers | A preset of KindLocal (Ollama, LM Studio, oMLX, MLX-Serve) is at its server's default port on this machine. Another address — a port, or another computer — is given in the window's editor, in its Server address field, shown first above the key and never folded (a folded one read as an LM Studio whose base URL can't be changed, mengxiangziyou on X), or in the TUI (asked on adding, w after); on the command line with address= (atAddress in providers_cli.go: every URL moves, from the preset's when the provider was saved with none, and address= alone puts a local server back at its preset's), or the URLs themselves (url=, anthropic=, responses=). AtAddress replaces only each URL's scheme, host and port, each API keeping its path; AddressOf is the address an editor starts from. The window sends the URLs moved only when the address was changed, so a Save doesn't move URLs set apart (another app's import). A provider of the user's own (no preset) has w in the TUI too: each base URL it has is asked in turn, typed in as it is, Enter alone keeping one (customURLsAsk). |
local_address.go, providers_cli.go |
| Protocol detection | Works out which of Chat, Responses, Anthropic Messages and Gemini generateContent a base URL speaks when a provider is added. Each is asked at the URL as it takes it (DetectBase); Gemini's at the …/v1beta beside a typed …/v1 or bare host, a Gemini model from the list picked for it, with the key in x-goog-api-key (#1346). Each API is asked with a model that chats, if the list has one; an embedding or rerank model (catalog.ServesOf) is asked only on Chat's URL, at its /embeddings or /rerank with the smallest body and no extra body, as the gateway's retrieve asks it, and the other APIs say why they weren't asked (heatonz on Discord: a vendor of only those detected nothing, asked to chat; TestDetectEmbeddingOnly). A saved provider whose list has nothing to chat with tests on such a model (testModel, TestTestEmbeddingOnly), and its editor and the add form's Fetch models say the models need no pick (retrieval in the list's answer and the provider's JSON, provider-retrieval-only.test.cjs). A model's test (Test models, a model's right-click, magpie provider test) asks the account or key a request for it goes to: provider.AccountsFor and provider.KeysFor (route_accounts.go), which the gateway's perKeyEvery routes by too, its usage and spend caps aside (one the user lets serve it, AccountModels; whose own list or plan has it, Account.Lists, PlanServing, Serving; in the user's order, AccountsOn), so a pool whose accounts list different models (a newapi plugin's) asks the one whose list has it, and one every account is barred from isn't asked. The provider's Test picks each endpoint's model from every account's and asks it of the account that serves it (routedTo), and with keys the first key with a model of its own to test (testWith). The request log's row names the account asked (loggedAs; #4992, TestModelTestAsksTheAccountThatServesIt). A model's right-click Test on account… (tmr11235 on X; a provider with two or more accounts or keys that are on, TestPicks) pins its test to one of them (TestOn, accountNamed, keyNamed, the GUI's account; TestModelTestPinnedToAKey, TestModelTestPinnedToAnAccount, model-test-account.test.cjs), and every result names the account or key it went to (Result.Account, testedAccount), so the status line says which one answered. Test models and magpie providers still test with routing's pick. Detection, endpoint tests and model tests share probe, which adds anthropic-version only for Anthropic Messages; OpenAI probes omit that default so a relay that refuses it can answer. A Chat or Responses URL typed without its version (CRS's …/openai, Cyrus_4433 on X: CRS serves /openai/v1/chat/completions and /openai/responses, and answers anything else 404 Not Found) that is answered 404 is asked once more under /v1 (missingV1, not for an account, Azure, Bedrock or Vertex); answered there, the saved provider's URL takes the /v1 (setV1), the result carries it (Result.V1), Detect hands it on as the base, and the editor's URL field follows (draft.onV1), so Save doesn't put it back. A model's own 404 at both stays a 404 and changes nothing. CRS lists at /api/v1/models, which catalog.RelayOpenAIList adds to an unversioned …/openai base's list URLs, and a list answered there adds /v1 as fixV1 does (TestCRSOpenAIBaseTestsUnderV1, TestCRSOpenAIBaseListsAtAPI, TestCRSOpenAIBaseDetectsV1, TestModel404KeepsBase, provider-test-v1.test.cjs). A model's test that the vendor turns away with its word that the model is served on another API (catalog.WrongEndpoint, the gateway's words) asks the next API the provider has a URL for, as the gateway's usable takes it (the model's picked or listed API, else each API it isn't named-only on), with a key that sees the model there (keySeeing); that API's answer is the model's, and with none left, or every one saying it, the first stays. As Codex the next API is asked with Codex's headers, as the gateway sends them on Responses and Chat; as Claude Code it isn't, since the gateway sends Claude Code's on Messages alone (#3766, TestTestModelsMovesToTheAPIServingIt, TestTestModelsKeepsAModelOnItsAPI, TestTestModelsAsAClientMovesAsTheGatewayDoes). User-supplied headers still apply through Sign. The editor asks with the form as it stands, before any Save (#1545): the URL, key and models typed (picked, else the saved picks, else the vendor list); a key not typed again is the saved provider's, or for an unsaved copy the copied one's (copyOf). The probe writes nothing and adds no provider, and the route stays behind magpie web's key. An endpoint or model test fails fast and can be stopped (RIck on Discord: 测试模型 took long to fail and couldn't be cancelled): a probe on magpie's own client that has no connection in connectWait (10s) fails then (connecting, an httptrace GotConn), and a host that couldn't be reached (no connection, DNS, refused, a bad certificate) fails the run's other models at once (withUnreached, TestTestModelsUnreachedHostFailsOnce); a stream that breaks off before an answer is a failure. While a test runs its Test models and endpoints' Test read Stop, which aborts the window's request and posts provider/teststop with the test's run, ending the vendor's request on the server too (testRuns in providers.go, since WebView2 doesn't end the request when a fetch is aborted; TestProviderTestStops, model-test-stop.test.cjs). |
detect.go, test.go |
| A pasted curl command | A curl command from a vendor's docs pasted into a custom provider's Base URL or API key fills the editor in (@mark_li21 on X). curlOf reads it as a shell would (lines joined by \, cmd's ^ or PowerShell's backtick; curl.exe; quotes and escapes), and takes: the API its URL's endpoint names (…/chat/completions Chat, …/messages Anthropic Messages, …/responses Responses) with the base URL before it, spelled as that API wants it (respellURL: Anthropic at its root, /v1 after a bare host); the key from Authorization: Bearer, x-api-key or api-key, unless it only stands for one ($OPENAI_API_KEY, ${X}, %X%, <token>, YOUR_API_KEY), when the key's box is left empty and focused; and the model of its JSON body, added to a new provider's models (a saved one's picks are left alone, since adding to none would narrow what it serves). A preset's editor takes only the key. A note (editorError, kind note) says what was taken, a placeholder like {WorkspaceId} left in the URL, and a URL with no known endpoint. Text that isn't a curl command pastes as before, several keys included. Tested on the docs' own examples (fixtures/curl). |
app.js (curlOf, fromCurl), provider-curl-paste.test.cjs |
| Saved proxies | settings.Proxies holds named proxies (NamedProxy: id, name, address, optional login), kept in Settings › Network. Wherever a proxy is chosen (global, plugin downloads, app updates, a provider, a key, a Claude account) the value is "" (inherit), direct, an address as typed, or @<id> for a saved one (@tsingchao on X). Addresses as typed are untouched. App updates take a proxy of their own, Settings › Network › App updates (settings.UpdateProxy, `magpie settings set updateProxy <url |
direct>; moonlityu on X: models direct, updates through a proxy): "" follows the global proxy as before, a proxy given to one magpie update --proxy run comes first, and it covers the feed, the notes and the release's file (updateProxy in [update.go](../../internal/update/update.go); TestUpdateTakesItsOwnProxy, settings-update-proxy.test.cjs). Per-model proxies within one provider are not offered: a proxy belongs to a provider, an account or a key, and a model that needs the other route is a second provider on the same URL. netproxy.Parse, Resolve, Redact, EnvWithandDispatchresolve an@idat the lowest layer, so an edit reaches every user at the next request; a Claude Codesettings.json env is a snapshot and is rewritten after an edit (provider.ProxyEdited). An @id this computer lacks fails closed (netproxy.DeadProxy, the request error and the provider row say "Proxy missing: {name}", provider.ProxyGone); it never goes direct. The password is written to settings.json (0600) and never read back by the page, logged or put in Settings sync; the list rides with the providers part of a sync (backup.Bundle.Proxies, settings.MergeProxies, passwords only with keys). A proxy in use cannot be deleted (409). A saved proxy can be an SSH server (ssh://host:port, a user, a password and/or a private key; @laiuuui on X, whose VPS gives only SSH): magpie logs in itself with golang.org/x/crypto/ssh, no ssh command, and resolves the @id to a SOCKS5 server of its own on loopback (socks5h://magpie:@127.0.0.1:, which takes only that login), carrying each CONNECT as a direct-tcpip channel, as ssh -D does. It logs in on the first request, keeps the connection with keepalive@openssh.com every 20s (15s with no answer ends it), and logs in again once when a channel finds it dead (sshTunnel in [ssh.go](../../internal/netproxy/ssh.go)). Save logs in first, so a refused login is said there and nothing is kept; the host key is trusted on first use and kept as HostKey (authorized_keys form, the page shows its SHA256 fingerprint), and a server showing another key is refused (HostKeyChangedError) until Advanced › Trust a new key. The key is a secret as the password is: WithoutProxyPasswords, MergeProxies, KeepSecretsOf. An ssh://typed as an address is refused: its login belongs to a saved proxy. Every request to the server needs it to allow forwarding: macOS 27's sshd hangs up on a forward (also with OpenSSH's ownssh -W), and that is said as "won't forward connections" (SSHForwardWhy). A failed proxy says why (netproxy.Why: an English template the page translates, its {addr}, {was}, {now}filled;failin api.go sends it ascode: proxy_why, a check as why/addr): Explainreads Go's error, andExplainServer, for a check the user asked for only, reads the server's first bytes when the text can't tell, since Go reads a real OpenSSH banner ("SSH-2.0-OpenSSH_9.6p1 Ubuntu-3ubuntu13.20") as an HTTP status line with a bad code. Each save is tested at once. TestSavedProxyChoice, TestDanglingProxyReferenceFailsClosed, TestSavedProxiesTravelWithProviders, TestSSHProxyCarriesRequests, TestSSHProxyRefusesAChangedHostKey, TestSSHProxySaysWhyItFailed, TestProxyFailureNamesAnSSHServer, TestSavedSSHProxyAPI, TestSavedSSHProxyThatWontForward(an SSH server in the test,netproxy/sshtest, never the network), saved-proxies.test.cjs, saved-ssh-proxy.test.cjs, provider-proxy-missing.test.cjs`. |
Remote magpie
The remote-magpie preset is of its own kind, KindRemote (remote), not
a relay: the app's Add sheet lists it under Another computer's magpie, after
On this machine, and magpie presets and the TUI's add list name it so too
(kindNote in tui/pages.go).
A remote-magpie provider derives Chat, Responses, Messages and System One
bases from one address (remoteMagpieEndpoints in
remote_magpie.go). Its model
list requests images, videos and decisions with X-Magpie-Drawers,
X-Magpie-Videomakers and X-Magpie-Deciders. The gateway includes these
only when asked, with kind of image, video or decision. Any other
client asks for image and video models with ?kind= (chat, image,
video, comma separated, or all; listKinds in
gateway.go); without it the list is
chat models alone, so no agent's chat picker offers an image or video
model, and an unknown kind is a 400 (axelburks on Discord;
TestModelsListMediaOnlyWhenAsked). Decision
entries pass through keyAllowed, including model and account restrictions.
catalog/live.go keeps each kind and all
models the remote already exposed, including retrieval models. The shared
list has no separate retrieval kind: these entries remain in Catalog and
agent model lists, just as on the remote. Keeping them makes retrieval
routing possible; their presence does not mean they support conversations.
DecidesModel uses the remote's explicit decision marker, so Clef and custom
names work and a chat model named Jev Router stays a chat model. Deciders
lists, and the gateway answers, these decisions even when the user's local
conversation picks omit them. What a routing group's pickers, templates and
the TUI offer is OfferedDeciders: with picks saved, only the picked
decision models plus any a group names already, as the provider editor
shows the rest unpicked (coeo91 on Discord: two free OpenRouter models
picked, OpenRouter's decision models still offered beside them). A
vendor's own one decision model beside its chat models (bailianApart: a
Bailian plan's, Ark's pay as you go) is no list to pick from, and is
offered whatever the picks. Only remote decision entries use entryFor
to apply user model names and limits; other decision providers retain their
previous entry formatting. The editor's providerInfo in
providers.go sends deciders: [] when
the remote has none, suppressing the UI's legacy name-based guessing.
The editor offers one remote address; its System One endpoint is derived
from that address and has no separate input. Unnamed decisions use their
model ids for display names and provider labels.
A key's provider with a System One URL beside a conversation URL
(TakesDecideAPI in
modelprefs.go: no account, no
remote magpie, no Vertex) takes decide as a model's API (DecideAPI,
saved in modelAPIs). DecidesModel is then true for that model alone, so
it leaves buildEntries, joins Deciders, and the gateway refuses a turn
for it; decideModels lists it first, and resolveDecideModel asks
System One by its own name (axelburks on Discord: an Ark endpoint id).
apisAmong ignores decide, so it never picks a conversation URL. The GUI
offers it when providerInfo's decideAPIKind is set and a System One URL
is saved or typed. A custom provider of any base URL API gives one under More
endpoints (System One URL, saved with any API; before, only a System One
base URL kept it, so a Responses provider had nowhere to give it). A
provider asked at Volcengine Ark's pay as you go (ark.<region>.volces.com/api/v3,
chat completions or Responses, its preset's or a custom one) needs none:
normalize sets its System One to …/api/v1 on the same host
(arkSystemOne), where the same key answers with Ark's beta header, so
ArkDecision is a routing group's classifier with no URL typed. Ark's
Coding and Agent Plans answer System One nothing (404) and get none; a
key of another plan is never asked it (decideKeys). A URL the user gave
is kept. TestArkPayAsYouGoDecides, TestArkDecisionSkipsPlanKeys,
custom-systemone-url.test.cjs.
Refresh replaces the list: removed decisions stop routing, and an empty
remote list never gains a fabricated Jev alias.
An older peer without the decision-list extension continues serving its
other APIs but must be updated before its decisions can be discovered.
See decide.go.
oMLX (#1641) and MLX-Serve are such mixed providers too: oMLX's server lists
Clef, Clef-Flash and OpenJev among its chat models with nothing to tell them
apart, so its decision models are the ones its /v1/models/status gives
model_type decision, by the name /v1/models uses (its alias), kept under
<id>.decisions like OpenRouter's (omlxDecides, listedOMLXDecide in
omlx_decide.go). MLX-Serve marks
them in its /v1/models with capabilities: ["decisions"], kept under
<id>.decisions (mlxServeDecides, listedMLXServeDecide in
mlxserve_decide.go). Ollama
and Ollama Cloud (Nanka on Discord; Ollama 0.35.0+, 0.40.5+ for cloud models)
serve System One at /v1/systemone beside their chat API, and list decision
models (Tev, Nimble, Clef) in /v1/models like any other. Their /api/tags,
asked with the same key, gives each model capabilities, decision for
these and vision for one that reads images. Those are kept under
<id>.decisions, with the cloud's 65,536-token window when the list gives
none (ollamaDecides, listedOllamaDecide in
ollama_decide.go). An Ollama
older than its System One lists no capabilities, so none. A server
with none lists none, and no Jev is made up for it. An oMLX, MLX-Serve or
Ollama provider saved before the preset had a decision base gets its chat
base as one.
A Remote magpie's agents' models are followed here (KoiLx0 on X: several
computers on one remote magpie, each setting every agent's models again by
hand, and again after each change there). The remote tells, for each agent
connected on it, the catalog ref of each model field at
GET /v1/magpie/agent-models (provider.RemoteAgentModelsPath,
agent.SharedModels, asked as the Library is: this computer, or a
full-access key of a magpie shared on the network). An agent connected here
starts on those picks where this magpie lists them as <remote id>/<ref>
(How remote, after again and joined; connectRemote in
remote_picks.go). A field set
from the remote, or found on the remote's pick, is recorded
(<agent>.<field>.remote in the stash) and follows the remote's change
every 5 minutes (FollowRemotePicks, from library.KeepLinked) while it
still holds that value; a model the user picks here is theirs, and the
field is left alone until it is on the remote's pick again. A pick this
magpie doesn't list is skipped. Routing groups need nothing of their own:
a group made on the remote is a model of its list, offered at once
(TestRemoteMagpieNewGroupServedBesidePicks).
TestConnectFollowsTheRemoteMagpiesPicks, TestSharedModelsTellsTheRefs.
An agent installed here that isn't connected is left alone, unless the
remote's editor has "Connect new agents to this remote" on (Advanced, off
by default; kept per computer in the stash as
remote.<id>.connectAgents, agent.SetConnectAgents). Then the same
follow connects an agent the remote has connected, on the remote's pick
(connectFromRemote), and records it as <agent>.remote.auto. An agent
the user disconnected here is never connected again: one with the
Disconnect mark, and one recorded on that is no longer connected
(taken out by hand in its file) is recorded off. An agent magpie put
back on quit (quit.restored) is left to RewireOnStart. Connecting it
by hand records on again. TestRemoteConnectsNewAgents,
TestProviderSaveConnectAgents.
The CLI and TUI report model-list fetch errors for remote and other mixed providers
(such as OpenRouter, serving conversation and decision models). Only a
decision-only provider keeps the separate decision discovery behavior
(announce in providers_cli.go, addKeyAsk in
pages.go). A remote's endpoint test reuses
successful model discovery for its decision result, and reports none when
no decision model was discovered (Test in
test.go).
Account discovery can be turned off (#1535): Settings → Privacy → Subscription accounts, magpie accounts discovery off, or MAGPIE_NO_ACCOUNTS=1 for one process. The first two save noAccountDiscovery: true, which this computer keeps through a sync or a restored backup (KeepOwn); the variable only ever turns discovery off, never on what the user saved off (settings.AccountDiscoveryOff). It is on by default. In the GUI, Off asks first and names the subscriptions in use that it stops (discoveryOffWarning in app.js, #1761: a user turned it off without meaning to and was left with no subscription working). While it is off, magpie reads no agent's sign-in: no credential file (~/.claude/.credentials.json, ~/.claude.json's account, ~/.codex/auth.json or Codex's keychain item, Copilot's, Cursor's, Devin's, Kiro's, Gemini's, ZCode's, Command Code's, OpenCode's auth.json), no Keychain or Secret Service item (security, secret-tool), and no agent CLI asked who is signed in. The gates sit at each reader (readAccountFile, discoveryOff in discovery.go) and at each route that would read or write a sign-in: Accounts and All, Logins, usage, renewal, warm-up, session identities, check-ins, switching, forgetting, SetLoginOn, StartSignIn, the imports, and moves onto plugins (MoveCandidates, HandOver, KeepRetiringMoved). Those that write refuse with errAccountDiscoveryOff, which says how to turn it back on. The agents' side is gated too: the Agents page's runs on line (Agent.Source), OpenCode's own providers (readOwnAuth), and wiring Codex, which goes by magpie's stash instead of auth.json (chatGPT in codex.go). Subscriptions aren't served; API-key providers, middleware plugins and Pi extensions run as before. So does a public plugin, one whose every way in is keyless (publicPlugin in plugin_accounts.go, OpenCode Zen Free): it holds no account of the user's, so it stays listed and served, and its sign-in goes through (lileo0668: it signed in, then was listed nowhere). Any other plugin's key is refused in PluginAPIKey, as its browser sign-in is, rather than saved and listed nowhere. What magpie kept of its own (logins.json, plugin-auth.json, migrations.json) is left as it is, unread for accounts, and serves again once discovery is on. A change takes effect at once (ForgetAccounts); no restart is needed.
A signed-in account's model list exists only at its vendor (the ChatGPT backend's /models for a Codex sign-in, …), so FetchNew asks for the lists not fetched yet. Every front end calls it at start: the window (startBackend, then FetchNewSoon behind /api/state), the TUI (fetchModelsCmd in Init) and magpie serve (#1789, reyoung: the terminal and a headless gateway had offered the built-in Cursor's fallback auto alone until the list was fetched by hand). Listing the accounts asks a CLI who is signed in, and a look waits firstAsk (3s) for that; cursor-agent about asks Cursor's servers and can take longer, so FetchNew waits for each CLI asked for the first time (awaitIdentities in cli_identity.go) and lists the accounts again. It reports whether an account was left without its list (failed, or waiting newFetchRetry after a failure): the TUI then asks again a minute later (modelsRetry) and serve loops the same way, while the window asks again from its pages. A TUI model picker open when the list arrives is filled in place (relist), keeping its filter and the model under the cursor. TestFetchNewAccount and the TUI's TestTUIFetchesSubscriptionModels / TestTUIAsksAgainForAMissingList cover it. A list fetched once is not left as it was: the magpie serving the gateway looks every hour (KeepAccountsListed, first two minutes after it starts) and fetches again each signed-in built-in account's list that is 45 minutes old (accountListAge, relistAccounts), so a model the vendor adds to the plan is served without Refresh or a magpie release (cliff_26651 on Discord: GPT-6.1 Terra, served to ChatGPT accounts from 10-26, missing from Codex through a magpie whose Codex list was fetched on 10-12). A plugin's accounts are KeepPluginsListed's, one switched off isn't asked, and a fetch that fails keeps the list there was. TestAccountListFollowsTheVendor and TestKeepAccountsListedAsks cover it. The saved ChatGPT accounts behind the one Codex is signed in to are listed with that fetch (codexFetchSaved), but not each time: one with no list yet is asked at once, the others once a day (codexSavedListAge) and one a look (codexSavedAtOnce), the one asked longest ago first, and one that failed waits its day too (codexSavedAsked). Asking every switched-on saved account each hour was a burst of /codex/models calls from one address for accounts no Codex used (TestSavedCodexListsOnceADay). Each list is kept with the Codex version it was asked for (catalog.SaveLiveAsked), as the backend lists a model only to a client new enough for it; a saved account's list asked for an older Codex than magpie speaks as now, or kept with no version, is asked at the next look as one with no list, an hour after a failed try (codexListBehind, codexBehindRetry, TestBehindListAskedAgain); so is one fetched more than listRound (10 minutes) before another account's list first had a model (catalog.LiveNewest, TestListOlderThanAnothersModelAskedAgain). An account's own list (Codex's, Antigravity's) is evidence its plan lacks a model only when it can know the model: AccountsFor routes over, as unknown, an account whose list was fetched more than listRound before another account's list first had the model (lists fetched in one look are the plans' difference; catalog.LiveSince, each model's first save kept from save to save) or, for ChatGPT, was asked for an older Codex (Account.listLags; wudao_85256 on Discord: the second of two Plus accounts was "its plan doesn't list gpt-6.1-sol" and never failed over to; TestStaleAccountListIsNotAPlanWithoutTheModel). Every call magpie makes about a ChatGPT account, not only /codex/models and /responses (codexSign), carries Codex's originator and User-Agent (codexClientHeaders, codex-rs default_headers): /wham/usage, the reset credits and their use (codexAccountHeaders), and the token endpoint's refresh and sign-in exchange. The refresh's body is codex-rs's: client_id, grant_type, refresh_token and a refresh_reason (proactive_expiry, scheduled from the keep-alive, unauthorized_recovery after a 401, forced), with no scope (TestCodexAccountCallsGoAsCodex, TestCodexRefreshSaysWhy).
Runtime path
- Add. The Providers page adds a key provider through
AddorSave, or an account throughStartSignIn. An agent signed in on its own is found byAccountswith no step from the user. - Resolve. The gateway calls
provider.ResolveorGroupForwith the model name, then plans candidates over the provider's keys or accounts. - Sign. For each try,
Signgives the request its auth. A token about to expire is refreshed first, and the rotated tokens go back to their one holder: the agent's store, orlogins.jsonfor an account standing behind it. - Allowance. Usage endpoints are rate limited, so
SubscriptionUsagecaches its results: a cached copy comes back at once and a stale one is refreshed in the background. When an account's windows start again,OnRenewedtells the gateway so a resting account can come back: a Codex reset spent (renewedNow), or a reading routing takes (Allowances, as the agent the account's usage is read under,claudeorplugin:<id>) that finds the account full till sooner than the last did (renewedFrom, the rule a key's reading goes by): the whole account, or a pool of some models with the whole account's windows over it. A window used belowSpentShareOfits routing, or whose reset passed, is full no more; one full with its reset not known is full for good. A Claude account is back as soon as a new/usageor the reset passing shows the window it was out of started again, not when the time Claude Code's refusal named comes; its five hours started again in a week used up tells nothing. A first reading, a failed one, one read alike, or one leaving the full window out tells nothing, and a reset spent is told once, byrenewedNow. A key's reading that finds a window it was full in (atSpentShareOfits routing) full no more, or full till sooner, tells it too, as agent""and the key'sKeyAllowanceID, so a key out of its limit is back once the limit is raised or its usage reset; a first reading, a failed one, or one that finds it fuller tells nothing. An account refused for its quota has its agent's allowances read again at the next ask (StaleAllowance). A reading already out then was asked before the refusal: what it read is kept, as not read, so the ask after it lands reads again, asStaleKeyAllowancedoes for a key.
A provider's fetched model list keeps the upstream ids and order, each id
once: a list that names a model more than once (#6582) keeps the first
copy, in its place, with what it leaves unsaid (a name other than the id,
window, output, levels, price, APIs, tiers, magpie_via, keys) taken from
the copies after it (catalog.Unique). It runs where every list passes:
the parse of an upstream /models (fetchOne, so the add form's List
too), every save (saveLive, the list and each base's part, whoever
fetched it), and every read, so a list saved before reads each id once
without a fetch (readLive). The pickers, /v1/models and the agents'
lists are built from those (TestFetchedListNamesEachModelOnce,
TestSavedListNamesEachModelOnce, TestProviderListsEachModelOnce). A
plugin's list is its plugin's, keyed by id there. Display
names prefer magpie_label, then display_name, then a name without a
vendor-style : prefix, then the id
(live.go, fetchOne). OpenRouter's
prefixed name is left to the catalog. Decorate and
Named fill missing names from the
catalog, keeping an id when a suggested name would collide with another
model in the list, including when exact ids differ only in case. Accepted
names supplied by the provider stay as supplied. Models picked by the user
that the upstream does not list are named against all listed names and ids;
listed models keep their Available names unchanged
(Exposed).
The list a magpie gives another magpie also names, as magpie_by, the
provider serving each model there (Entry.ServedBy: "routing group" for a
group, and for a model of its own Remote magpie the provider at the start
of that chain), kept as the model's By (live.go).
A Remote magpie set upstreamProviders (the editor's Model names tick,
magpie provider set <id> upstream-providers=on; lcc580 on X) names each
of its models by it, whatever either magpie's Provider in model names:
"DeepSeek Chat · Office › Relay A" (Entry.Label, upstream), so the same
model from two of the remote's providers can be told apart. Ids stay as
they were, and a remote older than the field names its models as before
(TestRemoteMagpieUpstreamNames, TestServedByAndUpstreamLabel,
name-suffix-remote.test.cjs).
A listed model's window, reply limit and levels come from the vendor's
list first; only what it leaves out is filled from models.dev. Decorate
matches the provider's own catalog by id, then by the same model under
another spelling (catalog.SameModel, the rule routing groups use): Ark's
glm-5-3-flash-260828 takes its plan catalog's glm-5.3-flash.
ContextOf, OutputOf, EffortsOf, Thinks, SeesImages and
ListedBy try another spelling last, only when no spelling matches as
given (normalFor, the spelling most entries list: Ark's
kimi-k3-1-pro-261024 reads as kimi-k3.1-pro; TestOtherSpellingLimits).
The id stays the upstream's, and its name isn't borrowed. A price never is:
PricedBy matches only as before (TestOtherSpellingIsNotPriced). The
usage report sends a model id only when models.dev knows it as written
(KnowsAsWritten).
A model no rule can read (a relay's rename, ds.4.1(WB) for
deepseek-v4.1-flash, pinmmis on X) takes its specs from the model the
user said it is the same as: the editor's Same as, settings'
ModelSameAs. The settings package hands it to the catalog
(catalog.UserSame, sameAsBare, by the bare model id at any provider),
and the same lookups ask it after the id as given and before magpie's own
guesses (renamed, normalFor); a model models.dev lists by its own id
stays its own, and the user's own window, reply limit, levels or images
still win. Its price stays the provider's SamePriceIn. Before giving up,
those lookups also take a channel's tag in brackets off the start or end
of an id (untagged: deepseek-v4.1-flash (WB), [WB] …, full-width
()【】); a [...] written onto the id with no space is not a tag, since
it may be a variant's (deepseek-v4.1-flash[fast]), and a tagged id is
never priced. TestUserSameGivesTheSpecs, TestTaggedIDHasTheModelsSpecs,
TestSameAsGivesAnUnlistedModelItsSpecs.
The Same as box has a picker beside it (timfang4162 on X): the app's menu
over GET /api/catalog/models (catalogModels in
catalog_models.go), the synced
models.dev catalog with one entry a model by catalog.SameModel, read from
the cache with no fetch, filtered by id, name and maker
(modelSamePick in modellimits.js).
A pick only fills the box, so it is staged and saved as a typed id is.
TestCatalogModelsListsTheSyncedCatalogOnce, model-same-pick.test.cjs.
A model can also be listed by an id the user gives it at its provider
(zeewell on X: a relay's deepseek-v4.1-flash-1017 as
deepseek-v4.1-flash, grok-4.6@500k as grok-4.6): the editor's
Model settings "Listed as" box beside Same as, magpie model id <provider/model> <id> (--reset takes it back, magpie model ids lists
them), settings' ModelIDs ("<pid>/<id>": "<own id>",
provider.SetModelID, localid.go).
Same as only lends specs and joins found groups; this id is what magpie
lists, picks, groups, finds groups by (auto/<id> with every other
provider serving it), limits gateway keys to and records usage under,
while the vendor is asked for its own id: Settings.Wires() turns each
entry round into a wire name, so every place a ModelWires name goes out
sends it, and an explicit ModelWires entry for the same id wins. A signed-in
account's and a plugin's provider take one too; only a provider that just
decides doesn't (TakesModelIDs). Their body goes out by the wire name as
any provider's, and what is read of the model by the vendor's id is read
by OwnModelID: a plugin's model (pluginModel, so its API, tiers and
prices), Claude Code's run on a Claude account, Code Assist's and
Antigravity's variant (codeAssistBody, SentNameOnIn), and an
account's own list, levels and tiers (Account.Lists in the fallback,
Levels, Tiers, AccountServes). One id is one model of a provider: the latest given it has it,
and the one before is listed by its own id again (the CLI names it; the
editor refuses two rows given one id in one save). A model of the
provider's own id that another is listed by (grok-4.6 beside
grok-4.6@500k) is not listed while it is. Giving the id moves what the
user set of the model (picks, contexts, fallbacks, routing groups'
members and rules, the pickers' lists, every per-model setting, gateway
keys' models through provider.ModelMoved) to it, but never over a value
the user already has under the new id (Settings.MoveModel). Agents'
files are not rewritten: an old provider/<own id> still resolves and is
asked for as it is. A gateway key held to either id passes for both
(modelAllowed). A group's match pattern is left as the user wrote it.
Usage records the model by the listed id and served by the vendor's;
the price is the own id's first (ListPrice). TestModelIDListedAndAskedForByOwn,
TestModelIDLatestWins, TestModelIDMovesTheUsersRefs,
TestLocalModelIDOnEveryRoute.
Constraints and failure behavior
An allowance deliberately not requested (a saved Claude account outside
its card refresh, or allowances set to When I ask) can use the last
reading with readDeferred: true. AsOf and ReadAt still date that
snapshot; the GUI says it was not refreshed this time rather than that a
request failed. Network failures, unavailable /usage and account refusals
are not deferred reads. The flag also reaches magpie quota --json and
the gateway report. quota_last.go,
TestQuotaDeferredReadIsNotFailure.
Allowance readings are kept by provider, lowercased account and window in
quota-history.json (quota_history.go),
for up to 45 days and 6000 points per window. Failed or stale readings add
nothing. A window set aside for routing is kept when it is measured (a
pool's window, or the Cursor plugin's Weekly and Grok Bot, #4612); a
text-only one tells no share and is not, and neither is a plugin's aside
window that leaves used out with no count to reckon one from: its Used
is 0 for want of a share, not a reading, and drew a flat 100%-left line
(noShare, #4825). newCycle preserves a boundary
when the previous deadline passes,
appears/disappears, moves backward by more than five minutes or forward by
more than the elapsed sampling time plus five minutes. A refill of more
than five percentage points with a deadline unchanged within five minutes
is also a boundary: a manual or vendor reset need not change the deadline.
Smaller corrections and a rolling deadline advancing with time do not
split that window. These are observed boundaries, not a record of who reset
it; multiple resets between readings and refills hidden by subsequent
spending cannot be recovered. Sampling compression and sync merging keep
readings on both sides of detected boundaries.
Whole-window estimates in window_holds.go
leave out a window whose calls fall in one of the account's dry runs, since a
call answered there may have been paid from credits or extra usage (#2010,
NorethSea). A known vendor reset ends a dry run, even when the next poll sees
the refill later, and a following dry run starts no earlier than that reset,
so calls between the two still count. A reset time that isn't known keeps the
run open. A stale dry reading taken after its own reset can't extend a run.
Credit balances are read account-wide and shown rounded, and the ledger has no
per-request credit charge. Comparing two balances can't tell which concurrent
or outside call spent credits, so no per-call attribution is attempted.
A refill observed later than reset minus span (QuotaPoint.StartsCycleAfter,
the same boundaries history sampling keeps) starts what is reckoned, so calls
before a fixed-deadline refill stay in the cycle before it. The card's window
keeps its span, so its Pace is the vendor's (withSpansOf). A first reading
with no recorded start is not a reset. HistoricalWindowHolds
(window_holds_history.go)
reckons a past cycle's windows the same way, each at its own last reading in
the range, with that reading's percentage and bounds, the cached card's model
scope, and only calls and readings before that reading. A card that is gated
live (a balance, a remote, an error) is gated for past cycles too, and a
window no longer on the cached card is left out. Past prices aren't kept, so
the cost is at today's API list prices. A call whose own id has no API price
is costed as the model the reply named (Served), as the ledger is (#1498).
Where a call was over a long-context tier's size, the whole is also told at
the models' base rates, the tiers left out and a peak hour's price kept
(BaseCost, baseRates, #5861, NorethSea): a plan's own use pays no such
premium, so cycles whose calls' sizes differ compare on that figure. It is
sent only when it differs from Cost; the card's figure is then a button that
switches every card, past cycles too, between the two, kept in the browser
(holdsBase, quota-holds.test.cjs,
TestWindowHoldsBaseCostLeavesOutLongContextPremiums). Tokens counts input
and output; with the Usage page's tokens pick on With cache the card adds
Routed.CacheRead and CacheWrite over the same share used (holdsLine). See
TestWindowHoldsDryAgainAfterReset, TestWindowHoldsUsesObservedRefillStart
and TestHistoricalWindowHoldsUsesEachWindowsOwnReading.
- A successful Codex allowance reset invalidates an account's in-flight reading even when the read and reset have the same clock timestamp.
AllowancessnapshotsusedCache.generationunder its lock, andforgetAllowanceadvances the generation for that account; a reading from before the reset is dropped before routing can use it.routing.go,TestResetAllowanceKnownAtOnce. - Each refresh token has exactly one holder. Vendors rotate tokens on refresh, so two copies of one token would sign each other out.
savedTokenMustops two requests refreshing one saved account at once. - A Claude subscription account is used only for Claude Code, through the genuine Claude Code binary (see Claude subscription bridge).
- Claude usage asks are ordered by
claudeAskGeneration, not wall-clock timestamps.AskClaudeUsageand a Claude card'sRefreshUsageadvance it while holding the subscription cache then the login cache lock (markClaudeUsageAsked). Each cache captures it under its own lock before launching a read and checks it under that lock when publishing: a newer ask preventsLoginUsagefrom keeping the older reading and leavesSubscriptionUsagedue to read again. EachclaudeWindowsentry records the generation its run answered. The timestamp's zero sentinel,tried/wait, the 30-second floor, idle behavior and saved-account scope remain unchanged.login_usage.go,subscription_usage.go,quota_refresh.go. - A saved Claude account's allowance is read only when its own card is refreshed (#1630;
savedRefresh:RefreshUsagefor that account, socardRefresh.wantsit and the read is asked), or when every allowance is refreshed by hand (#5380): the tray panel's and the Usage page's top refresh, Routing's Read allowances and the TUI'sraskusage/quotas?asked=1&all=1(AskEveryClaudeUsage), and so does the gateway'sPOST /v1/magpie/quotas/refreshwith no card named (ReadAllCards: another magpie's refresh of its card for this one, or an app with a gateway key, #5443;TestReadAllCardsReadsSavedClaude; a key told only some cards has each read again side by side,RefreshEach, and the other magpie waitsremoteRefreshWait, 25s, for the refresh, not the 8s of a kept-cards read), which marks its generation inclaudeEveryAsked, and forclaudeEveryFor(2 minutes) each saved account not read since is read as its card's refresh would, under the same due check and 30-second floor (TestRefreshEveryReadsSavedClaude). The real Claude Code runs/usagewithCLAUDE_CONFIG_DIRset to the account'sclaudeSavedDir(readSavedClaudeUsage, through the gateway'sclaudeUsage), so magpie never calls Anthropic with the token itself and the account Claude Code is signed in to is not switched. The Usage page or the Allowances tab opened,magpie quotaandmagpie accountsask every card withoutalland so start no saved account's Claude Code: they keep its last reading, orerrClaudeSavedbefore one. Background reads keep the last reading, and the 30-second per-account floor holds for repeated refreshes. Claude Code may refresh the account's token in that directory while it runs (its own lock file keeps two Claude Codes in one directory from refreshing at once). SoinSavedClaudeDirholdsclaudeDirRun(user)for reading while it runs, whichswitchSavedLogintakes for writing first. That lock is this process's only, so each run also holds a lock file of its own beside the account's directory (markClaudeRun,<dir>.run-<pid>-<n>.lock), and the switch waits on every one there first (waitClaudeRuns, up toclaudeRunWait, 90s, thenerrClaudeRunningwith the sign-in left as it was): before,magpie accounts switchdidn't wait for the app's run (#4532;TestClaudeSwitchWaitsForAnotherMagpiesRun,TestClaudeSwitchRunHeldAndLeft). A file whose run ended without removing it is free and taken out. After the switch, the gateway lets go of the account's idle runs, and a run in a turn then ends as the turn does rather than waiting for the next (handedOver,subscriptionRun.handed,TestClaudeHandOverEndsTheAccountsBusyRuns). After the runsyncSavedClaudecopies a rotated sign-in back intologins.jsonundersavedTokenMuandloginsMu. A saved account's warm-up runs the same way, and so does the keep-alive (#4532): every eight days (keepAliveEvery, as for a ChatGPT sign-in, since how long Anthropic keeps an idle Claude refresh token isn't known), one account a look shared with Codex's,RenewLoginsruns that/usageonce for each saved Claude account, on or off (one off is a sign-in kept for later, as a ChatGPT one is), that has a sign-in rather than a setup-token and isn't signed out (claudeKeptAlive,renewClaude), so Claude Code refreshes the sign-in if it is due andsyncSavedClaudekeeps it. The run goes through the account's reading as a card refresh's does (keepingAlivehasclaudeWindowsrun it, past the 30-second floor;loginReadingkeeps it beside the account and on disk,keepCardReadon its card when the Usage page has one), so under switch-only it is the reading a saved account gets. The run marksRenewed, refreshed or not. A refusal is kept as a request's is (NoteClaudeSignInFailure, or the emptied sign-insyncClaudeDirreads), so the account's row says to sign in again. A renewal that fails, of either agent, waitskeepAliveRetry(6 hours,renewWaiting) before the hourly look tries it again, so it doesn't take every look's one turn from the accounts after it;magpie accounts refreshtries it at once (TestRenewLoginsKeepsSavedClaudeSignedIn,TestRenewLoginsKeepsClaudeReading,TestRenewLoginsFailedWaitsItsTurn).claude_usage_saved_test.gocovers the refresh, the other accounts left alone, the floor, background reads, a switch waiting for the run and the rotated sign-in kept;TestClaudeUsageRunsInSavedAccountDirectorychecks the directory the command runs in. - Claude Code's
/usageprints a reset with no year when it falls this year ("Oct 9, 2:59pm (UTC)"), or, in older versions, as a time alone ("3pm").claudeResetTimereads it as the end of its window, so never further ahead than the window's length (5 hours for the session, 7 days for a week) andclaudeResetSlack: a date is in the first of last year, this year and next that is less than a day past and no further ahead, a time alone the next one no further ahead. Where none is, as for a reading days old, it is the latest one already past, so the window reads as renewed rather than full for a year. Where the clocks go back and show a time twice, the reading not yet past is taken. A week's time alone read just after its reset still reads as tomorrow's. - A Copilot account is known by its GitHub login and host (
CopilotAccountName, #1220):monaon github.com,mona@acme.ghe.comon an enterprise's GHE.com. That name is itslogins.jsonuser, its row in every list, its usage card and its per-account routing settings, and it is whatSwitchLogin,SetLoginOnandForgetLogintake, so one login on two hosts is two accounts, neither written over by the other nor dropped as the editors' own. One saved before on an enterprise's host under its login alone is read under its name with the host (copilotSavedName), keeping its id; the editors' own remembered so is renamed in place, still hidden if it was (copilotRenamed). Either rename takes the account's per-account settings inproviders.json(proxy, models, cap, concurrency) from the bare login to the new name before the new name is written tologins.json(renameSettled): a setting the new name has already stays, and whileproviders.jsoncan't be read or written the account stays saved under its old name, its settings with it.magpie accounts switch|forget copilottakes the full name, the login with--host <name>.ghe.com, or the login alone when it names one account. - A Codex account is known by its email, with the plan for a workspace seat (
codexUser), and a second seat of one email in another workspace by that name with its workspace after it (codexName):me@example.com · Team · ws-two. The account Codex is signed in to goes by the name it is saved under (codexLiveName) everywhere: its provider'sAccount.User(codexAccount),liveLogin, and its session identity (SessionIdentities). Its allowance, rests and sticks (restKey), cap, proxy, model list, a gateway key's account list (LoginID) and the Routing page all go by that name, so two seats of one email are never read as one (#1424). One ChatGPT sign-in reaches every workspace of its login with one refresh token, and the Codex app's workspace switch rewrites onlyaccount_idinauth.json, so two saved workspaces can share the sign-in Codex holds. Such an account is renewed where Codex holds it (heldByCodex,codexHeldIn) but its requests, allowance, plan and resets name its own workspace (codexOwnWorkspace), and a sign-in sync carries Codex's sign-in only on the record of its workspace (codexWorkspacesApartinliveCodexandapplyLogins). Before, the account not in use read the one in use's (JdAZzzzzz on X: a Team seat read as the personal Prolite with its resets;TestCodexAppWorkspaceSwitchReadsEachWorkspace). - Every request to the ChatGPT backend (
CodexBase's host) goes over HTTP/1.1, as Codex itself speaks to it: each transportnetproxy.Dispatchmakes (http.DefaultClient's, the gateway's) sends a requestnetproxy.HTTP1names through an HTTP/1.1 copy of itself whose TLS hello offers no h2, and the provider package setsHTTP1tocodexBackend(codex_http1.go). That covers the gateway's turns, the models list, the warm-up, the allowance, its resets and spending one, through the proxy in force, an account's own included. Every other vendor is still offered HTTP/2, except a provider held to HTTP/1.1 (HTTP1, below), a host whose HTTP/2 broke on a TLS record error, and the requests of a download trying again after its transfer broke off (netproxy.OverHTTP1,AgainOverHTTP1,BrokeOff: magpie's update, from where it stopped, the masking model's files, Bun, Claude Code and the Grok CLI; biubiu8802 on X: a proxy cut every HTTP/2 stream of the update part way, "unexpected EOF", while it carried HTTP/1.1 whole;TestDownloadBrokenOverHTTP2TriesHTTP1,TestAgainOverHTTP1). - Every request to OpenCode Zen's free tier (an OpenCode host's
/inference/paths, whereOpenCodeFreeURLsends free models) goes out through the plugin host's fetch, which is Bun's, not Go's: eachnetproxy.Dispatchtransport asksnetproxy.Elsewherefirst, and the provider package sets it tozenFreeInBun(zen_bun.go). Zen tells OpenCode from other clients by the connection: the bytes OpenCode 2.3.0 sent, sent again a minute apart, got 200 through Bun 1.4.2 and 1.4.4 and 429FreeUsageLimitError("Free models work in OpenCode") through Go's net/http and curl, with the public key or a user's own, since Zen checks a free model's limit before its key (biubiubiuzone on X). That covers the gateway's turns, the Test button and an OpenCode Go request asked again at Zen (RetryOpenCodeFreeOnZen). The host is told a provider no plugin claims (magpie-opencode-free), so no plugin's sign-in or fetch takes the request; a plugin'schat.headershook still runs, as for every fetch. Where Bun can't be had (plugin.HasBunfalse after the fetch failed), the request goes through Go as before. Zen's paid paths (/zen/v1,/zen/go/v1) stay in Go (TestZenFreeTierGoesThroughBun,TestZenPaidAndOthersStayInGo,TestZenFreeTierWithoutBun). - A Codex Responses Lite request (an
additional_toolsinput item, orreasoning.contextall_turns; Codex 0.165 and on) carries its instructions in the input, and Codex sends it with no top-levelinstructionsand noreasoning.summary.codexBodyadds neither to it (codexLite): before, it added Codex's full instructions andsummary: "auto", about 4K input tokens a request more than the official client (legeling567 on X;TestCodexBodyLiteGetsNoInstructions). A request that isn't Lite still gets them. The backend'sx-codex-turn-statestays with the account that issued it: the gateway keeps the state a reply gave for that account and turn (client_metadatathread_idandturn_id) and sends it on the turn's next request to the same account, as Codex over HTTP sends it back; a state Codex sends itself goes only to the account that issued it (codex_turnstate.go,TestCodexPoolTurnStateStaysWithItsAccount). - A streamed turn to the ChatGPT backend (POST
CodexBase/responses with"stream":true) goes over the backend's WebSocket, as Codex's own client sends it, and comes back as the server-sent events the HTTP route answers with (codexSocketin codex_socket.go, first in the gateway'supstreamTransport, so Codex's own sign-in passed through and magpie's ChatGPT accounts both take it, through the proxy in force). On some networks a streamed HTTP reply from chatgpt.com is cut at about 120 s, beforeresponse.completed, while the WebSocket runs to the end (brickhao on Discord). The handshake carries the turn's headers withOpenAI-Beta: responses_websockets=2026-02-06, withoutx-codex-turn-stateand the responses-lite header, which go in the message'sclient_metadataas Codex puts them; the message is the body with"type":"response.create"ahead of it (a zstd body is decoded first).codex.rate_limitsandcodex.response.metadata, read ahead of the reply, are also told as thex-codex-*andx-codex-turn-stateheaders the HTTP route carries;responsesapi.websocket_timingis dropped. Anerrorframe ahead of the reply is that status with its error as the body;websocket_connection_limit_reached, a refused handshake or a body that isn't a streamed turn goes over HTTP instead, and a host that refused the handshake (other than 401, 429 or 5xx) is spoken HTTP for 10 minutes (codexSocketShun). A socket that ends, or won't take the message, before any frame of the reply was handed on (any close status, a dropped connection, a normal close with no reply) sends the same body over HTTP (codexSocketEnded): Lamrfu's long conversation was closed 1009 (message too big) by chatgpt.com and got a 502. A conversation's socket is kept between its turns, and a turn that carries on from the last goes on it as only its new input afterprevious_response_id, as Codex's own client sends it (codexKeptin codex_socket_keep.go; codex-rsget_incremental_items): rem_thank on X saw magpie send the whole conversation on a new socket every turn, which a long one meets as 1009. A socket is kept for a turn that names its conversation (session-idorthread-id, elseprompt_cache_key) and endedresponse.completedwith an id, keyed by the host, a digest ofAuthorizationandchatgpt-account-id, the conversation's ids and the subagent headers (codexKeepKey), so another account's turn never finds it nor names its response; the next turn takes it out of the pool, so two turns at once each have a socket. It is let go after 10 minutes unused (codexKeepIdle), at 55 minutes from its handshake (codexKeepAge; the backend ends a connection at 60) and the oldest past 32 (codexKeepMax); the gateway's tests drain the pool in their cleanup (codexKeepDrain). The turn goes as a delta when every field butinput,client_metadataandstream_optionsis as the last turn sent it, and its input begins with the last turn's input and then that turn'sresponse.output_item.doneitems, each compared without its id, status, nulls, empty lists, annotations and logprobs (codexSocketItem); anything else goes whole on the kept socket. What is compared is the body as it goes, after masking and every translation, so a turn masked otherwise than the last goes whole. A kept socket that fails before the reply is handed on (closed while kept, the write fails, or anerrorframe first, such asprevious_response_not_foundor the connection limit) is closed and the turn goes whole on a new socket, and from there over HTTP as before (errCodexSocketAgain). A message at least as big as one a host closed 1009 goes to it over HTTP for 10 minutes (codexTooBig). A socket closed after the reply began reads as a cut stream (io.ErrUnexpectedEOF), and is not asked again. Codex speaks to magpie over its own WebSocket since #4058 (A Responses WebSocket), sending a turn as a delta afterprevious_response_id; magpie gives each turn the whole conversation before it goes on, and this leg cuts its own delta for the kept socket. A turn on the socket tells the try's client trace of itself as Go's client tells it of an HTTP request (socketTrace): on a kept socket it is a request on an open connection, on a new one the handshake's DNS, connect and TLS stand and its round trip is the wait for the connection; the message written is the request written and the first frame the reply's first byte. So the Routing page's "Where the time went" (TryNet) and the usage record's split have the vendor's wait for every socket turn, where a kept socket's turn had nothing but its masking and a new socket's put the backend's wait in its first token (buhaodeshiyehao on X,TestSocketTurnTellsWhereItsTimeWent). The gateway's tests turn it off in TestMain (codexSocketOff); codex_socket_test's fakes speak it. - A provider the user added may have its certificate left unchecked (
InsecureTLS, the editor's Certificate row, #2383: a vLLM on the LAN, Ollama behind a self-signed cert, a company CA). Only one with a base URL of the user's own takes it (TakesInsecureTLS: no account, no preset, not Vertex, not a subscription's or plugin's id);Saverefuses it on any other, and one written into providers.json by hand is ignored.Provider.Viathen addsnetproxy.WithUncheckedTLSwith the hosts of its own base URLs (UncheckedHosts: Chat, Responses, Anthropic, Gemini, Decide), so every request made on its behalf through aDispatchtransport (the gateway's turns, count_tokens, models, test and detect, balance) skips the check for those hosts alone, on a transport kept apart for each (route.unchecked). A redirect or a models, balance or image URL on another host is checked, andnetproxy.Withdrops the leave for a request made for another provider. Anhttps://proxy would be dialled with the same TLS config, so its certificate would go unchecked too: such a request is refused (ErrUncheckedOverHTTPSProxy); anhttp://orsocks5://proxy is taken. Backup, export and sync carry the field with the provider; an import link doesn't. - A provider the user added may show a client certificate and trust a CA of its own (
ClientCert,ClientKey,ServerCA: absolute PEM paths, a~taken as home, the editor's Client certificate rows under Advanced, shown while an address ishttps://; #5596, clxsh: Remote Magpie to a magpie or an Nginx asking for mTLS). It takes the same providers asInsecureTLS(TakesClientCert), andSaverefuses half a pair, a pair that doesn't match and a CA file with no certificate (netproxy.CheckClientCert).Provider.Viaaddsnetproxy.WithClientCertwith the hosts of its own base URLs, so the gateway's turns, streaming, models and the connection test show the certificate to those hosts alone, on a transport kept apart for each (clientRoute), the gateway key still sent; another host, and a request made for another provider, never see it. magpie's own requests of a Remote magpie take the same transport: its cards and quota history (remoteBodyAs), a key's limit (askRemoteKeyLimit), the model list's wait (waitRemoteList), and the Library's server for its MCP router, whose checks and calls go throughViaRemoteMagpieAt(viaRemoteMagpieininternal/library/mcp_check.go). A 403 from one is read as "isn't shared" only when the magpie there says so (remoteRefused); a client certificate check's or a proxy's refusal is said as it came (hhdaxia on X,TestRemoteMagpieOwnRequestsShowClientCert,TestRemoteForbiddenSaysWhatRefused,TestRemoteMagpieRouterShowsClientCert). Through anhttps://proxy such a request is refused (ErrClientCertOverHTTPSProxy). The route is keyed on the files' paths, mtimes and sizes, so a certificate renewed in place gets a new transport (TestRemoteMagpieClientCert,TestClientCertSaveChecks, theclientcert_test.gotests). - The same providers may instead pin their server's certificate (
ServerPin: the SHA-256 of its DER, lower-case hex; Zhangzhangi on X, a Remote magpie on a domain with a self-signed certificate macOS calls not standards compliant). Off by default, per provider. The editor's Advanced → Server certificate asksPOST /api/provider/peekcert, which reaches the form's firsthttps://address through its proxy and client certificate with the certificate unchecked (Provider.PeekServerCert) and shows its fingerprint, names, dates and why this computer doesn't take it (x509.Verifywith the system roots); Trust keeps the pin, and the row then says in red that the certificate isn't verified.Viapasses the pin tonetproxy.WithClientCert, whose transport for those hosts skips the chain, name and date checks and refuses inVerifyConnectionany leaf whose SHA-256 isn't the pin (pinTLS,PinMismatchError). The hosts it applies at arePinHosts: every endpoint of a provider that takes a client certificate, and of a preset's only thehttps://addresses at a host neither the preset nor its regions name (Zhangzhangi on X, "建议对别的自签名域名也生效": LM Studio or Ollama on another computer), never a subscription's, Vertex or a vendor's own host; a client certificate and Server CA still go only whereTakesClientCertholds.TakesServerPinis in/api/providers, and the editor shows the row while the form has such an address (pinAddrsin app.js).Saverefuses a pin that isn't 64 hex digits, or on a provider with no such address (TestServerPinRemoteMagpie,TestServerPinSaveChecks,TestServerPinPresetAtOwnServer,TestServerPinNoVendorHost,TestPinOnlyThatCertificate,provider-server-pin.test.cjs). - A provider may connect a host of its base URLs to addresses of the user's choosing, as
curl --resolve(Provider.Resolve, a map of host name to places; quantum_lsfc on X, a managed network whose domains go to an internal L4 SNI gateway, where an IP in the base URL fails the certificate and/etc/hostscan't be edited). A place is an IP address (with:portif the gateway listens elsewhere) ordns:<name>, looked up at each new connection so a rotating record is followed. Only the TCP target changes: the URL's name is still the TLS server name and theHost. The places are tried in order, each given 8s (resolveTry); when none connects, the name is dialled as if there were no rule.Viaputs the rule on the context (netproxy.WithResolve),Dispatchkeeps one transport clone per rule and wraps itsDialContext(resolveTLS). Through a proxy (the provider's, the global one, the environment's) the rule is not used: the proxy getsCONNECTwith the original name and connects itself;RoundTripmarks a request direct (directKey) only whent.Proxysays none.TakesResolveis whereTakesInsecureTLS,TakesClientCertorPinHostshold: a provider the user added, Remote magpie, a preset at a host of the user's own; never a subscription's account or a vendor's own host. Plugins are not covered: a plugin's requests arefetchcalls in the Bun plugin host, which has no hook for the connection's address, so a plugin's provider takes no rule (TakesResolveis false for an account).Saverunsnetproxy.CheckResolve(bare host names, IP ordns:places, at most 32 hosts and 16 places) and refuses a rule on a provider that doesn't take one. The gateway's offline check leaves such a provider's host out of the hosts it dials to tell whether the network is up (otherHosts), since it dials them by name. The editor's Advanced → Connect to is a box ofhost = place, placelines (resolveRowin tlscerts.js;TestResolveSaved,TestResolveVia,TestOtherHostsSkipResolved,TestProviderSaveResolve, thenetproxyTestResolve*tests,provider-resolve.test.cjs). - A provider the user added may be held to HTTP/1.1 (
HTTP1, the editor's "HTTP version" row under Advanced, shown while an address ishttps://; kepner_53726 on Discord: a company gateway whose HTTP/2 streams broke mid-reply with "tls: bad record MAC" while a plain Go client held). It takes the same providers asInsecureTLS(TakesInsecureTLS), andSaverefuses it on any other.Provider.Viaaddsnetproxy.WithHTTP1with the hosts of its own base URLs, so a request made on its behalf to one of those hosts goes through theDispatchtransport's HTTP/1.1 copy (route.h1); another host, and a request made for another provider (netproxy.Withdrops it), are offered HTTP/2 as before (TestHTTP1AskedOnlyItsHost,TestHTTP1OwnProviderOnly,TestProviderSaveHTTP1). Without it, a TLS record error read on an HTTP/2 reply (recordError: "bad record MAC", "received record with version …", an oversized record) moves that host:port to HTTP/1.1 for 6 hours (h2BrokenFor; see Gateway routing). - A provider the user added with a Responses address may send its turns over the Responses WebSocket, as the ChatGPT leg above does (
Socket, #5781, faithleysath; matrix0487 on Discord;magpie provider set <id> socket=auto|on|off, the editor's WebSocket row under Advanced). It takes a provider with no account, anhttp(s)://Responses address and not Vertex (TakesSocket); the CLI refuses it on any other.Provider.Viaputs the provider's Responses host and path in the request's context (withSocket), andcodexSocketspeaks the socket only to a POST to that host at<Responses>/responses(SocketTurn); a provider withoutSockethides a value an outer context carried, so it never dials a socket (TestResponsesProviderWithoutSocketNeverDials). Everything after is the ChatGPT leg's: the fallback to HTTP on a refused handshake or a socket that ends before the reply, the kept socket and its delta (keyed by scheme,Authorization,X-Api-KeyandApi-Keytoo), and a server-sent-events reply.autospeaks HTTP to a host for 10 minutes once it refused the handshake;ontries the socket every turn and never shuns. Routing, keys, limits, usage and masking are the HTTP route's, since the socket replaces only the transport. - A provider the user added may be set never to rest for a limit (
LimitRestOff,limitRestOff; the editor's Advanced fold, "Set it aside when out of quota or rate limited", ticked by default; zoecats on Discord: a local aggregator's "quota exhausted" while it switches upstreams). Off, a quota, credit or rate refusal and any 429 rest none of its keys and the next request is sent to it as usual (restAfterMarkedin the gateway, see gateway routing). The editor offers it only to a provider the user added (custom); a save that leaves it out keeps it (TestProviderSaveLimitRestOff,provider-limit-rest.test.cjs). - The Copilot account the editors and CLI keep is read by
copilotLogin(account.go): an editor's github.com sign-in in~/.config/github-copilot/apps.jsonorhosts.jsonfirst, then the Copilot CLI's, then an editor's on GHE.com. When GitHub refuses the editor token's trade for a session token (401 or 403,copilotRefusals, retried after an hour), the CLI's sign-in of the same login on the same host takes its place, sent as the CLI sends it, from that request on and on the Usage card (copilotStandIn); a CLI signed in to another account is never used for it, and the error names the editors' file (#1238). A sign-in from magpie of the account whose editor token is refused is kept and stands for it (copilotProbeEditor,addCopilotLogin); while the editor token works, it is let go as the agent's own, as before. - A keychain read that may have shown the user a dialog is not asked again for ten minutes after it was refused (
keychainDeniedTTLin account.go): Copilot's token read backs a denial off (copilotCLISecret), and the Cursor token (cursorKeychainToken) and Claude Code's item (readClaudeKeychainItem, throughclaudeCredential's cache) do too (#2408). 44, the item not being there, is no refusal and keeps the short TTL, so a sign-in made in the agent is still seen within it; a sign-in or out in magpie reads afresh (forgetCursorStatus,forgetClaudeCredential), backoff or not. - An unreadable
providers.jsonis an error, never an empty list. Saving over an empty list would lose every provider. - When
logins.jsoncannot be decoded as saved accounts, reads keep the accounts read before. Before saving a change,lastgood.Keep(lastgood.go) keeps the file there now: aslogins.json.bak, its last good generation, when it reads, or copied aside aslogins.json.bad-<time>(-2,-3… for another within one second) when it doesn't, including valid JSON with invalid account field types, so its credentials can be recovered. If the existing file cannot be read or the copy fails, saving returns the error and leaves the original file unchanged. A missing file can be created normally. - A Windows machine that went down mid-write left
logins.jsonandplugin-auth.jsonat their full length, every byte zero (#1505): the rename reached the disk before the data. Every write of magpie's own state goes throughsteady.WriteFile(oredit.WriteAtomic), which flushes the temp file before renaming it in, and the plugin host'swriteDurabledoes the same. So does every write of an agent's own sign-in (#2239):codexToken's rotated tokens into Codex'sauth.json(~/.codex, or$CODEX_HOMEwhen set; its keychain item instead when Codex keeps the sign-in there) andwriteClaudeCredential's.credentials.jsongo throughwritePrivate, never a truncatingos.WriteFile, so a machine going down mid-write leaves the old sign-in whole, and on Windows a file another program holds for a moment is waited out (steady.Rename) instead of the rotation being dropped while the refresh token on the disk is spent. A file that is there but doesn't read on a cold start is read from its.bak(lastgood.Read/Fallback):logins.json,providers.json,migrations.json,settings.json,profiles.json,plugins.json,plugin-auth.jsonandmcp-signins.json.caller-keys.jsonis flushed the same way but never read from a.bak: a key revoked in the last write would come back, so a store that doesn't read still refuses every key. The recovery is logged and listed in/api/state'srecovered, which the window tells once (recoveredOnce). The.baklags one write behind on purpose: a crash zeroes the latest write, so a copy made with it could be zeroed too. With no good.bakthe file is unknown, never empty: a sign-out leavesplugin-auth.jsonormcp-signins.jsonas it is (magpie's own returns the error), and a sign-in added copies the file aside before it writes. - A state file whose reader takes one that doesn't unmarshal into its type as empty is copied aside before it is written over (
lastgood.KeepUnparsedwithlastgood.Into[T], #2263): valid JSON of another shape,[]for a map, counts as not parsing. A copy that can't be made stops the write. These arestash.json,applied.json,wsl.jsonand Codex'smagpie-models.json(agent, whose hand-added model keyscodexcat.Keepcan't hold when the file doesn't parse),sessions-wsl.jsonandgateway-sessions-hidden.json(sessions),stepfun-auth.json,qianfan-auth.json,login-returns.json,quota-history.json,balance-history.jsonandcredits-daily.json(provider),claude-desktop.tiers.json,plugin-updates.json,usage-computer.jsonandsync-state.json. A daily check-in's file (workbuddy-checkin.json,trae-checkin.json,minimax-checkin.json,qoder-checkin.json,plugin-checkin.json) that is there but can't be read or doesn't parse into entries is unknown (readCheckinsinworkbuddy_checkin.go): its vendor's check-in asks nothing and writes nothing, so no account is checked in twice in a day and no entry is lost, the file is left as it is, each account's result isfailedwith the reason (the loop tries again after 30 minutes, a press says why), and the cards show what last read from it in this process. A file not there is empty.TestCheckinUnreadableFileLeftAlonecovers it. Caches magpie fills again by itself (last quota readings, warm-up marks, plugin icons, npm and GitHub lookups, client shapes, seats, alert marks,served.json,bun/state.json) are still written over: losing one costs a refetch or a repeated notice. - The gateway and a magpie run from a terminal change the same files (#1674).
loginsMuis afilelock.Mutex: besides the mutex it holds an OS lock onlogins.json.lock(flock,LockFileExon Windows), and taking it haslogins.jsonread afresh (filememo.Look), so every read a change is made from sees what another magpie wrote, and a refresh the gateway wrote is never written back over.savedTokenMuholdslogins.json.renew.lockthe same way, so two magpies never spend one refresh token.caller-keys.json(access) andmcp-signins.json(mcpauth, withmcp-signins.json.renew.lockaround a renewal) are changed under such locks too;plugin-auth.jsonalready was, underplugin-auth.json.lock, whichhost.jstakes too. A lock another magpie holds is waited for up tofilelock.Wait(10s), then gone on without, as before there was one.rememberLoginswrites nothing when onlySeenwould move on and the saved one is less thanseenEvery(10 minutes) old, so a run that only lists accounts (magpie ls,providers,sessions,usage) leaveslogins.jsonas it is.logins_lock_test.gocovers both, the second with another test process writing between this one's read and write. - The account Codex or Claude Code is signed in to can be paused (
SetLoginOnoff, #263) only while another of its accounts is on. The gateway then sends it nothing: Codex's own-model turns go through routing, which passes over it (OwnPaused), and a native compaction (/responses/compact) goes to the first account on that isn't resting, signed as that account (compactOnin codex_backend.go). The last other account off, the paused one is used again. A switched-off Codex provider is not a pause: Codex's own-model requests still relay on its sign-in as they came. - A switched-off provider (
Off, #163) stays saved. The gateway says it is off instead of saying the model is unknown. - A subscription switched off (
Off) or whose account was removed from magpie (Hidden) is left alone in the background (leftAloneinleft_alone.go; Riko on Discord, whose Claude switched off still ranclaude auth status --jsonevery minute). No CLI is asked who is signed in (claudeIdentity,cliIdentity.getfor Cursor and Devin): what it said last, in memory orcli-identity.json, is served, so the account stays listed to switch on again. Nor is its allowance read (fetchSubscriptionUsage,loginUsageAt), a saved ChatGPT sign-in renewed (RenewLogins), the agent's account switched (NextLogin), a window warmed (keepWarm), its model list fetched (newDue), a daily check-in made by the loop (checkinNowwithsoonfalse; a press still checks in), a plugin's idle sign-in renewed (KeepPluginsSignedIn, #5080), or a Codex reset about to run out read and spent (SpendExpiringCodexResets, #2226;TestExpiringResetLeftAlone). A Cursor switched off that was never asked who is signed in isn't listed until it is switched on.TestLeftAloneRunsNoCLIruns those paths with fakeclaude,cursor-agentanddevinCLIs on PATH and checks none ran. Plugins' model lists (KeepPluginsListed, and every listing after a sign-in or a plugin changes) are asked of the plugin host all at once, and a plugin provider switched off in magpie is named in the call (plugin.ListingOff,pluginsOffinplugins.go):host.jsruns no models hook for it, nor the sign-in renewal before one, and tells its list as fallen back, so the list told last is kept (ChangQiu on Discord:TestOffPluginProviderAskedNoModels,TestPluginsOffNamesThePluginsOwnIDs). Refreshing every list (the window's Refresh,POST /api/sync, andmagpie sync) goes throughRefreshLists, which asks no provider switched off, and a key added to one isn't given its own list (PrefillNewKeys), nor is a provider switched off asked for its list when it is saved or a key is switched on in its editor (TestRefreshListsAsksNoProviderSwitchedOff,TestPrefillAsksNoProviderSwitchedOff). - A subscription's warm-up and daily check-in are fields under its provider editor's Advanced (
provPrefsFieldinapp.js; Settings' search finds them too). Advanced opens on its own while that provider's warm-up (on reset or at times of day) or check-in is on (provPrefsOn), unless the reader opened or closed it by hand, so a user who set one finds it (ChrisYagao on X;warm-advanced.test.cjs). - Warm up now, the last row of Codex's and Claude Code's warm-up in their provider editors (
renderWarmNowinapp.js,POST /api/warm-now), sends one account the request the scheduled warm-up sends, whatever the warm-up settings say (warm_now.go):warmCodexLoginfor a ChatGPT account, thenStaleAllowance; for a Claude account Claude Code's own run,warmClaudeLoginover the gateway'swarmClaude(WarmClaudeVia), in the saved account's directory, thenclaudeWarmedNow, which has the account read again on its next look while its last reading keeps its own time, so the old windows never show as just read (TestClaudeWarmedReadAgain). With several accounts the press opens the app's menu of them. An account whose sign-in lapsed is sent nothing and says so, and the vendor's refusal comes back as the row's line, in red. The scheduled warm-up's file (codex-warmup.json) isn't written: its next look reads the window as started.TestWarmNowSendsTheScheduledWarmUpchecks the body and headers equal the scheduled warm-up's;warm-now.test.cjscovers the GUI. - All accounts, the first item of Warm up now's menu with several accounts (CoderMaurice on X,
POST /api/warm-all,WarmAllinwarm_now.go), sends Warm up now to every account in use (the one the agent is on, or one turned on beside it) whose windows aren't all running, as the cached readings tell them (windowsRunning: one never read is warmed), three at a time. An account turned off or paused, and one already in its windows, is sent nothing; one whose sign-in lapsed is sent nothing and failed. The row's line says each account's result: the ones warmed, the ones already in a window, and each refusal with its reason, in red; one turned off goes unsaid. A gateway rest isn't read here (the provider package can't see it): an account rested for a used-up window is in that window, so it is left alone as running.TestWarmAllWarmsEachIdleAccountInUse;warm-now.test.cjscovers the GUI. - The scheduled warm-up warms each window a Claude account is expected to have (
withExpected), the 5-hour and the week, also one its reading left out: Anthropic leaves a window out until the request that starts it. A window left out while a shorter one is running is one the account doesn't have, since any use starts every window it has (a Claude Enterprise account with only the 5-hour, koohoko5924 on Discord, whose week was warmed over and over and its state read Idle): the warmer marks itAbsentincodex-warmup.jsonand sends it nothing, andusageReaddoesn't count it as due (windowAbsent,shorterRunningincodex_warmup.go). A week once seen running, or left out of a reading that is only part of the plan's, is still warmed; one never read before is not.TestClaudeWarmLeavesAWeekTheAccountHasnt,TestClaudeWarmStartsAWeekThatReset,TestUsageReadLeavesAWeekTheAccountHasnt. - A Copilot subscription offers the union of its On accounts' models too (
copilotPoolModelsincopilot_pool.go, merged bypoolModelsas Codex's ChatGPT accounts are): each GitHub account's plan lists its own (/models), kept underaccountModelsforAccount.Lists. The first account's list is fetched as before (FetchNew,KeepAccountsListed, Refresh); each fetch of it also asks the other accounts on: one with no list at once, of the rest the one asked longest ago once its list is a day old (copilotFetchSaved). A model Copilot refused an account (copilotRefuses) goes to the others that list it, and stays in the provider's list while another account on lists it (copilotOthersList). Only a failed ask is remembered (copilotSavedAsked), so a list gone is asked for again at once. applemacssma on X;TestCopilotAccountsWithOtherModels,TestCopilotRefusedModelGoesToTheAccountServedIt. - An Antigravity subscription offers the union of its On accounts' models (
antigravityPoolModelsinantigravity_pool.go), each account's own list kept beside it (accountModels, read byAccount.Listsfor routing). The lists are fetched at the first listing, a probe, a sync or a Refetch, and also at each account's quota reading, which asksfetchAvailableModelsanyway: a reading whose models differ from the account's saved list saves it and merges the pooled list again from every On account's own (noteAntigravityList), so a model Google gives one account of several later (01huadalang on Discord: Gemini 4) is offered, routed to and given its bar without that account made preferred or probed. A switched-off account's reading changes nothing.TestAntigravityQuotaReadingListsNewModels. EachfetchAvailableModelsnames the account's paid and current tier first (entitlement.userTier,askTiers), then none; a tier Google answers 400 (a Google AI Pro account's g1-pro-tier, #1553) is left out of that account's lists and quota readings fortierRefusedFor(a day), and the refused request is no row of the request log. - A provider removed or switched off takes its models out of the catalog. Agent wiring's
Reseatmoves agents off them. - A preset marked
NoListuses its preset model list instead of requesting/models, and ignores previously fetched lists, including their protocol and key restrictions, unless the user setsModelsURLor chooses a region markedLists. Each region can carry a different list. Volcengine Ark's Coding Plan and Agent Plan use separate preset lists. Both plans include their embedding model separately from agents' chat-model lists; Agent Plan additionally exposes its image- and video-generation models to Settings → Models → Images; Ark itself refuses video generation on Small and Medium Agent Plans, which include it only in the Large and Max tiers. Models magpie does not yet serve (Agent Plan's speech models) are not advertised. Ark's pay-as-you-go region still fetches its own list. Coding's/api/coding/v3/modelsreturns a general Ark catalog instead of the plan's model ids, while Agent's/api/plan/v3/modelsreturns 404. A preset with no regions may name its embedding and rerank models itself (PresetDef.Embeddings,Rerankers): Voyage AI (voyage, heatonz on Discord) has no/modelsand serves only those, so they are its whole list, each marked with what it serves (catalog.Model.Serves), kept out of chat lists, and found on/v1/embeddingsor/v1/rerankalone byPlanRetrieval(kind)(TestVoyagePreset,TestVoyageModelsStayOnTheirRoutes).presets.godefines these choices;List,fetch,live,planModels,PlanEmbeddings,PlanRerankers,PlanRetrieval,PlanDrawersandPlanVideosinmodels.goapply them when adding, refreshing and reading cached models.TestVolcengineModelListschecks that the plans make no list requests, ignore old cached lists and return their own preset models; pay-as-you-go and an explicit list URL still make requests. - A key's provider can have its model list off (
Provider.ListOff,ListsOff(); axelburks on Discord: Ark's pay-as-you-go list names models that can't be asked for, each is asked by an endpoint id the user made). Nothing asks its vendor for a list:Fetch,Refetch,List,RefreshLists, a test, a new key's prefill and a resting key's probe (ListAsks) skip it, andFetch/ListreturnErrListOff. A list fetched before and models.dev's are not read, so only the ids the user added are served. A signed-in account and a plugin list their models as their sign-in does, so the switch is a key provider's alone (takesListOffin/api/providers). The editor shows it as Fetch the model list, ticked by default; unticked, Fetch models and Forget go. A save that doesn't namelistOffkeeps it. The CLI takeslist=off|on. Tests:TestListOffAsksNoListAndServesTheIDsAdded,TestProviderSaveListOff,provider-list-off.test.cjs. - A gateway key held to some accounts (#905) is held to those of the providers its list names: a provider it names no account of, the key uses as its models allow. A key that lists accounts and no model may use only those accounts' providers' models (
access.HeldModels, applied whereaccess.Authenticatemakes the request'sIdentity, so every route's model check holds it; Linka on Discord: ticking only an account let the key list and use every other provider's models;TestGatewayKeyAccountsOnlyHoldTheModels). The key's menu says so on each account of such a provider ("Used: no … account is picked" when its models reach the provider, "Not used: no … model or account is picked" when they don't), and its badge's tooltip that a key is kept off a provider by its models (#2077: unticking every Codex account left Codex's models served), or, with no model picked, that only the picked accounts' providers' models are the key's. The list keeps an account by its stable id —logins.json'sid, set once written and kept through renames; the agents that keep no logins (and plugins) are known by a hash of the account's name, so an account renamed there drops out of a key's list, holding it closer, never wider. Storing an id for every agent is a larger change, not this one's. An entry<provider>/!<ref>keeps an account out instead (access.ExcludeMark; LeiWang_2000 on X: a key of every account but a few, so one signed in later is used too).AllowsAccountrefuses it first and counts only the entries naming accounts to use for "the providers it names", so a provider with only kept-out entries is used on every other account;HeldModelsandAccountModelsignore such entries, so a key that only keeps some out may use every model; an issued key keeps out what its issuer does (foldAccounts),CleanAccountsrefuses an account both used and kept out, and a magpie older than the mark reads it as an account no provider has, holding the key to none of that provider's (fails closed). The row menu's "Keep accounts out…" picks them (gatewayKeptOutPick,gateway-key-kept-out.test.cjs);TestGatewayKeyKeptOut*andTestKeptOut*hold every route to it. - An account group is a named set of accounts of any providers (
access.AccountGroup,account-groups.jsonbesidecaller-keys.json, under the same lock; LeiWang_2000 on X). A key's list names one as@<id>to use its accounts or!@<id>to keep them out, picked by name in the same menus (the models badge, "Keep accounts out…") and made in the Gateway page's "Account groups" editor ormagpie gateway-key groups.identityOfputs each group's accounts in its place (expandGroups) when it makes the request'sIdentity, for the key and its issuer, so every route's account and model check reads the group as it is now: a change to a group reaches every key naming it on its next request. Groups are read only for a key that names one. A group that can't be read refuses the key; a group gone, or one held to with no account, becomes an entry matching no account and no model (heldToNothing), so the key is held to nothing, never let off. A group a key names can't be removed (the error names the keys); an account signed out since stays in the group matching nothing, as in a key's list, and a provider key rotated in place moves in the groups too (ReplaceAccount). A group holds accounts only, never another group or a kept-out entry, andCleanAccountsrefuses one both used and kept out. The groups ride the settings part of a backup and a sync with the keys (Bundle.AccountGroups). A magpie older than groups reads@<id>as an entry naming no provider, holding a key with no models to none (fails closed).TestAccountGroup*andTestGatewayKeyAccountGroups*hold it;gateway-key-account-groups.test.cjsthe GUI. - A routing group may be held to some accounts the same way (
Group.Accounts, duanckham on X): a request through it uses only those of a provider it names, and with a gateway key only those both allow. Entries are resolved and checked when the group is saved (cleanGroupAccounts,ResolveAccount), and dropped from a shared or imported group. See gateway-routing. - A sub2api key's windows are fixed: each starts at the key's first request after it was empty, aligned to the relay's day, and a window not started yet says
used 0with noreset_at, so it is taken to renew a span from now. They count this key's spend only, not the relay's accounts behind it.ForgetBalances(a key or Balance URL changed) has every key's windows read again at its next ask, a read begun before dropped; until then the last reading stands, fresher than the card's, which routing's reads never write. A key changed is another key (keyID), with windows of its own. - A Volcengine Ark provider's access key (
TakesVolcAccessKey: any of its bases onark.<region>.volces.com) is kept with its keys and never sent to the GUI:/api/providerstells the editor its ID and whether a Secret is saved (accessKey). A save that leaves the Secret blank keeps it, one that leaves the ID out or sends it blank keeps both (an editor opened before the key was given sends"", #1821), andclearAccessKeydrops both. The ID and Secret go together everywhere the keys go: a copy takes them, also when its form sends the source's ID without the Secret (AddCopy), a backup or sync without keys has neither (withoutKeys), and a restore, mirror or sync keeps this machine's (KeepSecretsinRestore,Mirror, davsync'stake) when it came without keys, or with the same key and no access key at all, as a magpie before v0.1.1142 or one the access key was never given on sends it (#1821); another key is another account and brings its own. A copy without keys keeps this machine's secret headers (SecretHeader) the same way. A plan endpoint with no provider on it holding the access key is a card that says which to give (accessKeyCard,needsAccessKey), with a button to the provider's settings, not a card left out. Aproviders.jsonsaved with a UTF-8 BOM is read through it, not taken for a broken file whose.bakstands in. The plan read is the endpoint's:/api/codingasksGetCodingPlanUsage,/api/planasksGetAFPUsage, pay-as-you-go (/api/v3) has no card; the region is the host's. One card is read for each access key and plan.GetCodingPlanUsage's reply (QuotaUsage[]withLevel,Percent,ResetTimestampin seconds) is the one three tools built on it read;GetAFPUsage's buckets are read in each form those tools read (UsedofQuotaorTotal, orPercent;ResetTimeorResetTimestamp), none of them seen from a real account here. A reply none of that reads says so on the card with the reply's head. Changing the access key drops the cached cards (ForgetPlanQuotas). - A Tencent Cloud provider's SecretId and SecretKey are kept, listed and saved the same way, in the same fields (
AccessKeyVendortells the editor whose:accessKey.vendor, the preset'saccessKeyVendor). Only the Token Plan's endpoints are read with them (TakesTencentAccessKey:/planontokenhub.tencentmaas.com, regionap-guangzhou, ortokenhub-intl.tencentmaas.com,ap-singapore). Since 10-22 Tencent serves 个人版 and 企业版 in China at the same/planendpoints with the samesk-tp-keys (product/1823/130060, 130659), so they are one region,plan(a key saved onenterpriseis on it,regionAliases/RegionID); 个人版 has no usage API, so a Guangzhou provider without a SecretId gets no card asking for one (tcSharedRegion), while Singapore's does. A Tencent Cloud provider saved at the old personal hostapi.lkeap.cloud.tencent.com/plan/...is moved to TokenHub's at load (movedEndpoints,moveEndpointsinnormalize), with Responses added; one of no preset keeps the address its user typed, and an app imported at the old host lands on the plan. TokenHub's pay as you go has no plan and no card. A custom provider (no preset) at a Token Plan's or Ark plan's address is the user's own: its editor and Usage page ask it for no access key (AsksAccessKey) until one is saved on it, and its key goes as typed,Authorization: Beareron chat and Responses (ysm119). The preset lists its regions that take one (accessKeyRegions,presetAccessKey), and the editor shows SecretId and SecretKey at those alone.DescribeTokenPlanListgives the account's team plans (a sub-user sees the ones it made); each is askedDescribeTokenPlanfor itsPackageInfoandTokenSummary, the list's kept for what the reply leaves out. The card's one window isTotalUsedofCycleQuota(elseTotalQuota), resetting atTokenSummary.CycleEndTime, else counted in months fromStartTimeand never pastExpireTime. A plan notenablesays its status beside the plan's name. Errors come back as 200 withResponse.Error; anAuthFailure…orUnauthorizedOperationone says to check the key. Built from the API docs (api/1823/132270 and siblings) and the signing doc's worked example; never seen from a real account here. - An Alibaba Cloud Token Plan provider's AccessKey ID and Secret are kept in the same fields (
AccessKeyVendor"alibaba"). Only the plan's two hosts attoken-plan.<region>.maas.aliyuncs.comtake them (TakesAlibabaAccessKey,aliPlanSite:cn-beijingisbailian-token-plan,ap-southeast-1isalibaba-token-plan, #2940); Qwen Cloud's plan has no read here (its console takes a browser sign-in, #5829). The Qwen AI platform's plan (qwen-token-plan,token-plan.maas.qianwenaiapi.com) is read through a sign-in to the platform instead, as the QianWen CLI 1.10.0 reads it (qianwen_plan.go, @imthe99galaxy on X): a device sign-in with PKCE att.qianwenai.com/cli/device/codeand/cli/device/token, the editor's Sign in to the Qwen AI platform (qianwenplan.js, imported when such a provider's editor opens) opening the approval page and polling it; the session is the provider's own, kept by provider id inqianwen-auth.json(0600) and moved or dropped with the provider. From itcli.qianwenai.com/data/v2/api.json(GenerateCLIAccessToken) mints a console token, kept and minted once more when the gateway answersNotLogined; the usage is the sameBroadScopeAspnGatewaycall atcs-data.qianwenai.comwith consoleSiteQIANWENAIand regioncn-beijing, read byaliAskUsageandaliReadWindows. The plan key (sk-sp-) is never sent there. Not signed in, the card says so with Open settings (NeedsAccessKey); a session the platform refuses is signed out.TestQianwenSignIn,TestQianwenPlanQuotas,TestQianwenFollowsProvider,TestQianwenSignInRoutes,qianwen-plan.test.cjs. Built from the CLI's source and the device endpoint's live replies; never signed in with a real account here. The plan key only authorizes inference. The usage is on the console's gateway behind a console token, whichPOST modelstudio.<region>.aliyuncs.com/modelstudio/cli/generateAccessToken(ACS3-HMAC-SHA256,aliACSSign; ActionGenerateCLIAccessToken, version2026-02-10; replycliAccessToken) makes from the AccessKey, as Alibaba's ownblCLI does. The token is kept 20 minutes per AccessKey and region and made again once when the gateway answersBailianGateway.Login.NotLogined. The gateway call isPOST <console>/cli/api.json?action=BroadScopeAspnGateway|IntlBroadScopeAspnGateway&product=sfm_bailian&api=zeldaHttp.apikeyMgr./tokenplan/personal/api/v2/usagewithBearerand a formparams,region; the windows are theper<N><Hour|Day|Week|Month>Percentage(a share used, 0 to 1) andResetTime(ms) fields ofdata.DataV2.data.data, so 5 hours, Weekly and Month show as the plan has them. A RAM user's key getsBailianGateway.Team.NotAuthoriseduntil the main account grants what Alibaba's Token Plan docs ask for RAM users: theAliyunTokenPlanReadOnlyAccessandAliyunBSSReadOnlyAccesssystem policies (theAliyunBailian*andAliyunModelStudio*ones don't cover the Token Plan) and the Administrator or Subscription plan permission on Model Studio's Account Management page; the card names all three (aliRAMHint, #6506), and the GUI says them in the reader's language: under the editor's AccessKey ID and on a card whose error carriesaliRAMHint(ALI_RAMin app.js, whichquotaErrormatches on the hint's opening words). The same API serves the main account and RAM users;blhas no other route. Another refusal shows the console'serrorMsg. Team plans (团队版) use other APIs and have no card. The gateway has no public doc: built from the official client's source; never seen from a real account here, and the international gateway host (bailian-singapore-cs.alibabacloud.com) is the least certain part. - Whether a Codex account spends its credits (
CodexNoCreditsin settings, opt-out, by lower-cased email) is the gateway's routing only. It never changes which account Codex is signed in to:NextLoginmoves off an account at its routing's spent share, 100% at most, credits or not. - Whether a Claude account spends Anthropic's extra usage past its plan (
ClaudeNoExtraUsagein settings, one switch for every Claude account, opt-out: Spend extra usage in the Claude editor's Advanced, ormagpie settings set claudeNoExtraUsage off) is the gateway's routing and the warm-up only; a cap on an account's Usage credits window holds that account the same way once its extra usage reaches it (provider/claude_extra.go). magpie can't turn extra usage off at Anthropic: a Claude Code signed in on its own, not through magpie, still spends it.NextLoginalready moves Claude Code off an account on overages, as the Extra usage row reads 100 (claudeOveragesWindow,usedPast). Claude Code's hidden/limit-resetis not driven: it spends or resets limits through a flow Anthropic hasn't made public, and calling its endpoints would be Claude Code's client imitated. - A Vertex AI provider's credentials are read only when a request is signed (
Sign), so adding, listing and showing one ask Google nothing. With nocredentialsgiven and no file where Application Default Credentials are looked for, the request fails withno Google credentials at <file>, naminggcloud auth application-default loginand the provider's credentials file as the ways to give it some. Acredentialsfile that isn't there fails with the same words, saying to correct it or clear it. When Google refuses a person's sign-in (revoked, or past the organization's session length), the error says how to sign in again for the file used (signInAgain): gcloud's Application Default Credentials withgcloud auth application-default login, adding--impersonate-service-account=<account>when the file impersonates one; a file under gcloud'slegacy_credentials/<account>/withgcloud auth login <account>; any other file by writing it anew or giving the provider another. The new file is read at the next request, with no restart. - Not read for Vertex AI: the metadata server of Compute Engine, Cloud Run and GKE; workload identity federation (
external_account,external_account_authorized_user, refused by name); credentials whoseuniverse_domainisn'tgoogleapis.com; Vertex AI's express-mode API keys (Save refuses a key). No quota project is sent: Vertex AI bills the project in the URL. GOOGLE_APPLICATION_CREDENTIALSandCLOUDSDK_CONFIGare inagentenv.Vars. The desktop app takes them from the login shell when it wasn't started with them (proc.UserPath, macOS and Linux), andtestenvclears both. Vertex AI reads them as set (vertexEnvPath), not throughappdir.Getenv, which takes a relative value as unset: a~/that starts one is the home, and one that still isn't a full path is refused, naming the variable. Passed over, it would have the request signed from gcloud's own file, which may be another account's (a person's, where the variable named a service account's key).- The Vertex AI preset's
HeaderHintsare Google's Priority PayGo and Flex PayGo headers,X-Vertex-AI-LLM-Request-TypeandX-Vertex-AI-LLM-Shared-Request-Type: the editor offers to add them, the values are the user's, and they go asHeadersdo. Priority PayGo couldn't be confirmed: on the project it was tried on, Vertex AI answered withtrafficTypeON_DEMAND. - An account's weight under
weightrouting is kept per account too (AccountWeights, by the account in lower case, 2–1000; one not in it weighs 1, and nothing sets one from the plan), as a key's is (KeyAccount.Weight), so a Max and a Pro account can share requests by how much more one allows (rubbzha on X).SetAccountWeight(GUIprovider/accountweight, the chip beside each account in use in the editor while the routing is By weight;magpie provider account-weight <id> [account [n|default]]) sets it,moveAccountSettingscarries it through a Copilot rename, andwithPicksputs it on the accountsAllgives, so the gateway'skeyWeightreads it with no file read (Provider.AccountWeight). - A usage cap is kept per account (
AccountCaps, 1–99) and, beside it, per window (AccountWindowCaps, by the account and the window'scapId, its name in lower case:WindowCapID). A window's own share wins over the account's; 100 is no cap on that window.CapsOfgives both (WindowCaps),CapHeldandcapReachedjudge each window by its own, andSetWindowCap(GUIprovider/windowcap,magpie provider account-cap <id> <account> --window <name>) sets one;SetWindowCapssets several at once, as the GUI's meter for a family of models (Antigravity's Gemini 3.1 Pro, High and Low) posts its models' windows inwindows. An Antigravity pool's own windows ("Gemini · 7 days") are set aside for routing but capped (WithCapped,capIdthe pool's name and its own, asLineName):allowanceOfhangs each on its members' windows (Limit.pool), andCapHeldandNearCapcount them throughcapLimits, so a cap on one holds that pool's models only (pluviophile714 on Discord,TestPoolWindowCapHeld). A window counted in a unit with its total (QuotaWindow.Amount,Limit,Unit: WorkBuddy's credits, a plan's requests) can instead be capped at a fixed amount of that unit (AccountWindowAmounts, by account andcapId; 9won_25273 on Discord).SetWindowAmount(GUIprovider/windowcapwithamountin place ofcap, the meter's menu's Amount…, typed in place) sets it, 0 lifts it; a window has a share of its own or an amount, never both, and setting one clears the other.limitSharemakes the amount a share of the window's total for marks andNearCap, whileCapHeldandcapReachedhold the account once the count reaches the amount (past);CapHoldand the trace carryAmount,CountandUnit, andcappedErrorsays "has used 300 credits … past its cap of 300". A reading with no total leaves the amount aside and the account's share applies. Every cap reads the vendor's own count of the window, so what the account spent outside magpie (the vendor's app, another machine) counts toward it as the vendor reports it, from the next reading on; magpie can only hold back its own requests (TestWindowAmountCapHeld,TestSetWindowAmount,window-cap.test.cjs). A config without window caps reads as before. A key of a provider whose windows magpie reads (TakesUsageCap) has the same caps, by its key id (GUIprovider/accountcapandwindowcapwith the key's id,magpie provider account-cap), kept whenReplaceKeychanges the key's value;KeyInfo.UsageCapandCapHeldgive its row's pill and held note (TestKeyTakesUsageCap,key-usage-cap.test.cjs). How a pool ends at its caps is kept with the provider (plugins#349):CapStopanswers 429 rather than going on to the fallbacks once every account in use is at its cap, andCapCarefulreads usage again near a cap and holds an account whose usage can't be told (both off by default; within 5 points of its cap an account takes one turn at a time whatever they say, gateway routing;SetCapStop,SetCapCareful, GUIprovider/capstopandprovider/capcareful, ticks under the account list once an account has a cap).UsageReadsays when an account's usage was last read well and whether the last try failed (a failed try keeps the good reading's time), andReadUsageNowreads it again.magpie provider pool <id> [--accounts a,b,…] [--cap percent|off] [--stop on|off] [--careful on|off]shows and sets the whole pool in one command: which accounts are on and in what order, each one's cap, and both settings, and names the accounts in use with no cap. - A wallet's window, one that tells only what is left (
QuotaWindow.Balance, no share and no total: AStudio's 通用积分 and 星火积分, SuperMagic's points), has its spend counted by magpie (wallet_spend.go, #5770, 9won on Discord: an account capped at 4 spent over 1,000 credits past it, since the wallet read 0% used until it was empty). Each reading a plugin's usage gives (pluginLoginQuota→withWalletSpend) is set against the one before: a fall is spent, a rise (a top-up, a daily grant) is not. The count runs over the window's own period when it tells a reset, else the local day, and starts at 0 at the period's first reading; what was spent before it, or between one period's last reading and the next's first, isn't known and isn't counted. Each window carries it asspentandspentSince. On an account with a usage cap (WindowCaps.Holds) the window reads asamountspent oflimit, what the period had (spent plus what is left), andusedthat share, so a cap by share holds it in routing and on the GUI's row as it holds any window; without a cap the window is its balance alone, and routing goes by that (Allowance.Left). A cap set is judged from the next reading on. The counts are kept inwallet-spend.jsonbeside providers.json, by provider, account and window, a period over for a week dropped; one that can't be read starts each count again.holdsBoundsleaves a wallet out of a window's holds (no whole).TestWalletSpendCounted,TestWalletCapHolds,TestPluginWalletCapHolds. - A key's spend cap (
KeySpendCaps, by the key's fingerprint,key_spend.go; sparkling_lemur_62868 on Discord: a team's OpenAI key whose granted credits other services spend from too) is how much magpie may spend on an API key, in USD, per calendar day or month in local time, or in all since it was set (Since, kept while the cap stays one in all, its amount changed or not). What counts is what the Usage page prices magpie's own calls on the key at (usage.KeySpent: records whoseProviderKeyIDis the key, not turned away, not reported by an app; the log is read once and each new call added byAppend, read again after 5 minutes), not the vendor's bill: a model with no known price counts nothing, and requests under way when it is reached still finish, so the key can go a little past it. At or past the cap the gateway passes the key over (gateway routing). Only a key has one:SetKeySpendCaprefuses a subscription, an amount not above 0 or overMaxSpendCap(1,000,000) and a period it doesn't know.ReplaceKeycarries it to the new value. Set from the key's row in the editor (a pill: "$7.50 of $20.00 today", the app's menu, then the amount typed in place, drawn bykeyspend.js, which app.js imports when it draws a key's row; GUIprovider/keyspendcap,key-spend-cap.test.cjs) ormagpie provider spend-cap <id> [key [usd [day|month|total]|off]], which also lists each key's spend.TestKeySpendCapSet,TestSpendCapWindow,TestParseSpendCap,TestKeySpentCountsTheKeysCalls,TestSpendCapCmd. - A key's balance typed by hand (
KeyOwnBalances, by the key's fingerprint:{usd | cny, at, refill, expirings},key_balance_own.go; tenacious_eagle on Discord) is for a key whose vendor tells no balance magpie can read (TakesOwnBalance: an API key with no balance source, not Cline's or OpenCode Zen's, not on a plan's windows). The user types what the vendor's page says is left; the key's card on the Usage page and the tray then shows it less what the Usage page prices magpie's own calls on the key at since then (usage.KeySpentfromat, through theprovider.KeySpenthook usage sets), as≈$12.50withEstimate(set,at,spent) and below nothing as≈$-2.00. Typing it again counts from then. It is an estimate, not a reading: it is kept out of the balance history (no trend or runs-out), is never shared, and routing reads nothing from it; a low-balance alert reads its number. A balance the vendor tells always wins: with a Balance URL or a source magpie knows the card is the vendor's, and a relay whose query is looked for shows the typed one only when none is found (errNoBalance); the typed value stays saved as the user left it.SetKeyOwnBalance(GUIprovider/keyownbalance, a pill in the key's row, "≈$12.50 left" or "Set balance", drawn bykeybalance.jswhiletakesOwnBalanceand no balance was found;magpie provider key-balance <id> [key [usd|¥cny|off] [--refill …]]) refuses a subscription, an amount outside ±MaxOwnBalance(1,000,000) in either currency (below 0 is a key the vendor let run past its balance, so typed as it reads: -1.84, -$1.84; AlanWang1027713 on X), and any currency but USD and CNY; nil takes it off,ReplaceKeycarries it to the new value, and saving the editor keeps it. It may be typed in yuan (cny, "¥100", or a bare number with ¥ CNY picked in the currency button beside the field, which starts at the balance's own currency, else Settings' one; picking keeps the number typed and posts nothing until the field is left or Enter is pressed, so a balance's currency changes without clearing it or going to Settings, tenacious_eagle on Discord): what is spent is counted in USD and turned into yuan atfx.Known(), the rateinternal/fxlast fetched (cached 12h infxrate.json, fetched again in the background, never on the request path);fx.Knownnever hands outfx.Fallback, so with no rate fetched yet and something spent the left is unknown (leftnull, the card'sErrorsays why) rather than a guess. It may refill (refill:{every: month, day: 1–31}, a day past the month's end meaning its last, or{every: week, day: 1 Monday–7 Sunday}, or{every: day, day: 0}, every midnight, Kelen_Yc on X), at midnight in the user's local time: nothing is stored on a refill; the spend is counted from the last refill boundary afterat(From), andNextis the next one. Typing the amount again keeps the refill.SetKeyBalanceRefill(GUIprovider/keybalancerefill, the pill's menu: Refills each month…, Refills each week…, Refills each day, Never refills; CLI--refill monthly[:day]|weekly[:mon…sun]|daily|off); a magpie before daily refills drops adayrefill as one written by hand that isn't one refuses a key with no balance. Part of it may expire, in grants (expirings: a list of{amount, until, at}, up toMaxExpiring(20), each amount in the balance's currency,untilthe last day it counts as 2006-01-02,atwhen it was typed; tenacious_eagle_96548 on Discord: money that stays and promotional credit twice, one good until tomorrow and one the day after). Grants are spent first, as DeepSeek spends its granted balance before the money topped up, and of them the one that ends soonest first (spendGrants): the spend is taken piece by piece over the times betweenFrom, now, and each grant'satand end (midnight afteruntil, local time), each piece going to the live grant that ends first, and only what grants took afterFromis off the rest, so a refill or typing the balance again doesn't count it twice.leftis the whole balance, the grants' remainders included; from a grant's end its remainder counts no more (expired, the latest such end), and unspent credit is simply gone. A grant whose end is at or beforeFromis dropped on the next write (liveGrants).AddKeyExpiring(GUIprovider/keyexpiring{expiring: {amount, until}}),RemoveKeyExpiring({expiring: {at, until}, remove: true}, matched byat, else byuntiland the amount when given; nothing matched is an error) andClearKeyExpiring({expiring: null}) edit them. The pill's menu has Add credit that expires…, which opens one small form (.abal-form, the app's popover, no native control but the date field) with the amount, in the balance's currency, and the last day, a month ahead to begin with: Add or Enter saves, Escape or a click outside leaves it, an amount in the other currency or a day gone by is refused with the form kept; then a Remove {amount} for each grant with when it goes beside it, and No credit that expires with two or more, or one that expired. The CLI takes--expiring amount@yyyy-mm-ddand--expiring-remove [amount@]yyyy-mm-dd, each as often as wanted and applied in order after the balance, every value read before anything is written;--expiring offtakes every grant off. Each refuses a key with no balance typed (type the rest first, 0 when all of it expires), an amount not above 0 or pastMaxOwnBalance, and a date that isn't one. A v0.1.3305 balance's oneexpiringobject is read as the first grant (UnmarshalJSON) and saved asexpiringson the next write; a magpie before this readsexpiringsas no grant, so going back loses them from the estimate, not from the file until it writes. Typing the balance again keeps the grants in the same currency and drops them in the other, where its amount would mean another sum. A balance saved before has none and is counted as it was. The estimate'sexpiring, one per grant soonest first (set,at,until,left,ends), is the pill's "≈$60.00 left · $5.00 expires tomorrow · $20.00 expires in 30 days" (wrapping at a grant on a narrow row), and the card'sBalanceSplita line each withexpires, which the Usage page and the panel label "Expires in 30 days" (expiresInin app.js), amber from a week; the TUI and CLI quota say "$20.00 until Dec 31" (SplitWords). Each key with one getsbalancein/api/providers'keyList(set,at,spent,currency,rate,left,from,refill,next,expiring,expired).TestTypedBalanceExpires,TestTypedBalanceSavedBeforeExpiring,TestTypedBalanceGrantsSoonestFirst,TestTypedBalanceGrantsEdited,TestTypedBalanceOneGrantMigrated,TestExpiringParsed,TestExpiringDayParsed,TestKeyBalanceCmd,key-balance-expiring.test.cjs,TestKnownIsNeverAGuess,TestTypedBalanceInYuan,TestTypedBalanceRefills,TestRefillDays,TestTypedBalanceCountsDown,TestToldBalanceWinsOverTyped,TestOwnBalanceParsed,TestKeyOwnBalanceRoutes,key-own-balance.test.cjs. - A window whose reset time has passed has started again, whatever share it was read at (
resetPassed). That holds for a reading kept from before (AsOf) and for a fresh one: Claude Code's/usagegives a reset to the minute and can lag it, so a run just after a reset can still say 100% with that reset.claudeWindowshands such a window back empty on every path, andusedPast,usedUp,BackAtandcapReachedleave it out when they judge an account spent, for Codex, Claude Code andmagpie quota waitalike. A card can still show a kept reading as it was read (reported, for a Claude card while/usageis unavailable); that changes what it shows, never which account is used. A reset/usagegives as a time alone ("resets 3pm") can be read as its next one, a day on (claudeResetTime), and is then not seen as passed here. - A restart to update can run two magpies for up to the old one's drain
(GUI shell), each
able to refresh a sign-in. A refresh that rotates its refresh token holds
a file lock beside
logins.json, so the second waits and takes the first's tokens instead of spending the used one: Codex'sauth.json(codexMu,.codex.lock) and the ChatGPT API's sign-in (siwcRefreshing,.siwc.lock) since this change; Claude's saved tokens (savedTokenMu), MCP servers' (mcpauth's renew lock) and plugins' were already held so. Google's, Vertex AI's and Copilot's refresh tokens don't rotate. Claude Code run in its own folder (claudeDirRun) is held in this process only; the bridge's turns hold the restart back, so the two don't overlap there.TestCodexRefreshWaitsForAnotherMagpie,TestChatGPTAPIRefreshWaitsForAnotherMagpie. - A switch of Claude Code's sign-in (
switchSavedLogin) and a sign-in that may write it (addLogin) take Claude Code's own refresh locks first (claude_lock.go), as Claude Code 2.1.316 takes them: the directory<config dir>/.oauth_refresh.lock, then<realpath(config dir)>.lock(~/.claude.lock), each made with mkdir, touched while held and taken over once untouched for 60s. Rewriting~/.claude.json'soauthAccount(putClaudeLogin) takes<that file>.lock(10s stale) after them, the order Claude Code saves it in. A switch read during a refresh kept the outgoing account with the refresh token that refresh spent, so it was signed out of magpie on its next use (#4532). A lock held past 20s fails the switch with nothing written (errClaudeLocked). magpie writes no.oauth_refresh.lock.owner, so Claude Code waits out a lock magpie left only by its stale time. Other~/.claude.jsonwriters (the Library's MCP servers) don't take the lock yet (#4747).TestClaudeSwitchWaitsForClaudeCodesRefresh,TestClaudeSwitchStaleAndHeldLocks.
Verification
go test -tags nogui ./internal/provider -run 'GoesThroughItsProxy'
go test -tags nogui ./internal/provider -run 'TestClaudeSwitchTakesTheAccountsProxy|TestClaudeAccountProxy'
go test -tags nogui ./internal/plugin -run TestPluginSignInProxy
node --test internal/gui/tests/signin-proxy.test.cjs internal/gui/tests/signin-close.test.cjs
go test -tags nogui ./internal/provider -run 'TestAccount|TestImport|TestCodex|TestGroup|TestQuota|TestLogin|TestSignIn|TestSeveralKeys|TestKeyProtocol|TestSetKeyWeight|TestReadSub2APIKeyLimits|TestSub2APIKeyLimitsOnItsCard|TestKeyAllowance|TestPlanKeyAllowance|TestPayAsYouGoKeyAskedSeldom|TestClaudeAccountToldRenewed|TestPluginAccountToldRenewed|TestAllowancesReadOnlyWhenAsked|TestAllowancesReadByThemselvesByDefault|TestKeyReadsOnlyWhenAsked|TestAtAddress|TestProviderAtAddress|TestAddressOf'
go test -tags nogui ./internal/provider -run 'TestFoldCopies|TestImportFoldsAKeyAnEntry'
go test -tags nogui ./internal/provider ./internal/gateway ./internal/gui -run 'TestRestKeysIsRestKey|TestKeysOnDropsRepeats|TestServingReadsListsOnce|TestKeyReadsEightAtOnce|TestKeySlots|TestPerKeyReadsListsOnce|TestProviderInfoListsKeysOnce'
node --test internal/gui/tests/provider-many-keys.test.cjs internal/gui/tests/provider-many-keys-proxy.test.cjs
go test -tags nogui ./internal/provider -run 'TestCapHeld|TestCapReached|TestWindowCapHeld|TestSetWindowCap'
go test -tags nogui ./internal/netproxy ./internal/provider ./internal/gateway -run 'TestDispatchHTTP1|OverHTTP1|TestAccountProxy|TestUncheckedTLS|TestInsecureTLS|TestHTTP1|TestH2Record|TestRecordError'
go test -tags nogui ./internal/provider ./internal/gateway ./internal/cli ./internal/gui -run 'TestSocket|TestResponsesProvider|TestProviderSetSocket|TestProviderSaveSocket'
node --test internal/gui/tests/provider-socket.test.cjs
go test -tags nogui ./internal/provider -run 'TestSeat|TestPlanOfASignedInAccountShownOnce|TestGLMPlanMatchesZCodePlugin|TestAccountName'
go test -tags nogui . -run TestAccountsAlias
node --test internal/gui/tests/account-alias.test.cjs
go test -tags nogui . -run TestAccountCapCmd
go test -tags nogui ./internal/provider ./internal/gateway ./internal/cli -run 'TestSetAccountWeight|TestAccountWeight'
node --test internal/gui/tests/account-weight.test.cjs
node --test internal/gui/tests/account-cap.test.cjs internal/gui/tests/window-cap.test.cjs
go test -tags nogui ./internal/provider ./internal/usage ./internal/gateway ./internal/cli -run 'TestKeySpendCap|TestSpendCap|TestParseSpendCap|TestKeySpent'
node --test internal/gui/tests/key-spend-cap.test.cjs
go test -tags nogui ./internal/provider -run 'TestRemoteMagpie'
go test -tags nogui ./internal/provider -run 'TestVolc|TestQianfan|TestBedrock|TestMantleBase|TestAddCopy|TestBackupBalanceToken'
go test -tags nogui ./internal/gui -run TestProviderSaveKeepsVolcengineSecret
go test -tags nogui ./internal/provider -run 'TestTC3|TestTencent|TestAli'
go test -tags nogui ./internal/gui -run TestProviderListTellsTencentAccessKey
go test -tags nogui ./internal/backup ./internal/davsync -run 'TestRoundTrip|TestNoKeys|BalanceToken'
node --test internal/gui/tests/volc-access-key.test.cjs internal/gui/tests/tencent-access-key.test.cjs
go test -tags nogui ./internal/provider -run '^TestProviderProbesUseProtocolHeaders$'
go test -tags nogui ./internal/provider -run '^Test(Partners|CountPartner|NoticePartners)'
go test -tags nogui ./internal/provider -run 'TestGeminiBase|TestCustomGeminiProvider|TestFactoryGeminiUnchanged'
node --test internal/gui/tests/partners.test.cjs site/worker.test.mjs
go test -tags nogui ./internal/provider
go test -tags nogui -run 'Vertex' .
go test -tags nogui ./internal/provider ./internal/agent -run 'TestAccountDiscovery'
node --test internal/gui/tests/account-discovery.test.cjs
go test -tags nogui ./internal/provider ./internal/gateway ./internal/gui -run ExtraBody
go test -tags nogui ./internal/provider ./internal/gateway -run 'TestHeadersTakeTheConversation|TestSentHeaders|TestExtraBodyThread|TestHeadersCarry|TestHeadersDerived|TestThreadIDIsCodexThread|TestHeaderSessionWithoutCRLF'
node --test internal/gui/tests/header-session-hint.test.cjs
go test -tags nogui ./internal/provider ./internal/davsync ./internal/gui -run 'KeepsAccessKey|ProvidersFileWithBOM|AccessKeySecret|PlanCardWithoutAccessKey|KeepsVolcengineSecret'
node --test internal/gui/tests/extra-body.test.cjs
go test -tags nogui ./internal/provider ./internal/gateway ./internal/gui -run ReplyHeaders
node --test internal/gui/tests/reply-headers.test.cjs
The package's tests use a home of their own (testenv). Never point them at
real ~/.codex, ~/.claude, ~/.config/gcloud or ~/.config/magpie files.
Vertex AI's tests send Vertex AI, Google's token endpoint and IAM Credentials
to a server of their own (VertexForTest). Check a change
against real accounts in a sandbox HOME, as Code standards describes.