diff --git a/docs/subsystems/providers-accounts.md b/docs/subsystems/providers-accounts.md index 9b61fb5ba..34122c6a7 100644 --- a/docs/subsystems/providers-accounts.md +++ b/docs/subsystems/providers-accounts.md @@ -67,7 +67,7 @@ keys and accounts per request is in [Gateway routing and fallback](gateway-routi | Used-up switch | When the account Codex or Claude Code is signed in to has used its allowance, the agent is signed in to the next account that is on and has room (#208). Claude Code whose requests go to magpie's gateway (`ClaudeThroughMagpie`: its settings' `ANTHROPIC_BASE_URL` is the gateway, either sign-in) is not moved: the gateway already sends its requests to an account with room, and moving the sign-in only took away what the user signed it in for, such as claude.ai connectors (oreoft on Discord set it back more than ten times; `TestClaudeRoutedThroughMagpieKeepsItsSignIn`). Not routed, or with *Only switch Claude Code's sign-in*, it still moves. Codex's sign-in goes back to the account it moved off once that has room again, as the gateway's Smart and In order give it requests again; routed Until used up it doesn't, as the gateway keeps the requests on the next (`routes.Drain`), so it stays with them till that one is used up too, as Claude Code's and a switch-only Codex's do unless routed In order (`returnsToFirst`; WalterAIBuilder on X: Codex signed back in to the first showed that one in use while the second's week was spent, `TestCodexDrainSignInStaysOnTheNext`). When every one is past its line too, it goes to the one with the most room left (`roomLeft`: the fullest stopping window's distance below the switch share, or the account's own cap when lower), when that has more than the account it is on by `roomMargin` (1 point), so two all but even accounts don't trade it each look; else it stays (StringKe in #4532, after cswap's `best`; `TestNextLoginTakesTheMostRoomWhenAllArePast`). A Claude account on overages (/usage's "You are currently using your overages…" line) is read with its windows and a spent *Extra usage* row of text (`claudeOveragesWindow`: Used 100, ending when the last used-up window renews, else at the next reading), so it is moved off as a used-up one; before, the line made the reading an error, and the switch, which stays on an account it can't read, left Claude Code billing overages (StringKe, #4532; `TestClaudeSwitchOffOverages`). The GUI says the row *In use* in the reader's language. Under the accounts of a Claude Code or Codex with more than one, the switch is a switch of its own, *Switch {agent}'s account automatically* (the `auto-switch` box in app.js; off is `KeepLogin`, posted to `provider/keeplogin`; before 11-11 a *Keep {agent} signed in to* tick that turned it off, which a user read as the switch gone). On, a line under it says what the switch does with that agent's sign-in (`SignInMovesOf`, `signInMoves` on its `/api/providers` row, `signInMovesLine`): left where the user put it while Claude Code's requests go through the gateway (`gateway`), else the share it moves at and whether it comes back to the first (`moves`), each decided as `NextLogin` decides it (`TestSignInMovesSaysWhatSwitchDoes`). Off, it names the account the agent stays on, with a pick of another (`keepLoginAs`). Switch-only always moves the sign-in, so the switch is held on there (sign-in-moves.test.cjs). Beside the switch, an ⓘ mark whose hover card (settingshints.js, the box a `.hint-row` with its `.hint` lines out of sight) says how the switch works and why it is the agent's own use of the account: the sign-in written where the agent keeps its own, as `/login` or `codex login` does; usage read by Claude Code's own `/usage` or where Codex's `/status` reads it; for Claude Code, every request still sent by Claude Code itself straight to Anthropic; and that sharing an account is against the vendor's terms. It promises nothing about bans (autoswitchtip.js, loaded when the switch is drawn). Only where the sign-in moves: `moves`, or `kept` without `routed`, which `SignInMovesOf` sets when Claude Code goes through the gateway, so turning the switch on would move its requests, not its sign-in. Routing (`Allowances`) skips Text rows, so the gateway's own choice of account doesn't count it. A model's own week (`Current week (Sonnet only)`, `(Fable)`) counts for that model in routing, not for the switch, which moves the sign-in only on windows that count every model (`usedPast`); "Sonnet only" is read as the Sonnet week, `7 days · Sonnet` counting `sonnet`, the window the `seven_day_sonnet` header keeps (#4532, `TestClaudeUsageSonnetOnly`). `magpie accounts switch next` (`NextInOrder`) takes the other accounts the agent can be signed in to (`switchable`, not lapsed), on or off in magpie as the accounts list's *Use* does, so one the agent signed itself in to, which starts off, is in the rotation (StringKe, #4532; `TestNextTakesAccountsThatAreOff`), from the one after the account the agent is on, wrapping round: the first with room, else the one with the most room left, said to be past its line; with no reading of any, it refuses rather than guess (`TestNextInOrder`). For Codex, *Only switch Codex's sign-in* (`SwitchOnly`, `SetSwitchOnly`) keeps magpie's `openai_base_url` failover out of Codex's config, so the switch is all magpie does (#1907); an unreadable providers.json reads as switch-only, so the failover is not written on a guess. For Claude, the same setting keeps the accounts to Claude Code (`Provider.KeptToAgent`): `On()` is false, so the gateway, catalog and groups serve nothing on them, while switching and usage, gated by `leftAlone` on the raw `Off`, go on. No request of a saved Claude account passes magpie then, so one Claude Code wasn't signed in to since has no reading: once the account Claude Code is on is spent, `NextLogin` reads such a spare (`readSpare`, `spareRead` in `claudeWindows`) by Claude Code's own `/usage` in the account's directory, in order and only till one has room; a spare read once is not read again, and one whose read failed waits `claudeUsageWait` (cn_Vincentzyx on X, `TestClaudeSwitchOnlyReadsUnreadSpares`). Codex's spares are read through their saved tokens and had no such gap. Claude Code on its own login is out long before a five-minute look notices (#4443: 4% left to refused in two minutes): while Claude has an account to move to, `KeepOnAnAccountWithRoom` looks at its sign-in every `claudeLookEvery` (a minute) between its full looks when `claudeLookDue`, that is when the account Claude Code is on is near out (`claudeNearOut`, `codexNearShare`; its `/usage` is then due after `claudeNearOutWait` rather than `claudeUsageWait`), or when Claude Code wrote a `rate_limit` refusal ("You've hit your … limit") into one of its sessions since that account's last `/usage` (`scanClaudeLimits`, which reads only what was appended to each `projects/*/*.jsonl` since the last scan). The refusal names no account, so it only makes the `/usage` read due (and the reading stale, `StaleAllowance`); the read decides (`TestClaudeNearOutIsReadEveryMinute`, `TestClaudeRefusalInSessionReadsAtOnce`, `TestKeepOnAnAccountWithRoomLooksAtClaudeNearOut`). | [`codex_switch.go`](../../internal/provider/codex_switch.go) | | Removing the signed-in account | `ForgetLogin` signs Codex or Claude Code in to another of its accounts first (`nextOnForget`: the first other that is on, else one whose sign-in holds, else any, never a setup-token account or one Codex keeps in another folder: `switchable`), then forgets this one; a switch that fails removes nothing (StringKe, #4532: Claude's was refused while Codex's switched). Codex's only account is signed out as `codex logout` does. Claude Code is never signed out: its last account it can be signed in to is refused with `SignedInError{Only}` (GUI code `signed_in_only`, and that account has no *Remove*). Claude Code's own credential is never deleted; the forgotten account's folder (`forgetClaudeDir`) is its own. `TestForgetLiveClaudeSwitchesFirst`, `TestForgetOnlyClaudeIsKept`, `codex-signout.test.cjs`. | | Claude Code's proxy | Claude Code on its own subscription asks Anthropic itself, through the proxy its env names. While any Claude account has a proxy of its own (`AccountProxies`), the `env` of Claude Code's `settings.json` names the proxy of the account it is signed in to (#1807): `HTTPS_PROXY` and `HTTP_PROXY` set to that account's own, else the subscription's `Proxy` (`ProxyOfLogin`), and `NO_PROXY` to loopback; none for `direct` or a SOCKS proxy, which Claude Code can't use. It is written on every switch (`switchLogin`, the user's or `SwitchWhenSpent`), when the Claude subscription is saved, and at the gateway's look every `loginSwitchEvery` (a sign-in made in Claude Code itself). Claude Code reads its env at start, so only sessions started after the switch take it. A proxy key the user set (in either case) is theirs: magpie then writes none and takes out none of theirs. What magpie wrote is kept in `claude-proxy-env.json`, and a key is magpie's only while it holds that value. A `settings.json` that doesn't parse is left as it is. Its log lines name the proxy through `netproxy.Redact`, without its user and password (#1886); the env gets it whole. | [`claude_proxy_env.go`](../../internal/provider/claude_proxy_env.go) | -| Routing groups | User-made groups from the Routing view, and auto-found groups of the same model across providers (derived, never stored). The same model is the same id as vendors agree on it (`sameModel`): lowercase, without a vendor's prefix, a version's dot as `-`, a run of spaces, `_` and `-` as one `-` (a relay listing its display name as the id, `GPT-6 Sol`, joins `gpt-6-sol`, Chill on Discord: `TestSameModelDisplayNameAsID`), and without a YYYYMMDD or Ark YYMMDD snapshot date. The found groups also merge a model a plugin offers at a context window of its own, after an `@` (`mergeName`, `windowless`: Cursor's `claude-haiku-5-5@1m` and `claude-opus-5-5@300k`, grok's `grok-4.7@500k` and `grok-4.7@131072`), into its model's group, listed by the model's id: the same model at the same price per token, and a group's members differ in window by provider anyway (Will on Discord: `claude-haiku-5-5@1m` ticked in Cursor stayed out of `auto/claude-haiku-5-5`). A provider is one member: its unsized model when it lists one, else the first size it lists; the editor's Same as shows the windowless name (`MergeName`). A Vertex `@20260801` is a snapshot date, and any other `@` stays (`TestAutoGroupsJoinAModelAtItsWindow`). Every word still counts (`gpt-6`, `gpt-6-mini` and `gpt-6-sol` stay apart), as do a `:variant`, a four-digit release and OpenAI's dashed date (`gpt-4o-2024-08-06`, a pinned snapshot whose group id agents may already name). A provider kept "Only through routing groups" joins them the same way. Members are `provider/model[:effort]`. A group can nest another (`group/`); `SaveGroup` refuses loops. A group given another id (`agent.RenameGroup`: the Routing groups page, `magpie groups rename`, the TUI) moves every agent field on `group/` to `group/`, spelled as the agent spells it, through the same `renameRefs` a provider's rename uses, then `SyncCatalog`; before, the agents stayed on a group magpie no longer had (lucis0116 on X, `TestRenameGroupMovesTheAgentsOnIt`). A provider's or group's display name needs no move: `store` and `SaveGroup` drop the catalog, and `SyncCatalog` writes the new labels into every agent's list. `Match` takes a glob or `re:` pattern (#766), both matched in any case (`compilePattern`; `(?-i)` inside a `re:` makes case matter). A `free:` before one (`FreePrefix`, `compileRule`, #5903) keeps, of the models the rest matches, those whose catalog entry says `free` (`Entry.Free`, the vendor's or plugin's flag as last read): `free:workbuddy/*`. A $0 price (`PricedFree`), a rate, an account's name or an id with free in it never counts, and the GUI's hint says the flag is no promise of no charge. A provider's `AutoInclude` takes no `free:` (`isIDPattern`). What a pattern matches follows the members named, in the catalog's order, until the user drags it elsewhere (usrname1833 on Discord): `Placed` keeps the whole order, named and matched alike, and the group is read and routed in it (`placedIn`); a model matched since goes last, one no longer matched drops out, a save that sends the named members only leaves the matched where they were (`placedOver`), and a provider's or group's rename carries it (`TestGroupPatternMembersKeepTheirPlace`, `group-member-drag.test.cjs`; a member is dragged by its number or its row's logo and room around its words, `group-member-row-drag.test.cjs`). A found group follows the providers magpie has: one removed leaves it, while one switched off stays in it (`foundGroups`, `heldOffEntries`; one without a key, such as a plugin not signed in, finds no group), skipped by `membersIn`, left off a found group's card, logos and TUI line with a count of those switched off (XYenon on Discord: `routing-provider-off.test.cjs`, `TestFoundGroupLineLeavesASwitchedOffProviderOut`) and said as switched off in its editor and the TUI's group page, so switching one of two providers off for a while doesn't take the group away from the agents, rules and groups set to it; it is back in its place once on again (#2671: `TestFoundGroupStaysWithAProviderOff`, `TestFoundGroupWithAProviderOff`, `TestReseatKeepsAFoundGroupWithAProviderOff`, `TestFoundGroupMemberOfASwitchedOffProvider`). A found group the user changed (an `auto-…` id stored) is read without the members of providers magpie no longer has (`withoutRemoved`, not written back, so a provider back under its id is back in it), except a manual group's pick, a rule's model, or all of them when none would be left. It keeps following its model as a found group does (Kxsg79bEYFP4 on X: a third provider with the model, a plugin's, had stayed out of a group the user had changed): `SaveGroup` stores, for an `auto-…` id, what it had seen (`Group.Seen`: the models magpie found in it by that save, and those the user named, as `provider/model`), and a provider that serves the model since joins it as it is read, after the user's own members (`joined`, not written back), unless kept out of found groups. A model seen and not a member is one the user took out, and stays out; a provider's rename or a fold carries `Seen` (`mapModelRefs`), and a shared group leaves it behind. A found group changed before `Seen` was kept takes in nothing, as nothing says which of its models the user took out; its next save sees what is found then (`TestChangedFoundGroupTakesInANewProvider`, `TestChangedFoundGroupFromBeforeKeepsItsMembers`, `TestChangedFoundGroupTakesInAPluginProvider`). A switched-off provider's members stay in it, skipped by `membersIn`, and the Routing groups page says them as switched off (`memberJSON.providerOff`). The user's own groups keep their members. Three templates make a group in one click from the models the user has (`provider.Templates`, `AddTemplate`; the Routing groups page's cards before a first group and its Templates menu after, `magpie group template [kind] [name]`): `smart` sends a hard turn to the strongest model and an easy one or a compaction to a cheap one, asked by a classifier (the decision API when there is one, else the cheapest priced model that doesn't reason); `thrifty` starts on two cheap models of different providers and sends high reasoning to the strongest; `steady` fails over between the strongest model of up to three providers. A model is weighed by its maker's list price when known, else what its provider charges, else by its id's size words (`sizeOf`); one over `tooDear` (USD 100 a million output tokens) is never picked. A template that can't be made says what is missing (`Need`). It is saved under a name and id no group has (`freeGroupName`, shared with `CopyGroup`), never over one. A group is shared as text (`ShareGroup`, a group row's Copy to share): JSON marked `"magpie": "routing-group"` with a format `version` (`ShareVersion`), holding the group's members as it names them, patterns, routing, rules, classifier and settings. A group holds only `provider/model` ids, never a key, account or address, and the derived matches, found/hidden/off flags and the rules that hold by a folder (a path on the sharer's machine, `Rule.Folders`) stay behind; a pasted one is left out too. `ImportGroup` (the Routing groups page's Import, `POST /api/groups/import`) reads it with words or a code fence around it, refuses another text, a newer format or none (`ShareError`, said in the reader's language). A member whose provider the importer has is kept; else the same model (`AutoGroupOf`) under the first provider of theirs that serves it (`Instead`); else it is left out and named (`Missing`), with the rules that send to it, its place among the off and fast members, and a classifier gone takes the intent rules and auto effort with it. Nothing is added when no member is left; what is added gets a free name, never replacing a group. A group of patterns only that match nothing now (a plugin's models not listed) has no members: `/api/groups` says them, and an unmakeable template's, as `[]`, never `null`; the Routing groups page reads the response through `groupsFrom` and draws a group it still can't draw as one row saying so, so one bad group never hides the rest (#1585). | [`group.go`](../../internal/provider/group.go), [`grouptemplate.go`](../../internal/provider/grouptemplate.go), [`group_share.go`](../../internal/provider/group_share.go) | +| Routing groups | User-made groups from the Routing view, and auto-found groups of the same model across providers (derived, never stored). The same model is the same id as vendors agree on it (`sameModel`): lowercase, without a vendor's prefix, a version's dot as `-`, a run of spaces, `_` and `-` as one `-` (a relay listing its display name as the id, `GPT-6 Sol`, joins `gpt-6-sol`, Chill on Discord: `TestSameModelDisplayNameAsID`), and without a YYYYMMDD or Ark YYMMDD snapshot date. The found groups also merge a model a plugin offers at a context window of its own, after an `@` (`mergeName`, `windowless`: Cursor's `claude-haiku-5-5@1m` and `claude-opus-5-5@300k`, grok's `grok-4.7@500k` and `grok-4.7@131072`), into its model's group, listed by the model's id: the same model at the same price per token, and a group's members differ in window by provider anyway (Will on Discord: `claude-haiku-5-5@1m` ticked in Cursor stayed out of `auto/claude-haiku-5-5`). A provider is one member: its unsized model when it lists one, else the first size it lists; the editor's Same as shows the windowless name (`MergeName`). A Vertex `@20260801` is a snapshot date, and any other `@` stays (`TestAutoGroupsJoinAModelAtItsWindow`). Every word still counts (`gpt-6`, `gpt-6-mini` and `gpt-6-sol` stay apart), as do a `:variant`, a four-digit release and OpenAI's dashed date (`gpt-4o-2024-08-06`, a pinned snapshot whose group id agents may already name). A provider kept "Only through routing groups" joins them the same way. Members are `provider/model[:effort]`. A group can nest another (`group/`); `SaveGroup` refuses loops. A group given another id (`agent.RenameGroup`: the Routing groups page, `magpie groups rename`, the TUI) moves every agent field on `group/` to `group/`, spelled as the agent spells it, through the same `renameRefs` a provider's rename uses, then `SyncCatalog`; before, the agents stayed on a group magpie no longer had (lucis0116 on X, `TestRenameGroupMovesTheAgentsOnIt`). A provider's or group's display name needs no move: `store` and `SaveGroup` drop the catalog, and `SyncCatalog` writes the new labels into every agent's list. `Match` takes a glob or `re:` pattern (#766), both matched in any case (`compilePattern`; `(?-i)` inside a `re:` makes case matter). A `free:` before one (`FreePrefix`, `compileRule`, #5903) keeps, of the models the rest matches, those whose catalog entry says `free` (`Entry.Free`, the vendor's or plugin's flag as last read): `free:workbuddy/*`. A $0 price (`PricedFree`), a rate, an account's name or an id with free in it never counts, and the GUI's hint says the flag is no promise of no charge. A provider's `AutoInclude` takes no `free:` (`isIDPattern`). What a pattern matches follows the members named, in the catalog's order, until the user drags it elsewhere (usrname1833 on Discord): `Placed` keeps the whole order, named and matched alike, and the group is read and routed in it (`placedIn`); a model matched since goes last, one no longer matched drops out, a save that sends the named members only leaves the matched where they were (`placedOver`), and a provider's or group's rename carries it (`TestGroupPatternMembersKeepTheirPlace`, `group-member-drag.test.cjs`; a member is dragged by its number or its row's logo and room around its words, `group-member-row-drag.test.cjs`). A found group follows the providers magpie has: one removed leaves it, while one switched off stays in it (`foundGroups`, `heldOffEntries`; one without a key, such as a plugin not signed in, finds no group), skipped by `membersIn`, left off a found group's card, logos and TUI line with a count of those switched off (XYenon on Discord: `routing-provider-off.test.cjs`, `TestFoundGroupLineLeavesASwitchedOffProviderOut`) and said as switched off in its editor and the TUI's group page, so switching one of two providers off for a while doesn't take the group away from the agents, rules and groups set to it; it is back in its place once on again (#2671: `TestFoundGroupStaysWithAProviderOff`, `TestFoundGroupWithAProviderOff`, `TestReseatKeepsAFoundGroupWithAProviderOff`, `TestFoundGroupMemberOfASwitchedOffProvider`). A found group the user changed (an `auto-…` id stored) is read without the members of providers magpie no longer has (`withoutRemoved`, not written back, so a provider back under its id is back in it), except a manual group's pick, a rule's model, or all of them when none would be left. It keeps following its model as a found group does (Kxsg79bEYFP4 on X: a third provider with the model, a plugin's, had stayed out of a group the user had changed): `SaveGroup` stores, for an `auto-…` id, what it had seen (`Group.Seen`: the models magpie found in it by that save, and those the user named, as `provider/model`), and a provider that serves the model since joins it as it is read, after the user's own members (`joined`, not written back), unless kept out of found groups. A model seen and not a member is one the user took out, and stays out; a provider's rename or a fold carries `Seen` (`mapModelRefs`), and a shared group leaves it behind. A found group changed before `Seen` was kept takes in nothing, as nothing says which of its models the user took out; its next save sees what is found then (`TestChangedFoundGroupTakesInANewProvider`, `TestChangedFoundGroupFromBeforeKeepsItsMembers`, `TestChangedFoundGroupTakesInAPluginProvider`). A switched-off provider's members stay in it, skipped by `membersIn`, and the Routing groups page says them as switched off (`memberJSON.providerOff`). The user's own groups keep their members. Three templates make a group in one click from the models the user has (`provider.Templates`, `AddTemplate`; the Routing groups page's cards before a first group and its Templates menu after, `magpie group template [kind] [name]`): `smart` sends a hard turn to the strongest model and an easy one or a compaction to a cheap one, asked by a classifier (the decision API when there is one, else the cheapest priced model that doesn't reason); `thrifty` starts on two cheap models of different providers and sends high reasoning to the strongest; `steady` fails over between the strongest model of up to three providers. A model is weighed by its maker's list price when known, else what its provider charges, else by its id's size words (`sizeOf`); one over `tooDear` (USD 100 a million output tokens) is never picked. A cheap one beside the strongest (`cheapest`) costs a quarter of it or less, or less than it with an id that says small where the strongest's doesn't: a vendor's own tiers are often nearer than four times apart (DeepSeek V4 Pro $1.98 out and V4.1 Flash $0.60, so both templates read "Needs a model cheap beside" with both on the provider; @qinzhidaoa on X; `TestTemplatesCheapBesideACloseFlagship`). A template that can't be made says what is missing (`Need`). It is saved under a name and id no group has (`freeGroupName`, shared with `CopyGroup`), never over one. A group is shared as text (`ShareGroup`, a group row's Copy to share): JSON marked `"magpie": "routing-group"` with a format `version` (`ShareVersion`), holding the group's members as it names them, patterns, routing, rules, classifier and settings. A group holds only `provider/model` ids, never a key, account or address, and the derived matches, found/hidden/off flags and the rules that hold by a folder (a path on the sharer's machine, `Rule.Folders`) stay behind; a pasted one is left out too. `ImportGroup` (the Routing groups page's Import, `POST /api/groups/import`) reads it with words or a code fence around it, refuses another text, a newer format or none (`ShareError`, said in the reader's language). A member whose provider the importer has is kept; else the same model (`AutoGroupOf`) under the first provider of theirs that serves it (`Instead`); else it is left out and named (`Missing`), with the rules that send to it, its place among the off and fast members, and a classifier gone takes the intent rules and auto effort with it. Nothing is added when no member is left; what is added gets a free name, never replacing a group. A group of patterns only that match nothing now (a plugin's models not listed) has no members: `/api/groups` says them, and an unmakeable template's, as `[]`, never `null`; the Routing groups page reads the response through `groupsFrom` and draws a group it still can't draw as one row saying so, so one bad group never hides the rest (#1585). | [`group.go`](../../internal/provider/group.go), [`grouptemplate.go`](../../internal/provider/grouptemplate.go), [`group_share.go`](../../internal/provider/group_share.go) | | Allowance | `Quotas` asks every vendor at once: subscription windows (`SubscriptionUsage`), key-bought plans (`PlanQuotas`) and key balances (`KeyBalances`). The Usage page, `magpie quota --json` and `GET /v1/magpie/quotas` read it, each window with its whole-window estimate (`Holds`/`HoldsWhy`, `usage.WithWindowHolds`, which `quotaReport` reaches through the `ReckonHolds` hook since package provider can't import usage, #2333). A Remote magpie's cards (`GET /v1/magpie/quotas/cards`, `writeCards`) carry the estimate too, for the owner or a key with no limits on what it sees, since the computer reading them has none of the remote's calls to reckon from (linkaww on Discord: a Docker magpie's ChatGPT Pro week showed no whole on the other computer; `TestRemoteMagpieCardsCarryTheirWholes`). A Codex card's estimate counts the calls of a ChatGPT API account (`chatgpt-api`) that is the same ChatGPT account, whose plan limits they share: the tokens of both must name the same `chatgpt_account_id` and `chatgpt_user_id`, never matched by name, so two Team seats of one email stay apart (`SamePlanAccounts` in [`chatgpt_same_plan.go`](../../internal/provider/chatgpt_same_plan.go), jctaoo on Discord, `TestWindowHoldsCountsTheSameChatGPTAccountThroughTheAPI`). Routing weighs such a ChatGPT API account by that Codex account's reading too: `Allowances("chatgpt-api")` gives it the Codex account's allowance (`samePlanAllowances`; tmr11235 on X, `TestChatGPTAPIAllowanceIsTheSameAccountsCodexReading`), so Smart no longer puts it after every known account as unknown; one with no Codex twin stays unknown. A window that has just reset, with too little used to scale (`HoldsLow`, `HoldsNoneRouted`), keeps the account's last whole for that window, marked `holds.prevAt` (the time it was reckoned; the GUI's tooltip says which window it came from, as a past cycle's does) until it tells its own; the last whole per account and window is kept in `window-holds.json` (`carryHolds` in [`window_holds_carry.go`](../../internal/usage/window_holds_carry.go), every provider's, Musikrv77852 on X; `TestWholeKeptAcrossReset`, `quota-holds.test.cjs`). A single card can be read again on its own (#840). A remote magpie's cards come from what it has kept (`CachedCards`, `GET /v1/magpie/quotas/cards`) and are never read there for this computer except by a card's refresh (`POST /v1/magpie/quotas/refresh`, throttled per card). What it has kept is the Usage page's cards with the readings made behind the requests since laid over them, a later one over an earlier by `readSeq` (`cards_kept.go`): each account's `LoginUsage` reading (the used-up switch, the Codex warm-up, routing's `Allowances`), and each key's `KeyAllowance` windows on its plan or balance card. A Claude account's windows Claude Code told as it answered (`NoteClaudeLimits`, kept in `claudeUsage` with their own `heardSeq`, which drops the account's `LoginUsage` reading) stand on its card over any reading started before them (`withHeardClaude`, #2206), so a magpie only requests reach still tells them. An account or key read that way and never on the page gets a card from that reading, and after a restart, before either is read again, the cards come from `quotas.json`, dated (`AsOf`). A magpie serving only other magpies has nobody on its page (#1313). What it has kept includes its own Remote magpies' cards as it last read them (`passedOnCards`, no remote asked), so a chain passes every card on (yuyong_id on Discord: magpie3 → magpie2 → magpie1 showed none of magpie1's Codex at magpie3), named after each magpie (`magpie2/magpie1/codex`, "Codex · magpie1 · magpie2"); the card standing for a remote and its keys' limits stay the reader's own. Each card carries `via`, the `catalog.Self` of each magpie it went through, and a reader leaves out one that loops (`catalog.Loops`, as a model's `magpie_via`). A refresh of such a card is passed to the magpie it came from (`quotaCardsRefresh` takes a card id this magpie has from a remote); a Codex reset is offered on the magpie next door only, and quota history isn't passed on. The status line's kept report (`KeptQuotaReport`) has a remote's cards the same way. A ChatGPT account's card has an *Image generation* row (`WithImageLane`, [`image_lane.go`](../../internal/provider/image_lane.go), `Lane` `images`, Text and Aside so routing, holds and history never see it; hqqqqqqqh on X, #6160): ChatGPT's images have a quota apart from the 5-hour and weekly windows, which `/wham/usage` doesn't tell (`additional_rate_limits` is null). Every reply of the images API, a 200 too, does: `x-codex-active-limit: imagegen_premium` with the window in `x-codex-primary-*` (1440 minutes, `reset-at`), or in the limit's own family (`x-imagegen-premium-primary-*`, as Codex's `parse_all_rate_limits` reads it). The gateway keeps that window per account (`heardCodexImage` in [`codex_image_limits.go`](../../internal/gateway/codex_image_limits.go), from magpie's drawing and from Codex's own relayed `/images/*`; `provider.ImageHeard`), and never takes it for a chat window (`codexHeaderLimits` tells none when the active limit is an image one; #6412, Green14964 on X: the card said "2 minutes" of a 24-hour window). So the row says *Available* with the window's reset, *Used up* when the headers say 100% or while the image model is resting on that account after a refusal (`ImageRest`, the gateway's `restingUntil`, whose time is the refusal's `resets_at`, #2244, else the heard window's reset for a 429 with that window full, not `quotaRest`'s 15 minutes), and *Unknown* before any drawing, never a share or a count (`TestWithImageLaneOnlyReadCodexCards`, `TestCodexImageRowIsTheRefusalsResetTime`, `TestCodexImageRowFromA200sHeaders`, `TestCodexImageRefusalRestsUntilItsWindow`, `codex-image-row.test.cjs`). The window heard lives in memory only, so after a restart the row is *Unknown* until the next drawing. Not done: the count of images made in the window. Each key of a remote-magpie provider also gets a card of its own, under `/~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=/~keys&user=`). A read that fails keeps the last numbers, dated (`AsOf`); with none the card says why, never zero or no limit. A remote from before `/v1/magpie/limit` (404) says it is too old to tell (`errRemoteNoKeyLimit`). A remote's Codex card keeps its `Resets` (not a GLM team's, `ByWindow`), and its check-ins are dropped: **Use one…** there goes through `/api/usage/codex-reset` with the card's `provider`, and `UseRemoteCodexReset` asks the remote's `POST /v1/magpie/quotas/codex-reset?user=` with the provider's key (#3850). The remote spends it with `SpendCodexReset`, the same function as the Usage page (`UseCodexResetCard`, then `AwaitAllowance`). The account is always named. A 403 `gateway_key_read_only` is told as a read-only key there, and a 404 as a remote too old. No answer within `RemoteResetWait` says the reset may have been used, and it is never asked again by itself. A remote that holds the key to a budget, models or accounts answers its cards 403 `gateway_key_held` (#1981, `errKeyHeld`): the cards kept from before are dropped, and beside the key's own card the remote's card says it tells this key no quotas, and that on that computer Quotas is turned on for the key and it is let use every model of a provider whose usage it is to see (`errRemoteHeld`; yi_time on Discord saw the remote's Claude vanish from every page with no word). Its owner can let the key be told the cards of what it may use (#2216, `magpie gateway-key quotas on`); the remote then answers those, and 403 held as before when that is none (`writeCards`), so that key shows the same card. A remote's cards are kept by provider and key (`remoteCardsID`), so a changed key never shows what the old one was told, and a read is kept only over one asked before it (`keepRemoteCards`). Each card also carries `routing`, each window's span, the model it alone counts and whether it is aside (`provider.ToldRouting` in `writeCards`), which a window's own json leaves out; the magpie reading them lays them back on the windows (`withRouting` in `keepRemoteCards`), and only such a card is weighed by routing (`provider.RemoteAllowance`, #6708, [gateway routing](gateway-routing.md)). Passed on, the cards keep them, so a third magpie weighs them too. A read the test hook dropped (`ForgetRemoteCardsForTest` moves `remoteCardCache.gen` on) is not kept. Cursor, Grok and a Kiro key keep the page's cards only. With Settings → Allowances → *Allowance reads* at *When I ask* (`QuotaReads == "asked"`, #1518: magpie started at login before the proxy app read by itself, direct), only a read the user asked for goes out: the Usage page or the tray panel's Allowances opened (no more than once in 30s, `quotasOpened`, #1588) or refreshed (`?asked=1`), a card's refresh (`RefreshUsage`), `magpie quota`, `magpie accounts`, `magpie quota wait` and the TUI's quotas (`Asked`). Any other read (`quotaReading` → `holdUnasked`) carries `netproxy.Hold`, so its requests fail before they leave, and every reader gives back what it last read, dated, or "not read yet" (`errNotAsked`): routing, the used-up switch, the menu bar and alerts go by that. An account refused for its quota (`StaleAllowance` → `markStaleRead`) or a key refused (`StaleKeyAllowance` → `refused`) is still read, once (`unheld`). Warm-up and check-in are not reads and are unchanged. A plugin's window may carry a prepaid wallet's `balance` in its `unit` and no share (`QuotaWindow.Balance`, #3950): the card and `magpie quota` show the figure (`BalanceText`), and routing reads it through `Allowance.Left`. | [`cards_kept.go`](../../internal/provider/cards_kept.go), [`quotas.go`](../../internal/provider/quotas.go), [`subscription_usage.go`](../../internal/provider/subscription_usage.go), [`planquota.go`](../../internal/provider/planquota.go), [`balance.go`](../../internal/provider/balance.go), [`quota_refresh.go`](../../internal/provider/quota_refresh.go), [`remote_quotas.go`](../../internal/provider/remote_quotas.go), [`remote_key_limits.go`](../../internal/provider/remote_key_limits.go), [`quota_asked.go`](../../internal/provider/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](gateway-routing.md)). 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`](../../internal/provider/remote_magpie.go), [`models.go`](../../internal/provider/models.go), [`gateway.go`](../../internal/gateway/gateway.go) (`models`), [`live.go`](../../internal/catalog/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). Ultrafast is added where the remote's own key or account offers it (`UltraOn`, read in `CodexTiersWith` with `UltraModels` read once a list): an OpenAI key's or a relay's GPT-6.2 Sol, a ChatGPT account whose plan lists it, and a group with such a member (the gateway asks that member for it and the others for `priority`, `tierMate`). `codexcat.Entries` keeps it beside the Fast it gives a group or a ChatGPT account's model and the tiers it takes from Codex's own catalog (`withTiers`), naming it Ultrafast where that catalog doesn't. Before, only Codex's own catalog could add it, so a remote in Docker, with no Codex beside it, offered Fast alone and the local's GUI never offered Ultrafast on its models (OoopsHh on X, `TestRemoteMagpieOffersUltrafast`). Both ends need it: the remote to list the tier, the local to read it (which it already did). 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`](../../internal/codexcat/codexcat.go), [`codex_models.go`](../../internal/provider/codex_models.go), [`codex_catalog.go`](../../internal/gateway/codex_catalog.go), [`gateway.go`](../../internal/gateway/gateway.go), [`live.go`](../../internal/catalog/live.go) | diff --git a/internal/provider/grouptemplate.go b/internal/provider/grouptemplate.go index e31a97e59..8988247b4 100644 --- a/internal/provider/grouptemplate.go +++ b/internal/provider/grouptemplate.go @@ -181,8 +181,9 @@ func strongest(ms []rated) []rated { } // cheapest are the models fit to be a cheap one beside strong, ranked -// best first: priced at a quarter of strong or less (or, with no prices -// to go by, a small model by its id), a known maker's first, the tiny ones +// best first: priced at a quarter of strong or less, or below it with +// an id that says small where strong's doesn't (or, with no prices to go +// by, a small model by its id), a known maker's first, the tiny ones // last, then the newest and the dearest of them — the most able of the // cheap. func cheapest(ms []rated, strong rated) []rated { @@ -192,7 +193,11 @@ func cheapest(ms []rated, strong rated) []rated { continue } if strong.out > 0 && m.out > 0 { - if m.out <= strong.out/4 { + // a quarter of the price, or less dear and the small one by + // its id: a vendor's own tiers are often nearer than four + // times apart (DeepSeek V4 Pro $1.98 out, V4.1 Flash $0.60; + // Sonnet and Haiku three times, @qinzhidaoa on X) + if m.out <= strong.out/4 || m.out < strong.out && m.small && !strong.small { out = append(out, m) } } else if m.small && !strong.small { diff --git a/internal/provider/grouptemplate_tier_test.go b/internal/provider/grouptemplate_tier_test.go new file mode 100644 index 000000000..385d76683 --- /dev/null +++ b/internal/provider/grouptemplate_tier_test.go @@ -0,0 +1,78 @@ +package provider + +import ( + "os" + "path/filepath" + "slices" + "testing" + + "github.com/yetone/magpie/internal/catalog" +) + +// A cheaper model whose id says it is the small one is the cheap one +// beside a flagship that costs less than four times as much +// (@qinzhidaoa on X): DeepSeek lists deepseek-v4-pro at $1.98 out and +// V4.1 Flash at $0.60, 3.3 times less, so "Hard to strong, easy to +// cheap" and "Cheap first" read "Needs a model cheap beside +// DeepSeek-V4-Pro" with both models on the provider. +func TestTemplatesCheapBesideACloseFlagship(t *testing.T) { + isolate(t) + home := t.TempDir() + t.Setenv("HOME", home) + t.Setenv("USERPROFILE", home) + t.Setenv("XDG_CONFIG_HOME", filepath.Join(home, ".config")) + t.Setenv("XDG_CACHE_HOME", filepath.Join(home, ".cache")) + t.Setenv("XDG_DATA_HOME", filepath.Join(home, ".local", "share")) + // models.dev's DeepSeek as the catalog magpie ships (2026-11-10) has it + b, err := os.ReadFile(filepath.Join("testdata", "models-dev-deepseek-2026-11-10.json")) + if err != nil { + t.Fatal(err) + } + if err := os.MkdirAll(filepath.Dir(catalog.CachePath()), 0o700); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(catalog.CachePath(), b, 0o600); err != nil { + t.Fatal(err) + } + catalog.Reset() + t.Cleanup(catalog.Reset) + // the reporter's provider: the DeepSeek preset, its two models + if err := Save(Provider{ID: "deepseek", Name: "DeepSeek", Key: "sk-test", Catalog: "deepseek", + Chat: "https://api.deepseek.com/v1", Anthropic: "https://api.deepseek.com/anthropic", + Models: []string{"deepseek-v4.1-flash", "deepseek-v4-pro"}}); err != nil { + t.Fatal(err) + } + ms := templateModels() + for _, m := range ms { + t.Logf("%s out=%v maker=%v small=%v", m.e.ID, m.out, m.maker, m.small) + } + want := map[string][]string{ + TemplateSmart: {"deepseek/deepseek-v4-pro", "deepseek/deepseek-v4.1-flash"}, + TemplateThrifty: {"deepseek/deepseek-v4.1-flash", "deepseek/deepseek-v4-pro"}, + } + for _, tp := range Templates() { + if w, ok := want[tp.Kind]; ok && (tp.Need != "" || !slices.Equal(tp.Group.Members, w)) { + t.Errorf("%s = need %q of %q, members %v; want %v", tp.Kind, tp.Need, tp.Of, tp.Group.Members, w) + } + } + + // the class: Sonnet and Haiku are three times apart, Pro and Flash four + for _, c := range [][2]rated{ + {tm("anthropic", "claude-sonnet-5-5", 15, true, "2026-09-01"), tm("anthropic", "claude-haiku-5-5", 5, true, "2026-09-01")}, + {tm("google", "gemini-3-pro", 12, true, "2026-08-01"), tm("google", "gemini-3-flash", 3.5, true, "2026-08-01")}, + } { + if tp := templateOf(TemplateSmart, c[:], nil); !slices.Equal(tp.Group.Members, []string{c[0].e.ID, c[1].e.ID}) { + t.Errorf("%s beside %s: %+v", c[1].e.Model, c[0].e.Model, tp) + } + } + // a model no cheaper is never the cheap one, however its id reads, + // nor one that costs as much without a small id + for _, c := range [][2]rated{ + {tm("x", "big-model", 2, true, ""), tm("x", "big-model-flash", 2, true, "")}, + {tm("x", "big-model", 2, true, ""), tm("x", "other-model", 1, true, "")}, + } { + if tp := templateOf(TemplateSmart, c[:], nil); tp.Need != NeedCheap { + t.Errorf("%s beside %s: %+v, want no cheap one", c[1].e.Model, c[0].e.Model, tp) + } + } +} diff --git a/internal/provider/testdata/models-dev-deepseek-2026-11-10.json b/internal/provider/testdata/models-dev-deepseek-2026-11-10.json new file mode 100644 index 000000000..ef5ebd80c --- /dev/null +++ b/internal/provider/testdata/models-dev-deepseek-2026-11-10.json @@ -0,0 +1,218 @@ +{ + "deepseek": { + "id": "deepseek", + "env": [ + "DEEPSEEK_API_KEY" + ], + "npm": "@ai-sdk/openai-compatible", + "api": "https://api.deepseek.com", + "name": "DeepSeek", + "doc": "https://api-docs.deepseek.com/quick_start/pricing", + "models": { + "deepseek-v4-pro": { + "id": "deepseek-v4-pro", + "name": "DeepSeek V4 Pro", + "description": "DeepSeek V4 Pro snapshot with million-token context and support for thinking and non-thinking modes", + "family": "deepseek-thinking", + "attachment": false, + "reasoning": true, + "reasoning_options": [ + { + "type": "toggle" + }, + { + "type": "effort", + "values": [ + "low", + "high", + "max" + ] + } + ], + "tool_call": true, + "interleaved": { + "field": "reasoning_content" + }, + "structured_output": true, + "temperature": true, + "release_date": "2026-08-13", + "last_updated": "2026-08-22", + "modalities": { + "input": [ + "text" + ], + "output": [ + "text" + ] + }, + "open_weights": true, + "limit": { + "context": 1048576, + "output": 393216 + }, + "cost": { + "input": 0.66, + "output": 1.98, + "reasoning": 1.98, + "cache_read": 0.022 + }, + "canonical_model_id": "deepseek/deepseek-v4-pro-0813" + }, + "deepseek-flash": { + "id": "deepseek-flash", + "name": "DeepSeek V4.1 Flash 1017", + "description": "October 17 update of DeepSeek V4.1 Flash with improved reasoning, coding, agentic tasks, and visual understanding", + "family": "deepseek-flash", + "attachment": true, + "reasoning": true, + "reasoning_options": [ + { + "type": "toggle" + }, + { + "type": "effort", + "values": [ + "low", + "high", + "max" + ] + } + ], + "tool_call": true, + "interleaved": { + "field": "reasoning_content" + }, + "structured_output": true, + "temperature": true, + "knowledge": "2025-05", + "release_date": "2026-10-17", + "last_updated": "2026-10-17", + "modalities": { + "input": [ + "text", + "image" + ], + "output": [ + "text" + ] + }, + "open_weights": true, + "limit": { + "context": 1048576, + "output": 393216 + }, + "cost": { + "input": 0.15, + "output": 0.6, + "reasoning": 0.6, + "cache_read": 0.003 + }, + "canonical_model_id": "deepseek/deepseek-v4.1-flash-1017" + }, + "deepseek-v4-flash-vision-exp": { + "id": "deepseek-v4-flash-vision-exp", + "name": "DeepSeek V4 Flash Vision Exp", + "description": "October 17 update of DeepSeek V4.1 Flash with improved reasoning, coding, agentic tasks, and visual understanding", + "family": "deepseek-flash", + "attachment": true, + "reasoning": true, + "reasoning_options": [ + { + "type": "toggle" + }, + { + "type": "effort", + "values": [ + "low", + "high", + "max" + ] + } + ], + "tool_call": true, + "interleaved": { + "field": "reasoning_content" + }, + "structured_output": true, + "temperature": true, + "knowledge": "2025-05", + "release_date": "2026-10-17", + "last_updated": "2026-10-17", + "modalities": { + "input": [ + "text", + "image" + ], + "output": [ + "text" + ] + }, + "open_weights": true, + "limit": { + "context": 1048576, + "output": 393216 + }, + "status": "deprecated", + "cost": { + "input": 0.15, + "output": 0.6, + "reasoning": 0.6, + "cache_read": 0.003 + }, + "canonical_model_id": "deepseek/deepseek-v4.1-flash-1017" + }, + "deepseek-v4-flash": { + "id": "deepseek-v4-flash", + "name": "DeepSeek V4 Flash", + "description": "October 17 update of DeepSeek V4.1 Flash with improved reasoning, coding, agentic tasks, and visual understanding", + "family": "deepseek-flash", + "attachment": true, + "reasoning": true, + "reasoning_options": [ + { + "type": "toggle" + }, + { + "type": "effort", + "values": [ + "low", + "high", + "max" + ] + } + ], + "tool_call": true, + "interleaved": { + "field": "reasoning_content" + }, + "structured_output": true, + "temperature": true, + "knowledge": "2025-05", + "release_date": "2026-10-17", + "last_updated": "2026-10-17", + "modalities": { + "input": [ + "text", + "image" + ], + "output": [ + "text" + ] + }, + "open_weights": true, + "limit": { + "context": 1048576, + "output": 393216 + }, + "status": "deprecated", + "cost": { + "input": 0.15, + "output": 0.6, + "reasoning": 0.6, + "cache_read": 0.003 + }, + "canonical_model_id": "deepseek/deepseek-v4.1-flash-1017" + } + } + } +} \ No newline at end of file