Files
magpie/docs/subsystems/providers-accounts.md
T
yetone d6fd9b3a36 provider, agent, gui, cli: Codex can switch only its own sign-in between accounts, never through the gateway (#1907, foobra)
foobra wants Codex Desktop and the CLI kept on their own ChatGPT
subscription, moved to the next saved account when the signed-in one is
used up and back when it resets, without magpie's gateway in the way.
magpie already did the switch (codex_switch.go: 98%, 100% In order, back
under 90%, unknown usage never switches), but with more than one Codex
account on it also wrote openai_base_url into config.toml so a refused
request fails over through the gateway (codexFailover). There was no way
to have the first without the second.

Now Codex's subscription has SwitchOnly (providers.json "switchOnly",
opt-in, off by default so nothing changes for anyone who doesn't tick it):
- provider.SetSwitchOnly / provider.SwitchOnly; only Codex's own
  subscription takes it. An unreadable providers.json reads as on, so
  magpie's own failover is never written on a guess.
- agent.codexFailover is false when it is on: no openai_base_url, no
  failover note, no magpie models in Codex's list. A base URL the user
  wrote stays.
- The account Save copy keeps it.
- GUI: "Only switch Codex's sign-in" tick under Providers > Codex's
  accounts (with more than one on), posting provider/switchonly; the
  Agents row's failover title points at it. zh, zh-TW, ja, de.
- CLI: magpie accounts switch-only codex [on|off].
- docs/reference.md and providers-accounts.md say what it does and that
  an open Codex app or app-server stays on its account until reopened.

Run (darwin, sandbox HOME, -tags nogui):
- go test ./internal/provider -run 'TestCodexSwitchOnly|TestCodexSwitchedWhenUsedUp|KeepLogin'
- go test ./internal/agent -run 'TestCodexSwitchOnly|TestCodexFailover|TestCodexOwnModelThroughMagpie|TestCodexHandWritten'
- Broken by hand, each red: codexFailover guard removed (agent test),
  SwitchOnly dropped from the Save copy, SwitchOnly reading false on an
  unreadable file (provider test), the tick drawn unticked (GUI, 16/16).
- GUI: switch-only (new), keep-login, agent-failover, gui-ja, gui-de,
  gui-zh-tw in Chromium and WebKit, en/zh/ja/de at 1100 and 420: 77 pass.
- The built binary's `accounts switch-only` in an empty sandbox HOME:
  reads off, refuses on with no Codex provider, refuses claude.
- gofmt -l clean; darwin go vet.

Reviewed and rerun after rebasing onto eba718736 (darwin, sandbox HOME).
The rebase met #1899's withPicks; SwitchOnly is copied there now.
- gofmt -l clean; go vet -tags nogui on darwin, GOOS=linux and
  GOOS=windows for internal/provider, agent, cli, gui.
- go test -tags nogui -timeout 40m ./internal/provider ./internal/agent
  ./internal/cli ./internal/gui: all ok. (On the base before, provider's
  TestCopilotSecretToolUsername timed out once under load: #1627,
  untouched code, 3 of 3 alone.)
- Broken by hand, each red: the codexFailover guard removed
  (TestCodexSwitchOnlyKeepsCodexOffTheGateway), SwitchOnly dropped from
  the Save copy, from withPicks, and an unreadable providers.json
  reading off (TestCodexSwitchOnlyStillSwitchesTheSignIn).
- GUI: switch-only, keep-login, agent-failover, gui-ja, gui-de, gui-zh-tw
  in Chromium and WebKit at 1100 and 420: 77 of 77 pass.

Rebased again onto 81f587d7b (clean; it touches provider, cli, gui but
not agent): vet on all three OSes again, go test -timeout 40m
./internal/provider ./internal/cli ./internal/gui all ok, -run TestCodex
./internal/agent ok, and the 77 GUI cases above pass again.

Rebased once more onto d45b20757 (clean; no lines of this change touched):
vet on all three OSes, -run 'TestCodex|KeepLogin|SwitchOnly'
./internal/provider ./internal/agent ok, switch-only and agent-failover
in Chromium and WebKit pass.

Not run: not tried with real ChatGPT accounts or the Codex app.
2026-10-13 14:35:08 +08:00

74 KiB
Raw Blame History

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 has no key: it is signed with the user's Google credentials.
  • 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, Affinity, concurrency and queue limits, 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. 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 (…/v1beta added to a bare host, a pasted endpoint or model list cut back), requests go to models/{model}:streamGenerateContent?alt=sse under it (GeminiPath) 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
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
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. 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 the first user message (magpie- and its hash), so it stays the same through one conversation; Test and Detect send magpie-test- and 12 random letters, a new one each time. 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. One object goes to every API; fields for one API alone are not a thing yet. extrabody.go, gateway.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
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). 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). A file without noModels reads as before, and a pick clears it. 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. 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. models.go, provider.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). 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. keys.go
Google Vertex AI google-vertex (VertexPreset, IsVertex) is a provider of the user's own with no key. 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 key given it, 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 Gemini alone (Speaks, Base). It is Ready once that address can be made, never from a key or 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. 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. 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
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 into ~/.codex/auth.json for Codex CLI. A 400 or 401 from the vendor's refresh endpoint means it was refused (refreshFailed). account.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. Signed in anew (upsertLogin with another credential, addSideLogin), refreshed, or served a request (ServedSignIn), 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
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. logins.go, logins_on.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). 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. 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), or with the sign-in's while one asks it. 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's are kept as the file has them. A refresh token magpie holds already is exists, never refreshed; accounts are matched by email and workspace (sameLogin). An entry with an access token and no refresh token is refused (accessOnly). 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
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). 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. codex_switch.go
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). Members are provider/model[:effort]. A group can nest another (group/<id>); SaveGroup refuses loops. Match takes a glob or re: pattern (#766). A found group follows its providers: one switched off or removed leaves it, and one on again is back. 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. A switched-off provider's members stay in it, skipped by membersIn, and the Routing 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 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 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 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. 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. 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). 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). 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. 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 prices (a remote request without a valid key never reaches the list: lanGuard refuses it). 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, asked with X-Magpie-Drawers (DrawersHeader), 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). A remote from before this sends no tiers, and its models are offered none, as before. codexcat.go, codex_models.go, codex_catalog.go, gateway.go, live.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, 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 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). 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: 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). 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. StepFun's Step Plan is read through a sign-in, not the key, and isn't one of them. 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
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 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 Seat), as /v1/magpie/quotas, magpie quota and magpie accounts do. 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 every 6 hours (10 minutes after a failure), keeping the list in partners.json in the cache folder. 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. 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, under Server address, or in the TUI (asked on adding, w after); on the command line 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). local_address.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). 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. 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. detect.go, test.go

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. 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 and the provider editor offer these decisions even when the user's local conversation picks omit them. 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. 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) is such a mixed provider too: its 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). A server with none lists none, and no Jev is made up for it. An oMLX provider saved before the preset had a decision base gets its chat base as one.

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, 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. 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 (Cursor's cursor-agent models, WorkBuddy's config, …), 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 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. TestFetchNewWaitsForASlowSignIn, TestFetchNewAccount and the TUI's TestTUIFetchesSubscriptionModels / TestTUIAsksAgainForAMissingList cover it.

Runtime path

  1. Add. The Providers page adds a key provider through Add or Save, or an account through StartSignIn. An agent signed in on its own is found by Accounts with no step from the user.
  2. Resolve. The gateway calls provider.Resolve or GroupFor with the model name, then plans candidates over the provider's keys or accounts.
  3. Sign. For each try, Sign gives 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, or logins.json for an account standing behind it.
  4. Allowance. Usage endpoints are rate limited, so SubscriptionUsage caches 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, OnRenewed tells 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, claude or plugin:<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 below SpentShareOf its 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 /usage or 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, by renewedNow. A key's reading that finds a window it was full in (at SpentShareOf its routing) full no more, or full till sooner, tells it too, as agent "" and the key's KeyAllowanceID, 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, as StaleKeyAllowance does for a key. Built-in Grok's own per-account cache (grokLoginUsage) doesn't keep such a reading at all: it goes to its caller only, so that next ask reaches xAI.

A provider's fetched model list keeps the upstream ids and order. 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).

Constraints and failure behavior

  • Each refresh token has exactly one holder. Vendors rotate tokens on refresh, so two copies of one token would sign each other out. savedTokenMu stops 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. AskClaudeUsage and a Claude card's RefreshUsage advance 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 prevents LoginUsage from keeping the older reading and leaves SubscriptionUsage due to read again. Each claudeWindows entry 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: RefreshUsage for that account, so cardRefresh.wants it and the read is asked). The real Claude Code runs /usage with CLAUDE_CONFIG_DIR set to the account's claudeSavedDir (readSavedClaudeUsage, through the gateway's claudeUsage), so magpie never calls Anthropic with the token itself and the account Claude Code is signed in to is not switched. The Usage page opened, magpie quota and magpie accounts ask every card and so start no saved account's Claude Code: they keep its last reading, or errClaudeSaved before 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). So inSavedClaudeDir holds claudeDirRun(user) for reading while it runs, which switchSavedLogin takes for writing first, and after the run syncSavedClaude copies a rotated sign-in back into logins.json under savedTokenMu and loginsMu. A saved account's warm-up runs the same way. claude_usage_saved_test.go covers the refresh, the other accounts left alone, the floor, background reads, a switch waiting for the run and the rotated sign-in kept; TestClaudeUsageRunsInSavedAccountDirectory checks the directory the command runs in.
  • Claude Code's /usage prints a reset with no year when it falls this year ("Oct 9, 2:59pm (UTC)"), or, in older versions, as a time alone ("3pm"). claudeResetTime reads 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) and claudeResetSlack: 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): mona on github.com, mona@acme.ghe.com on an enterprise's GHE.com. That name is its logins.json user, its row in every list, its usage card and its per-account routing settings, and it is what SwitchLogin, SetLoginOn and ForgetLogin take, 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 in providers.json (proxy, models, cap, concurrency) from the bare login to the new name before the new name is written to logins.json (renameSettled): a setting the new name has already stays, and while providers.json can't be read or written the account stays saved under its old name, its settings with it. magpie accounts switch|forget copilot takes 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's Account.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).
  • Every request to the ChatGPT backend (CodexBase's host) goes over HTTP/1.1, as Codex itself speaks to it: each transport netproxy.Dispatch makes (http.DefaultClient's, the gateway's) sends a request netproxy.HTTP1 names through an HTTP/1.1 copy of itself whose TLS hello offers no h2, and the provider package sets HTTP1 to codexBackend (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.
  • 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.json or hosts.json first, 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.
  • An unreadable providers.json is an error, never an empty list. Saving over an empty list would lose every provider.
  • When logins.json cannot be decoded as saved accounts, reads keep the accounts read before. Before saving a change, lastgood.Keep (lastgood.go) keeps the file there now: as logins.json.bak, its last good generation, when it reads, or copied aside as logins.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.json and plugin-auth.json at their full length, every byte zero (#1505): the rename reached the disk before the data. Every write of magpie's own state goes through steady.WriteFile (or edit.WriteAtomic), which flushes the temp file before renaming it in, and the plugin host's writeDurable does the same. 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.json and mcp-signins.json. caller-keys.json is 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's recovered, which the window tells once (recoveredOnce). The .bak lags one write behind on purpose: a crash zeroes the latest write, so a copy made with it could be zeroed too. With no good .bak the file is unknown, never empty: a sign-out leaves plugin-auth.json or mcp-signins.json as it is (magpie's own returns the error), and a sign-in added copies the file aside before it writes.
  • The gateway and a magpie run from a terminal change the same files (#1674). loginsMu is a filelock.Mutex: besides the mutex it holds an OS lock on logins.json.lock (flock, LockFileEx on Windows), and taking it has logins.json read 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. savedTokenMu holds logins.json.renew.lock the same way, so two magpies never spend one refresh token. caller-keys.json (access) and mcp-signins.json (mcpauth, with mcp-signins.json.renew.lock around a renewal) are changed under such locks too; plugin-auth.json already was, under plugin-auth.json.lock, which host.js takes too. A lock another magpie holds is waited for up to filelock.Wait (10s), then gone on without, as before there was one. rememberLogins writes nothing when only Seen would move on and the saved one is less than seenEvery (10 minutes) old, so a run that only lists accounts (magpie ls, providers, sessions, usage) leaves logins.json as it is. logins_lock_test.go covers 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 (SetLoginOn off, #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 (compactOn in 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 provider removed or switched off takes its models out of the catalog. Agent wiring's Reseat moves agents off them.
  • A preset marked NoList uses its preset model list instead of requesting /models, and ignores previously fetched lists, including their protocol and key restrictions, unless the user sets ModelsURL or chooses a region marked Lists. 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 → 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/models returns a general Ark catalog instead of the plan's model ids, while Agent's /api/plan/v3/models returns 404. presets.go defines these choices; List, fetch, live, planModels, PlanEmbeddings, PlanDrawers and PlanVideos in models.go apply them when adding, refreshing and reading cached models. TestVolcengineModelLists checks 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 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 it always did. The list keeps an account by its stable id — logins.json's id, 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.
  • 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 0 with no reset_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 on ark.<region>.volces.com) is kept with its keys and never sent to the GUI: /api/providers tells 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), and clearAccessKey drops 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 (KeepSecrets in Restore, Mirror, davsync's take) 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. A providers.json saved with a UTF-8 BOM is read through it, not taken for a broken file whose .bak stands in. The plan read is the endpoint's: /api/coding asks GetCodingPlanUsage, /api/plan asks GetAFPUsage, 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[] with Level, Percent, ResetTimestamp in seconds) is the one three tools built on it read; GetAFPUsage's buckets are read in each form those tools read (Used of Quota or Total, or Percent; ResetTime or ResetTimestamp), 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 (AccessKeyVendor tells the editor whose: accessKey.vendor, the preset's accessKeyVendor). Only the Token Plan 企业版's endpoints are read with them (TakesTencentAccessKey: /plan on tokenhub.tencentmaas.com, region ap-guangzhou, or tokenhub-intl.tencentmaas.com, ap-singapore); the personal plan (api.lkeap.cloud.tencent.com) has no usage API and TokenHub's pay as you go no plan, so neither has a card. The preset lists its regions that take one (accessKeyRegions, presetAccessKey), and the editor shows SecretId and SecretKey at those alone. DescribeTokenPlanList gives the account's team plans (a sub-user sees the ones it made); each is asked DescribeTokenPlan for its PackageInfo and TokenSummary, the list's kept for what the reply leaves out. The card's one window is TotalUsed of CycleQuota (else TotalQuota), resetting at TokenSummary.CycleEndTime, else counted in months from StartTime and never past ExpireTime. A plan not enable says its status beside the plan's name. Errors come back as 200 with Response.Error; an AuthFailure… or UnauthorizedOperation one 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.
  • Whether a Codex account spends its credits (CodexNoCredits in settings, opt-out, by lower-cased email) is the gateway's routing only. It never changes which account Codex is signed in to: NextLogin moves off an account at its routing's spent share, 100% at most, credits or not.
  • 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 no credentials given and no file where Application Default Credentials are looked for, the request fails with no Google credentials at <file>, naming gcloud auth application-default login and the provider's credentials file as the ways to give it some. A credentials file 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 with gcloud auth application-default login, adding --impersonate-service-account=<account> when the file impersonates one; a file under gcloud's legacy_credentials/<account>/ with gcloud 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 whose universe_domain isn't googleapis.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_CREDENTIALS and CLOUDSDK_CONFIG are in agentenv.Vars. The desktop app takes them from the login shell when it wasn't started with them (proc.UserPath, macOS and Linux), and testenv clears both. Vertex AI reads them as set (vertexEnvPath), not through appdir.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 HeaderHints are Google's Priority PayGo and Flex PayGo headers, X-Vertex-AI-LLM-Request-Type and X-Vertex-AI-LLM-Shared-Request-Type: the editor offers to add them, the values are the user's, and they go as Headers do. Priority PayGo couldn't be confirmed: on the project it was tried on, Vertex AI answered with trafficType ON_DEMAND.
  • A usage cap is kept per account (AccountCaps, 1–99) and, beside it, per window (AccountWindowCaps, by the account and the window's capId, its name in lower case: WindowCapID). A window's own share wins over the account's; 100 is no cap on that window. CapsOf gives both (WindowCaps), CapHeld and capReached judge each window by its own, and SetWindowCap (GUI provider/windowcap, magpie provider account-cap <id> <account> --window <name>) sets one. A config without window caps reads as before.
  • 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 /usage gives a reset to the minute and can lag it, so a run just after a reset can still say 100% with that reset. claudeWindows hands such a window back empty on every path, and usedPast, usedUp, BackAt and capReached leave it out when they judge an account spent, for Codex, Claude Code and magpie quota wait alike. A card can still show a kept reading as it was read (reported, for a Claude card while /usage is unavailable); that changes what it shows, never which account is used. A reset /usage gives 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.

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 'TestCapHeld|TestCapReached|TestWindowCapHeld|TestSetWindowCap'
go test -tags nogui ./internal/netproxy ./internal/provider ./internal/gateway -run 'TestDispatchHTTP1|OverHTTP1|TestAccountProxy'
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
node --test internal/gui/tests/account-cap.test.cjs internal/gui/tests/window-cap.test.cjs
go test -tags nogui ./internal/provider -run 'TestRemoteMagpie'
go test -tags nogui ./internal/provider -run 'TestVolc|TestQianfan|TestBedrock|TestAddCopy|TestBackupBalanceToken'
go test -tags nogui ./internal/gui -run TestProviderSaveKeepsVolcengineSecret
go test -tags nogui ./internal/provider -run 'TestTC3|TestTencent'
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/davsync ./internal/gui -run 'KeepsAccessKey|ProvidersFileWithBOM|AccessKeySecret|PlanCardWithoutAccessKey|KeepsVolcengineSecret'
node --test internal/gui/tests/extra-body.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.