From 08a42c40ff6552b9c01bfdfe0f8b2d2c05ca3cf1 Mon Sep 17 00:00:00 2001 From: yetone Date: Mon, 9 Nov 2026 12:27:57 +0800 Subject: [PATCH] provider: a Remote magpie's cards are passed on down a chain of magpies MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit yuyong_id (Discord) chains three magpies through Remote: magpie1 has a Codex subscription, magpie2 uses magpie1, magpie3 uses magpie2. magpie2 showed magpie1's Codex card; magpie3 showed none. Cause: since 8c71cd27f a magpie told only its own cards (CachedCards kept From == "") and the receiver skipped any card it was told with a From (remoteCards). So no card from a remote, of any provider, reached a third magpie; Codex wasn't special. Antigravity and DeepSeek showing at magpie3 means magpie2 has those accounts itself (not checked with the reporter). Fix: - CachedCards passes on the cards it already holds from each Remote magpie (passedOnCards, from the 30s cache: it asks no remote, and a held remote's cards stay home). - Each card told carries Via, the magpies (catalog.Self) it passed through; a receiver leaves out a card that comes back to it or has passed more than MaxVia magpies (catalog.Loops, the same rule as magpie_via for models). - Refresh on a passed-on card ("m1/codex" at magpie2) goes to RefreshUsage, which asks that remote again, instead of a 400. - Sibling: the status line (KeptQuotaReport, /v1/magpie/quotas?kept=1) read CachedCards too, so a magpie's own Remote cards were missing from it; now there. - A held key still sees only own cards (quotaScope unchanged). - Codex's resets stay with the magpie next door only, as before. - catalog.Self becomes a func with SetSelfForTest, so one test process can play magpie2 and then magpie3. Run on mote at b9cdac0c6 (rebased on origin/main 8a7f77cb7): - gofmt -l clean; go vet ./...; GOOS=linux go vet -tags nogui ./...; GOOS=windows go vet ./...; go build ./...: ok. - New TestRemoteChainPassesOnCards (magpie1 fake -> this gateway as magpie2 -> magpie3 reading it: Codex, Antigravity, GLM plan and a DeepSeek balance arrive, named "Codex · M1 · M2", Via [m1 m2], refresh reaches magpie1, a looped card is dropped), TestKeptReportHasRemoteCards and the updated TestRemoteMagpieCards, with TestRemoteMagpie*, TestRemoteSelf, Quota* and TestCachedCards: ok; -race -count=3 on the new and changed ones: ok. - On origin/main with only these tests (and the Via field / Self func they compile against): all three FAIL. magpie3 gets just the "nothing read on that magpie yet" stand-in for magpie2, the kept report is empty, and the third magpie's card is nil. - Full suite (-tags nogui -timeout 45m ./... under the suite lock): cut short when mote closed the connection, before any package reported. Rerunning at the pushed head. - Rebased again onto origin/main e0f6eda64 (gateway changed): go vet of gateway, provider and catalog and the same targeted tests: ok on Linux (wsl-run magpie-desktop, -tags nogui); mote was refusing ssh. Not tried: three real magpies on separate machines. Not changed: a passed-on card's quota history (#5747). Reported-by: yuyong_id (Discord) --- docs/subsystems/providers-accounts.md | 2 +- internal/catalog/magpie_via.go | 27 +++- internal/gateway/gateway.go | 8 +- internal/gateway/quotas_chain_test.go | 191 ++++++++++++++++++++++++ internal/provider/remote_quotas.go | 52 ++++++- internal/provider/remote_quotas_test.go | 23 ++- internal/provider/subscription_usage.go | 5 + 7 files changed, 292 insertions(+), 16 deletions(-) create mode 100644 internal/gateway/quotas_chain_test.go diff --git a/docs/subsystems/providers-accounts.md b/docs/subsystems/providers-accounts.md index e4b280e7c..e4be16d78 100644 --- a/docs/subsystems/providers-accounts.md +++ b/docs/subsystems/providers-accounts.md @@ -59,7 +59,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 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). What a pattern matches follows the members named, in the catalog's order, until the user drags it elsewhere (usrname1833 on Discord): `Placed` keeps the whole order, named and matched alike, and the group is read and routed in it (`placedIn`); a model matched since goes last, one no longer matched drops out, a save that sends the named members only leaves the matched where they were (`placedOver`), and a provider's or group's rename carries it (`TestGroupPatternMembersKeepTheirPlace`, `group-member-drag.test.cjs`). A found group follows the providers magpie has: one removed leaves it, while one switched off stays in it (`foundGroups`, `heldOffEntries`; one without a key, such as a plugin not signed in, finds no group), skipped by `membersIn`, left off a found group's card, logos and TUI line with a count of those switched off (XYenon on Discord: `routing-provider-off.test.cjs`, `TestFoundGroupLineLeavesASwitchedOffProviderOut`) and said as switched off in its editor and the TUI's group page, so switching one of two providers off for a while doesn't take the group away from the agents, rules and groups set to it; it is back in its place once on again (#2671: `TestFoundGroupStaysWithAProviderOff`, `TestFoundGroupWithAProviderOff`, `TestReseatKeepsAFoundGroupWithAProviderOff`, `TestFoundGroupMemberOfASwitchedOffProvider`). A found group the user changed (an `auto-…` id stored) is read without the members of providers magpie no longer has (`withoutRemoved`, not written back, so a provider back under its id is back in it), except a manual group's pick, a rule's model, or all of them when none would be left. It keeps following its model as a found group does (Kxsg79bEYFP4 on X: a third provider with the model, a plugin's, had stayed out of a group the user had changed): `SaveGroup` stores, for an `auto-…` id, what it had seen (`Group.Seen`: the models magpie found in it by that save, and those the user named, as `provider/model`), and a provider that serves the model since joins it as it is read, after the user's own members (`joined`, not written back), unless kept out of found groups. A model seen and not a member is one the user took out, and stays out; a provider's rename or a fold carries `Seen` (`mapModelRefs`), and a shared group leaves it behind. A found group changed before `Seen` was kept takes in nothing, as nothing says which of its models the user took out; its next save sees what is found then (`TestChangedFoundGroupTakesInANewProvider`, `TestChangedFoundGroupFromBeforeKeepsItsMembers`, `TestChangedFoundGroupTakesInAPluginProvider`). A switched-off provider's members stay in it, skipped by `membersIn`, and the Routing groups page says them as switched off (`memberJSON.providerOff`). The user's own groups keep their members. Three templates make a group in one click from the models the user has (`provider.Templates`, `AddTemplate`; the Routing groups page's cards before a first group and its Templates menu after, `magpie group template [kind] [name]`): `smart` sends a hard turn to the strongest model and an easy one or a compaction to a cheap one, asked by a classifier (the decision API when there is one, else the cheapest priced model that doesn't reason); `thrifty` starts on two cheap models of different providers and sends high reasoning to the strongest; `steady` fails over between the strongest model of up to three providers. A model is weighed by its maker's list price when known, else what its provider charges, else by its id's size words (`sizeOf`); one over `tooDear` (USD 100 a million output tokens) is never picked. A template that can't be made says what is missing (`Need`). It is saved under a name and id no group has (`freeGroupName`, shared with `CopyGroup`), never over one. A group is shared as text (`ShareGroup`, a group row's Copy to share): JSON marked `"magpie": "routing-group"` with a format `version` (`ShareVersion`), holding the group's members as it names them, patterns, routing, rules, classifier and settings. A group holds only `provider/model` ids, never a key, account or address, and the derived matches, found/hidden/off flags and the rules that hold by a folder (a path on the sharer's machine, `Rule.Folders`) stay behind; a pasted one is left out too. `ImportGroup` (the Routing groups page's Import, `POST /api/groups/import`) reads it with words or a code fence around it, refuses another text, a newer format or none (`ShareError`, said in the reader's language). A member whose provider the importer has is kept; else the same model (`AutoGroupOf`) under the first provider of theirs that serves it (`Instead`); else it is left out and named (`Missing`), with the rules that send to it, its place among the off and fast members, and a classifier gone takes the intent rules and auto effort with it. Nothing is added when no member is left; what is added gets a free name, never replacing a group. A group of patterns only that match nothing now (a plugin's models not listed) has no members: `/api/groups` says them, and an unmakeable template's, as `[]`, never `null`; the Routing groups page reads the response through `groupsFrom` and draws a group it still can't draw as one row saying so, so one bad group never hides the rest (#1585). | [`group.go`](../../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`). 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 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`). A single card can be read again on its own (#840). A remote magpie's cards come from what it has kept (`CachedCards`, `GET /v1/magpie/quotas/cards`) and are never read there for this computer except by a card's refresh (`POST /v1/magpie/quotas/refresh`, throttled per card). What it has kept is the Usage page's cards with the readings made behind the requests since laid over them, a later one over an earlier by `readSeq` (`cards_kept.go`): each account's `LoginUsage` reading (the used-up switch, the Codex warm-up, routing's `Allowances`), and each key's `KeyAllowance` windows on its plan or balance card. A Claude account's windows Claude Code told as it answered (`NoteClaudeLimits`, kept in `claudeUsage` with their own `heardSeq`, which drops the account's `LoginUsage` reading) stand on its card over any reading started before them (`withHeardClaude`, #2206), so a magpie only requests reach still tells them. An account or key read that way and never on the page gets a card from that reading, and after a restart, before either is read again, the cards come from `quotas.json`, dated (`AsOf`). A magpie serving only other magpies has nobody on its page (#1313). What it has kept includes its own Remote magpies' cards as it last read them (`passedOnCards`, no remote asked), so a chain passes every card on (yuyong_id on Discord: magpie3 → magpie2 → magpie1 showed none of magpie1's Codex at magpie3), named after each magpie (`magpie2/magpie1/codex`, "Codex · magpie1 · magpie2"); the card standing for a remote and its keys' limits stay the reader's own. Each card carries `via`, the `catalog.Self` of each magpie it went through, and a reader leaves out one that loops (`catalog.Loops`, as a model's `magpie_via`). A refresh of such a card is passed to the magpie it came from (`quotaCardsRefresh` takes a card id this magpie has from a remote); a Codex reset is offered on the magpie next door only, and quota history isn't passed on. The status line's kept report (`KeptQuotaReport`) has a remote's cards the same way. Each key of a remote-magpie provider also gets a card of its own, under `/~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/catalog/magpie_via.go b/internal/catalog/magpie_via.go index fb63bf43b..67d3b4397 100644 --- a/internal/catalog/magpie_via.go +++ b/internal/catalog/magpie_via.go @@ -5,6 +5,7 @@ import ( "encoding/hex" "slices" "sync" + "sync/atomic" ) // Two magpies can each be the other's Remote magpie (cdredfox on Discord: @@ -35,12 +36,31 @@ const MaxVia = 8 // Self is this run of magpie's name in magpie_via: random, made up once a // run, and told only to a magpie that asks for its list. -var Self = sync.OnceValue(func() string { +func Self() string { + if s := selfForTest.Load(); s != nil { + return *s + } + return self() +} + +var self = sync.OnceValue(func() string { b := make([]byte, 8) rand.Read(b) return hex.EncodeToString(b) }) +// selfForTest stands for Self while a test plays another magpie +// (SetSelfForTest). +var selfForTest atomic.Pointer[string] + +// SetSelfForTest has Self be s, for a test that plays several magpies +// in one process one after another, until the returned func puts it +// back. +func SetSelfForTest(s string) (restore func()) { + was := selfForTest.Swap(&s) + return func() { selfForTest.Store(was) } +} + // loops reports whether a model another magpie lists by way of via leaves // this magpie and comes back to it. func loops(via []string) bool { @@ -50,6 +70,11 @@ func loops(via []string) bool { return len(via) > 1 && slices.Contains(via, Self()) } +// Loops reports whether what another magpie passes on by way of via (a +// model's magpie_via, a quota card's Via) leaves this magpie and comes +// back to it, or has passed through more magpies than MaxVia. +func Loops(via []string) bool { return loops(via) } + // ViaHere is the magpie_via a model goes out with in this magpie's list // to another: the way it came here by, when it came from another magpie, // then this one. diff --git a/internal/gateway/gateway.go b/internal/gateway/gateway.go index 3e09bc2f9..5245b54db 100644 --- a/internal/gateway/gateway.go +++ b/internal/gateway/gateway.go @@ -1207,8 +1207,12 @@ func (s *Server) quotaCardsRefresh(w http.ResponseWriter, r *http.Request) { return } id, user := r.URL.Query().Get("provider"), r.URL.Query().Get("user") - if strings.Contains(id, "/") || provider.IsRemoteCard(id) { // a card this magpie has from another: not passed on - writeError(w, provider.Chat, http.StatusBadRequest, "this magpie reads only its own cards again") + // a card this magpie has from a Remote magpie of its own, which it + // passes on (provider.CachedCards), is read again there; the card + // standing for that remote itself, and any other id with a "/", is + // none this magpie tells + if remote := provider.IsRemoteCard(id); strings.Contains(id, "/") && !remote || remote && !strings.Contains(id, "/") { + writeError(w, provider.Chat, http.StatusBadRequest, "this magpie reads again only the cards it tells") return } // a key told only some cards (#2216) has only those read again: a diff --git a/internal/gateway/quotas_chain_test.go b/internal/gateway/quotas_chain_test.go new file mode 100644 index 000000000..6725a30bc --- /dev/null +++ b/internal/gateway/quotas_chain_test.go @@ -0,0 +1,191 @@ +package gateway + +import ( + "context" + "encoding/json" + "io" + "net/http" + "net/http/httptest" + "slices" + "sync" + "testing" + + "github.com/yetone/magpie/internal/catalog" + "github.com/yetone/magpie/internal/provider" +) + +// yuyong_id on Discord: magpie1 holds a Codex (ChatGPT) sign-in, magpie2 +// uses magpie1 as a Remote magpie, and magpie3 uses magpie2. magpie2 +// showed magpie1's Codex card; magpie3 showed none of it, as magpie2 +// told another magpie only the cards of its own accounts. Every kind of +// card magpie1 tells comes through to magpie3 now, named after both +// magpies; a refresh pressed at magpie3 reaches magpie1; a card that +// comes round to a magpie it went through is left out. +func TestRemoteChainPassesOnCards(t *testing.T) { + fresh(t) + t.Setenv("MAGPIE_ADDR", "") + // magpie1, as its gateway answers (CachedCards): its own cards, each + // with the way it came by, magpie1 alone + var mu sync.Mutex + var refreshes []string + m1 := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.Header.Get("x-api-key") != "sk-magpie-m1" { + w.WriteHeader(http.StatusUnauthorized) + return + } + switch r.Method + " " + r.URL.Path { + case "GET " + provider.RemoteCardsPath: + case "POST " + provider.RemoteRefreshPath: + mu.Lock() + refreshes = append(refreshes, r.URL.Query().Get("provider")+"|"+r.URL.Query().Get("user")) + mu.Unlock() + default: + w.WriteHeader(http.StatusNotFound) + return + } + io.WriteString(w, `{"object":"list","data":[ +{"provider":"codex","name":"Codex","icon":"codex-color","plan":"plus","user":"a@x.com","kind":"subscription","via":["m1"], + "windows":[{"name":"5h","used":37,"resetSecs":3600},{"name":"Week","used":12,"resetSecs":86400}],"resets":{"count":1}}, +{"provider":"antigravity","name":"Antigravity","icon":"antigravity","user":"g@x.com","kind":"subscription","via":["m1"], + "windows":[{"name":"Gemini","used":5}]}, +{"provider":"zhipu","name":"GLM Coding","kind":"plan","via":["m1"],"windows":[{"name":"5h","used":10}]}, +{"provider":"deepseek","name":"DeepSeek","kind":"balance","balance":"¥12.00","via":["m1"],"windows":[]}]}`) + })) + defer m1.Close() + + // magpie2: this process's gateway, magpie1 its Remote magpie + gw := httptest.NewServer(lanGuard(New().Handler())) + defer gw.Close() + if err := provider.Save(provider.Provider{ID: "m1", Name: "M1", Preset: provider.RemoteMagpiePreset, Key: "sk-magpie-m1", Chat: m1.URL}); err != nil { + t.Fatal(err) + } + ctx := context.Background() + // magpie2's Usage page reads magpie1's cards, as reported + var m2Codex bool + for _, q := range provider.RemoteCards(ctx) { + m2Codex = m2Codex || q.Provider == "m1/codex" && q.User == "a@x.com" + } + if !m2Codex { + t.Fatal("magpie2 doesn't show magpie1's Codex card") + } + m2Self := catalog.Self() + get := func(path string) []byte { + t.Helper() + res, err := http.Get(gw.URL + path) + if err != nil { + t.Fatal(err) + } + defer res.Body.Close() + b, _ := io.ReadAll(res.Body) + if res.StatusCode != 200 { + t.Fatalf("%s: %d %s", path, res.StatusCode, b) + } + return b + } + // what magpie2 tells magpie3, through its real handler + told := get(provider.RemoteCardsPath) + + // magpie3: another magpie, with magpie2 as its Remote magpie, told + // what magpie2's gateway told + defer catalog.SetSelfForTest("m3")() + m2 := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.Method+" "+r.URL.Path != "GET "+provider.RemoteCardsPath { + w.WriteHeader(http.StatusNotFound) + return + } + w.Write(told) + })) + defer m2.Close() + if err := provider.Save(provider.Provider{ID: "m2", Name: "M2", Preset: provider.RemoteMagpiePreset, Key: "sk-magpie-m2", Chat: m2.URL}); err != nil { + t.Fatal(err) + } + byID := map[string]provider.SubscriptionQuota{} + for _, q := range remoteOnly(provider.RemoteCards(ctx)) { + byID[q.Provider] = q + } + c, ok := byID["m2/m1/codex"] + if !ok || c.Name != "Codex · M1 · M2" || c.From != "M2" || c.User != "a@x.com" || c.Kind != "subscription" || + len(c.Windows) != 2 || c.Windows[0].Used != 37 || c.Windows[1].Used != 12 { + t.Fatalf("magpie1's Codex card at magpie3: %+v (all: %+v)", c, byID) + } + // a reset is spent on the magpie next door only (UseRemoteCodexReset) + if c.Resets != nil { + t.Errorf("a reset two magpies away is offered: %+v", c.Resets) + } + if !slices.Equal(c.Via, []string{"m1", m2Self}) { + t.Errorf("the Codex card came by %v, want [m1 %s]", c.Via, m2Self) + } + // every kind passes on alike + for id, kind := range map[string]string{"m2/m1/antigravity": "subscription", "m2/m1/zhipu": "plan", "m2/m1/deepseek": "balance"} { + if q, ok := byID[id]; !ok || q.Kind != kind { + t.Errorf("%s at magpie3: %+v", id, q) + } + } + if q := byID["m2/m1/deepseek"]; q.Balance != "¥12.00" { + t.Errorf("magpie1's DeepSeek balance at magpie3: %+v", q) + } + // magpie2's own stand-in for magpie1, and its key's limit there, are + // its own business with magpie1 + var cards []provider.SubscriptionQuota + json.Unmarshal(told, &struct { + Data *[]provider.SubscriptionQuota `json:"data"` + }{&cards}) + for _, q := range cards { + if q.Provider == "m1" || q.GatewayKey != nil { + t.Errorf("magpie2 told magpie3 its own card of magpie1: %+v", q) + } + } + + // a refresh pressed at magpie3 is read again at magpie1, by magpie2 + res, err := http.Post(gw.URL+provider.RemoteRefreshPath+"?provider=m1/codex&user=a@x.com", "", nil) + if err != nil { + t.Fatal(err) + } + res.Body.Close() + mu.Lock() + got := slices.Clone(refreshes) + mu.Unlock() + if res.StatusCode != 200 || !slices.Equal(got, []string{"codex|a@x.com"}) { + t.Errorf("magpie3's refresh of m1/codex: %d, magpie1 asked %v", res.StatusCode, got) + } + + // a card that went through this magpie before is left out: magpie3 + // told a card that came m3 → m2 shows nothing of it + told = []byte(`{"object":"list","data":[{"provider":"m2/codex","name":"Codex · M2","from":"M2","kind":"subscription","user":"loop@x.com","via":["m3","m2x"],"windows":[]}]}`) + provider.ForgetRemoteCardsForTest() + for _, q := range provider.RemoteCards(ctx) { + if q.User == "loop@x.com" { + t.Errorf("a card that came back round: %+v", q) + } + } +} + +// magpie2's status line (GET /v1/magpie/quotas?kept=1, KeptQuotaReport) +// is told its Remote magpie's cards as last read, as its Usage page shows +// them: a magpie whose Codex is another's had none on its status line. +func TestKeptReportHasRemoteCards(t *testing.T) { + fresh(t) + t.Setenv("MAGPIE_ADDR", "") + m1 := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + io.WriteString(w, `{"object":"list","data":[{"provider":"codex","name":"Codex","user":"a@x.com","kind":"subscription","via":["m1"],"windows":[{"name":"5h","used":37}]}]}`) + })) + defer m1.Close() + if err := provider.Save(provider.Provider{ID: "m1", Name: "M1", Preset: provider.RemoteMagpiePreset, Key: "sk-magpie-m1", Chat: m1.URL}); err != nil { + t.Fatal(err) + } + provider.RemoteCards(context.Background()) + r := httptest.NewRequest("GET", "/v1/magpie/quotas?kept=1", nil) + r.RemoteAddr = "127.0.0.1:5000" + w := httptest.NewRecorder() + lanGuard(New().Handler()).ServeHTTP(w, r) + var got struct { + Data []provider.Quota `json:"data"` + } + json.Unmarshal(w.Body.Bytes(), &got) + for _, q := range got.Data { + if q.Provider == "m1/codex" && q.From == "M1" && len(q.Windows) == 1 && q.Windows[0].Used == 37 { + return + } + } + t.Fatalf("kept report: %d %s", w.Code, w.Body) +} diff --git a/internal/provider/remote_quotas.go b/internal/provider/remote_quotas.go index 4c7360151..8fb2b06aa 100644 --- a/internal/provider/remote_quotas.go +++ b/internal/provider/remote_quotas.go @@ -105,8 +105,11 @@ const errRemoteUnreachable = "couldn't reach the remote magpie" // CachedCards is the Usage page's cards as this magpie last read them, // each with its kind, for another magpie to show: no vendor is asked, -// whatever their age, and another magpie's cards shown here aren't -// passed on. +// whatever their age. The cards a Remote magpie gave this one, as last +// read from it (passedOnCards), are passed on too, so a magpie that +// uses this one sees the accounts behind it as well (yuyong_id on +// Discord: a third magpie in a chain had none of the first's Codex +// cards). Each card carries the way it came by, this magpie last (Via). // // The cards are the page's with what was read of the same accounts and // keys behind it since (cards_kept.go): a magpie serving only other @@ -146,10 +149,36 @@ func CachedCards(now time.Time) []SubscriptionQuota { for _, q := range g.qs { if q.From == "" { q.Kind = g.kind + q.Via = catalog.ViaHere(nil) out = append(out, q) } } } + return append(out, passedOnCards()...) +} + +// passedOnCards are the cards of each Remote magpie this one uses, as +// last read from it (remoteCards, at most 30 seconds old while anything +// here shows them): no remote is asked, so a chain of magpies, or two +// that are each the other's Remote, never asks along itself. A remote +// read nothing from, or holding this magpie's key (errKeyHeld), passes +// on nothing; the card standing for the remote itself and its keys' +// limits (remoteKeyCards) are this magpie's own business with it. +func passedOnCards() []SubscriptionQuota { + var out []SubscriptionQuota + for _, p := range remoteMagpies() { + c := &remoteCardCache + c.Lock() + r := c.m[remoteCardsID(p)] + c.Unlock() + if r.held { + continue + } + for _, q := range namedRemoteCards(p, r.cards) { + q.Via = catalog.ViaHere(q.Via) + out = append(out, q) + } + } return out } @@ -266,9 +295,22 @@ func remoteCards(ctx context.Context, p Provider, fresh bool) []SubscriptionQuot } return []SubscriptionQuota{{Provider: p.ID, Name: name, Icon: "magpie", Kind: "subscription", From: name, Windows: []QuotaWindow{}, Error: msg}} } - out := make([]SubscriptionQuota, 0, len(r.cards)) - for _, q := range r.cards { - if q.From != "" || q.Provider == "" { + return namedRemoteCards(p, r.cards) +} + +// namedRemoteCards is cards, as the remote magpie p told them, named for +// this computer. A card p has from a magpie behind it (its own Remote +// magpie, yuyong_id on Discord: magpie3 → magpie2 → magpie1, and +// magpie3 had magpie1's Codex card from nobody) comes with the way it +// came by (Via) and is named after it ("Codex · magpie1 · magpie2", +// "magpie2/magpie1/codex"); one whose way leaves this magpie and comes +// back to it (two magpies each the other's Remote) is left out, as a +// model listed that way is (catalog.Loops). +func namedRemoteCards(p Provider, cards []SubscriptionQuota) []SubscriptionQuota { + name := remoteName(p) + out := make([]SubscriptionQuota, 0, len(cards)) + for _, q := range cards { + if q.Provider == "" || catalog.Loops(q.Via) { continue } q.Provider = p.ID + "/" + q.Provider diff --git a/internal/provider/remote_quotas_test.go b/internal/provider/remote_quotas_test.go index 75321d55f..e29c5894f 100644 --- a/internal/provider/remote_quotas_test.go +++ b/internal/provider/remote_quotas_test.go @@ -11,6 +11,8 @@ import ( "sync/atomic" "testing" "time" + + "github.com/yetone/magpie/internal/catalog" ) // fakePeer is another magpie's gateway as RemoteCards asks it: its kept @@ -102,8 +104,10 @@ func remoteQuotaHome(t *testing.T, peer http.Handler) { // 莫 on Discord: a computer whose providers are another's magpie showed // no quota at all. It now shows the other magpie's cards, named with it // and kept apart from its own by id, in their kinds; what a card's -// buttons would do to this computer's accounts is left off, and a card -// the other magpie has from a third isn't passed on. +// buttons would do to this computer's accounts is left off. A card the +// other magpie has from a third is shown too, named after both +// (yuyong_id on Discord), with no reset to spend from here; one that has +// been through this magpie before is left out (a loop). func TestRemoteMagpieCards(t *testing.T) { peer := &fakePeer{cards: []SubscriptionQuota{ {Provider: "codex", Name: "Codex", Icon: "codex", User: "a@x.com", Kind: "subscription", Windows: []QuotaWindow{{Name: "5h", Used: 40}}, @@ -111,7 +115,9 @@ func TestRemoteMagpieCards(t *testing.T) { {Provider: "zhipu", Name: "GLM Coding", Kind: "plan", Windows: []QuotaWindow{{Name: "5h", Used: 10}}, Resets: &ResetCredits{Count: 2, ByWindow: true}}, {Provider: "deepseek", Name: "DeepSeek", Kind: "balance", Balance: "¥12.00"}, - {Provider: "home/codex", Name: "Codex · Home", Kind: "subscription", From: "Home"}, + {Provider: "home/codex", Name: "Codex · Home", Kind: "subscription", From: "Home", User: "b@x.com", Via: []string{"home-self", "office-self"}, + Windows: []QuotaWindow{{Name: "5h", Used: 20}}, Resets: &ResetCredits{Count: 1}}, + {Provider: "back/codex", Name: "Codex · Back", Kind: "subscription", From: "Back", User: "c@x.com", Via: []string{catalog.Self(), "office-self"}}, }} remoteQuotaHome(t, peer) ctx := context.Background() @@ -139,10 +145,14 @@ func TestRemoteMagpieCards(t *testing.T) { if b := find(balances, "office/deepseek"); b == nil || b.Balance != "¥12.00" { t.Errorf("balance: %+v", balances) } + h := find(subs, "office/home/codex") + if h == nil || h.Name != "Codex · Home · Office" || h.From != "Office" || h.User != "b@x.com" || len(h.Windows) != 1 || h.Windows[0].Used != 20 || h.Resets != nil { + t.Errorf("a third magpie's card: %+v", h) + } for _, qs := range [][]SubscriptionQuota{subs, plans, balances} { for _, q := range qs { - if strings.Contains(q.Provider, "home") { - t.Errorf("a third magpie's card passed on: %+v", q) + if strings.Contains(q.Provider, "back") { + t.Errorf("a card that came back through this magpie: %+v", q) } } } @@ -233,8 +243,7 @@ func TestRemoteMagpieUnreachable(t *testing.T) { } // The cards told to another magpie are this one's as last read: nothing -// is read for it, however old they are, and another magpie's aren't -// passed on. +// is read for it, however old they are. func TestCachedCardsAskNobody(t *testing.T) { azureHome(t) c := &subscriptionUsageCache diff --git a/internal/provider/subscription_usage.go b/internal/provider/subscription_usage.go index 8dd31ba72..3b9571eb2 100644 --- a/internal/provider/subscription_usage.go +++ b/internal/provider/subscription_usage.go @@ -240,6 +240,11 @@ type SubscriptionQuota struct { // From is the remote magpie a card is that one's (remote_quotas.go), // by its name here; "" for this computer's own. From string `json:"from,omitempty"` + // Via is the magpies (catalog.Self) a card told another magpie + // passed through, the one that read it first, this one last + // (CachedCards): the receiver leaves out a card that comes back to + // it (catalog.Loops). Only between magpies; nil here. + Via []string `json:"via,omitempty"` // LastServedAt is when the account, plan or key last answered a // request through this computer's gateway, nil when it hasn't in the // last 30 days (served.go); set by Quotas, never cached.