Skip to content

Every agent's model. One place. Codex on DeepSeek, Claude Code on Kimi, from the menu bar.

149 KB
Raw Blame

Providers and accounts

The gateway can send a request to three kinds of upstream:

  • A provider in providers.json: an endpoint with one or more API keys. Google Vertex AI's has no key: it is signed with the user's Google credentials.
  • A subscription account: an agent's own sign-in (Codex, Claude Code, Copilot and others) that magpie reads from the agent's store, or an account signed in from magpie.
  • A plugin's account: a subscription served by an OpenCode plugin.

Package internal/provider holds all three, the routing groups built over them, and what is left of each one's allowance.

Plugin ownership of the deprecated built-in subscriptions is in Provider and plugin ownership. How the gateway orders keys and accounts per request is in Gateway routing and fallback.

Responsibilities and sources of truth

Part Responsibility Source
Provider Provider holds the endpoint bases for each Protocol (Chat, Responses, Anthropic, Gemini), the keys, Fallback, Routing, Sink, Affinity, concurrency and queue limits, Headers, Proxy, models, and balance settings. BaseAPI is the API a custom provider's editor shows its Base URL as: the one the user picked and saved, while it has a URL, so a provider with a chat URL beside its Responses one isn't shown as OpenAI compatible after Responses was picked. Requests go by which URLs are set. A custom provider's Gemini URL is the base of Google's Gemini API, or of one that answers as it does (#1346): GeminiBase keeps it as the base (…/v1beta added to a bare host, a pasted endpoint or model list cut back), requests go to models/{model}:streamGenerateContent?alt=sse under it (GeminiPath) signed with x-goog-api-key (AuthHeaders), and its models are listed by catalog.FetchGemini (paged, only those serving generateContent). Factory's sign-in alone keeps its own /generate route and token (FactoryGemini). Account is set only for a subscription and is never saved (json:"-"). provider.go
Anthropic key header A provider of the user's own on a third-party Anthropic API is sent its key as both x-api-key and Authorization: Bearer (AuthHeaders); Anthropic's own API, Bedrock, Azure, Vertex and every subscription account have their own and never this choice (BothAuth is false). Some services refuse the two together with a 401 (Aloha on Discord: "鉴权 header, x-api-key 和 Authorization 不可以同时存在"), so Provider.AuthHeader (authHeader: empty for both, x-api-key or bearer; anything else is read as empty) sends one alone, picked in the editor's Key header row (shown while bothAuth is true, or a custom provider's Anthropic URL is a third party's). Left at both, a 401 whose body catalog.BothAuthRefused tells as that refusal (it names both headers and says they can't be together, in Chinese or English) is asked once more with x-api-key alone, then Bearer alone (RetryOneAuth, in the gateway's forwardOnce and the provider test's probe; catalog.fetchOne for the model list through listAuth); the first not answered 401 or 403 is kept with LearnAuthHeader, which never changes a pick the user made. A request carrying the user's own Authorization or x-api-key header is never retried. authheader.go, test.go, catalog/authheader.go, catalog/live.go
GLM Coding Plan key at pay as you go Zhipu's and Z.ai's presets offer Pay as you go first (/api/paas/v4) and the Coding Plan (/api/coding/paas/v4, Responses at /api/v1); both share /api/anthropic, which bills the plan, so a plan's key left at Pay as you go worked in Claude Code and was refused 429 code 1113 "余额不足或无可用资源包" in Codex (@cleverpigo on X). Nothing in the key tells the two apart, so a Chat request to open.bigmodel.cn or api.z.ai at /api/paas/v4 refused 1113 is asked once more at /api/coding/paas/v4 (RetryZhipuCoding, in the gateway's forwardOnce and the provider test's probe). Served there, LearnZhipuCoding moves a saved provider with that one key, still at that URL, to the plan's OpenAI URL (and the preset's plan Responses URL when it has none); one with other keys stays and is asked again each time. Refused there too, the 1113 body keeps its code and gets both URLs and what to change in its message (ZhipuNoBalanceHint). A pay-as-you-go key with a balance is never answered 1113 and never sent to the plan's endpoint. zhipu_coding.go, test.go
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 the first user message (magpie- and its hash), so it stays the same through one conversation; Test and Detect send magpie-test- and 12 random letters, a new one each time. ${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. 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; 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} and ${threadId} 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
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
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). 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 (waitsForPicks), not the vendor's list. KeepPluginsListed asks again after relistSoon (5 minutes) when a list left a pick out. TestPluginPicksComeBackWithTheirList, TestEveryPickDelistedServesNone 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). autolist.go, models.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). 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. keys.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; 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 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, and 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. The provider's test asks Gemini alone, since a partner model answers only after the project turns it on in Model Garden. Each partner model has its own test (TestModel, TestVertexPartnerModels), 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, the usage card's codexUntil, 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) nor removed (forgetLogin): each error names the folder and the CODEX_HOME=… codex command. 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. 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
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). A plugin's browser sign-in (auto) whose page names a port on this machine to come back to takes its pasted address too: magpie opens it there on 127.0.0.1, for the plugin's own listener (pluginCallback, loopbackPorts); Command Code's page posts its key from script, so it offers the API key way instead. A Claude account is signed in by Claude Code itself. Signing in brings back an account removed from magpie (ShowAccount). A sign-in started in magpie (StartSignIn, StartPluginSignIn) reads as done (SignInStatus, WaitSignIn) only after finish has run ShowAccount for its account, so the window, which opens the account as soon as it sees done, finds it listed. If providers.json can't be written then, the account stays hidden and the sign-in still ends done. Signing in to a plugin's provider from the command line (pluginLogin, with a key or the browser) brings it back too. It also takes off the mark a sign-in its vendor turned away left on the account (Lapsed) and shows again the agent's own account removed in magpie (clearPluginLapse). The window's plugin sign-in does the same with the browser (pluginDone, then finish) or with a key (PluginAPIKey); a key and the command line share these steps in PluginSignedIn. A sign-in leaves through the proxy the account's own requests will use (#1663): ProxyOfLogin (the account's, else the subscription's, else the global one) for the account being signed in again, the subscription's for a new one. Every request of the flow goes through signInFlow.via, Claude Code's own login gets it as *_PROXY (netproxy.EnvWith), and a plugin's sign-in runs its fetch under that proxy (via in host.js; plugins_cli.go for the command line). The window's sign-in box shows it as a "Proxy: …" link (signInProxyLink, the app menu, no userinfo shown) with Global, Direct, the subscription's and each account's proxy, or a typed one; picking one starts the sign-in again through it (SignInOptions.Proxy), and when it ends the pick is kept as the account's (keepSignInProxy: the subscription's own when it is its only account, else the account's entry). Global isn't offered while the subscription has a proxy and other accounts, since nothing could keep it. The browser's own leg goes through the browser's network, not magpie's. Signing out leaves through the same exit: a ChatGPT account's refresh token is revoked through its own proxy, read before the account is forgotten (forgetSIWCLogin), and Devin's CLI, asked who is signed in or for its models, runs with the account's proxy (devinCommand, devinProxy). 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. A refresh token magpie holds already is exists, never refreshed; accounts are matched by email and workspace, or for Claude organization (sameLogin). An entry with an access token and no refresh token is refused (accessOnly). One file of several that holds no account is a failed row with its place (ImportedAccount.File), never skipped. The files are only read. login_import.go, google_import.go, factory_key.go, accounts_cli.go
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. Not in the tray panel (it reads no provider list), 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). 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 by leftAlone on the raw Off, go on. codex_switch.go
Claude Code's proxy Claude Code on its own subscription asks Anthropic itself, through the proxy its env names. While any Claude account has a proxy of its own (AccountProxies), the env of Claude Code's settings.json names the proxy of the account it is signed in to (#1807): HTTPS_PROXY and HTTP_PROXY set to that account's own, else the subscription's Proxy (ProxyOfLogin), and NO_PROXY to loopback; none for direct or a SOCKS proxy, which Claude Code can't use. It is written on every switch (switchLogin, the user's or SwitchWhenSpent), when the Claude subscription is saved, and at the gateway's look every loginSwitchEvery (a sign-in made in Claude Code itself). Claude Code reads its env at start, so only sessions started after the switch take it. A proxy key the user set (in either case) is theirs: magpie then writes none and takes out none of theirs. What magpie wrote is kept in claude-proxy-env.json, and a key is magpie's only while it holds that value. A settings.json that doesn't parse is left as it is. Its log lines name the proxy through netproxy.Redact, without its user and password (#1886); the env gets it whole. claude_proxy_env.go
Routing groups User-made groups from the Routing view, and auto-found groups of the same model across providers (derived, never stored). 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 page, magpie groups rename, the TUI) moves every agent field on group/<old> to group/<new>, spelled as the agent spells it, through the same renameRefs a provider's rename uses, then SyncCatalog; before, the agents stayed on a group magpie no longer had (lucis0116 on X, TestRenameGroupMovesTheAgentsOnIt). A provider's or group's display name needs no move: store and SaveGroup drop the catalog, and SyncCatalog writes the new labels into every agent's list. Match takes a glob or re: pattern (#766), both matched in any case (compilePattern; (?-i) inside a re: makes case matter). A 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. A switched-off provider's members stay in it, skipped by membersIn, and the Routing page says them as switched off (memberJSON.providerOff). The user's own groups keep their members. Three templates make a group in one click from the models the user has (provider.Templates, AddTemplate; the Routing page's cards before a first group and its Templates menu after, magpie group template [kind] [name]): smart sends a hard turn to the strongest model and an easy one or a compaction to a cheap one, asked by a classifier (the decision API when there is one, else the cheapest priced model that doesn't reason); thrifty starts on two cheap models of different providers and sends high reasoning to the strongest; steady fails over between the strongest model of up to three providers. A model is weighed by its maker's list price when known, else what its provider charges, else by its id's size words (sizeOf); one over tooDear (USD 100 a million output tokens) is never picked. A template that can't be made says what is missing (Need). It is saved under a name and id no group has (freeGroupName, shared with CopyGroup), never over one. A group is shared as text (ShareGroup, a group row's Copy to share): JSON marked "magpie": "routing-group" with a format version (ShareVersion), holding the group's members as it names them, patterns, routing, rules, classifier and settings. A group holds only provider/model ids, never a key, account or address, and the derived matches, found/hidden/off flags and the rules that hold by a folder (a path on the sharer's machine, Rule.Folders) stay behind; a pasted one is left out too. ImportGroup (the Routing page's Import, POST /api/groups/import) reads it with words or a code fence around it, refuses another text, a newer format or none (ShareError, said in the reader's language). A member whose provider the importer has is kept; else the same model (AutoGroupOf) under the first provider of theirs that serves it (Instead); else it is left out and named (Missing), with the rules that send to it, its place among the off and fast members, and a classifier gone takes the intent rules and auto effort with it. Nothing is added when no member is left; what is added gets a free name, never replacing a group. A group of patterns only that match nothing now (a plugin's models not listed) has no members: /api/groups says them, and an unmakeable template's, as [], never null; the Routing page reads the response through groupsFrom and draws a group it still can't draw as one row saying so, so one bad group never hides the rest (#1585). group.go, grouptemplate.go, group_share.go
Allowance Quotas asks every vendor at once: subscription windows (SubscriptionUsage), key-bought plans (PlanQuotas) and key balances (KeyBalances). The Usage page, magpie quota --json and GET /v1/magpie/quotas read it, 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 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). 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 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 only the key's own card shows. 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 as before when that is none. 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
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 membership's $0 catalog models.dev lists every model of Kimi Code's plans (kimi-code-plan-global, kimi-code-plan-cn) and of Xiaomi MiMo's Token Plans (xiaomi-token-plan-cn, -sgp, -ams) at $0: what the membership charges per token, not what the model costs. membershipCatalogs are never read for a price (priceCatalogs, makerPriceCatalogs), so a Xiaomi MiMo model is priced at xiaomi's list price at every region, and each region of the preset names its own catalog, pay as you go xiaomi alone (#1873). A Kimi Code provider's model is priced at the Kimi API model it is (kimiCodeAPI, from Kimi Code's docs: k3 and k3-256k are kimi-k3, kimi-for-coding-highspeed is kimi-k2.7-code-highspeed), and kimi-for-coding (K2.8 Preview, not on the API) is unpriced rather than free (#1370). The alias is Kimi Code's alone (kimiCodePlans): a relay's own k3 keeps its own price. A catalog other than these that lists a model at $0 still prices it at $0: models.dev has truly free models (nvidia, modelscope). The Requests list names the API model it was priced as (PricedNameFor). models.go
A 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: 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. Ollama Cloud's ollama.com/api/balance (#1888, readOllamaPlan) tells the plan's included allowance as one window in USD, Month when its period is a month long, renewing at period.until, and Aside while credits bought on top are left; those credits are the key's balance card (readOllamaCredits), and a reply that names none has no balance card rather than $0. StepFun's Step Plan is read through a 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
Account names and seats AccountNames (by the account, in lower case, like AccountCaps) are names the user gives accounts, set by SetAccountName (GUI provider/accountname, magpie accounts alias); they live in providers.json only, never in a vendor's or plugin's sign-in. A GLM Coding Plan read with a key (glmPlan) and a ZCode account (built-in or zcode-plugin) whose windows' resets agree are one seat (seatMatch, #90/#953), shown once, on the account's card (seatCards, used by quotas, Allotted and CachedCards). A match is remembered in seats.json beside quotas.json: a failed read or a window with no reset yet is unknown and keeps the key's card off while the account is signed in; windows that disagree forget it (#1515). Cards carry Seat (the key provider's name, and the key's when it has several) and Alias (the user's name, else Seat), as /v1/magpie/quotas, magpie quota and magpie accounts do. 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. 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). 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. 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. 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). Only remote decision entries use entryFor to apply user model names and limits; other decision providers retain their previous entry formatting. The editor's providerInfo in providers.go sends deciders: [] when the remote has none, suppressing the UI's legacy name-based guessing. The editor offers one remote address; its System One endpoint is derived from that address and has no separate input. Unnamed decisions use their model ids for display names and provider labels. Refresh replaces the list: removed decisions stop routing, and an empty remote list never gains a fabricated Jev alias. An older peer without the decision-list extension continues serving its other APIs but must be updated before its decisions can be discovered. See decide.go.

oMLX (#1641) 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). 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.

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. 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). The real Claude Code runs /usage with CLAUDE_CONFIG_DIR set to the account's claudeSavedDir (readSavedClaudeUsage, through the gateway's claudeUsage), so magpie never calls Anthropic with the token itself and the account Claude Code is signed in to is not switched. The Usage page opened, magpie quota and magpie accounts ask every card and so start no saved account's Claude Code: they keep its last reading, or errClaudeSaved before one. Background reads keep the last reading, and the 30-second per-account floor holds for repeated refreshes. Claude Code may refresh the account's token in that directory while it runs (its own lock file keeps two Claude Codes in one directory from refreshing at once). So inSavedClaudeDir holds claudeDirRun(user) for reading while it runs, which switchSavedLogin takes for writing first, and after the run syncSavedClaude copies a rotated sign-in back into logins.json under savedTokenMu and loginsMu. A saved account's warm-up runs the same way. claude_usage_saved_test.go covers the refresh, the other accounts left alone, the floor, background reads, a switch waiting for the run and the rotated sign-in kept; TestClaudeUsageRunsInSavedAccountDirectory checks the directory the command runs in.
  • Claude Code's /usage prints a reset with no year when it falls this year ("Oct 9, 2:59pm (UTC)"), or, in older versions, as a time alone ("3pm"). claudeResetTime reads it as the end of its window, so never further ahead than the window's length (5 hours for the session, 7 days for a week) and claudeResetSlack: a date is in the first of last year, this year and next that is less than a day past and no further ahead, a time alone the next one no further ahead. Where none is, as for a reading days old, it is the latest one already past, so the window reads as renewed rather than full for a year. Where the clocks go back and show a time twice, the reading not yet past is taken. A week's time alone read just after its reset still reads as tomorrow's.
  • A Copilot account is known by its GitHub login and host (CopilotAccountName, #1220): mona on github.com, [email protected] 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): [email protected] · Team · ws-two. The account Codex is signed in to goes by the name it is saved under (codexLiveName) everywhere: its provider's Account.User (codexAccount), liveLogin, and its session identity (SessionIdentities). Its allowance, rests and sticks (restKey), cap, proxy, model list, a gateway key's account list (LoginID) and the Routing page all go by that name, so two seats of one email are never read as one (#1424).
  • Every request to the ChatGPT backend (CodexBase's host) goes over HTTP/1.1, as Codex itself speaks to it: each transport netproxy.Dispatch makes (http.DefaultClient's, the gateway's) sends a request netproxy.HTTP1 names through an HTTP/1.1 copy of itself whose TLS hello offers no h2, and the provider package sets HTTP1 to codexBackend (codex_http1.go). That covers the gateway's turns, the models list, the warm-up, the allowance, its resets and spending one, through the proxy in force, an account's own included. Every other vendor is still offered HTTP/2.
  • 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. magpie opens a socket per turn and sends the whole body, where Codex's own client sends a delta after previous_response_id on a kept socket. 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, so this leg still sends the whole body. 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 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), 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) are asked of the plugin host all at once and aren't held back per provider.
  • 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. 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.
  • 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 → Images; Ark itself refuses video generation on Small and Medium Agent Plans, which include it only in the Large and Max tiers. Models magpie does not yet serve (Agent Plan's speech models) are not advertised. Ark's pay-as-you-go region still fetches its own list. Coding's /api/coding/v3/models returns a general Ark catalog instead of the plan's model ids, while Agent's /api/plan/v3/models returns 404. presets.go defines these choices; List, fetch, live, planModels, PlanEmbeddings, PlanDrawers and PlanVideos in models.go apply them when adding, refreshing and reading cached models. TestVolcengineModelLists checks that the plans make no list requests, ignore old cached lists and return their own preset models; pay-as-you-go and an explicit list URL still make requests.
  • A gateway key held to some accounts (#905) is held to those of the providers its list names: a provider it names no account of, the key uses as 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 sub2api key's windows are fixed: each starts at the key's first request after it was empty, aligned to the relay's day, and a window not started yet says used 0 with no reset_at, so it is taken to renew a span from now. They count this key's spend only, not the relay's accounts behind it. ForgetBalances (a key or Balance URL changed) has every key's windows read again at its next ask, a read begun before dropped; until then the last reading stands, fresher than the card's, which routing's reads never write. A key changed is another key (keyID), with windows of its own.
  • A Volcengine Ark provider's access key (TakesVolcAccessKey: any of its bases on ark.<region>.volces.com) is kept with its keys and never sent to the GUI: /api/providers tells the editor its ID and whether a Secret is saved (accessKey). A save that leaves the Secret blank keeps it, one that leaves the ID out or sends it blank keeps both (an editor opened before the key was given sends "", #1821), and clearAccessKey drops both. The ID and Secret go together everywhere the keys go: a copy takes them, also when its form sends the source's ID without the Secret (AddCopy), a backup or sync without keys has neither (withoutKeys), and a restore, mirror or sync keeps this machine's (KeepSecrets in Restore, Mirror, davsync's take) when it came without keys, or with the same key and no access key at all, as a magpie before v0.1.1142 or one the access key was never given on sends it (#1821); another key is another account and brings its own. A copy without keys keeps this machine's secret headers (SecretHeader) the same way. A plan endpoint with no provider on it holding the access key is a card that says which to give (accessKeyCard, needsAccessKey), with a button to the provider's settings, not a card left out. A providers.json saved with a UTF-8 BOM is read through it, not taken for a broken file whose .bak stands in. The plan read is the endpoint's: /api/coding asks GetCodingPlanUsage, /api/plan asks GetAFPUsage, pay-as-you-go (/api/v3) has no card; the region is the host's. One card is read for each access key and plan. GetCodingPlanUsage's reply (QuotaUsage[] with Level, Percent, ResetTimestamp in seconds) is the one three tools built on it read; GetAFPUsage's buckets are read in each form those tools read (Used of Quota or Total, or Percent; ResetTime or ResetTimestamp), none of them seen from a real account here. A reply none of that reads says so on the card with the reply's head. Changing the access key drops the cached cards (ForgetPlanQuotas).
  • A Tencent Cloud provider's SecretId and SecretKey are kept, listed and saved the same way, in the same fields (AccessKeyVendor tells the editor whose: accessKey.vendor, the preset's accessKeyVendor). Only the Token Plan 企业版's endpoints are read with them (TakesTencentAccessKey: /plan on tokenhub.tencentmaas.com, region ap-guangzhou, or tokenhub-intl.tencentmaas.com, ap-singapore); the personal plan (api.lkeap.cloud.tencent.com) has no usage API and TokenHub's pay as you go no plan, so neither has a card. The preset lists its regions that take one (accessKeyRegions, presetAccessKey), and the editor shows SecretId and SecretKey at those alone. DescribeTokenPlanList gives the account's team plans (a sub-user sees the ones it made); each is asked DescribeTokenPlan for its PackageInfo and TokenSummary, the list's kept for what the reply leaves out. The card's one window is TotalUsed of CycleQuota (else TotalQuota), resetting at TokenSummary.CycleEndTime, else counted in months from StartTime and never past ExpireTime. A plan not enable says its status beside the plan's name. Errors come back as 200 with Response.Error; an AuthFailure… or UnauthorizedOperation one says to check the key. Built from the API docs (api/1823/132270 and siblings) and the signing doc's worked example; never seen from a real account here.
  • Whether a Codex account spends its credits (CodexNoCredits in settings, opt-out, by lower-cased email) is the gateway's routing only. It never changes which account Codex is signed in to: NextLogin moves off an account at its routing's spent share, 100% at most, credits or not.
  • A Vertex AI provider's credentials are read only when a request is signed (Sign), so adding, listing and showing one ask Google nothing. With no credentials given and no file where Application Default Credentials are looked for, the request fails with no Google credentials at <file>, naming gcloud auth application-default login and the provider's credentials file as the ways to give it some. A credentials file that isn't there fails with the same words, saying to correct it or clear it. When Google refuses a person's sign-in (revoked, or past the organization's session length), the error says how to sign in again for the file used (signInAgain): gcloud's Application Default Credentials with gcloud auth application-default login, adding --impersonate-service-account=<account> when the file impersonates one; a file under gcloud's legacy_credentials/<account>/ with gcloud auth login <account>; any other file by writing it anew or giving the provider another. The new file is read at the next request, with no restart.
  • Not read for Vertex AI: the metadata server of Compute Engine, Cloud Run and GKE; workload identity federation (external_account, external_account_authorized_user, refused by name); credentials whose universe_domain isn't googleapis.com; Vertex AI's express-mode API keys (Save refuses a key). No quota project is sent: Vertex AI bills the project in the URL.
  • GOOGLE_APPLICATION_CREDENTIALS and CLOUDSDK_CONFIG are in agentenv.Vars. The desktop app takes them from the login shell when it wasn't started with them (proc.UserPath, macOS and Linux), and testenv clears both. Vertex AI reads them as set (vertexEnvPath), not through appdir.Getenv, which takes a relative value as unset: a ~/ that starts one is the home, and one that still isn't a full path is refused, naming the variable. Passed over, it would have the request signed from gcloud's own file, which may be another account's (a person's, where the variable named a service account's key).
  • The Vertex AI preset's HeaderHints are Google's Priority PayGo and Flex PayGo headers, X-Vertex-AI-LLM-Request-Type and X-Vertex-AI-LLM-Shared-Request-Type: the editor offers to add them, the values are the user's, and they go as Headers do. Priority PayGo couldn't be confirmed: on the project it was tried on, Vertex AI answered with trafficType ON_DEMAND.
  • A usage cap is kept per account (AccountCaps, 1–99) and, beside it, per window (AccountWindowCaps, by the account and the window's capId, its name in lower case: WindowCapID). A window's own share wins over the account's; 100 is no cap on that window. CapsOf gives both (WindowCaps), CapHeld and capReached judge each window by its own, and SetWindowCap (GUI provider/windowcap, magpie provider account-cap <id> <account> --window <name>) sets one. A config without window caps reads as before. 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; 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 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.

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'
go test -tags nogui ./internal/provider -run 'TestSeat|TestPlanOfASignedInAccountShownOnce|TestGLMPlanMatchesZCodePlugin|TestAccountName'
go test -tags nogui . -run TestAccountsAlias
node --test internal/gui/tests/account-alias.test.cjs
go test -tags nogui . -run TestAccountCapCmd
node --test internal/gui/tests/account-cap.test.cjs internal/gui/tests/window-cap.test.cjs
go test -tags nogui ./internal/provider -run 'TestRemoteMagpie'
go test -tags nogui ./internal/provider -run 'TestVolc|TestQianfan|TestBedrock|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.