diff --git a/docs/subsystems/gateway-routing.md b/docs/subsystems/gateway-routing.md index a95dff065..cf3e12dea 100644 --- a/docs/subsystems/gateway-routing.md +++ b/docs/subsystems/gateway-routing.md @@ -43,7 +43,7 @@ removed records stay and turning them on again restores the groups as they were. | A found group's two ids | A group magpie found is listed (`/v1/models`, the catalog, the lists written into agents, the pickers, the CLI and TUI) as `auto/`: the model's id as a vendor spells it, dots kept and with no vendor prefix (`auto/claude-opus-5.5`; `provider.Group.Ref`, `spelledIn`), so a client that looks the part after the slash up on models.dev finds it (ZeroClover on X). The spelling is the one models.dev gives the model most (`catalog.Spelling`, its `normal` index: `glm-5.3-flash` whether the members serve `glm-5-3-flash`, Ark's dated id or `glm-5.3-flash`), so it no longer follows the order the providers were added in; for a model models.dev doesn't know, the first member's spelling it lists, else the first member's. The group's name comes from the same choice (`autoGroups`): the name models.dev gives that spelling (`catalog.NameOf`), else a vendor's own name for it, else the spelling itself; they were picked apart, a name of `glm-5-3-flash` beside `auto/glm-5.3-flash` (XYenon on Discord, `TestFoundGroupIDAndNameAreOneSpelling`). A found group the user changed keeps the name they saved. Every spelling it was listed by before is still the group (`CanonicalRef`), and `PublicRef` takes one to the spelling now. Its old id `group/auto-` is served forever. Inside magpie the group keeps that one id: `validateModel` takes `auto/` (with `:level` or `[1m]`) back to it with `provider.CanonicalRef` before key limits, routing, affinity and the usage log see the request, and the request body is rewritten to it, so both ids count as one group. A gateway key naming either id, `group/*` or `auto/*` passes for both (`allows` in `key_models.go`). `SaveGroup` stores a member, rule or classifier picked as `auto/` by the old id. An agent field magpie set to `group/auto-`, or to an `auto/` spelt otherwise than the group is listed now, moves to `auto/` on the next `SyncCatalog` (`agent.renameFoundGroups`, `TestFoundGroupMovedOffAnOldSpelling`), but only while its value is still what applied.json says magpie wrote; a value the user set or changed stays, and is still served. A pick of the group by its old id written now (`Agent.Apply`) is written as `auto/`. An agent's hidden, picked and ordered models saved by the old id hold for the new one (`PublicRef` in `visible.go`), and a bare model id still reaches its found group (`bareTarget`). Claude Code is given a dotted Claude version dashed, so it may send `auto/claude-sonnet-4-5`: that is the same group, and `Reseat` still moves an agent off it once the group is gone (`samePick`). `auto` is no provider id: `Save` and `Rename` refuse it for a new provider, and a plugin's `auto` is `auto-plugin` (`PluginID`). A provider of the user's saved as `auto` before keeps its models: while it exists, `auto/` is its model and found groups list as `group/auto-` (`autoRefsOn`). Hand-made groups stay `group/`. | [`internal/provider/autoref.go`](../../internal/provider/autoref.go), [`key_models.go`](../../internal/gateway/key_models.go), [`internal/agent/autoref.go`](../../internal/agent/autoref.go) | | A model's own id at a provider | A model the user lists by an id of theirs at a provider (a signed-in account's and a plugin's too; settings' `ModelIDs`, `magpie model id `, the editor's "Listed as"; [Providers and accounts](providers-accounts.md#runtime-path)) is that id everywhere the gateway names it: `/v1/models` and the lists written into agents (`Available`), `Resolve`, the routing groups and the group magpie finds for it (`auto/`, with every other provider serving that id), a gateway key's models, `X-Magpie-Model` and the usage log's `model`. Only the upstream request differs: every place that sends a wire name reads `settings.Wires()`, which is `ModelWires` with each `ModelIDs` entry turned round (`"/"` → the vendor's own id, wrapped by a `/*` wire), so the body, a Vertex path and the usage log's endpoint carry the vendor's id; an explicit `ModelWires` entry for that id wins. The vendor's reply names its own id, which the usage log, recent calls and the Routing page keep as `served`; the agent gets the id it asked for back in the reply, in every protocol, streamed or whole (`memberWriter` in [`member.go`](../../internal/gateway/member.go), `replyNamingOf`: the reply's `model`, Responses' `response.model`, Anthropic's `message.model`, Gemini's `modelVersion`; issennknight on Discord, whose agent warned that `deepseek-v4.1-flash` came back as `deepseek-v4.1-flash-1017`). The same holds for a group or a `provider/model` id the vendor knows by another name. A reply whose vendor sent the wire name as asked keeps the vendor's name (a dated `-20261017` included). Settings' `replyModel` (Settings › Models › Replies › Model name in replies) picks for every request: `""` the model asked for, `member` the group's member, `vendor` the vendor's own name, as before the asked-for name, each for every agent, Claude Code, Claude Desktop and Codex included (ZoeCats on Discord: in v0.1.2760 `member` still gave those three the model asked for; `TestPluginReplyNamesMember` holds it on a plugin too). A file from before it with `memberModel` on reads as `member`, and `memberModel` is written beside `replyModel` for an older magpie (`normal` in settings.go; `Merge` in settingsapi takes an older page's `memberModel` only when its switch moved). A request's `X-Magpie-Response-Model` (`asked`, `member` or `vendor`) overrides the setting for that request, for every agent (`TestReplyNamesAskedModel`, `TestGeminiReplyNamesAskedModel`, `TestReplyNamesMember`, `TestReplyModelFoldsMemberModel`, `TestReplyModelSaves`). A request still naming `provider/` (an agent's file magpie didn't rewrite) resolves and goes out as it is. A key held to either id passes for both (`modelAllowed` checks the ref, then `OwnModelID`, then `ListedModelID`); a group member passes the same way. An id is given to a model of the provider's chat list or its picks; the image, video and embeddings routes send no wire name, so they are not served under one (`TestLocalModelIDOnEveryRoute`). At an account or a plugin the account's own say of the model is read by the vendor's id: a plugin's API and fetch, Claude Code's `--model`, Antigravity's variant, and which accounts list it and at what levels (`TestLocalModelIDAtAPlugin`, `TestLocalModelIDAtAClaudeAccount`, `TestLocalModelIDAtAnAntigravityAccount`). | [`internal/provider/localid.go`](../../internal/provider/localid.go), [`internal/settings/settings.go`](../../internal/settings/settings.go), [`key_models.go`](../../internal/gateway/key_models.go) | | Candidates | `plan` lists one provider's candidates: one per key or account on, then each `Fallback` model, with resting ones last (`restLast`). A fallback the user unchecked in its own provider's model list is skipped, as a group's member is (`provider.ResolveRoute`, #3911; `fallback_unpicked_test.go`), and so is it where fallbacks are read for careful accounts, native compaction, redaction and Codex's own turns. A fallback can be a routing group (`group/`, 01huadalang on Discord): `planPaused` hands its members to `planLevel` as a request to the group would (`planFallbackGroup`), in the group's own routing and sink, its pause rules applied in `serve`, and its trace rows marked `Fallback` with the group in `Via`. Its turn rules (`ruleFor`, which may ask a classifier) are not applied: the plan is made before the primary is tried, and a classifier call on every request the primary answers costs too much. Each provider/model is tried once a round: a member that is the primary, an earlier fallback or another fallback group's is left out where it came second, so a group holding this provider is no loop (groups have no fallbacks of their own, and a member's are not followed). A group that is gone is passed over. Every place that reads fallbacks (careful accounts, native compaction, redaction, Codex's own turns, Claude's review) reads a group's members through `provider.FallbackModels`. `fallback_group_test.go`. `planGroup` and `planLevel` weigh a group's members together. A nested group plans by its own routing (#576); one left on the default (Smart) in a group that pools (Smart, In turn, Least used, Use before expiry, Free first, Speed first, a plugin's) takes the outer group's, as a provider left on the default does (`provider.Group.Within`, set on `Member.Via`, so the trace's `Subs` and the Routing page read the routing that applies, #3847). In a group In order, By weight or Manual it stays Smart. `TestFreeFirstReachesAGroupInItLeftOnTheDefault`. So does a member whose provider routes other than Smart (`ownRouting`): weighed as one by its first not resting (`firstAwake`), tried whole in its own order; `leastHeld` leaves such a group's order alone too. A provider on Smart, or routed as the group is, is pooled with the group's other keys and accounts. `group_own_routing_test.go`. A member's own fallbacks are not the group's. | [`fallback.go`](../../internal/gateway/fallback.go) | -| Order of keys and accounts | `Routing`: smart (""), `order`, `rotate`, `usage` (least used, with an `usageHalfLife` of 1h), `pace`, `weight`, `free` (free first), `fast` (speed first), `drain` (until used up) or, a group's only, `cheap` (cheapest first) or `expiring` (free quota by expiry). `weighRouted` reads each candidate into a `routes.Seat` and asks the strategy serving its routing (`routes.Find`, the router strategy point of [the plugin runtime](plugin-runtime.md#gateway-extension-points-p3-router-strategy)) for the order: Smart is `routes.Smart`, the core's; the others are `routes.Builtin`, registered by the built-in plugin `rotation`. With it off a routing no strategy serves is tried in its listed order, and `routingOf` treats it as `order` wherever the core asks about a routing (a turn's mark, `goesRound`, `sinks`, a rotate group's sessions, a group's heads). Smart, `usage` and `pace` weigh a subscription by its allowance (`allowances`), and a key by its own usage windows when magpie reads them (`keyAllowance`: a sub2api key given a 5-hour, day or 7-day limit, or a key bought as a plan, such as Kimi Code's or a GLM Coding Plan's); any other key has none. Among accounts a plugin reads as prepaid wallets (a window's `balance`, #3950), Smart, `usage` and `pace` put the one with more left first where they would otherwise tie, only within one provider and unit (`routes.Seat.Left`/`LeftIn`, see [provider plugins](provider-plugins.md#a-wallets-balance)): each kind is ordered in the places its own seats take, so a group weighing several providers' accounts as one pool orders each provider's wallets too (#4095, `TestGroupWalletsGoByWhatTheyHaveLeft`). `free` weighs by what a model costs there and nothing else: only a strategy with `routes.Strategy.ByFree` set (`routes.FreeFirst` is the one) has `weighRouted` fill `routes.Seat.Free`, from `provider.FreeModel` — the user's word that the whole provider costs them nothing (`Provider.CountFree`: the editor's Free for me, `magpie provider set free=yes`; jiabubu on Discord, ModelScope's free daily quota), else the vendor's own `catalog.Model.Free` word, else a list price of $0 on every count — so a pool routed any other way never reads a model list for it, and one routed `free` spends the members whose model costs nothing before those that spend the allowance or credits, each tier in its listed order (nothing free is left behind a paid one, and a pool with no free model behaves as `order`). A group routed `free` weighs its members whole, each over its own accounts or keys as its provider routes them. Whatever a group's routing, the Routing groups page tags a member `provider.FreeModel` counts free "free", on the group's card and beside its provider in the editor (`groupsState`'s `memberInfo[].free`, jiabubu on Discord, `TestGroupMemberSaysFree`, `group-member-free.test.cjs`). `fast` weighs by speed lately and nothing else: only a strategy with `routes.Strategy.BySpeed` set (`routes.Fastest`) has `weighRouted` fill `routes.Seat.TTFT` and `TPS`, from `speedOf` ([`speed.go`](../../internal/gateway/speed.go)): per `restID` (account or key, and model), a decayed average (half-life 20m) of a streamed answer's ms to its first content and of its output tokens a second as `usage.DecodeOf` counts them, written once as an answer ends (`noteTrySpeed`, beside `servedCandidate`) and read with one map lookup per candidate, never from the usage history; past an hour since its last answer a seat counts as not measured, the records are capped at 4096, and a restart forgets them. `routes.Fastest` ranks the awake by their first token plus 200 tokens at their pace (a seat with no pace at the measured seats' middle pace), keeps seats within a tenth of their band's fastest in listed order, and of a pool's requests with seats both measured and not, gives every fifth to one not measured (round the unmeasured, `probes`, so one is never starved); resting seats go after the awake, used-up ones (`UsedShare`) after those, and rests and failover are as for any routing. The trace's rows carry `lateTtft`/`lateTps` for the Routing page's story ("answered fastest lately — first token in 0.8s"). A non-streamed reply tells nothing (no first token), so a pool that never streams stays in listed order bar the probes. `cheap` (a group's only: `provider.normalize` drops it from a provider, whose keys and accounts all bill one price, and the CLI refuses it there) weighs by price now and nothing else: only a strategy with `routes.Strategy.ByPrice` set (`routes.Cheapest`) has `weighRouted` fill `routes.Seat.Priced`, `Cost` and `CacheCost`, from `provider.Provider.PriceAt` at `priceClock()` — the price Usage would count a call made then (the user's `ModelPrices`, else list or maker price, at the price rate and `RateAt`'s window, a `FreeModel` at 0), doubled in its vendor's peak hours by `catalog.Price.In` (`PeakOf`: DeepSeek's API, Command Code's and OpenCode Go's DeepSeek models, each at DeepSeek's hours; Ollama Cloud's deepseek-v4.1-flash and deepseek-v4-pro, dated tags too, at its own 12:00–18:00 UTC weekdays, `catalog.PeakOllama`). `routes.Cheapest` sorts stably by a million in plus a million out, a tie (within a millionth) by cache read, and unpriced seats after every priced one in listed order; rests and failover are as for any routing. The trace's rows carry `price` (`input`, `output`, `cacheRead`, `peak`) for the Routing page's story ("costs least on Ollama now — $0.150 in, $0.600 out a million tokens"). `TestCheapestFirstGroupFollowsPeakHours` holds the clock at a peak and an off-peak hour, and `TestCheapestFirstGroupFollowsOllamaOffPeak` at each edge of Ollama Cloud's hours, a Saturday, and in far zones. A group routed `expiring` (`provider.FreeExpiring`, `routes.FreeExpiring`; wowbbs on Discord, five check-in accounts of WorkBuddy, MiniMax, Trae and Qoder in one group) spends free quota before paid, the soonest lost first. Its strategy sets `ByFree` and `ByPlan`, so `weighRouted` fills `Seat.Free` (the model is free there, as for `free`) and `Seat.FreePlan` (`provider.FreePlan` of the account's `Plan`: free, trial, 免费, 试用, 体验, 體驗). It orders three tiers: the free ones with quota left, by `routes.Expires` (the earliest of a window's renewal and a credit's `RunsOut`, `Lapse` included) truncated to the hour, a stable tie in listed order and an unknown expiry after every known one; then the paid ones as `Smart` orders them among themselves; then the used up and resting, by when they come back. A paid account takes a request only when no free one has quota left, and failover walks the same tiers. The trace's rows carry `free` and `expires` for the Routing page's story ("its free quota is lost soonest, in 1d 2h"). It is a group's only: `provider.normalize` keeps it off a provider, and `magpie provider set … routing=expiring` is refused like `cheap`. Nothing changes for a group not routed `expiring`. `TestGroupSpendsFreeQuotaSoonestToExpireFirst` (gateway), `TestFreeExpiringSpendsSoonestFreeFirst` (routes) and routing-free-expiring.test.cjs hold it. A plugin whose usage doesn't say when free credits lapse (Trae, Qoder's add-on pools) is ordered after the ones that do. A group routed `weight` (#1910) takes its members, not their keys, by smooth weighted round robin: `planLevel` makes each model member (its keys ordered by its own provider's routing) and each nested group one unit, and `weightedUnits` puts the round's pick (`routes.Round` over `group/`, keyed by the member's spelling, `Group.Weights`, 1 if unset) first and the rest in member order for failover; a unit whose head rests leaves the round, while one whose accounts are only near their limit (Smart's 90% band, not resting) keeps its share, the band ordering only its own accounts (`TestWeightedGroupGivesALowGroupItsShare`; Creat.wu on Discord read the Routing page's "kept for when the others can't" as the member passed over, so the page now tells a member behind another by a group's weights or order as such, `memberSplit` in the routing plugin's `client.js`), and a kept conversation moves the round's charge to the member that kept it (`wrrSeat`, `routes.MoveRound`). `weight` on a provider spreads its keys by each key's `Weight` and a subscription's accounts by each account's (`AccountWeights`, rubbzha on X): `keyWeight` gives a seat its `Weight`, 1 when none is set, and `routes.Weighted` takes them by smooth weighted round robin, a resting one leaving the round and a kept conversation staying as Stays says (`TestWeightedKeys`, `TestAccountWeightSharesRequests`). A lone key or account is weighed against nobody, but what it has left is still read into the trace (`weighRouted`), so the Routing page shows it as it does for several (#1016); all but used up, it keeps its conversation rather than being said to move (`affine`). `drain` (dzxx0496 on Discord: free accounts one after another, the first not taking the requests back once it renews) stays on one seat per pool (`routes.Drain`, which remembers the seat's `Key` per pool) until it is used up — a known window at 100% (`provider.SpentShareOf`, as In order) or resting out of quota or credit (`routes.Seat.Spent`, filled by `spentRest` from `restingOf`'s `failQuota`/`failCredit`) — then goes on to the next not used up in listed order and stays there, wrapping round; the others follow it in listed order for failover. A rate limit or a failure only rests the seat, tried last meanwhile, and the pool comes back to it; with every seat used up it stays put, and a seat that leaves the pool leaves it on the first not used up. A group routed `drain` pools its members' accounts and keys under `group/`, as Smart does. A restart forgets where each pool was, and it starts again at the first not used up (`TestDrainKeepsTheOneThatTookOver`). A failure rests a candidate (`failure`, `failureOf`). | [`routing.go`](../../internal/gateway/routing.go), [`weighted.go`](../../internal/gateway/weighted.go), [`internal/routes/`](../../internal/routes), [`internal/provider/routing.go`](../../internal/provider/routing.go) | +| Order of keys and accounts | `Routing`: smart (""), `order`, `rotate`, `usage` (least used, with an `usageHalfLife` of 1h), `pace`, `weight`, `free` (free first), `fast` (speed first), `drain` (until used up) or, a group's only, `cheap` (cheapest first) or `expiring` (free quota by expiry). `weighRouted` reads each candidate into a `routes.Seat` and asks the strategy serving its routing (`routes.Find`, the router strategy point of [the plugin runtime](plugin-runtime.md#gateway-extension-points-p3-router-strategy)) for the order: Smart is `routes.Smart`, the core's; the others are `routes.Builtin`, registered by the built-in plugin `rotation`. With it off a routing no strategy serves is tried in its listed order, and `routingOf` treats it as `order` wherever the core asks about a routing (a turn's mark, `goesRound`, `sinks`, a rotate group's sessions, a group's heads). Smart, `usage` and `pace` weigh a subscription by its allowance (`allowances`), and a key by its own usage windows when magpie reads them (`keyAllowance`: a sub2api key given a 5-hour, day or 7-day limit, or a key bought as a plan, such as Kimi Code's or a GLM Coding Plan's); any other key has none. A Remote magpie is weighed by the card of the provider serving the model there, as last read from it (`provider.RemoteAllowance`: the model's longest provider path with a card, `claude` for `claude/claude-sonnet-5-5`, the account there with the most left for the inner model): before #6708 (zzh11223311 on X) a group of Remote magpies had every member not known (used 0 in the trace) and went by tokens and stickiness alone. It never waits: when the routing weighs the remote against another and its cards are older than 30 seconds, they are read again in the background (one read at a time per remote; the remote answers from the cards it keeps), so a request to one Remote magpie alone sends it nothing more (`TestRemoteMagpiesWeighedByTheirCards`). A remote too old to tell what routing reads of its windows stays not known. A Remote magpie is still not an account for cap holds and Codex credits (`candidate.allowance`). Among accounts a plugin reads as prepaid wallets (a window's `balance`, #3950), Smart, `usage` and `pace` put the one with more left first where they would otherwise tie, only within one provider and unit (`routes.Seat.Left`/`LeftIn`, see [provider plugins](provider-plugins.md#a-wallets-balance)): each kind is ordered in the places its own seats take, so a group weighing several providers' accounts as one pool orders each provider's wallets too (#4095, `TestGroupWalletsGoByWhatTheyHaveLeft`). `free` weighs by what a model costs there and nothing else: only a strategy with `routes.Strategy.ByFree` set (`routes.FreeFirst` is the one) has `weighRouted` fill `routes.Seat.Free`, from `provider.FreeModel` — the user's word that the whole provider costs them nothing (`Provider.CountFree`: the editor's Free for me, `magpie provider set free=yes`; jiabubu on Discord, ModelScope's free daily quota), else the vendor's own `catalog.Model.Free` word, else a list price of $0 on every count — so a pool routed any other way never reads a model list for it, and one routed `free` spends the members whose model costs nothing before those that spend the allowance or credits, each tier in its listed order (nothing free is left behind a paid one, and a pool with no free model behaves as `order`). A group routed `free` weighs its members whole, each over its own accounts or keys as its provider routes them. Whatever a group's routing, the Routing groups page tags a member `provider.FreeModel` counts free "free", on the group's card and beside its provider in the editor (`groupsState`'s `memberInfo[].free`, jiabubu on Discord, `TestGroupMemberSaysFree`, `group-member-free.test.cjs`). `fast` weighs by speed lately and nothing else: only a strategy with `routes.Strategy.BySpeed` set (`routes.Fastest`) has `weighRouted` fill `routes.Seat.TTFT` and `TPS`, from `speedOf` ([`speed.go`](../../internal/gateway/speed.go)): per `restID` (account or key, and model), a decayed average (half-life 20m) of a streamed answer's ms to its first content and of its output tokens a second as `usage.DecodeOf` counts them, written once as an answer ends (`noteTrySpeed`, beside `servedCandidate`) and read with one map lookup per candidate, never from the usage history; past an hour since its last answer a seat counts as not measured, the records are capped at 4096, and a restart forgets them. `routes.Fastest` ranks the awake by their first token plus 200 tokens at their pace (a seat with no pace at the measured seats' middle pace), keeps seats within a tenth of their band's fastest in listed order, and of a pool's requests with seats both measured and not, gives every fifth to one not measured (round the unmeasured, `probes`, so one is never starved); resting seats go after the awake, used-up ones (`UsedShare`) after those, and rests and failover are as for any routing. The trace's rows carry `lateTtft`/`lateTps` for the Routing page's story ("answered fastest lately — first token in 0.8s"). A non-streamed reply tells nothing (no first token), so a pool that never streams stays in listed order bar the probes. `cheap` (a group's only: `provider.normalize` drops it from a provider, whose keys and accounts all bill one price, and the CLI refuses it there) weighs by price now and nothing else: only a strategy with `routes.Strategy.ByPrice` set (`routes.Cheapest`) has `weighRouted` fill `routes.Seat.Priced`, `Cost` and `CacheCost`, from `provider.Provider.PriceAt` at `priceClock()` — the price Usage would count a call made then (the user's `ModelPrices`, else list or maker price, at the price rate and `RateAt`'s window, a `FreeModel` at 0), doubled in its vendor's peak hours by `catalog.Price.In` (`PeakOf`: DeepSeek's API, Command Code's and OpenCode Go's DeepSeek models, each at DeepSeek's hours; Ollama Cloud's deepseek-v4.1-flash and deepseek-v4-pro, dated tags too, at its own 12:00–18:00 UTC weekdays, `catalog.PeakOllama`). `routes.Cheapest` sorts stably by a million in plus a million out, a tie (within a millionth) by cache read, and unpriced seats after every priced one in listed order; rests and failover are as for any routing. The trace's rows carry `price` (`input`, `output`, `cacheRead`, `peak`) for the Routing page's story ("costs least on Ollama now — $0.150 in, $0.600 out a million tokens"). `TestCheapestFirstGroupFollowsPeakHours` holds the clock at a peak and an off-peak hour, and `TestCheapestFirstGroupFollowsOllamaOffPeak` at each edge of Ollama Cloud's hours, a Saturday, and in far zones. A group routed `expiring` (`provider.FreeExpiring`, `routes.FreeExpiring`; wowbbs on Discord, five check-in accounts of WorkBuddy, MiniMax, Trae and Qoder in one group) spends free quota before paid, the soonest lost first. Its strategy sets `ByFree` and `ByPlan`, so `weighRouted` fills `Seat.Free` (the model is free there, as for `free`) and `Seat.FreePlan` (`provider.FreePlan` of the account's `Plan`: free, trial, 免费, 试用, 体验, 體驗). It orders three tiers: the free ones with quota left, by `routes.Expires` (the earliest of a window's renewal and a credit's `RunsOut`, `Lapse` included) truncated to the hour, a stable tie in listed order and an unknown expiry after every known one; then the paid ones as `Smart` orders them among themselves; then the used up and resting, by when they come back. A paid account takes a request only when no free one has quota left, and failover walks the same tiers. The trace's rows carry `free` and `expires` for the Routing page's story ("its free quota is lost soonest, in 1d 2h"). It is a group's only: `provider.normalize` keeps it off a provider, and `magpie provider set … routing=expiring` is refused like `cheap`. Nothing changes for a group not routed `expiring`. `TestGroupSpendsFreeQuotaSoonestToExpireFirst` (gateway), `TestFreeExpiringSpendsSoonestFreeFirst` (routes) and routing-free-expiring.test.cjs hold it. A plugin whose usage doesn't say when free credits lapse (Trae, Qoder's add-on pools) is ordered after the ones that do. A group routed `weight` (#1910) takes its members, not their keys, by smooth weighted round robin: `planLevel` makes each model member (its keys ordered by its own provider's routing) and each nested group one unit, and `weightedUnits` puts the round's pick (`routes.Round` over `group/`, keyed by the member's spelling, `Group.Weights`, 1 if unset) first and the rest in member order for failover; a unit whose head rests leaves the round, while one whose accounts are only near their limit (Smart's 90% band, not resting) keeps its share, the band ordering only its own accounts (`TestWeightedGroupGivesALowGroupItsShare`; Creat.wu on Discord read the Routing page's "kept for when the others can't" as the member passed over, so the page now tells a member behind another by a group's weights or order as such, `memberSplit` in the routing plugin's `client.js`), and a kept conversation moves the round's charge to the member that kept it (`wrrSeat`, `routes.MoveRound`). `weight` on a provider spreads its keys by each key's `Weight` and a subscription's accounts by each account's (`AccountWeights`, rubbzha on X): `keyWeight` gives a seat its `Weight`, 1 when none is set, and `routes.Weighted` takes them by smooth weighted round robin, a resting one leaving the round and a kept conversation staying as Stays says (`TestWeightedKeys`, `TestAccountWeightSharesRequests`). A lone key or account is weighed against nobody, but what it has left is still read into the trace (`weighRouted`), so the Routing page shows it as it does for several (#1016); all but used up, it keeps its conversation rather than being said to move (`affine`). `drain` (dzxx0496 on Discord: free accounts one after another, the first not taking the requests back once it renews) stays on one seat per pool (`routes.Drain`, which remembers the seat's `Key` per pool) until it is used up — a known window at 100% (`provider.SpentShareOf`, as In order) or resting out of quota or credit (`routes.Seat.Spent`, filled by `spentRest` from `restingOf`'s `failQuota`/`failCredit`) — then goes on to the next not used up in listed order and stays there, wrapping round; the others follow it in listed order for failover. A rate limit or a failure only rests the seat, tried last meanwhile, and the pool comes back to it; with every seat used up it stays put, and a seat that leaves the pool leaves it on the first not used up. A group routed `drain` pools its members' accounts and keys under `group/`, as Smart does. A restart forgets where each pool was, and it starts again at the first not used up (`TestDrainKeepsTheOneThatTookOver`). A failure rests a candidate (`failure`, `failureOf`). | [`routing.go`](../../internal/gateway/routing.go), [`weighted.go`](../../internal/gateway/weighted.go), [`internal/routes/`](../../internal/routes), [`internal/provider/routing.go`](../../internal/provider/routing.go) | | Limits | Each key or account (a candidate's `who()`) has at most `MaxConcurrency` requests out at once (its own `AccountConcurrency` over it); one more waits in its lane's queue, bounded by `QueueLimit` and `QueueWait` and turned away with a 429 past either (`lanes.take`). One with no limit still counts its requests out in a lane of `Limit` 0, which never waits, so `Lanes` (`/v1/magpie/concurrency`, the GUI's `/api/lanes`) says how many run there too and the Providers page's pill shows it (chentuoyan on Discord, `TestLanesCountWithNoLimit`); a limit set while they are out counts them. `MaxRPM` (coeo91 on Discord: OpenRouter's free models take 20 a minute) bounds how many requests it sends the vendor in any rolling 60 seconds (`rpms`), counting each for a second more (`rpmSlack`), since the vendor counts a request when it arrives and the first on a new connection arrives later by its dial: one more waits for room in the minute, in the order they came, after it has its slot and right before it is sent. A wait that would be longer than 2 minutes (or the provider's `QueueWait`, when shorter: `rpmWait`) is turned away at once with a 429 whose `Retry-After` is when the minute has room; nothing rests for it. An agent gone while it waits gives its place back. Every request that reaches the vendor counts: each try of the candidate loop (a retry, the next key, a fallback) waits in `serve`, and the requests a try makes on the way and the gateway's own asks (count_tokens, System One's decisions, embeddings, drawing, Kimi's search) are counted by `rpmTransport` on `s.client` (`metered`, `paidFor`). count_tokens never waits: a candidate with no room is skipped, and the local estimate answers. A full lane or a minute with no room gives way to a ready key or account of the provider or the group (`laneMate`, `ready`) that isn't resting: its lane is free only because nothing is sent there. A request already waiting in a lane doesn't stay bound to it: whenever a slot is given back in any lane or a rest is lifted (`lanes.freed`, signalled by the releaser, `Unrest` and `UnrestAll`), and when the soonest rest among the others runs out (at most every `laneRecheck`), it goes to the first key or account after it in the planned order that has a free slot with no queue, minute room, isn't resting and isn't a reserve now (`waitMate`, `keepAtOnce` re-derived over the provider's candidates, `errMoved`). So one that took a seat while those before it rested, then became a reserve once they were back, doesn't keep requests waiting behind its own long turns (01huadalang on Discord: three ZCode accounts at three at once, the first two back from a 405 while the waiting ones stayed on the third until its requests were cut by hand; `TestWaitingRequestGoesToAccountBackFromRest` under Smart and In turn, with Stays on and off, `TestWaitingRequestTakesSlotGivenBackElsewhere` under every routing). Strict stays leaves no other candidate, so the request waits for its own. A fallback is never asked for want of a slot or a minute (`TestFullMemberGivesWay`). A plugin's account sends through its own transport, so only its tries are counted, not a plugin's own extra requests. Set in the provider editor (Concurrency, Requests per minute, Queue size, Queue wait) or with `magpie provider account-concurrency`, `queue` and `rpm`; a subscription's are kept with its picks, and every account of it keeps them, those on beside the first as well (`withPicks`, called by `All` and `AlsoOn`; #1899: a second WorkBuddy AI account had none, and queued 62s with the wait set to 1s). | [`concurrency.go`](../../internal/gateway/concurrency.go), [`rpm.go`](../../internal/gateway/rpm.go), [`internal/provider/concurrency.go`](../../internal/provider/concurrency.go) | | Accounts at once | A provider's `MaxAccounts` (01huadalang on Discord: three ZCode accounts used at once got the exit address refused with a 405, two didn't) is how many of its keys or accounts take requests at the same time: `provider.AtOnce()` is the user's own value, else what its plugin declares (`maxAccounts` on the auth hook or in package.json's `magpie`, read by host.js `atOnceOf`; zcode says 2), else no limit; the user's 0 is no limit over the plugin's. `perKeyBarred` keeps the first N in the user's own order (`rank`, so a dragged list counts), preferring ones not resting, and hands the rest to `keepAtOnce`'s reserves: they go after everything else as asides with `candidate.reserve` set (`Weighed.Reserve`), so whatever the routing mode, a reserve is asked only once the kept ones failed or rest, and a kept one that rests gives its seat to the first reserve on the next request. Three guards keep a reserve from being reached for anything else: `laneMate` never spills a full lane onto one, a full queue (`laneErr`) drops the provider's reserves before passing on (`dropReserves`), so the request is turned away with the 429 instead, and session affinity keeps no conversation on a reserve once the kept ones can take it (`affine`'s "reserve"; Strict still holds). Leak known: a failure that rests nobody (a 5xx on one try) still passes that one request to the reserve, as it does to any next candidate. Set in the provider editor's Advanced (Accounts at once, beside Concurrency) or with `magpie provider at-once`; Routing's row says "in reserve · {n} at once" (`TestAtOnceKeepsFirstInUserOrder`, `TestAtOnceFullLaneWaitsForTheKept`, `TestAtOnceReserveTakesOverAndGivesBack`, `provider-at-once.test.cjs`). | [`fallback.go`](../../internal/gateway/fallback.go), [`concurrency.go`](../../internal/gateway/concurrency.go), [`internal/provider/concurrency.go`](../../internal/provider/concurrency.go) | | Sink | With `Sink` on, a key or account that answers 429 while it still has quota goes to the back, behind every one not rate limited since. Held in memory until restart, or until its rest is lifted by hand (Try now, `Unrest` calls `unsink`, `UnrestAll` `unsinkAll` for the key and each of its models), which puts it back in its place (`TestTryNowPutsASunkAccountBack`, `TestUnrestAllUnsinksTheModels`). Another magpie's model rate limited there, whose rest is the model's alone (`remoteModelRest`), sinks alone too (`restID`), and `sunkAt` reads a candidate's model before its key, so the remote's other models keep their place (#2167, ggbdpq; `TestRemoteMagpieRateLimitSinksTheModel`, `TestMagpieAddedByHandRateLimitSinksTheModel`). A group in a group sinks by its own Sink, within its own order (`sinkOwn`, #2255), and the group asked for then sinks the whole by its own; `TestNestedGroupSinksItsOwnOrder`. | [`sink.go`](../../internal/gateway/sink.go) | diff --git a/docs/subsystems/providers-accounts.md b/docs/subsystems/providers-accounts.md index 1426f2bf7..477a73538 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 | 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`). Routing weighs such a ChatGPT API account by that Codex account's reading too: `Allowances("chatgpt-api")` gives it the Codex account's allowance (`samePlanAllowances`; tmr11235 on X, `TestChatGPTAPIAllowanceIsTheSameAccountsCodexReading`), so Smart no longer puts it after every known account as unknown; one with no Codex twin stays unknown. A window that has just reset, with too little used to scale (`HoldsLow`, `HoldsNoneRouted`), keeps the account's last whole for that window, marked `holds.prevAt` (the time it was reckoned; the GUI's tooltip says which window it came from, as a past cycle's does) until it tells its own; the last whole per account and window is kept in `window-holds.json` (`carryHolds` in [`window_holds_carry.go`](../../internal/usage/window_holds_carry.go), every provider's, Musikrv77852 on X; `TestWholeKeptAcrossReset`, `quota-holds.test.cjs`). A single card can be read again on its own (#840). A remote magpie's cards come from what it has kept (`CachedCards`, `GET /v1/magpie/quotas/cards`) and are never read there for this computer except by a card's refresh (`POST /v1/magpie/quotas/refresh`, throttled per card). What it has kept is the Usage page's cards with the readings made behind the requests since laid over them, a later one over an earlier by `readSeq` (`cards_kept.go`): each account's `LoginUsage` reading (the used-up switch, the Codex warm-up, routing's `Allowances`), and each key's `KeyAllowance` windows on its plan or balance card. A Claude account's windows Claude Code told as it answered (`NoteClaudeLimits`, kept in `claudeUsage` with their own `heardSeq`, which drops the account's `LoginUsage` reading) stand on its card over any reading started before them (`withHeardClaude`, #2206), so a magpie only requests reach still tells them. An account or key read that way and never on the page gets a card from that reading, and after a restart, before either is read again, the cards come from `quotas.json`, dated (`AsOf`). A magpie serving only other magpies has nobody on its page (#1313). What it has kept includes its own Remote magpies' cards as it last read them (`passedOnCards`, no remote asked), so a chain passes every card on (yuyong_id on Discord: magpie3 → magpie2 → magpie1 showed none of magpie1's Codex at magpie3), named after each magpie (`magpie2/magpie1/codex`, "Codex · magpie1 · magpie2"); the card standing for a remote and its keys' limits stay the reader's own. Each card carries `via`, the `catalog.Self` of each magpie it went through, and a reader leaves out one that loops (`catalog.Loops`, as a model's `magpie_via`). A refresh of such a card is passed to the magpie it came from (`quotaCardsRefresh` takes a card id this magpie has from a remote); a Codex reset is offered on the magpie next door only, and quota history isn't passed on. The status line's kept report (`KeptQuotaReport`) has a remote's cards the same way. A ChatGPT account's card has an *Image generation* row (`WithImageLane`, [`image_lane.go`](../../internal/provider/image_lane.go), `Lane` `images`, Text and Aside so routing, holds and history never see it; hqqqqqqqh on X, #6160): ChatGPT's images have a quota apart from the 5-hour and weekly windows, which `/wham/usage` doesn't tell (`additional_rate_limits` is null). Every reply of the images API, a 200 too, does: `x-codex-active-limit: imagegen_premium` with the window in `x-codex-primary-*` (1440 minutes, `reset-at`), or in the limit's own family (`x-imagegen-premium-primary-*`, as Codex's `parse_all_rate_limits` reads it). The gateway keeps that window per account (`heardCodexImage` in [`codex_image_limits.go`](../../internal/gateway/codex_image_limits.go), from magpie's drawing and from Codex's own relayed `/images/*`; `provider.ImageHeard`), and never takes it for a chat window (`codexHeaderLimits` tells none when the active limit is an image one; #6412, Green14964 on X: the card said "2 minutes" of a 24-hour window). So the row says *Available* with the window's reset, *Used up* when the headers say 100% or while the image model is resting on that account after a refusal (`ImageRest`, the gateway's `restingUntil`, whose time is the refusal's `resets_at`, #2244, else the heard window's reset for a 429 with that window full, not `quotaRest`'s 15 minutes), and *Unknown* before any drawing, never a share or a count (`TestWithImageLaneOnlyReadCodexCards`, `TestCodexImageRowIsTheRefusalsResetTime`, `TestCodexImageRowFromA200sHeaders`, `TestCodexImageRefusalRestsUntilItsWindow`, `codex-image-row.test.cjs`). The window heard lives in memory only, so after a restart the row is *Unknown* until the next drawing. Not done: the count of images made in the window. Each key of a remote-magpie provider also gets a card of its own, under `/~keys`, one section per key (#1547, `remoteKeyCards` in `remote_key_limits.go`): the gateway key's limit as that magpie holds it, read from `GET /v1/magpie/limit` asked with that key alone, so a key never sees another's numbers. It shows a window per cap (tokens, spend) named for the period, used against the cap, with its reset, plus `GatewayKey` (what is left, calls, a cycle of days, used up); a key held to no limit shows `Unlimited`. It is kept for `remoteCardsFor` like the remote's cards and read again by the card's refresh (`?provider=/~keys&user=`). A read that fails keeps the last numbers, dated (`AsOf`); with none the card says why, never zero or no limit. A remote from before `/v1/magpie/limit` (404) says it is too old to tell (`errRemoteNoKeyLimit`). A remote's Codex card keeps its `Resets` (not a GLM team's, `ByWindow`), and its check-ins are dropped: **Use one…** there goes through `/api/usage/codex-reset` with the card's `provider`, and `UseRemoteCodexReset` asks the remote's `POST /v1/magpie/quotas/codex-reset?user=` with the provider's key (#3850). The remote spends it with `SpendCodexReset`, the same function as the Usage page (`UseCodexResetCard`, then `AwaitAllowance`). The account is always named. A 403 `gateway_key_read_only` is told as a read-only key there, and a 404 as a remote too old. No answer within `RemoteResetWait` says the reset may have been used, and it is never asked again by itself. A remote that holds the key to a budget, models or accounts answers its cards 403 `gateway_key_held` (#1981, `errKeyHeld`): the cards kept from before are dropped, and beside the key's own card the remote's card says it tells this key no quotas, and that on that computer Quotas is turned on for the key and it is let use every model of a provider whose usage it is to see (`errRemoteHeld`; yi_time on Discord saw the remote's Claude vanish from every page with no word). Its owner can let the key be told the cards of what it may use (#2216, `magpie gateway-key quotas on`); the remote then answers those, and 403 held as before when that is none (`writeCards`), so that key shows the same card. A remote's cards are kept by provider and key (`remoteCardsID`), so a changed key never shows what the old one was told, and a read is kept only over one asked before it (`keepRemoteCards`). 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`). Routing weighs such a ChatGPT API account by that Codex account's reading too: `Allowances("chatgpt-api")` gives it the Codex account's allowance (`samePlanAllowances`; tmr11235 on X, `TestChatGPTAPIAllowanceIsTheSameAccountsCodexReading`), so Smart no longer puts it after every known account as unknown; one with no Codex twin stays unknown. A window that has just reset, with too little used to scale (`HoldsLow`, `HoldsNoneRouted`), keeps the account's last whole for that window, marked `holds.prevAt` (the time it was reckoned; the GUI's tooltip says which window it came from, as a past cycle's does) until it tells its own; the last whole per account and window is kept in `window-holds.json` (`carryHolds` in [`window_holds_carry.go`](../../internal/usage/window_holds_carry.go), every provider's, Musikrv77852 on X; `TestWholeKeptAcrossReset`, `quota-holds.test.cjs`). A single card can be read again on its own (#840). A remote magpie's cards come from what it has kept (`CachedCards`, `GET /v1/magpie/quotas/cards`) and are never read there for this computer except by a card's refresh (`POST /v1/magpie/quotas/refresh`, throttled per card). What it has kept is the Usage page's cards with the readings made behind the requests since laid over them, a later one over an earlier by `readSeq` (`cards_kept.go`): each account's `LoginUsage` reading (the used-up switch, the Codex warm-up, routing's `Allowances`), and each key's `KeyAllowance` windows on its plan or balance card. A Claude account's windows Claude Code told as it answered (`NoteClaudeLimits`, kept in `claudeUsage` with their own `heardSeq`, which drops the account's `LoginUsage` reading) stand on its card over any reading started before them (`withHeardClaude`, #2206), so a magpie only requests reach still tells them. An account or key read that way and never on the page gets a card from that reading, and after a restart, before either is read again, the cards come from `quotas.json`, dated (`AsOf`). A magpie serving only other magpies has nobody on its page (#1313). What it has kept includes its own Remote magpies' cards as it last read them (`passedOnCards`, no remote asked), so a chain passes every card on (yuyong_id on Discord: magpie3 → magpie2 → magpie1 showed none of magpie1's Codex at magpie3), named after each magpie (`magpie2/magpie1/codex`, "Codex · magpie1 · magpie2"); the card standing for a remote and its keys' limits stay the reader's own. Each card carries `via`, the `catalog.Self` of each magpie it went through, and a reader leaves out one that loops (`catalog.Loops`, as a model's `magpie_via`). A refresh of such a card is passed to the magpie it came from (`quotaCardsRefresh` takes a card id this magpie has from a remote); a Codex reset is offered on the magpie next door only, and quota history isn't passed on. The status line's kept report (`KeptQuotaReport`) has a remote's cards the same way. A ChatGPT account's card has an *Image generation* row (`WithImageLane`, [`image_lane.go`](../../internal/provider/image_lane.go), `Lane` `images`, Text and Aside so routing, holds and history never see it; hqqqqqqqh on X, #6160): ChatGPT's images have a quota apart from the 5-hour and weekly windows, which `/wham/usage` doesn't tell (`additional_rate_limits` is null). Every reply of the images API, a 200 too, does: `x-codex-active-limit: imagegen_premium` with the window in `x-codex-primary-*` (1440 minutes, `reset-at`), or in the limit's own family (`x-imagegen-premium-primary-*`, as Codex's `parse_all_rate_limits` reads it). The gateway keeps that window per account (`heardCodexImage` in [`codex_image_limits.go`](../../internal/gateway/codex_image_limits.go), from magpie's drawing and from Codex's own relayed `/images/*`; `provider.ImageHeard`), and never takes it for a chat window (`codexHeaderLimits` tells none when the active limit is an image one; #6412, Green14964 on X: the card said "2 minutes" of a 24-hour window). So the row says *Available* with the window's reset, *Used up* when the headers say 100% or while the image model is resting on that account after a refusal (`ImageRest`, the gateway's `restingUntil`, whose time is the refusal's `resets_at`, #2244, else the heard window's reset for a 429 with that window full, not `quotaRest`'s 15 minutes), and *Unknown* before any drawing, never a share or a count (`TestWithImageLaneOnlyReadCodexCards`, `TestCodexImageRowIsTheRefusalsResetTime`, `TestCodexImageRowFromA200sHeaders`, `TestCodexImageRefusalRestsUntilItsWindow`, `codex-image-row.test.cjs`). The window heard lives in memory only, so after a restart the row is *Unknown* until the next drawing. Not done: the count of images made in the window. Each key of a remote-magpie provider also gets a card of its own, under `/~keys`, one section per key (#1547, `remoteKeyCards` in `remote_key_limits.go`): the gateway key's limit as that magpie holds it, read from `GET /v1/magpie/limit` asked with that key alone, so a key never sees another's numbers. It shows a window per cap (tokens, spend) named for the period, used against the cap, with its reset, plus `GatewayKey` (what is left, calls, a cycle of days, used up); a key held to no limit shows `Unlimited`. It is kept for `remoteCardsFor` like the remote's cards and read again by the card's refresh (`?provider=/~keys&user=`). A read that fails keeps the last numbers, dated (`AsOf`); with none the card says why, never zero or no limit. A remote from before `/v1/magpie/limit` (404) says it is too old to tell (`errRemoteNoKeyLimit`). A remote's Codex card keeps its `Resets` (not a GLM team's, `ByWindow`), and its check-ins are dropped: **Use one…** there goes through `/api/usage/codex-reset` with the card's `provider`, and `UseRemoteCodexReset` asks the remote's `POST /v1/magpie/quotas/codex-reset?user=` with the provider's key (#3850). The remote spends it with `SpendCodexReset`, the same function as the Usage page (`UseCodexResetCard`, then `AwaitAllowance`). The account is always named. A 403 `gateway_key_read_only` is told as a read-only key there, and a 404 as a remote too old. No answer within `RemoteResetWait` says the reset may have been used, and it is never asked again by itself. A remote that holds the key to a budget, models or accounts answers its cards 403 `gateway_key_held` (#1981, `errKeyHeld`): the cards kept from before are dropped, and beside the key's own card the remote's card says it tells this key no quotas, and that on that computer Quotas is turned on for the key and it is let use every model of a provider whose usage it is to see (`errRemoteHeld`; yi_time on Discord saw the remote's Claude vanish from every page with no word). Its owner can let the key be told the cards of what it may use (#2216, `magpie gateway-key quotas on`); the remote then answers those, and 403 held as before when that is none (`writeCards`), so that key shows the same card. A remote's cards are kept by provider and key (`remoteCardsID`), so a changed key never shows what the old one was told, and a read is kept only over one asked before it (`keepRemoteCards`). Each card also carries `routing`, each window's span, the model it alone counts and whether it is aside (`provider.ToldRouting` in `writeCards`), which a window's own json leaves out; the magpie reading them lays them back on the windows (`withRouting` in `keepRemoteCards`), and only such a card is weighed by routing (`provider.RemoteAllowance`, #6708, [gateway routing](gateway-routing.md)). Passed on, the cards keep them, so a third magpie weighs them too. A read the test hook dropped (`ForgetRemoteCardsForTest` moves `remoteCardCache.gen` on) is not kept. Cursor, Grok and a Kiro key keep the page's cards only. With Settings → Allowances → *Allowance reads* at *When I ask* (`QuotaReads == "asked"`, #1518: magpie started at login before the proxy app read by itself, direct), only a read the user asked for goes out: the Usage page or the tray panel's Allowances opened (no more than once in 30s, `quotasOpened`, #1588) or refreshed (`?asked=1`), a card's refresh (`RefreshUsage`), `magpie quota`, `magpie accounts`, `magpie quota wait` and the TUI's quotas (`Asked`). Any other read (`quotaReading` → `holdUnasked`) carries `netproxy.Hold`, so its requests fail before they leave, and every reader gives back what it last read, dated, or "not read yet" (`errNotAsked`): routing, the used-up switch, the menu bar and alerts go by that. An account refused for its quota (`StaleAllowance` → `markStaleRead`) or a key refused (`StaleKeyAllowance` → `refused`) is still read, once (`unheld`). Warm-up and check-in are not reads and are unchanged. A plugin's window may carry a prepaid wallet's `balance` in its `unit` and no share (`QuotaWindow.Balance`, #3950): the card and `magpie quota` show the figure (`BalanceText`), and routing reads it through `Allowance.Left`. | [`cards_kept.go`](../../internal/provider/cards_kept.go), [`quotas.go`](../../internal/provider/quotas.go), [`subscription_usage.go`](../../internal/provider/subscription_usage.go), [`planquota.go`](../../internal/provider/planquota.go), [`balance.go`](../../internal/provider/balance.go), [`quota_refresh.go`](../../internal/provider/quota_refresh.go), [`remote_quotas.go`](../../internal/provider/remote_quotas.go), [`remote_key_limits.go`](../../internal/provider/remote_key_limits.go), [`quota_asked.go`](../../internal/provider/quota_asked.go) | | A remote magpie's prices | A local magpie asks a remote magpie's `/v1/models` with `X-Magpie-Prices` (`PricesHeader`, sent by `listHeaders`). The remote answers each model's `magpie_price`: what its own Usage page counts the model at (`EntryPriceIn`: the price its user set, else its provider's list price at its price rate; a routing group only when every member costs the same). It tells it only to a request from its own computer or one let in with a gateway key (`local` or `sharedWith`); a list that didn't ask gets no `magpie_price` (a remote request without a valid key never reaches the list: `lanGuard` refuses it); every list told to those callers also carries the same price as OpenRouter's `pricing`, for agents ([gateway routing](gateway-routing.md)). The local keeps the price with the fetched list (`catalog.Model.Price`; a value that isn't a price, or has a negative part, is dropped, the model kept) and uses it as that provider's list price (`ListPrice` → `remotePrice`). A price the local user set (`provider/model`, `provider/*`, `*/model`) still comes first, and the local provider's own price rate still applies on top. A remote from before this sends no field and the models stay priced as before; an older local sends no header and is sent nothing new. The model editor says the greyed price is the other magpie's (`remoteList`). | [`remote_magpie.go`](../../internal/provider/remote_magpie.go), [`models.go`](../../internal/provider/models.go), [`gateway.go`](../../internal/gateway/gateway.go) (`models`), [`live.go`](../../internal/catalog/live.go) | | A remote magpie's service tiers | A remote magpie's `/v1/models` gives each model the `service_tiers` its own Codex is offered on it (`codexTiers` → `codexcat.ServiceTiers`, from the same `CodexCatalog` and `codexcat.Entries` as its `/v1/codex/models`: Fast on a ChatGPT account's GPT model, the tiers of Codex's own entry on a relay's, none on a model it offers none). 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 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, and all shown for a Remote set to Select none (it serves no model, its usage is still read; a user on X, 0.1.3929, `TestRemoteSelectNoneStillShowsItsCards`). 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) | diff --git a/internal/gateway/quotas_scope.go b/internal/gateway/quotas_scope.go index 2749acf21..defa1e9f7 100644 --- a/internal/gateway/quotas_scope.go +++ b/internal/gateway/quotas_scope.go @@ -150,7 +150,9 @@ func writeCards(w http.ResponseWriter, r *http.Request, s *quotaScope) { if s == nil && provider.ReckonHolds != nil { cs = provider.ReckonHolds(cs, time.Now()) } - writeJSON(w, 200, map[string]any{"object": "list", "data": cs}) + // with what routing reads of each window, so the other magpie can + // weigh this one by them (#6708) + writeJSON(w, 200, map[string]any{"object": "list", "data": provider.ToldRouting(cs)}) } // quotas is qs as the key may be told them. A window's whole (Holds, diff --git a/internal/gateway/remote_route_quota_test.go b/internal/gateway/remote_route_quota_test.go new file mode 100644 index 000000000..4603952e1 --- /dev/null +++ b/internal/gateway/remote_route_quota_test.go @@ -0,0 +1,122 @@ +package gateway + +import ( + "context" + "encoding/json" + "io" + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" + + "github.com/yetone/magpie/internal/provider" +) + +// #6708 (zzh11223311 on X): a group of two Remote magpies, each serving +// a Claude subscription signed in there. Smart and Use before expiry had +// both "not known" (used 0 in the routing log) and went by tokens and +// stickiness alone. Each is weighed now by its Claude card, as last read +// from it: B, with more of a week that renews sooner, goes first. A +// magpie passes on what routing reads of the cards it has from another, +// so a third magpie weighs them too. +func TestRemoteMagpiesWeighedByTheirCards(t *testing.T) { + fresh(t) + t.Setenv("MAGPIE_ADDR", "") + provider.ForgetRemoteCardsForTest() + t.Cleanup(provider.ForgetRemoteCardsForTest) + now := time.Now() + at := func(d time.Duration) *time.Time { t := now.Add(d); return &t } + claude := func(user string, week float64, renews time.Duration) []provider.SubscriptionQuota { + return []provider.SubscriptionQuota{{Provider: "claude", Name: "Claude Code", User: user, Kind: "subscription", Windows: []provider.QuotaWindow{ + {Name: "5 hours", Used: 5, ResetsAt: at(4 * time.Hour), Span: 5 * time.Hour}, + {Name: "7 days", Used: week, ResetsAt: at(renews), Span: 7 * 24 * time.Hour}, + {Name: "7 days · Opus", Used: 99, ResetsAt: at(renews), Span: 7 * 24 * time.Hour, Model: "opus"}, + }}} + } + remote := func(key string, cards []provider.SubscriptionQuota) *httptest.Server { + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.Header.Get("x-api-key") != key && r.Header.Get("Authorization") != "Bearer "+key { + w.WriteHeader(http.StatusUnauthorized) + return + } + if r.Method+" "+r.URL.Path != "GET "+provider.RemoteCardsPath { + w.WriteHeader(http.StatusNotFound) + return + } + json.NewEncoder(w).Encode(map[string]any{"object": "list", "data": provider.ToldRouting(cards)}) + })) + t.Cleanup(srv.Close) + return srv + } + ra := remote("sk-magpie-a", claude("a@x.com", 51, 117*time.Hour)) + rb := remote("sk-magpie-b", claude("b@x.com", 25, 44*time.Hour)) + for _, p := range []provider.Provider{ + {ID: "mac-a", Name: "Mac A", Preset: provider.RemoteMagpiePreset, Key: "sk-magpie-a", Chat: ra.URL}, + {ID: "mac-b", Name: "Mac B", Preset: provider.RemoteMagpiePreset, Key: "sk-magpie-b", Chat: rb.URL}, + } { + if err := provider.Save(p); err != nil { + t.Fatal(err) + } + } + // the Usage page's read, which routing goes by from then on + provider.RemoteCards(context.Background()) + member := func(id string) candidate { + p, err := provider.Find(id) + if err != nil { + t.Fatal(err) + } + return candidate{p: *p, model: "claude/claude-sonnet-5-5", rest: id + "-6708"} + } + a, b := member("mac-a"), member("mac-b") + for _, routing := range []string{provider.Pace, ""} { + g := provider.Provider{ID: "auto-6708", Routing: routing} + got, wg := weigh(g, []candidate{a, b}, "claude-sonnet-5-5", provider.Anthropic) + if got[0].p.ID != "mac-b" { + t.Errorf("routing %q: %s first, want mac-b", routing, got[0].p.ID) + } + la, oka := wg.lefts[a.allowanceKey()] + lb, okb := wg.lefts[b.allowanceKey()] + if !oka || !okb || la.used != 51 || lb.used != 25 { + t.Errorf("routing %q: used a %v (%v) b %v (%v), want 51 and 25", routing, la.used, oka, lb.used, okb) + } + if !lb.due.Equal(*at(44 * time.Hour)) { + t.Errorf("routing %q: b due %v, want its week's renewal", routing, lb.due) + } + } + + // this gateway tells a magpie using it what routing reads of the cards + // it has from mac-a and mac-b + gw := httptest.NewServer(lanGuard(New().Handler())) + defer gw.Close() + res, err := http.Get(gw.URL + provider.RemoteCardsPath) + if err != nil { + t.Fatal(err) + } + body, _ := io.ReadAll(res.Body) + res.Body.Close() + if res.StatusCode != 200 || !strings.Contains(string(body), `"routing"`) || !strings.Contains(string(body), `"mac-b/claude"`) { + t.Fatalf("the cards told on: %d %s", res.StatusCode, body) + } + via := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path != provider.RemoteCardsPath { + w.WriteHeader(http.StatusNotFound) + return + } + w.Write(body) + })) + defer via.Close() + if err := provider.Save(provider.Provider{ID: "home", Name: "Home", Preset: provider.RemoteMagpiePreset, Key: "sk-magpie-via", Chat: via.URL}); err != nil { + t.Fatal(err) + } + provider.RemoteCards(context.Background()) + home, err := provider.Find("home") + if err != nil { + t.Fatal(err) + } + if al, inner, ok := provider.RemoteAllowance(*home, "mac-b/claude/claude-sonnet-5-5", false); !ok || inner != "claude-sonnet-5-5" { + t.Errorf("a third magpie doesn't know mac-b's Claude: %v %q", ok, inner) + } else if u, _ := al.For(inner, now); u != 25 { + t.Errorf("a third magpie reads mac-b's Sonnet used %v, want 25", u) + } +} diff --git a/internal/gateway/routing.go b/internal/gateway/routing.go index d29759a33..fbd932c3a 100644 --- a/internal/gateway/routing.go +++ b/internal/gateway/routing.go @@ -994,6 +994,8 @@ func narrowWhenRead(c candidate, r Rest) { var ( keyAllowance = provider.KeyAllowance staleKeyAllowance = provider.StaleKeyAllowance + // remoteAllowance is provider.RemoteAllowance, swapped in tests + remoteAllowance = provider.RemoteAllowance ) // RestOf is why what rests by key — a provider's id, or its id#key — is @@ -2560,7 +2562,14 @@ func weighRouted(p provider.Provider, cs []candidate, model string, from provide var a provider.Allowance var ok bool whose := c.p.ID // whose wallet a balance is in - if c.p.Account == nil { + m := c.model // the model as its allowance counts it + if c.p.IsRemoteMagpie() { + // another magpie's: by the card of its provider serving the + // model there, as last read from it (#6708, zzh11223311 on X); + // read again in the background only when there is another to + // weigh it against + a, m, ok = remoteAllowance(c.p, c.model, len(cs) > 1) + } else if c.p.Account == nil { // a key that reads its own windows is weighed by them as an // account is; any other key isn't known a, ok = keyAllowance(c.p) @@ -2573,16 +2582,16 @@ func weighRouted(p provider.Provider, cs []candidate, model string, from provide a, ok = known[ag][c.p.Account.User] } if ok { - u, r := a.For(c.model, now) - pc, due := a.Pace(c.model, now) - amt, of, unit := a.Count(c.model, now) + u, r := a.For(m, now) + pc, due := a.Pace(m, now) + amt, of, unit := a.Count(m, now) rs := a.Restarts(now) - l := left{used: u, renews: r, fullest: a.Fullest(c.model, now), fullestName: a.FullestName(c.model, now), soon: a.Renewal(c.model, now), unreached: a.Unreached(c.model, now), lapse: a.Lapse(c.model, now), lapsing: a.Lapsing(c.model, now), pace: pc, due: due, amount: amt, of: of, unit: unit, + l := left{used: u, renews: r, fullest: a.Fullest(m, now), fullestName: a.FullestName(m, now), soon: a.Renewal(m, now), unreached: a.Unreached(m, now), lapse: a.Lapse(m, now), lapsing: a.Lapsing(m, now), pace: pc, due: due, amount: amt, of: of, unit: unit, restarts: rs, dueRestart: !rs.IsZero() && due.Equal(rs), credits: spendsCredits(c.p, a)} // one not known counts as unused l.dueExpiry = !l.dueRestart && !l.lapse.IsZero() && due.Equal(l.lapse) - l.weekLow = u >= lowShare && u < usedShare && a.CapUsed(c.model, now) < lowShare + l.weekLow = u >= lowShare && u < usedShare && a.CapUsed(m, now) < lowShare l.first = l.credits && provider.CodexCreditsFirst(c.p.Account.User) - if b, bu, has := a.Left(c.model); has { + if b, bu, has := a.Left(m); has { // a wallet's figure is weighed only against the same // provider's in the same unit (routes.Seat.LeftIn) l.bal, l.balUnit, l.balIn = b, bu, whose+"\x00"+bu diff --git a/internal/provider/remote_allowance.go b/internal/provider/remote_allowance.go new file mode 100644 index 000000000..ad444f306 --- /dev/null +++ b/internal/provider/remote_allowance.go @@ -0,0 +1,155 @@ +package provider + +import ( + "context" + "net/http" + "strings" + "sync" + "time" +) + +// A Remote magpie's allowance, for routing (#6708, zzh11223311 on X): a +// group whose members are two Remote magpies, each with a Claude +// subscription signed in there, had every member "not known" (used 0 in +// the routing log), so Smart and Use before expiry went by the tokens +// sent lately and stickiness alone. The other magpie already tells its +// cards (RemoteCardsPath, read here for the Usage page): routing now goes +// by them too, as kept here, never waiting on the network. +// +// A window's json leaves out what routing reads (Span, Model, Aside), so +// a magpie tells another its cards with Routing beside the windows +// (ToldRouting), and the cards read are given them back (withRouting). A +// card from a magpie too old to tell them isn't weighed: a "7 days · +// Opus" window would count against Sonnet, a five hours as a week. + +// ToldRouting is cs, each card with its windows' Routing, for another +// magpie: the gateway's answer of RemoteCardsPath. +func ToldRouting(cs []SubscriptionQuota) []SubscriptionQuota { + out := make([]SubscriptionQuota, len(cs)) + for i, q := range cs { + if len(q.Windows) > 0 { + q.Routing = make([]lastWindow, len(q.Windows)) + for j, w := range q.Windows { + q.Routing[j] = lastWindow{w.Span, w.Model, w.Aside} + } + } + out[i] = q + } + return out +} + +// withRouting lays each card's Routing back on its windows, as a remote +// magpie told them, and marks the card one routing may go by. A window +// whose span wasn't known there is named for it here ("7 days"). +func withRouting(cs []SubscriptionQuota) []SubscriptionQuota { + out := make([]SubscriptionQuota, len(cs)) + for i, q := range cs { + if len(q.Routing) == len(q.Windows) && len(q.Windows) > 0 { + ws := make([]QuotaWindow, len(q.Windows)) + for j, w := range q.Windows { + r := q.Routing[j] + w.Span, w.Model, w.Aside = r.Span, r.Model, r.Aside + if w.Span == 0 { + w.Span = windowSpan(w) + } + ws[j] = w + } + q.Windows, q.routable = ws, true + } + q.Routing = nil + out[i] = q + } + return out +} + +// remoteRouteReads are the remote magpies whose cards routing has asked +// for in the background, by remoteCardsID: one ask at a time each. +var remoteRouteReads struct { + sync.Mutex + m map[string]bool +} + +// RemoteAllowance is what the Remote magpie p has left for model, its id +// there ("claude/claude-sonnet-5-5"), by the card of the provider serving +// it there ("claude"; "relay" for "relay/strata/m" when no card of +// relay/strata is told), as last read from p. inner is model as that +// card counts it ("claude-sonnet-5-5"). Of several accounts there, the +// one with the most left for the model: the other magpie's own routing +// sends it there. ok is false when nothing is known. +// +// It never waits. With ask, cards older than remoteCardsFor, or none, are +// asked for in the background (the other magpie answers from what it +// keeps, asking no vendor), and what was read stands meanwhile: routing +// asks only when it weighs p against another, so a request to one Remote +// magpie alone sends it nothing more. +func RemoteAllowance(p Provider, model string, ask bool) (a Allowance, inner string, ok bool) { + if !p.IsRemoteMagpie() || p.Key == "" || p.Anthropic == "" { + return nil, "", false + } + id := remoteCardsID(p) + c := &remoteCardCache + c.Lock() + r, had := c.m[id] + c.Unlock() + if ask && (!had || time.Since(r.at) >= remoteCardsFor) { + askRemoteForRouting(p, id) + } + if r.held || len(r.cards) == 0 { + return nil, "", false + } + now := time.Now() + for path := model; ; { + i := strings.LastIndex(path, "/") + if i <= 0 { + return nil, "", false + } + path = path[:i] + inner = model[len(path)+1:] + best, bestUsed := Allowance(nil), 0.0 + for _, q := range r.cards { + if q.Provider != path || !q.routable || q.Error != "" || q.Held { + continue + } + qa := allowanceOf(q.Windows, now) + if len(qa) == 0 { + continue + } + if u, _ := qa.For(inner, now); best == nil || u < bestUsed { + best, bestUsed = qa, u + } + } + if best != nil { + return best, inner, true + } + } +} + +// askRemoteForRouting reads p's cards in the background, unless that is +// under way. +func askRemoteForRouting(p Provider, id string) { + rr := &remoteRouteReads + rr.Lock() + if rr.m[id] { + rr.Unlock() + return + } + if rr.m == nil { + rr.m = map[string]bool{} + } + rr.m[id] = true + rr.Unlock() + c := &remoteCardCache + c.Lock() + gen := c.gen + c.Unlock() + goRead(func() { + defer func() { + rr.Lock() + delete(rr.m, id) + rr.Unlock() + }() + asked := time.Now() + cards, err := askRemote(context.Background(), p, http.MethodGet, RemoteCardsPath, remoteWait) + keepRemoteCardsOf(id, gen, asked, cards, err) + }) +} diff --git a/internal/provider/remote_allowance_test.go b/internal/provider/remote_allowance_test.go new file mode 100644 index 000000000..06073ad9b --- /dev/null +++ b/internal/provider/remote_allowance_test.go @@ -0,0 +1,117 @@ +package provider + +import ( + "context" + "testing" + "time" +) + +// #6708 (zzh11223311 on X): routing weighs a Remote magpie by the cards +// it tells, as last read here. Each window is read as the remote's +// routing reads it (its span, the model it alone counts), the account +// with the most left for the model when the remote has several, and +// nothing is asked of the remote again within remoteCardsFor. A remote +// too old to tell what routing reads isn't weighed. +func TestRemoteAllowance(t *testing.T) { + now := time.Now() + at := func(d time.Duration) *time.Time { t := now.Add(d); return &t } + claude := func(user string, week float64, renews time.Duration) SubscriptionQuota { + return SubscriptionQuota{Provider: "claude", Name: "Claude Code", User: user, Kind: "subscription", Windows: []QuotaWindow{ + {Name: "5 hours", Used: 10, ResetsAt: at(3 * time.Hour), Span: 5 * time.Hour}, + {Name: "7 days", Used: week, ResetsAt: at(renews), Span: 7 * 24 * time.Hour}, + {Name: "7 days · Opus", Used: 95, ResetsAt: at(renews), Span: 7 * 24 * time.Hour, Model: "opus"}, + {Name: "Extra usage", Used: 0, Aside: true}, + }} + } + cards := []SubscriptionQuota{ + claude("a@x.com", 51, 117*time.Hour), + claude("b@x.com", 80, 20*time.Hour), + // a card it has from a magpie behind it, by its whole path + {Provider: "home/codex", Name: "Codex · Home", User: "c@x.com", Kind: "subscription", Via: []string{"home-self"}, + Windows: []QuotaWindow{{Name: "Week", Used: 30, ResetsAt: at(48 * time.Hour)}}}, + } + + t.Run("old remote", func(t *testing.T) { + peer := &fakePeer{cards: cards} // no Routing told + remoteQuotaHome(t, peer) + RemoteCards(context.Background()) + p, err := Find("office") + if err != nil { + t.Fatal(err) + } + if a, _, ok := RemoteAllowance(*p, "claude/claude-sonnet-5-5", true); ok { + t.Errorf("a card with no routing facts is weighed: %+v", a) + } + }) + + peer := &fakePeer{cards: ToldRouting(cards)} + remoteQuotaHome(t, peer) + t.Cleanup(func() { endReadsOut(t, "after the test") }) + p, err := Find("office") + if err != nil { + t.Fatal(err) + } + // not asked to read: nothing is sent + if _, _, ok := RemoteAllowance(*p, "claude/claude-sonnet-5-5", false); ok { + t.Fatal("known before any read") + } + endReadsOut(t, "after a weighing that doesn't ask") + peer.Lock() + asked := peer.gets + peer.Unlock() + if asked != 0 { + t.Fatalf("the remote was asked %d times by a weighing that doesn't ask", asked) + } + // nothing read yet: not known, never waited for; the read it starts + // in the background makes it known + if _, _, ok := RemoteAllowance(*p, "claude/claude-sonnet-5-5", true); ok { + t.Fatal("known before any read") + } + var a Allowance + var inner string + for deadline := time.Now().Add(20 * time.Second); ; { + var ok bool + if a, inner, ok = RemoteAllowance(*p, "claude/claude-sonnet-5-5", true); ok { + break + } + if time.Now().After(deadline) { + t.Fatal("the remote's cards were never read for routing") + } + time.Sleep(10 * time.Millisecond) + } + if inner != "claude-sonnet-5-5" { + t.Errorf("inner model %q", inner) + } + // a@x.com, the one with most left; the Opus week and the extra usage + // don't count Sonnet + if u, renews := a.For(inner, now); u != 51 || len(renews) != 2 || !renews[0].Equal(*at(117 * time.Hour)) { + t.Errorf("Sonnet: used %v, renews %v", u, renews) + } + // the five hours is a rate cap, not the week: the pace goes by the week + if _, due := a.Pace(inner, now); !due.Equal(*at(117 * time.Hour)) { + t.Errorf("pace due %v, want the week's renewal", due) + } + if a, _, ok := RemoteAllowance(*p, "claude/claude-opus-5", true); !ok { + t.Error("Opus not known") + } else if u, _ := a.For("claude-opus-5", now); u != 95 { + t.Errorf("Opus used %v, want 95", u) + } + // a third magpie's card, its span named by the window's name + if a, inner, ok := RemoteAllowance(*p, "home/codex/gpt-5.6-sol", true); !ok || inner != "gpt-5.6-sol" { + t.Errorf("home/codex: %v %q", ok, inner) + } else if _, due := a.Pace(inner, now); !due.Equal(*at(48 * time.Hour)) { + t.Errorf("home/codex pace due %v", due) + } + // a provider the remote tells no card of, and a group there + for _, m := range []string{"deepseek/deepseek-chat", "auto-claude"} { + if _, _, ok := RemoteAllowance(*p, m, true); ok { + t.Errorf("%s known", m) + } + } + peer.Lock() + gets := peer.gets + peer.Unlock() + if gets != 1 { + t.Errorf("the remote was asked %d times, want 1 within remoteCardsFor", gets) + } +} diff --git a/internal/provider/remote_quotas.go b/internal/provider/remote_quotas.go index 21e7f312d..7e0a4efc9 100644 --- a/internal/provider/remote_quotas.go +++ b/internal/provider/remote_quotas.go @@ -201,6 +201,9 @@ func ReadAllCards(ctx context.Context) { var remoteCardCache struct { sync.Mutex m map[string]remoteCardsRead + // gen counts the times the cards were forgotten (a test's + // ForgetRemoteCardsForTest): a read asked before isn't kept after + gen int } type remoteCardsRead struct { @@ -223,6 +226,7 @@ func ForgetRemoteCardsForTest() { c := &remoteCardCache c.Lock() c.m = nil + c.gen++ c.Unlock() k := &remoteKeyCache k.Lock() @@ -391,11 +395,18 @@ func refreshRemote(ctx context.Context, p Provider, card, user string) { // that comes back after one asked later is not kept over it, so a slow // answer from before the key was held can't bring its cards back. func keepRemoteCards(id string, asked time.Time, cards []SubscriptionQuota, err error) remoteCardsRead { + return keepRemoteCardsOf(id, -1, asked, cards, err) +} + +// keepRemoteCardsOf is keepRemoteCards for a read asked while the cards +// were of generation gen (remoteCardCache.gen; -1, whichever): one asked +// before they were forgotten isn't kept. +func keepRemoteCardsOf(id string, gen int, asked time.Time, cards []SubscriptionQuota, err error) remoteCardsRead { c := &remoteCardCache c.Lock() defer c.Unlock() r := c.m[id] - if asked.Before(r.at) { + if asked.Before(r.at) || gen >= 0 && gen != c.gen { return r } r.at = asked @@ -405,8 +416,9 @@ func keepRemoteCards(id string, asked time.Time, cards []SubscriptionQuota, err case err != nil: r.err = err.Error() default: - // a card that came back round isn't kept, nor told again - r.cards, r.err, r.held = withoutLoops(cards), "", false + // a card that came back round isn't kept, nor told again; what + // the remote told for routing is laid on the windows (#6708) + r.cards, r.err, r.held = withRouting(withoutLoops(cards)), "", false } if c.m == nil { c.m = map[string]remoteCardsRead{} diff --git a/internal/provider/subscription_usage.go b/internal/provider/subscription_usage.go index f5fbd0520..bd609a1fb 100644 --- a/internal/provider/subscription_usage.go +++ b/internal/provider/subscription_usage.go @@ -283,6 +283,14 @@ type SubscriptionQuota struct { // this computer (#1547, remote_key_limits.go): the limit that magpie // holds the key to, beside the windows that show it. GatewayKey *GatewayKeyLimit `json:"gatewayKey,omitempty"` + // Routing is, on a card told another magpie (RemoteCardsPath), what + // each window's json leaves out for routing (Span, Model, Aside), in + // the windows' order: that magpie weighs its Remote magpie by the card + // (RemoteAllowance, #6708). Set only as cards are told; nil elsewhere. + Routing []lastWindow `json:"routing,omitempty"` + // routable: a remote magpie's card whose windows have Routing laid + // back on them (keepRemoteCards), so routing may go by them + routable bool // In-process read order, separate from the vendor's ReadAt and never // persisted: restarting starts a new sequence. readSeq uint64