diff --git a/docs/subsystems/providers-accounts.md b/docs/subsystems/providers-accounts.md index 2857e83e2..062c796ea 100644 --- a/docs/subsystems/providers-accounts.md +++ b/docs/subsystems/providers-accounts.md @@ -57,7 +57,7 @@ keys and accounts per request is in [Gateway routing and fallback](gateway-routi | 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. 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 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). What a pattern matches follows the members named, in the catalog's order, until the user drags it elsewhere (usrname1833 on Discord): `Placed` keeps the whole order, named and matched alike, and the group is read and routed in it (`placedIn`); a model matched since goes last, one no longer matched drops out, a save that sends the named members only leaves the matched where they were (`placedOver`), and a provider's or group's rename carries it (`TestGroupPatternMembersKeepTheirPlace`, `group-member-drag.test.cjs`). A found group follows the providers magpie has: one removed leaves it, while one switched off stays in it (`foundGroups`, `heldOffEntries`; one without a key, such as a plugin not signed in, finds no group), skipped by `membersIn`, left off a found group's card, logos and TUI line with a count of those switched off (XYenon on Discord: `routing-provider-off.test.cjs`, `TestFoundGroupLineLeavesASwitchedOffProviderOut`) and said as switched off in its editor and the TUI's group page, so switching one of two providers off for a while doesn't take the group away from the agents, rules and groups set to it; it is back in its place once on again (#2671: `TestFoundGroupStaysWithAProviderOff`, `TestFoundGroupWithAProviderOff`, `TestReseatKeepsAFoundGroupWithAProviderOff`, `TestFoundGroupMemberOfASwitchedOffProvider`). A found group the user changed (an `auto-…` id stored) is read without the members of providers magpie no longer has (`withoutRemoved`, not written back, so a provider back under its id is back in it), except a manual group's pick, a rule's model, or all of them when none would be left. It keeps following its model as a found group does (Kxsg79bEYFP4 on X: a third provider with the model, a plugin's, had stayed out of a group the user had changed): `SaveGroup` stores, for an `auto-…` id, what it had seen (`Group.Seen`: the models magpie found in it by that save, and those the user named, as `provider/model`), and a provider that serves the model since joins it as it is read, after the user's own members (`joined`, not written back), unless kept out of found groups. A model seen and not a member is one the user took out, and stays out; a provider's rename or a fold carries `Seen` (`mapModelRefs`), and a shared group leaves it behind. A found group changed before `Seen` was kept takes in nothing, as nothing says which of its models the user took out; its next save sees what is found then (`TestChangedFoundGroupTakesInANewProvider`, `TestChangedFoundGroupFromBeforeKeepsItsMembers`, `TestChangedFoundGroupTakesInAPluginProvider`). A switched-off provider's members stay in it, skipped by `membersIn`, and the Routing 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`](../../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 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 `/~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`). 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) | +| 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 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`). 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 `/~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`). 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). 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) | | Two magpies each the other's remote | The list a magpie gives another magpie (`X-Magpie-Drawers`) names, as `magpie_via`, the magpies each model passes through to its vendor, itself last (`catalog.ViaHere`, `viaOf`; a routing group's are its members' together, so a group with the other magpie's own group of the model in it is left out there too). Each process has a random id (`catalog.Self`). A fetched list leaves out a model whose `magpie_via` has this magpie and another one (it went out of here and came back), or more than `MaxVia` (8), so two magpies that are each other's remote no longer list each other's models back one level deeper on every 10-minute fetch, without end, each level another member of the found `auto/` group and another trip round the two (cdredfox on Discord, 100-200% CPU). A remote that is this magpie itself (sync carries a Remote magpie provider to the computer it names, hanslin1666) has its models through this id alone, taken once; one through this id twice or more is left out. Such a remote is found by its own list: a fetch whose models' `magpie_via` ends with this magpie's own `Self` is kept, by provider id and the address it answered at, in `remote-self.json` (`noteSelf`; another lister, or a list with no via, takes it away; an empty list or a failed fetch changes nothing; this computer's own file, never in a backup or a sync). The provider is then left out (`SelfLeftOut` in `On`, `SwitchedOff`, `remoteMagpies`): its models are not listed beside this magpie's own nor in a found group, and a request naming one, an agent's pick sync brought from the other computer, is served here with the remote's id taken off the front (`ThroughSelf` in `Resolve` and `ResolveRoute`), not passed through the gateway again. The Providers row says *This magpie* (greyed while left out) and its editor says why, with **Use it anyway** (`KeepSelf`, `provider/keepself`, `SetKeepSelf`), the user's to set (hanslin1666): kept, it is served as any remote, each request twice through this magpie. `KeepSelf` is this computer's own like `KeepLogin` (`Mirror`, `Restore`, blanked in davsync's `hashes`), since the other computer's copy points at this one, which is not itself (`TestRemoteMagpieThatIsThisOneIsLeftOut`, `TestRemoteSelfRecord`, `remote-self.test.cjs`). Each request passed on to a Remote magpie says how many magpies it went through (`X-Magpie-Hops`, `passOnCaller`); one that arrives having passed `MaxVia` is answered 508 Loop Detected (`withCaller`), read only from a magpie's request and taken off every request as it arrives. A magpie older than the field sends none, and its models are taken as they were. | [`magpie_via.go`](../../internal/catalog/magpie_via.go), [`live.go`](../../internal/catalog/live.go), [`gateway.go`](../../internal/gateway/gateway.go), [`remote_magpie.go`](../../internal/provider/remote_magpie.go), [`remote_self.go`](../../internal/provider/remote_self.go) | diff --git a/internal/provider/chatgpt_same_plan.go b/internal/provider/chatgpt_same_plan.go new file mode 100644 index 000000000..e6a560753 --- /dev/null +++ b/internal/provider/chatgpt_same_plan.go @@ -0,0 +1,88 @@ +package provider + +import ( + "cmp" + "encoding/json" + "strings" +) + +// One ChatGPT plan, two ways in (jctaoo on Discord): an account signed in +// through Sign in with ChatGPT (chatgpt-api) and the same account signed in +// to Codex draw on one plan's five-hour and weekly limits, while only the +// Codex account's card reads them. A whole-window estimate (usage's +// WithWindowHolds) over the Codex card counts the chatgpt-api account's +// calls too, by this. + +// SamePlanAccounts maps each ChatGPT API account to the Codex account that +// is the same ChatGPT account, both as provider + "\x00" + lowercased name, +// the way the usage ledger's calls are keyed. They are matched on what the +// tokens say, never on a name: the ChatGPT account (workspace) id and the +// user's id, both known and both equal. Two Team seats of one email share +// a name and a user, not an account id; an account whose tokens don't say +// both is matched to none. +func SamePlanAccounts() map[string]string { + ls := sharedLogins() + type who struct{ account, user string } + codex := map[who]string{} + for _, l := range ls { + if l.Agent != "codex" { + continue + } + var a codexAuth + if json.Unmarshal(l.Auth, &a) != nil { + continue + } + w := who{codexAccountID(a), chatgptUserID(a.Tokens.IDToken, a.Tokens.AccessToken)} + if w.account == "" || w.user == "" { + continue + } + if _, ok := codex[w]; !ok { + codex[w] = "codex\x00" + strings.ToLower(l.User) + } + } + out := map[string]string{} + if len(codex) == 0 { + return out + } + for _, l := range ls { + if l.Agent != ChatGPTAPIID { + continue + } + c, ok := siwcSaved(l) + if !ok { + continue + } + w := who{chatgptAccountID(c.IDToken, c.Access), chatgptUserID(c.IDToken, c.Access)} + if w.account == "" || w.user == "" { + continue + } + if to, ok := codex[w]; ok { + out[ChatGPTAPIID+"\x00"+strings.ToLower(l.User)] = to + } + } + return out +} + +// chatgptAccountID is the ChatGPT account (workspace) the first of toks +// that names one is for. +func chatgptAccountID(toks ...string) string { + for _, t := range toks { + if a := claimString(jwtClaims(t), "https://api.openai.com/auth", "chatgpt_account_id"); a != "" { + return a + } + } + return "" +} + +// chatgptUserID is the ChatGPT user the first of toks that names one is +// for: its chatgpt_user_id, as OpenAI's own tokens say it beside the +// account id. +func chatgptUserID(toks ...string) string { + for _, t := range toks { + auth := jwtClaims(t) + if u := cmp.Or(claimString(auth, "https://api.openai.com/auth", "chatgpt_user_id"), claimString(auth, "https://api.openai.com/auth", "user_id")); u != "" { + return u + } + } + return "" +} diff --git a/internal/usage/same_plan_holds_test.go b/internal/usage/same_plan_holds_test.go new file mode 100644 index 000000000..63b4aecdf --- /dev/null +++ b/internal/usage/same_plan_holds_test.go @@ -0,0 +1,140 @@ +package usage + +import ( + "encoding/base64" + "encoding/json" + "os" + "path/filepath" + "testing" + "time" + + "github.com/yetone/magpie/internal/catalog" + "github.com/yetone/magpie/internal/provider" +) + +// samePlanLogins writes logins.json in the test's home: each entry is an +// agent, a name and the ChatGPT account and user its tokens name ("" for +// a token that names none). +func samePlanLogins(t *testing.T, ls ...[4]string) { + t.Helper() + jwt := func(email, account, user string) string { + auth := map[string]string{"chatgpt_plan_type": "plus"} + if account != "" { + auth["chatgpt_account_id"] = account + } + if user != "" { + auth["chatgpt_user_id"] = user + } + b, _ := json.Marshal(map[string]any{"sub": "auth0|" + user, "email": email, "https://api.openai.com/auth": auth}) + return "h." + base64.RawURLEncoding.EncodeToString(b) + ".sig" + } + var out []map[string]any + for _, l := range ls { + agent, name, account, user := l[0], l[1], l[2], l[3] + tok := jwt(name, account, user) + var auth map[string]any + switch agent { + case "codex": // auth.json as `codex login` writes it + auth = map[string]any{"auth_mode": "chatgpt", "tokens": map[string]string{"id_token": tok, "access_token": tok, "refresh_token": "r", "account_id": account}} + case provider.ChatGPTAPIID: // what Sign in with ChatGPT keeps + auth = map[string]any{"clientId": "app_1", "hostId": "urn:uuid:1", "sub": "auth0|" + user, "email": name, "idToken": tok, "access": tok, "refresh": "r", "expires": time.Now().Add(time.Hour)} + } + out = append(out, map[string]any{"agent": agent, "user": name, "auth": auth}) + } + b, _ := json.Marshal(out) + path := filepath.Join(filepath.Dir(provider.Path()), "logins.json") + if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(path, b, 0o600); err != nil { + t.Fatal(err) + } +} + +// jctaoo on Discord: a ChatGPT account signed in through Sign in with +// ChatGPT (chatgpt-api) and to Codex draws on one plan's five hours and +// week, which only the Codex card reads. The card's whole-window estimate +// counts the chatgpt-api account's calls too, and only when the tokens +// say it is the same ChatGPT account: two Team seats of one email share a +// name and a user, never an account id. +func TestWindowHoldsCountsTheSameChatGPTAccountThroughTheAPI(t *testing.T) { + now := time.Date(2026, 11, 5, 12, 0, 0, 0, time.UTC) + reset := now.Add(3 * time.Hour) + card := func(user string) provider.SubscriptionQuota { + return provider.SubscriptionQuota{Provider: "codex", User: user, Windows: []provider.QuotaWindow{ + {Name: "5 hours", Used: 40, ResetsAt: &reset, Span: 5 * time.Hour}}} + } + call := func(prov, who string, tokens int) Record { + return Record{Time: now.Add(-time.Hour), Agent: "codex", Provider: prov, ProviderAccount: who, Model: "gpt-5.5", Input: tokens, Output: 0, Status: 200} + } + holds := func(qs []provider.SubscriptionQuota, recs ...Record) []provider.SubscriptionQuota { + return windowHolds(qs, now, now.Add(-30*24*time.Hour), func(Record) *catalog.Price { return nil }, provider.Renames{}, + provider.SamePlanAccounts(), nil, func(fn func(Record)) { + for _, r := range recs { + fn(r) + } + }) + } + tokens := func(q provider.SubscriptionQuota) int64 { + if h := q.Windows[0].Holds; h != nil { + return h.Tokens + } + return 0 + } + + t.Run("one account, both ways in", func(t *testing.T) { + holdsHome(t) + samePlanLogins(t, + [4]string{"codex", "dee@example.com", "acct-1", "user-1"}, + [4]string{provider.ChatGPTAPIID, "dee@example.com", "acct-1", "user-1"}) + got := holds([]provider.SubscriptionQuota{card("dee@example.com")}, + call("codex", "dee@example.com", 1000), call(provider.ChatGPTAPIID, "dee@example.com", 3000)) + // 4000 routed at 40% used: 10000 the whole window + if n := tokens(got[0]); n != 10000 { + t.Fatalf("whole 5 hours %d tokens, want 10000 (codex's 1000 and chatgpt-api's 3000 over 40%%)", n) + } + }) + + t.Run("two seats of one email stay apart", func(t *testing.T) { + holdsHome(t) + samePlanLogins(t, + [4]string{"codex", "dee@example.com · Team", "acct-team", "user-1"}, + [4]string{"codex", "dee@example.com", "acct-own", "user-1"}, + [4]string{provider.ChatGPTAPIID, "dee@example.com", "acct-own", "user-1"}) + got := holds([]provider.SubscriptionQuota{card("dee@example.com · Team"), card("dee@example.com")}, + call("codex", "dee@example.com · Team", 2000), call("codex", "dee@example.com", 1000), + call(provider.ChatGPTAPIID, "dee@example.com", 3000)) + if n := tokens(got[0]); n != 5000 { + t.Fatalf("the Team seat holds %d tokens, want 5000: its own 2000 only, not the personal account's chatgpt-api calls", n) + } + if n := tokens(got[1]); n != 10000 { + t.Fatalf("the personal account holds %d tokens, want 10000 with its chatgpt-api calls", n) + } + }) + + t.Run("a token that names no account matches none", func(t *testing.T) { + holdsHome(t) + samePlanLogins(t, + [4]string{"codex", "dee@example.com", "acct-1", "user-1"}, + [4]string{provider.ChatGPTAPIID, "dee@example.com", "", "user-1"}) + got := holds([]provider.SubscriptionQuota{card("dee@example.com")}, + call("codex", "dee@example.com", 1000), call(provider.ChatGPTAPIID, "dee@example.com", 3000)) + if n := tokens(got[0]); n != 2500 { + t.Fatalf("whole 5 hours %d tokens, want 2500: an account the tokens don't name isn't taken for the same by its email", n) + } + }) + + t.Run("chatgpt-api alone", func(t *testing.T) { + holdsHome(t) + samePlanLogins(t, [4]string{provider.ChatGPTAPIID, "dee@example.com", "acct-1", "user-1"}) + if m := provider.SamePlanAccounts(); len(m) != 0 { + t.Fatalf("matched with no Codex account: %v", m) + } + // its card reads no windows (OpenAI's API tells none): nothing to reckon + api := provider.SubscriptionQuota{Provider: provider.ChatGPTAPIID, User: "dee@example.com", Windows: []provider.QuotaWindow{}, Error: "no usage"} + got := holds([]provider.SubscriptionQuota{api}, call(provider.ChatGPTAPIID, "dee@example.com", 3000)) + if len(got) != 1 || len(got[0].Windows) != 0 { + t.Fatalf("got %+v", got) + } + }) +} diff --git a/internal/usage/window_holds.go b/internal/usage/window_holds.go index a1aaaf1e6..b47bffc3a 100644 --- a/internal/usage/window_holds.go +++ b/internal/usage/window_holds.go @@ -28,13 +28,13 @@ func init() { provider.ReckonHolds = WithWindowHolds } func WithWindowHolds(qs []provider.SubscriptionQuota, now time.Time) []provider.SubscriptionQuota { since, ok := holdsSince(qs, now) if !ok { // none can be reckoned: each one only says why - return windowHolds(qs, now, time.Time{}, nil, provider.Renames{}, nil, func(func(Record)) {}) + return windowHolds(qs, now, time.Time{}, nil, provider.Renames{}, nil, nil, func(func(Record)) {}) } s := readLogSnapshot() hist := provider.QuotaHistories(since, "", "") started := withRecordedWindowStarts(qs, hist, now) dry := dryRuns(started, hist, now) - out := windowHolds(started, now, s.firstOwn, apiPricer(), provider.UsageRenames(), dry, func(fn func(Record)) { s.visit(since, fn) }) + out := windowHolds(started, now, s.firstOwn, apiPricer(), provider.UsageRenames(), provider.SamePlanAccounts(), dry, func(fn func(Record)) { s.visit(since, fn) }) return withSpansOf(out, qs) } @@ -180,8 +180,11 @@ func dryRuns(qs []provider.SubscriptionQuota, hist []provider.QuotaHistory, now // it has calls magpie can't see, and isn't reckoned. Nor is a window with a // call in one of its account's dry runs that may have been paid otherwise: // one where the vendor answered a call after a reading of none left, or -// where no reading with some left is known before it. -func windowHolds(qs []provider.SubscriptionQuota, now, first time.Time, priceOf func(Record) *catalog.Price, renamed provider.Renames, dry map[string][]dryRun, read func(func(Record))) []provider.SubscriptionQuota { +// where no reading with some left is known before it. same maps an account +// to the one whose card reads the plan it draws on (a ChatGPT API account +// to the same ChatGPT account in Codex, provider.SamePlanAccounts): its +// calls are counted as that one's. +func windowHolds(qs []provider.SubscriptionQuota, now, first time.Time, priceOf func(Record) *catalog.Price, renamed provider.Renames, same map[string]string, dry map[string][]dryRun, read func(func(Record))) []provider.SubscriptionQuota { type slot struct{ q, w int } type span struct{ start, end time.Time } want := map[slot]span{} @@ -231,6 +234,9 @@ func windowHolds(qs []provider.SubscriptionQuota, now, first time.Time, priceOf who = r.ProviderKeyName } acct := r.Provider + "\x00" + strings.ToLower(who) + if to, ok := same[acct]; ok { + acct = to + } var runs []runKey for i, d := range dry[acct] { if !d.holds(r.Time) { diff --git a/internal/usage/window_holds_history.go b/internal/usage/window_holds_history.go index 91898c800..5ac9429d1 100644 --- a/internal/usage/window_holds_history.go +++ b/internal/usage/window_holds_history.go @@ -71,7 +71,7 @@ func HistoricalWindowHolds(cards []provider.SubscriptionQuota, hist []provider.Q past = append(past, a) } s := readLogSnapshot() - return windowHolds(snapshots, to, s.firstOwn, apiPricer(), provider.UsageRenames(), dryRuns(snapshots, past, to), func(fn func(Record)) { + return windowHolds(snapshots, to, s.firstOwn, apiPricer(), provider.UsageRenames(), provider.SamePlanAccounts(), dryRuns(snapshots, past, to), func(fn func(Record)) { s.visit(since, func(r Record) { if r.Time.Before(to) { fn(r) diff --git a/internal/usage/window_holds_test.go b/internal/usage/window_holds_test.go index a57ecb92c..984782a5a 100644 --- a/internal/usage/window_holds_test.go +++ b/internal/usage/window_holds_test.go @@ -158,19 +158,19 @@ func TestWindowHoldsNeedsTheWholeWindowLogged(t *testing.T) { } } priceOf := func(Record) *catalog.Price { return nil } - if got := windowHolds(qs, now, now.Add(-2*24*time.Hour), priceOf, provider.Renames{}, nil, read); got[0].Windows[0].Holds != nil || got[0].Windows[0].HoldsWhy != provider.HoldsBeforeLog { + if got := windowHolds(qs, now, now.Add(-2*24*time.Hour), priceOf, provider.Renames{}, nil, nil, read); got[0].Windows[0].Holds != nil || got[0].Windows[0].HoldsWhy != provider.HoldsBeforeLog { t.Fatalf("the log began 2 days into the week, and the week was reckoned: %+v, why %q", got[0].Windows[0].Holds, got[0].Windows[0].HoldsWhy) } - got := windowHolds(qs, now, now.Add(-30*24*time.Hour), priceOf, provider.Renames{}, nil, read) + got := windowHolds(qs, now, now.Add(-30*24*time.Hour), priceOf, provider.Renames{}, nil, nil, read) if h := got[0].Windows[0].Holds; h == nil || h.Tokens != 500 || h.Priced { t.Fatalf("logged since before the week: %+v, want 500 tokens, unpriced", h) } - if got := windowHolds(qs, now, now.Add(-30*24*time.Hour), priceOf, provider.Renames{}, nil, func(func(Record)) {}); got[0].Windows[0].Holds != nil || got[0].Windows[0].HoldsWhy != provider.HoldsNoneRouted { + if got := windowHolds(qs, now, now.Add(-30*24*time.Hour), priceOf, provider.Renames{}, nil, nil, func(func(Record)) {}); got[0].Windows[0].Holds != nil || got[0].Windows[0].HoldsWhy != provider.HoldsNoneRouted { t.Fatalf("nothing routed, and the week was reckoned: %+v, why %q", got[0].Windows[0].Holds, got[0].Windows[0].HoldsWhy) } // a provider since renamed: its calls under the old id are the account's recs[0].Provider = "claude-old" - if got := windowHolds(qs, now, now.Add(-30*24*time.Hour), priceOf, provider.RenamesOf(map[string]string{"claude-old": "claude"}), nil, read); got[0].Windows[0].Holds == nil { + if got := windowHolds(qs, now, now.Add(-30*24*time.Hour), priceOf, provider.RenamesOf(map[string]string{"claude-old": "claude"}), nil, nil, read); got[0].Windows[0].Holds == nil { t.Fatal("a call under the provider's old id wasn't counted") } } @@ -207,7 +207,7 @@ func TestWindowHoldsReckonsAPlanKeysWindowByItsName(t *testing.T) { fn(r) } } - got := windowHolds(qs, now, now.Add(-30*24*time.Hour), func(Record) *catalog.Price { return nil }, provider.Renames{}, nil, read) + got := windowHolds(qs, now, now.Add(-30*24*time.Hour), func(Record) *catalog.Price { return nil }, provider.Renames{}, nil, nil, read) newHolds, oldFive, oldWeek := got[0].Windows[0], got[1].Windows[0], got[1].Windows[1] if h := newHolds.Holds; h == nil || h.Routed.Tokens != 2500 || h.Tokens != 2874 { t.Fatalf("new's 5 hours: %+v (why %q), want 2500 routed, whole 2874", newHolds.Holds, newHolds.HoldsWhy) @@ -273,7 +273,7 @@ func TestWindowHoldsLeavesOutCallsPaidOtherwise(t *testing.T) { } var whys [2]string holds := func(qs []provider.SubscriptionQuota, h []provider.QuotaHistory, recs ...Record) (five, week *provider.WindowHolds) { - got := windowHolds(qs, now, first, priceOf, provider.Renames{}, dryRuns(qs, h, now), reads(recs...)) + got := windowHolds(qs, now, first, priceOf, provider.Renames{}, nil, dryRuns(qs, h, now), reads(recs...)) whys = [2]string{got[0].Windows[0].HoldsWhy, got[0].Windows[1].HoldsWhy} return got[0].Windows[0].Holds, got[0].Windows[1].Holds } @@ -338,7 +338,7 @@ func TestWindowHoldsResetBeforeRefillReading(t *testing.T) { } { t.Run(tc.name, func(t *testing.T) { call := Record{Time: tc.at, Provider: providerID, ProviderAccount: "sample@example.com", Model: "m", Input: 1000, Status: 200} - got := windowHolds(qs, now, now.Add(-30*24*time.Hour), func(Record) *catalog.Price { return nil }, provider.Renames{}, dryRuns(qs, hist, now), func(fn func(Record)) { fn(call) }) + got := windowHolds(qs, now, now.Add(-30*24*time.Hour), func(Record) *catalog.Price { return nil }, provider.Renames{}, nil, dryRuns(qs, hist, now), func(fn func(Record)) { fn(call) }) h := got[0].Windows[1].Holds if (h != nil) != tc.want { t.Fatalf("week holds = %+v, want present %v", h, tc.want) @@ -379,7 +379,7 @@ func TestWindowHoldsDryAgainAfterReset(t *testing.T) { {Time: now.Add(-3 * 24 * time.Hour), Input: 1000, Status: 200}, {Time: r1.Add(time.Hour), Input: 1000, Status: 200}, // after the reset, before the next dry reading } - got := windowHolds(qs, now, now.Add(-30*24*time.Hour), func(Record) *catalog.Price { return nil }, provider.Renames{}, dryRuns(qs, hist, now), func(fn func(Record)) { + got := windowHolds(qs, now, now.Add(-30*24*time.Hour), func(Record) *catalog.Price { return nil }, provider.Renames{}, nil, dryRuns(qs, hist, now), func(fn func(Record)) { for _, c := range calls { c.Provider, c.ProviderAccount, c.Model = "codex", "u", "m" fn(c)