diff --git a/docs/subsystems/providers-accounts.md b/docs/subsystems/providers-accounts.md index 5c9ed3a1e..587f36a4b 100644 --- a/docs/subsystems/providers-accounts.md +++ b/docs/subsystems/providers-accounts.md @@ -66,7 +66,7 @@ keys and accounts per request is in [Gateway routing and fallback](gateway-routi | 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. A ChatGPT account's card has an *Image generation* row (`WithImageLane`, [`image_lane.go`](../../internal/provider/image_lane.go), `Lane` `images`, Text and Aside so routing, holds and history never see it; hqqqqqqqh on X, #6160): ChatGPT's images have a quota apart from the 5-hour and weekly windows, and neither `/wham/usage` (`additional_rate_limits` is null) nor the reply headers (`x-codex-primary-*`, `x-codex-secondary-*`) tell it. So the row says *Used up* with the reset time while the image model is resting on that account after a refusal (`ImageRest`, the gateway's `restingUntil`, whose time is the refusal's `resets_at`, #2244) and *Unknown* otherwise, never a share or a count (`TestWithImageLaneOnlyReadCodexCards`, `TestCodexImageRowIsTheRefusalsResetTime`, `codex-image-row.test.cjs`). Not done: the count of images made in the window. Each key of a remote-magpie provider also gets a card of its own, under `/~keys`, one section per key (#1547, `remoteKeyCards` in `remote_key_limits.go`): the gateway key's limit as that magpie holds it, read from `GET /v1/magpie/limit` asked with that key alone, so a key never sees another's numbers. It shows a window per cap (tokens, spend) named for the period, used against the cap, with its reset, plus `GatewayKey` (what is left, calls, a cycle of days, used up); a key held to no limit shows `Unlimited`. It is kept for `remoteCardsFor` like the remote's cards and read again by the card's refresh (`?provider=/~keys&user=`). A read that fails keeps the last numbers, dated (`AsOf`); with none the card says why, never zero or no limit. A remote from before `/v1/magpie/limit` (404) says it is too old to tell (`errRemoteNoKeyLimit`). A remote's Codex card keeps its `Resets` (not a GLM team's, `ByWindow`), and its check-ins are dropped: **Use one…** there goes through `/api/usage/codex-reset` with the card's `provider`, and `UseRemoteCodexReset` asks the remote's `POST /v1/magpie/quotas/codex-reset?user=` with the provider's key (#3850). The remote spends it with `SpendCodexReset`, the same function as the Usage page (`UseCodexResetCard`, then `AwaitAllowance`). The account is always named. A 403 `gateway_key_read_only` is told as a read-only key there, and a 404 as a remote too old. No answer within `RemoteResetWait` says the reset may have been used, and it is never asked again by itself. A remote that holds the key to a budget, models or accounts answers its cards 403 `gateway_key_held` (#1981, `errKeyHeld`): the cards kept from before are dropped, and beside the key's own card the remote's card says it tells this key no quotas, and that on that computer Quotas is turned on for the key and it is let use every model of a provider whose usage it is to see (`errRemoteHeld`; yi_time on Discord saw the remote's Claude vanish from every page with no word). Its owner can let the key be told the cards of what it may use (#2216, `magpie gateway-key quotas on`); the remote then answers those, and 403 held as before when that is none (`writeCards`), so that key shows the same card. A remote's cards are kept by provider and key (`remoteCardsID`), so a changed key never shows what the old one was told, and a read is kept only over one asked before it (`keepRemoteCards`). 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. The quota cards a Remote passes on follow the same ways (X on 0.1.3678: A → B → C → A told Kiro and Codex by `remote-B/kiro` and `remote-B/remote-C/remote-A/remote-B/remote-C/kiro`, hours apart, to a Remote enabled for one local model): a card's `via` that names any magpie twice is a loop too, so one that came round after this magpie restarted (its old `Self` is no longer this one's) is left out (`catalog.Loops`), and isn't kept in `remoteCardCache` (`keepRemoteCards`). A Remote's cards are shown, and passed on, only for the providers it is enabled for: the first part of the card's provider id must be the first part of an exposed model's id there (`remoteCardWanted`), unknown, so all shown, while its list isn't read. One subscription account's copies (same provider, same `user`) are one card, the newest complete reading, then the shorter way (`oneCardPerAccount`, in `RemoteCards` and `CachedCards`; a key's cards, whose `user` is a name two keys may share, are not merged) (`TestRemoteCardsFollowEnabledModelsAndDedupe`, `TestLoopsOnARepeatedMagpie`). | [`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), [`remote_quotas_scope.go`](../../internal/provider/remote_quotas_scope.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. The quota cards a Remote passes on follow the same ways (X on 0.1.3678: A → B → C → A told Kiro and Codex by `remote-B/kiro` and `remote-B/remote-C/remote-A/remote-B/remote-C/kiro`, hours apart, to a Remote enabled for one local model): a card's `via` that names any magpie twice is a loop too, so one that came round after this magpie restarted (its old `Self` is no longer this one's) is left out (`catalog.Loops`), and isn't kept in `remoteCardCache` (`keepRemoteCards`). A Remote's cards are shown, and passed on, only for the providers it is enabled for: the card's provider id must be the provider path of an exposed model there (its id less the last part, or a parent of it, whole parts only: relay/strata enabled tells relay/strata, never relay/kiro; `remoteCardWanted`, `cardWantedFor`, `TestRemoteCardWantedByWholePath`, 748975219 on X), unknown, so all shown, while its list isn't read. One subscription account's copies (same provider, same `user`) are one card, the newest complete reading, then the shorter way (`oneCardPerAccount`, in `RemoteCards` and `CachedCards`; a key's cards, whose `user` is a name two keys may share, are not merged) (`TestRemoteCardsFollowEnabledModelsAndDedupe`, `TestLoopsOnARepeatedMagpie`). | [`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), [`remote_quotas_scope.go`](../../internal/provider/remote_quotas_scope.go) | | A remote magpie that moved | Computer A's router hands it a new address now and then (luckymanjc on Discord), and B's Remote magpie, saved at the old one, reached nothing. When B can't connect to it at all (a dial error, `unconnected`), its list fetch (`fetch` in [`models.go`](../../internal/provider/models.go)) and the gateway's request (`forward` in [`gateway.go`](../../internal/gateway/gateway.go)) call `SeekMoved` ([`remote_moved.go`](../../internal/provider/remote_moved.go)): every address of the old one's /24 and of up to four of B's own private /24s is dialled at A's port (500ms each, 128 at once, `lanNeighbours`). Whatever takes the connection there may be anyone's (a café's network, A switched off), so it is sent neither the key nor the provider's headers until it proves it holds the key (`proves`): B POSTs a nonce of its own and `RemoteKeyID` (the key's sha256, hex) to `RemoteProvePath` (`/v1/magpie/prove`) with no key and no proxy, and checks with `hmac.Equal` that the answer is `RemoteProof`: HMAC-SHA256 under the key of the nonce and the address B dialled. A answers it ([`remote_prove.go`](../../internal/gateway/remote_prove.go)) for an enabled gateway key of that id (`access.ProveSecret`: constant-time compares over every key, then `Check`) at the address the connection reached it on (`http.LocalAddrContextKey`), so a host passing B's nonce on to A elsewhere hands back a proof for A's address, not its own; 404 for a key it hasn't or has turned off. Only an address that proved is asked `/v1/models` with the key, and the first that lists 200 and whose list this magpie didn't make (`magpie_via`) is saved as the provider's address and asked again. A magpie from before the route, one behind a port forward or NAT (it is reached at another address than its own), or one behind a proxy that needs the provider's headers, is not found, and the user types the new address. A name or a public address is never looked around, an address the user changed meanwhile stands, and a provider is looked for once a minute at most, callers at once sharing the look (`TestRemoteMagpieKeyGoesToNoNeighbour`: an impostor that lists 200 for anything, one with a proof under another key, one with a garbled proof and one relaying to the real magpie are sent no key or header and not saved, and the real one is; `TestRemoteProof`, `TestRemoteMagpieFoundMoved`, `TestRemoteMagpieNotFoundStays`, `TestRemoteMagpieMovedIsFound`, `TestRemoteProveAnswersOnlyTheKeysHolder`). | | A relay's Codex entries | A provider the user added by its address with a Responses URL may list its models in Codex's own shape (`slug`, `supported_reasoning_levels`, `shell_type`, `base_instructions`: `catalog.CodexEntry`), plainly or when asked with Codex's `client_version`, as sub2api does (ctopsc on Discord: GPT-6.1 Terra was handed models.dev's 922000 window where the relay said 272000). `fetchOne` keeps such a row whole (`catalog.Model.Codex`, with its window, max window and inputs read off it), and when the plain list has none it asks the same URL once more with `client_version` (`codexEntries`): only where the list is fetched (add, key change, Refresh), never per Codex poll. The answer only adds entries to models the plain list has; one that fails or can't be read keeps the last list's entries (failed read = unknown), one that answers plainly says there are none. `codexcat.listedEntry` hands Codex the relay's entry as given, `base_instructions` included, with magpie's slug, name, priority and " via magpie" description; the user's window, compaction, levels and image setting still win (levels keep the relay's descriptions). A saved list from before is enriched at its next Refresh. `TestCodexListedEntry`, `TestCodexListedEntryInPlainList`. | [`codex_entries.go`](../../internal/provider/codex_entries.go), [`live.go`](../../internal/catalog/live.go), [`codexcat.go`](../../internal/codexcat/codexcat.go) | | An endpoint's catalog | A key's provider with no catalog of its own (none named, none from a preset) is priced from the models.dev catalog whose `api` is one of its endpoints (`EndpointCatalog`, `catalog.AtEndpoint`; a trailing slash and case don't count, and an Anthropic base, kept as its root, is also matched with its `/v1`). Only when exactly one catalog is at that address, and it isn't a plan's (an id with `-plan`, or a `membershipCatalogs` one): a plan lists its membership's $0, and two catalogs at one address can't be told apart. A subscription's account never gets one. A provider at AMD's own endpoint is priced from `amd`, which lists Qwen3.8-27B at $0, a price, where its maker sells no such model and it had none (#2052); a relay's endpoint matches nothing and its model stays unpriced, never priced at a reseller's guess. `magpie model price` names the catalog, and says how to give a price when none is known. | [`models.go`](../../internal/provider/models.go), [`catalog.go`](../../internal/catalog/catalog.go) | diff --git a/internal/provider/remote_quotas_scope.go b/internal/provider/remote_quotas_scope.go index b0f0e8b3a..7976edda0 100644 --- a/internal/provider/remote_quotas_scope.go +++ b/internal/provider/remote_quotas_scope.go @@ -15,9 +15,10 @@ import ( // the same account at different hours). // // - A card is shown for a Remote only when the Remote is enabled for a -// model of the provider the card is of (remoteCardWanted): the first -// part of the card's id is the first part of those models' ids -// (provider/model, as that remote lists them). +// model of the provider the card is of (remoteCardWanted): the +// card's id is the provider path of one of those models' ids, or a +// parent of it, whole parts only (provider/model, as that remote lists +// them; relay/strata enabled does not tell relay/kiro). // - A card whose way names a magpie twice, or this one and another, is // no card (catalog.Loops): it isn't kept (keepRemoteCards) nor told. // - One account's copies are one card, the newest complete reading @@ -35,18 +36,37 @@ func remoteCardWanted(p Provider) func(id string) bool { if len(ms) == 0 { return func(string) bool { return true } } - heads := map[string]bool{} - for _, m := range ms { - head, _, ok := strings.Cut(m.ID, "/") - if !ok { + ids := make([]string, len(ms)) + for i, m := range ms { + ids[i] = m.ID + } + return cardWantedFor(ids) +} + +// cardWantedFor is remoteCardWanted for the enabled model ids as the remote +// lists them: a model's provider path is its id less the last part +// ("relay/strata/m" is of relay/strata). A card is wanted when its id is +// such a path or one of its parents, whole parts only: relay/strata +// enabled tells relay/strata and relay, never relay/kiro or relay/strat. +// A model with no provider before its name leaves it unknown, so wanted. +func cardWantedFor(ids []string) func(id string) bool { + paths := map[string]bool{} + for _, mid := range ids { + i := strings.LastIndex(mid, "/") + if i <= 0 { return func(string) bool { return true } } - heads[head] = true - } - return func(id string) bool { - head, _, _ := strings.Cut(id, "/") - return heads[head] + path := mid[:i] + for { + paths[path] = true + j := strings.LastIndex(path, "/") + if j < 0 { + break + } + path = path[:j] + } } + return func(id string) bool { return paths[id] } } // withoutLoops is cards less those whose way comes back to this magpie. diff --git a/internal/provider/remote_quotas_test.go b/internal/provider/remote_quotas_test.go index e5710611d..80e617b32 100644 --- a/internal/provider/remote_quotas_test.go +++ b/internal/provider/remote_quotas_test.go @@ -668,3 +668,36 @@ func TestRemoteCardsFollowEnabledModelsAndDedupe(t *testing.T) { } } } + +// @748975219 on X (0.1.3771): with only relay/strata/model enabled, the +// cards of relay/kiro and relay/codex still passed, as only the first part +// of the card's id was compared. +func TestRemoteCardWantedByWholePath(t *testing.T) { + cases := []struct { + name string + ids []string + yes []string + no []string + }{ + {"two levels", []string{"relay/strata/m"}, []string{"relay/strata", "relay"}, []string{"relay/kiro", "relay/codex", "kiro", "relay/strata/x"}}, + {"three levels", []string{"a/b/c/m"}, []string{"a/b/c", "a/b", "a"}, []string{"a/b/d", "a/x", "a/b/c/d", "b"}}, + {"not at a boundary", []string{"relay/kiro/m"}, []string{"relay/kiro"}, []string{"relay/kir", "relay/kiro2", "relay/kiroo", "rel"}}, + {"prefix of the other way", []string{"relay/kir/m"}, []string{"relay/kir"}, []string{"relay/kiro"}}, + {"several", []string{"relay/strata/m", "relay/kiro/n"}, []string{"relay/strata", "relay/kiro"}, []string{"relay/codex"}}, + {"one level", []string{"kiro/m"}, []string{"kiro"}, []string{"codex", "kiro/x"}}, + {"unknown provider", []string{"m"}, []string{"anything", "a/b"}, nil}, + } + for _, c := range cases { + w := cardWantedFor(c.ids) + for _, id := range c.yes { + if !w(id) { + t.Errorf("%s: %v should tell %q", c.name, c.ids, id) + } + } + for _, id := range c.no { + if w(id) { + t.Errorf("%s: %v should not tell %q", c.name, c.ids, id) + } + } + } +}