Files
magpie/docs/subsystems/providers-accounts.md
T
yetone fdd38154b8 docs: the Usage, Video generation and sign-in links to their settings
gui-shell.md, gateway-routing.md and providers-accounts.md name the
links 22c665d6f, cedacf1ae and 3b550a99c added: the Usage page's
Allowances head to Settings › Allowances, Video generation's how-to
to the Providers page, and a sign-in kept to its link to Privacy's
Sign-in pages row. Library's limit tag (8607a7a02) has no passage in
library.md to change.

Docs only; nothing run.
2026-11-10 00:02:22 +08:00

227 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, UseFirst (Smart puts it ahead of the other providers it weighs it with, gateway routing), 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; 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 (…/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
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)
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
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. 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.
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. 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. 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). 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
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 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 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, 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
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. Guarded by TestSignInAlertClaudeSignedOut, TestSignInAlertClaudeEnding, TestDueSignInsandTestSignInAlertOpensItsProvider`.
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. 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). 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
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. Claude Code itself is never signed in to it: addLogin, switchLogin, putClaudeLogin, SetKeepLoginAs, NextLogin and signInToFirst pass it over, and the window shows Remove and magpie only in place of Use and Make first. Not tried with a real token. claude_setup_token.go, claude_subscription.go (inClaudeDir), providers.go
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 failing over (#1385) 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. 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. 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). 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 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). 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. 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). 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. magpie_via.go, live.go, gateway.go, remote_magpie.go, remote_self.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. 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
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). 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. 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, account.go, codex_models.go, claude.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. 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). 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 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

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.

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

  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.

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).

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.

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). 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. Allowances snapshots usedCache.generation under its lock, and forgetAllowance advances 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. 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), 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's r ask usage/quotas?asked=1&all=1 (AskEveryClaudeUsage), and so does the gateway's POST /v1/magpie/quotas/refresh with 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 waits remoteRefreshWait, 25s, for the refresh, not the 8s of a kept-cards read), which marks its generation in claudeEveryAsked, and for claudeEveryFor (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 /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 or the Allowances tab opened, magpie quota and magpie accounts ask every card without all 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. 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 to claudeRunWait, 90s, then errClaudeRunning with the sign-in left as it was): before, magpie accounts switch didn'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 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, 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, RenewLogins runs that /usage once 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 and syncSavedClaude keeps it. The run goes through the account's reading as a card refresh's does (keepingAlive has claudeWindows run it, past the 30-second floor; loginReading keeps it beside the account and on disk, keepCardRead on its card when the Usage page has one), so under switch-only it is the reading a saved account gets. The run marks Renewed, refreshed or not. A refusal is kept as a request's is (NoteClaudeSignInFailure, or the emptied sign-in syncClaudeDir reads), so the account's row says to sign in again. A renewal that fails, of either agent, waits keepAliveRetry (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 refresh tries it at once (TestRenewLoginsKeepsSavedClaudeSignedIn, TestRenewLoginsKeepsClaudeReading, TestRenewLoginsFailedWaitsItsTurn). 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). One ChatGPT sign-in reaches every workspace of its login with one refresh token, and the Codex app's workspace switch rewrites only account_id in auth.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 (codexWorkspacesApart in liveCodex and applyLogins). 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 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, 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).
  • 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 (codexSocket in codex_socket.go, first in the gateway's upstreamTransport, 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, before response.completed, while the WebSocket runs to the end (brickhao on Discord). The handshake carries the turn's headers with OpenAI-Beta: responses_websockets=2026-02-06, without x-codex-turn-state and the responses-lite header, which go in the message's client_metadata as Codex puts them; the message is the body with "type":"response.create" ahead of it (a zstd body is decoded first). codex.rate_limits and codex.response.metadata, read ahead of the reply, are also told as the x-codex-* and x-codex-turn-state headers the HTTP route carries; responsesapi.websocket_timing is dropped. An error frame 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 after previous_response_id, as Codex's own client sends it (codexKept in codex_socket_keep.go; codex-rs get_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-id or thread-id, else prompt_cache_key) and ended response.completed with an id, keyed by the host, a digest of Authorization and chatgpt-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 but input, client_metadata and stream_options is as the last turn sent it, and its input begins with the last turn's input and then that turn's response.output_item.done items, 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 an error frame first, such as previous_response_not_found or 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 after previous_response_id; magpie gives each turn the whole conversation before it goes on, and this leg cuts its own delta for the kept socket. 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); Save refuses it on any other, and one written into providers.json by hand is ignored. Provider.Via then adds netproxy.WithUncheckedTLS with the hosts of its own base URLs (UncheckedHosts: Chat, Responses, Anthropic, Gemini, Decide), so every request made on its behalf through a Dispatch transport (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, and netproxy.With drops the leave for a request made for another provider. An https:// proxy would be dialled with the same TLS config, so its certificate would go unchecked too: such a request is refused (ErrUncheckedOverHTTPSProxy); an http:// or socks5:// proxy is taken. Backup, export and sync carry the field with the provider; an import link doesn't.
  • 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 is https://; 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 as InsecureTLS (TakesInsecureTLS), and Save refuses it on any other. Provider.Via adds netproxy.WithHTTP1 with the hosts of its own base URLs, so a request made on its behalf to one of those hosts goes through the Dispatch transport's HTTP/1.1 copy (route.h1); another host, and a request made for another provider (netproxy.With drops 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, an http(s):// Responses address and not Vertex (TakesSocket); the CLI refuses it on any other. Provider.Via puts the provider's Responses host and path in the request's context (withSocket), and codexSocket speaks the socket only to a POST to that host at <Responses>/responses (SocketTurn); a provider without Socket hides 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-Key and Api-Key too), and a server-sent-events reply. auto speaks HTTP to a host for 10 minutes once it refused the handshake; on tries 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 (restAfterMarked in 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.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.
  • A keychain read that may have shown the user a dialog is not asked again for ten minutes after it was refused (keychainDeniedTTL in account.go): Copilot's token read backs a denial off (copilotCLISecret), and the Cursor token (cursorKeychainToken) and Claude Code's item (readClaudeKeychainItem, through claudeCredential'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.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. So does every write of an agent's own sign-in (#2239): codexToken's rotated tokens into Codex's auth.json (~/.codex, or $CODEX_HOME when set; its keychain item instead when Codex keeps the sign-in there) and writeClaudeCredential's .credentials.json go through writePrivate, never a truncating os.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.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.
  • 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.KeepUnparsed with lastgood.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 are stash.json, applied.json, wsl.json and Codex's magpie-models.json (agent, whose hand-added model keys codexcat.Keep can't hold when the file doesn't parse), sessions-wsl.json and gateway-sessions-hidden.json (sessions), stepfun-auth.json, login-returns.json, quota-history.json, balance-history.json and credits-daily.json (provider), claude-desktop.tiers.json, plugin-updates.json, usage-computer.json and sync-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 (readCheckins in workbuddy_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 is failed with 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. TestCheckinUnreadableFileLeftAlone covers 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). 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 subscription switched off (Off) or whose account was removed from magpie (Hidden) is left alone in the background (leftAlone in left_alone.go; Riko on Discord, whose Claude switched off still ran claude auth status --json every minute). No CLI is asked who is signed in (claudeIdentity, cliIdentity.get for Cursor and Devin): what it said last, in memory or cli-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 (checkinNow with soon false; 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. TestLeftAloneRunsNoCLI runs those paths with fake claude, cursor-agent and devin CLIs 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, pluginsOff in plugins.go): host.js runs 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, and magpie sync) goes through RefreshLists, 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).
  • Warm up now, the last row of Settings › Usage's Codex and Claude Code warm-up tabs (renderWarmNow in app.js, POST /api/warm-now), sends one account the request the scheduled warm-up sends, whatever the warm-up settings say (warm_now.go): warmCodexLogin for a ChatGPT account, then StaleAllowance; for a Claude account Claude Code's own run, warmClaudeLogin over the gateway's warmClaude (WarmClaudeVia), in the saved account's directory, then claudeWarmedNow, 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. TestWarmNowSendsTheScheduledWarmUp checks the body and headers equal the scheduled warm-up's; warm-now.test.cjs covers 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 it Absent in codex-warmup.json and sends it nothing, and usageRead doesn't count it as due (windowAbsent, shorterRunning in codex_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.
  • An Antigravity subscription offers the union of its On accounts' models (antigravityPoolModels in antigravity_pool.go), each account's own list kept beside it (accountModels, read by Account.Lists for 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 asks fetchAvailableModels anyway: 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. Each fetchAvailableModels names 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 for tierRefusedFor (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 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 → 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/models returns a general Ark catalog instead of the plan's model ids, while Agent's /api/plan/v3/models returns 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 /models and 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/embeddings or /v1/rerank alone by PlanRetrieval(kind) (TestVoyagePreset, TestVoyageModelsStayOnTheirRoutes). presets.go defines these choices; List, fetch, live, planModels, PlanEmbeddings, PlanRerankers, PlanRetrieval, 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 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, and Fetch/List return ErrListOff. 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 (takesListOff in /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 name listOff keeps it. The CLI takes list=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 where access.Authenticate makes the request's Identity, 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'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 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 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). Since 10-22 Tencent serves 个人版 and 企业版 in China at the same /plan endpoints with the same sk-tp- keys (product/1823/130060, 130659), so they are one region, plan (a key saved on enterprise is 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 host api.lkeap.cloud.tencent.com/plan/... is moved to TokenHub's at load (movedEndpoints, moveEndpoints in normalize), 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: Bearer on chat and Responses (ysm119). 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.
  • An account's weight under weight routing 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 (GUI provider/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, moveAccountSettings carries it through a Copilot rename, and withPicks puts it on the accounts All gives, so the gateway's keyWeight reads 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'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; SetWindowCaps sets 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 in windows. An Antigravity pool's own windows ("Gemini · 7 days") are set aside for routing but capped (WithCapped, capId the pool's name and its own, as LineName): allowanceOf hangs each on its members' windows (Limit.pool), and CapHeld and NearCap count them through capLimits, 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 and capId; 9won_25273 on Discord). SetWindowAmount (GUI provider/windowcap with amount in place of cap, 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. limitShare makes the amount a share of the window's total for marks and NearCap, while CapHeld and capReached hold the account once the count reaches the amount (past); CapHold and the trace carry Amount, Count and Unit, and cappedError says "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. How a pool ends at its caps is kept with the provider (plugins#349): CapStop answers 429 rather than going on to the fallbacks once every account in use is at its cap, and CapCareful reads 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, GUI provider/capstop and provider/capcareful, ticks under the account list once an account has a cap). UsageRead says when an account's usage was last read well and whether the last try failed (a failed try keeps the good reading's time), and ReadUsageNow reads 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 as spent and spentSince. On an account with a usage cap (WindowCaps.Holds) the window reads as amount spent of limit, what the period had (spent plus what is left), and used that 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 in wallet-spend.json beside providers.json, by provider, account and window, a period over for a week dropped; one that can't be read starts each count again. holdsBounds leaves 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 whose ProviderKeyID is the key, not turned away, not reported by an app; the log is read once and each new call added by Append, 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: SetKeySpendCap refuses a subscription, an amount not above 0 or over MaxSpendCap (1,000,000) and a period it doesn't know. ReplaceKey carries 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 by keyspend.js, which app.js imports when it draws a key's row; GUI provider/keyspendcap, key-spend-cap.test.cjs) or magpie 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.KeySpent from at, through the provider.KeySpent hook usage sets), as ≈$12.50 with Estimate (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 (GUI provider/keyownbalance, a pill in the key's row, "≈$12.50 left" or "Set balance", drawn by keybalance.js while takesOwnBalance and no balance was found; magpie provider key-balance <id> [key [usd|¥cny|off] [--refill …]]) refuses a subscription, an amount outside 0 to MaxOwnBalance (1,000,000) in either currency, and any currency but USD and CNY; nil takes it off, ReplaceKey carries 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 at fx.Known(), the rate internal/fx last fetched (cached 12h in fxrate.json, fetched again in the background, never on the request path); fx.Known never hands out fx.Fallback, so with no rate fetched yet and something spent the left is unknown (left null, the card's Error says 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}), at midnight in the user's local time: nothing is stored on a refill; the spend is counted from the last refill boundary after at (From), and Next is the next one. Typing the amount again keeps the refill. SetKeyBalanceRefill (GUI provider/keybalancerefill, the pill's menu: Refills each month…, Refills each week…, Never refills; CLI --refill monthly[:day]|weekly[:mon…sun]|off) refuses a key with no balance. Part of it may expire, in grants (expirings: a list of {amount, until, at}, up to MaxExpiring (20), each amount in the balance's currency, until the last day it counts as 2006-01-02, at when 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 between From, now, and each grant's at and end (midnight after until, local time), each piece going to the live grant that ends first, and only what grants took after From is off the rest, so a refill or typing the balance again doesn't count it twice. left is 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 before From is dropped on the next write (liveGrants). AddKeyExpiring (GUI provider/keyexpiring {expiring: {amount, until}}), RemoveKeyExpiring ({expiring: {at, until}, remove: true}, matched by at, else by until and the amount when given; nothing matched is an error) and ClearKeyExpiring ({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-dd and --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 off takes 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 past MaxOwnBalance, and a date that isn't one. A v0.1.3305 balance's one expiring object is read as the first grant (UnmarshalJSON) and saved as expirings on the next write; a magpie before this reads expirings as 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's expiring, 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's BalanceSplit a line each with expires, which the Usage page and the panel label "Expires in 30 days" (expiresIn in app.js), amber from a week; the TUI and CLI quota say "$20.00 until Dec 31" (SplitWords). Each key with one gets balance in /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 /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.
  • 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's auth.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's oauthAccount (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.json writers (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'
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.