Every agent's model. One place. Codex on DeepSeek, Claude Code on Kimi, from the menu bar.
provider: a plugin's usage window can be a prepaid wallet's balance (#3950)
yetone8bade6c5e246
diff --git a/docs/subsystems/gateway-routing.md b/docs/subsystems/gateway-routing.mdindex 9779787d9..e485b8e13 100644--- a/docs/subsystems/gateway-routing.md+++ b/docs/subsystems/gateway-routing.md@@ -33,7 +33,7 @@ backfilled; see [Gateway Session Aggregation](gateway-sessions.md).| Model resolution | `serve` resolves the model the agent asked for: Claude tier stand-ins, a routing group (`provider.GroupFor`: its id, the model's id however a vendor spells it, else the one group whose name it is, unless a provider serves a model by that id; the user's own groups only while the `groups` plugin is on, [the plugin runtime](plugin-runtime.md#gateway-extension-points-p3-router-strategy)), auto stand-ins, the agent's own stand-in (`StandIn`: Codex's config.toml `model` when magpie is its provider — in a WSL distro, the distro's own, of the ones running now — for a name it sends that magpie doesn't serve, such as its auto-review's `codex-auto-review`), itself taken through `GroupFor` and auto stand-ins so a config naming a group bare reaches it, then `provider.Resolve`. A Codex memory call or auto-review (`x-openai-subagent: guardian`, or `codex-auto-review`) that still names no served model goes to the model Codex's last turn was answered on (`codexMemoryStandIn`, per agent and gateway key; a memory call first waits beside the turn it was started with, through `codexLeads`, see the side turns below), so a Codex on magpie through another provider table, a profile or another computer isn't answered 404 (Adam on Discord, `TestCodexAutoReviewReachesItsTurnsModel`). A bare model id several providers serve (MOMO on Discord: `glm-5.3` under opencode-go and a6api) is never refused: with found groups on (the default) `GroupFor` takes it to the group magpie found for it (`auto-<slug>`), its members in the Providers order, routed and failed over as any group, a conversation staying with the member that answered it while its cache is worth it (affinity); with them off, `Resolve` takes the first provider in the Providers order that exposes it, with no fallback. magpie writes only `provider/model` ids into agents' configs (`magpieModels`), so a bare id is one the user wrote. `/v1/models` lists bare ids only when the user asks for them ([Model ids without the provider](#model-ids-without-the-provider)). Every reply says who answered in `X-Magpie-Provider` and `X-Magpie-Model` (`noteMember`), and the usage log and the Routing page keep it. A model id with `~` and no slash that resolves as nothing else is the one served id (a provider's model or a group) whose slashes it spells as `~` (`unflat`, `provider.Unflat`; MiniMax Code's spelling, #1387), taken back in `validateModel` before key limits, middleware and usage see it; two ids spelled alike are neither. A Claude model id whose version is dashed (`relay/claude-opus-4-6-us`, with or without `:level` and `[1m]`) that is not served as spelled is the one served id it dashes (`provider.ClaudeUndashed`; the spelling magpie gives Claude Code, which reads a dotted version as Claude Opus 4), taken back in `validateModel` and `unprefixed` the same way. An unknown model gets a 404 naming why: a switched-off provider, a disabled group or an empty group. Otherwise it names up to three ids nearest to what was asked (`provider.Closest`: words of a model's display name count before words of its id, and a provider's id or name only alongside them, so "Zen-Space-Bunny" is told `opencode-zen-free/space-bunny-free`, MOMO on Discord), then the ways a model can be named, then every id (`unknownModel`; chat and embeddings). | [`gateway.go`](../../internal/gateway/gateway.go), [`internal/provider/group.go`](../../internal/provider/group.go), [`internal/provider/flat.go`](../../internal/provider/flat.go), [`internal/provider/claudedash.go`](../../internal/provider/claudedash.go) || 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/<model>`: 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`, preferring a spelling models.dev lists), so a client that looks the part after the slash up on models.dev finds it (ZeroClover on X). Its old id `group/auto-<slug>` is served forever. Inside magpie the group keeps that one id: `validateModel` takes `auto/<model>` (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/<model>` by the old id. An agent field magpie set to `group/auto-<slug>` moves to `auto/<model>` on the next `SyncCatalog` (`agent.renameFoundGroups`), but only while its value is still what applied.json says magpie wrote; a value the user set or changed stays. A pick of the group by its old id written now (`Agent.Apply`) is written as `auto/<model>`. 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/<x>` is its model and found groups list as `group/auto-<slug>` (`autoRefsOn`). Hand-made groups stay `group/<id>`. | [`internal/provider/autoref.go`](../../internal/provider/autoref.go), [`key_models.go`](../../internal/gateway/key_models.go), [`internal/agent/autoref.go`](../../internal/agent/autoref.go) || Candidates | `plan` lists one provider's candidates: one per key or account on, then each `Fallback` model, with resting ones last (`restLast`). `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, Weekly pace, 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) or `fast` (speed first). `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. `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 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. `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. 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/<id>`, 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`). 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`). 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) or `fast` (speed first). `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)). `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 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. `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. 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/<id>`, 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`). 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`). 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`). `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`); a fallback is never asked for want of either. 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) || 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) || Image generation | `/v1/images/generations` and `/v1/images/edits` are translated to the selected model's image API. OpenRouter image-only models use its `/images` endpoint and send reference images as `input_references`; OpenRouter models that return images through chat stay on Chat Completions. Volcengine Ark (`isArk`: an `ark.*.volces.com` base, the preset's plans or one added by hand) is asked at `/images/generations` only, as its doc (https://www.volcengine.com/docs/82379/1541523) takes it (`drawArk`): `watermark: false`, since it marks every image otherwise; reference images as JSON `image` (a URL or data URL, an array for several), never a multipart edit; no `n`, so one request per image (`eachDrawing`); no ratio as `size`, so a ratio its doc lists is sent as that ratio's 2K size and any other is a 400 that says to put it in the prompt; no mask, no quality (JL on Discord, `TestArkDrawsWithoutWatermarkOncePerImage`). A routing group named for a drawing or a video (`drawingGroup`: `group/<id>`, or a bare id the group goes by that resolved to one of its members) is tried member by member in the order its routing plans for a chat (`drawingTries` over `planGroup`), each member over its own keys or accounts (`drawOnAccounts`, `startVideo`); the next member is asked while one fails as a chat's would move on (`retryable`: its vendor 5xx, out of quota, the model not served), never for a refusal of the request itself, and the call's `Fallback` names those tried first (#2005, tianxia3111: a group of two relays answered the first one's 502). Pause rules and a gateway key's group hold apply as for a chat. A failed drawing rests no member and no key. An account out of quota for the image model (`failure` reads `failQuota`) rests that model on it alone (`restDrawer`, keyed by `restID`), until the reset its refusal names (`resetsAt`: Antigravity's "Your quota will reset after 3h19m30s.") or `quotaRest`, so the next drawing asks the accounts that still have it first (`restLast`), and the account's text models stay in. Antigravity also tells a model's quota used up as a 200 whose stream is the error; `drawCodeAssist` gives such an error the status its words stand for (`saidStatus`: quota or rate 429, credit 402, else 502), as the images API's 200 with no image does, so a spent account hands the drawing to the next one as its 429 does (01huadalang on Discord: a 502 ended the drawing on the spent account; `TestAntigravityDrawingOutOfQuotaInsideTheReplyGoesOn`, `TestAntigravityDrawingQuotaRestsTheImageModel`). `TestImageGroupMovesOnToTheNextMember`, `TestVideoGroupMovesOnToTheNextMember`. An account's own list of models (#474) never bars a ChatGPT account's GPT Image, a Grok subscription's Grok Imagine or a WorkBuddy plan's image models (`listsCantName`): the list is picked from the editor's chat models, which they are never among, so a list kept for some chat models had every drawing refused as "set not to be served by any account" (heyiwei5 on X). A key's list, picked from models that include its image ones, still bars them. `TestCodexDrawsPastAccountModelLists`. A drawing is given Settings → Images → Image generation timeout (`imageTimeout`, 1 to 60 minutes, 5 when unset; neighbads on X: a slow image endpoint needed more) as its context's deadline (`drawTimeout`, `drawWithin`), and so is downloading an image answered as a link (`imageLongest`, never under `ImageLongest`). A drawing's request goes through a transport with no `ResponseHeaderTimeout` (`drawsApart`), since an images API sends its headers only once it has drawn, and every other request keeps `upstreamHeaderWait` (10 minutes). A video's submit, status and download calls keep 5 minutes each (`videoTimeout`). The `magpie mcp image` process, which may not read these settings (WSL), waits on a call up to `callLongest` (two hours and a minute), so it never cuts one the gateway still waits on. `TestLongImageTimeoutLetsASlowVendorFinish`, `TestImageTimeoutSettingReachesTheVendor`, `TestOnlyDrawingsWaitPastTheHeaderWait`. | [`draw.go`](../../internal/gateway/draw.go), [`draw_volcengine.go`](../../internal/gateway/draw_volcengine.go), [`video.go`](../../internal/gateway/video.go), [`catalog.go`](../../internal/catalog/catalog.go) |diff --git a/docs/subsystems/plugin-runtime.md b/docs/subsystems/plugin-runtime.mdindex babf1906e..720ce969e 100644--- a/docs/subsystems/plugin-runtime.md+++ b/docs/subsystems/plugin-runtime.md@@ -194,7 +194,7 @@ the core. The seven other routings are the built-in plugin `rotation`'s.| Part | What it does | Source || --- | --- | --- || `routes.Strategy` | `Order(pool, seats) []int`: a permutation of the seats' indexes. `pool` is a provider's id or `group/<id>`, for a strategy that keeps a round per pool. `Exact` keeps the order as given; otherwise a provider's API keys that fit the request better go first, each in its order. `ByUse` puts each seat's recent tokens in the trace; `ByFree` has the gateway fill `Seat.Free`, and `BySpeed` `Seat.TTFT` and `TPS` (its speed lately, gateway `speed.go`), each only for a strategy that asks. | [`routes.go`](../../internal/routes/routes.go) |-| `routes.Seat` | What a strategy weighs, read by `weighRouted` under the routing state's lock: its rest key, whether it is an account, whether its allowance is known or it learns it as it answers, the share used, when its windows renew, its weekly pace, its key's weight, whether it rests now, its tokens of the last hours, and, when the strategy asks, whether its model is free and its ms to the first token and tokens a second lately. | [`routes.go`](../../internal/routes/routes.go), [`routing.go`](../../internal/gateway/routing.go) |+| `routes.Seat` | What a strategy weighs, read by `weighRouted` under the routing state's lock: its rest key, whether it is an account, whether its allowance is known or it learns it as it answers, the share used, when its windows renew, its weekly pace, its key's weight, whether it rests now, its tokens of the last hours, a prepaid wallet's balance and the provider and unit it is in (`Left`, `LeftIn`, #3950), and, when the strategy asks, whether its model is free and its ms to the first token and tokens a second lately. | [`routes.go`](../../internal/routes/routes.go), [`routing.go`](../../internal/gateway/routing.go) || `Register`, `Find`, `Apply` | `Register(routing, s)` serves a routing until its remove; registering again stacks, and the last one serves. `Find("")` is `Smart` always. `Apply` fails open: a strategy that panics, or answers what isn't a permutation, leaves the pool in its listed order, logged. Every route is still tried. | [`routes.go`](../../internal/routes/routes.go) || Strategies | `Smart` (core), and `Ordered`, `Rotate`, `LeastUsed`, `Pace`, `Weighted`, `FreeFirst` and `Fastest` in `routes.Builtin`. `Rotate` keeps a turn per pool and `Weighted` a smooth weighted round (`Round`, `MoveRound`), both moved out of the gateway, and `Fastest` a probe count per pool, so a seat not measured lately gets one request in `ProbeEvery`; `Forget` clears them. | [`strategies.go`](../../internal/routes/strategies.go), [`round.go`](../../internal/routes/round.go) || Off | A routing no strategy serves is its listed order. `routingOf` in the gateway reads it as `order` wherever the core asks about a routing (a turn's mark, `sinks`, a rotate group's sessions, a group's heads), so nothing of the routing is left half on. | [`routing.go`](../../internal/gateway/routing.go) |diff --git a/docs/subsystems/provider-plugins.md b/docs/subsystems/provider-plugins.mdindex f5eadebdd..116a6998a 100644--- a/docs/subsystems/provider-plugins.md+++ b/docs/subsystems/provider-plugins.md@@ -42,6 +42,10 @@ The gateway parses the field into `Usage.Deferred` ([`cUsage`](../../internal/gaA usage window's `used` (percent) may be left out when the plugin can't tell it: the Loomy plugins send only `display` ([#3650](https://github.com/yetone/magpie/issues/3650)). Left out is not 0. The host passes it on as `null` (`usageOf` in [`host.js`](../../internal/plugin/host.js)), `plugin.UsageWindow.Used` is a `*float64`, and [`quotaOfPlugin`](../../internal/provider/plugin_usage.go) makes such a window `Text` and `Aside`: the card shows its `display` (else "No allowance reported"), never a percentage or a meter (`quotaNoShare` in `app.js`), and `allowanceOf` leaves it out. An account whose windows all tell no share has no allowance, so routing counts it not known (`routedAllowance` in [`routing.go`](../../internal/provider/routing.go), for a fresh reading and the one kept on disk alike), as one never read, rather than as the one with all of it left. A window that says `used: 0` is a reading at 0, as before. [`plugin_usage_absent_test.go`](../../internal/provider/plugin_usage_absent_test.go) and `usage-no-reading.test.cjs` cover both.+## A wallet's balance++A prepaid wallet (SuperMagic's points, [#3950](https://github.com/yetone/magpie/issues/3950)) has a balance and nothing it is a share of. A usage window may send `balance` (a number, in `unit`) and leave out `used`, `limit` and `aside`: `{name: "积分", balance: 6291, unit: "积分"}`. The host passes a finite number on, at least 0, and anything else as `null` (`usageOf` in [`host.js`](../../internal/plugin/host.js)); `plugin.UsageWindow.Balance` and `provider.QuotaWindow.Balance` are `*float64`. [`quotaOfPlugin`](../../internal/provider/plugin_usage.go) keeps the figure and does not make the window `Text` or `Aside`, so the account is known to routing with no `Used` invented. `allowanceOf` copies it into `Limit.Balance`, and an empty wallet (0) counts as used up. `Allowance.Left(model)` is the least balance of the windows that count the model, with its unit. `weighRouted` sets `routes.Seat.Left` to it and `Seat.LeftIn` to the account's provider and unit; Smart, `pace` and `usage` put the seat with more left first where they would otherwise tie (`byLeft` in [`strategies.go`](../../internal/routes/strategies.go)), and only when every seat that has a balance shares one `LeftIn`, so balances in two units or two providers are never weighed against each other. The card, the Routing page (`Weighed.Balance`) and the CLI show the figure ("6,291 积分 left", `provider.BalanceText`) and no meter. Tests: `TestPluginWalletBalanceIsAReading`, `TestPluginHostPassesABalanceOn`, `TestWalletsGoByWhatTheyHaveLeft`, `TestWalletWithMoreLeftGoesFirst`, `usage-wallet-balance.test.cjs`, `routing-wallet-balance.test.cjs`.+## Cache a vendor doesn't countA plugin whose vendor counts no cache tokens says so with `usage.magpie_cache_unknown: true` in its Anthropic usage, and leaves the cache fields out. Kiro does this: it caches on its side (a repeated prompt costs about half the credits), but its replies carry credits and a context share, never tokens (opencode-kiro-auth 0.1.16, zeewell on X). The gateway reads the field in [`aUsage`](../../internal/gateway/anthropic.go) into `Usage.cacheUnknown`, ORed across a reply's usage events. [`routeUsage`](../../internal/gateway/trace.go) then sets `RouteUsage.CacheUnknown` on a try that counted no cache read or write. The Routing page's `promptOf` (`plugins/routing/client.js`) leaves such a try out of the hit rate, so the request shows none, not 0%. The field is never told to a client: `Usage.anthropic()` leaves it out, and a passthrough forwards the plugin's bytes as they are. The usage ledger carries it too ([#3464](https://github.com/yetone/magpie/issues/3464)): the gateway records `usage.Record.CacheUnknown` on a call that counted no cache (`Usage.cacheNotCounted`), the ledger keeps it as row flag 8192 (`rowCacheUnknown`), and `usage.Totals` sums such calls' prompt into `cache_unknown` and their count into `cache_unknown_calls`. Every hit rate leaves that prompt out of its denominator: `Totals.HitRate`, and `cacheHitOf` in app.js, used by the tray panel's card, the Usage page's agent rows and cache tile, the requests' Cache hit rate card (which says how many it left out, `cacheLeftOut`) and each ranking row. One of only such calls shows no rate. A request row's cache cells show "—" and its details say the vendor doesn't count the cache. Calls kept before Kiro's plugin said so carry no flag, so a Kiro call (`kiro` or `kiro-plugin`) with no cache counted is read as one (`usage.CountsNoCache`): in the ledger's `rowChunk.row`, in `Totals.countCache`, and for Routing's history in `pricedRoutes` (`cacheCounted`, `internal/gui/trace.go`). The context view (`internal/gui/context.go`, `context.js`) shows no cache for such a call and doesn't score it as a miss. Not covered: hit rates read from agents' own session files (`sessions.Tokens`: the TUI and CLI session lists, the Sessions tab's totals), which carry Kiro's 0 as a miss. [`cache_unknown_test.go`](../../internal/gateway/cache_unknown_test.go) covers the passthrough and translated replies, both whole and streamed.diff --git a/docs/subsystems/providers-accounts.md b/docs/subsystems/providers-accounts.mdindex 935eb334d..ff8d940e6 100644--- a/docs/subsystems/providers-accounts.md+++ b/docs/subsystems/providers-accounts.md@@ -46,7 +46,7 @@ keys and accounts per request is in [Gateway routing and fallback](gateway-routi| Used-up switch | When the account Codex or Claude Code is signed in to has used its allowance, the agent is signed in to the next account that is on and has room (#208). For Codex, *Only switch Codex's sign-in* (`SwitchOnly`, `SetSwitchOnly`) keeps magpie's `openai_base_url` failover out of Codex's config, so the switch is all magpie does (#1907); an unreadable providers.json reads as switch-only, so the failover is not written on a guess. | [`codex_switch.go`](../../internal/provider/codex_switch.go) || 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/<id>`); `SaveGroup` refuses loops. A group given another id (`agent.RenameGroup`: the Routing page, `magpie groups rename`, the TUI) moves every agent field on `group/<old>` to `group/<new>`, spelled as the agent spells it, through the same `renameRefs` a provider's rename uses, then `SyncCatalog`; before, the agents stayed on a group magpie no longer had (lucis0116 on X, `TestRenameGroupMovesTheAgentsOnIt`). A provider's or group's display name needs no move: `store` and `SaveGroup` drop the catalog, and `SyncCatalog` writes the new labels into every agent's list. `Match` takes a glob or `re:` pattern (#766), both matched in any case (`compilePattern`; `(?-i)` inside a `re:` makes case matter). A 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` and said as switched off on the Routing 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. A switched-off provider's members stay in it, skipped by `membersIn`, and the Routing page says them as switched off (`memberJSON.providerOff`). The user's own groups keep their members. Three templates make a group in one click from the models the user has (`provider.Templates`, `AddTemplate`; the Routing page's cards before a first group and its Templates menu after, `magpie group template [kind] [name]`): `smart` sends a hard turn to the strongest model and an easy one or a compaction to a cheap one, asked by a classifier (the decision API when there is one, else the cheapest priced model that doesn't reason); `thrifty` starts on two cheap models of different providers and sends high reasoning to the strongest; `steady` fails over between the strongest model of up to three providers. A model is weighed by its maker's list price when known, else what its provider charges, else by its id's size words (`sizeOf`); one over `tooDear` (USD 100 a million output tokens) is never picked. A template that can't be made says what is missing (`Need`). It is saved under a name and id no group has (`freeGroupName`, shared with `CopyGroup`), never over one. A group is shared as text (`ShareGroup`, a group row's Copy to share): JSON marked `"magpie": "routing-group"` with a format `version` (`ShareVersion`), holding the group's members as it names them, patterns, routing, rules, classifier and settings. A group holds only `provider/model` ids, never a key, account or address, and the derived matches, found/hidden/off flags and the rules that hold by a folder (a path on the sharer's machine, `Rule.Folders`) stay behind; a pasted one is left out too. `ImportGroup` (the Routing page's Import, `POST /api/groups/import`) reads it with words or a code fence around it, refuses another text, a newer format or none (`ShareError`, said in the reader's language). A member whose provider the importer has is kept; else the same model (`AutoGroupOf`) under the first provider of theirs that serves it (`Instead`); else it is left out and named (`Missing`), with the rules that send to it, its place among the off and fast members, and a classifier gone takes the intent rules and auto effort with it. Nothing is added when no member is left; what is added gets a free name, never replacing a group. A group of patterns only that match nothing now (a plugin's models not listed) has no members: `/api/groups` says them, and an unmakeable template's, as `[]`, never `null`; the Routing page reads the response through `groupsFrom` and draws a group it still can't draw as one row saying so, so one bad group never hides the rest (#1585). | [`group.go`](../../internal/provider/group.go), [`grouptemplate.go`](../../internal/provider/grouptemplate.go), [`group_share.go`](../../internal/provider/group_share.go) |-| Allowance | `Quotas` asks every vendor at once: subscription windows (`SubscriptionUsage`), key-bought plans (`PlanQuotas`) and key balances (`KeyBalances`). The Usage page, `magpie quota --json` and `GET /v1/magpie/quotas` read it, each window with its whole-window estimate (`Holds`/`HoldsWhy`, `usage.WithWindowHolds`, which `quotaReport` reaches through the `ReckonHolds` hook since package provider can't import usage, #2333). A single card can be read again on its own (#840). A remote magpie's cards come from what it has kept (`CachedCards`, `GET /v1/magpie/quotas/cards`) and are never read there for this computer except by a card's refresh (`POST /v1/magpie/quotas/refresh`, throttled per card). What it has kept is the Usage page's cards with the readings made behind the requests since laid over them, a later one over an earlier by `readSeq` (`cards_kept.go`): each account's `LoginUsage` reading (the used-up switch, the Codex warm-up, routing's `Allowances`), and each key's `KeyAllowance` windows on its plan or balance card. A Claude account's windows Claude Code told as it answered (`NoteClaudeLimits`, kept in `claudeUsage` with their own `heardSeq`, which drops the account's `LoginUsage` reading) stand on its card over any reading started before them (`withHeardClaude`, #2206), so a magpie only requests reach still tells them. An account or key read that way and never on the page gets a card from that reading, and after a restart, before either is read again, the cards come from `quotas.json`, dated (`AsOf`). A magpie serving only other magpies has nobody on its page (#1313). Each key of a remote-magpie provider also gets a card of its own, under `<remote>/~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=<remote>/~keys&user=<key name>`). 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 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 only the key's own card shows. Its owner can let the key be told the cards of what it may use (#2216, `magpie gateway-key quotas <id> on`); the remote then answers those, and 403 as before when that is none. 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. | [`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 single card can be read again on its own (#840). A remote magpie's cards come from what it has kept (`CachedCards`, `GET /v1/magpie/quotas/cards`) and are never read there for this computer except by a card's refresh (`POST /v1/magpie/quotas/refresh`, throttled per card). What it has kept is the Usage page's cards with the readings made behind the requests since laid over them, a later one over an earlier by `readSeq` (`cards_kept.go`): each account's `LoginUsage` reading (the used-up switch, the Codex warm-up, routing's `Allowances`), and each key's `KeyAllowance` windows on its plan or balance card. A Claude account's windows Claude Code told as it answered (`NoteClaudeLimits`, kept in `claudeUsage` with their own `heardSeq`, which drops the account's `LoginUsage` reading) stand on its card over any reading started before them (`withHeardClaude`, #2206), so a magpie only requests reach still tells them. An account or key read that way and never on the page gets a card from that reading, and after a restart, before either is read again, the cards come from `quotas.json`, dated (`AsOf`). A magpie serving only other magpies has nobody on its page (#1313). Each key of a remote-magpie provider also gets a card of its own, under `<remote>/~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=<remote>/~keys&user=<key name>`). 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 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 only the key's own card shows. Its owner can let the key be told the cards of what it may use (#2216, `magpie gateway-key quotas <id> on`); the remote then answers those, and 403 as before when that is none. A remote's cards are kept by provider and key (`remoteCardsID`), so a changed key never shows what the old one was told, and a read is kept only over one asked before it (`keepRemoteCards`). Cursor, Grok and a Kiro key keep the page's cards only. With Settings → Allowances → *Allowance reads* at *When I ask* (`QuotaReads == "asked"`, #1518: magpie started at login before the proxy app read by itself, direct), only a read the user asked for goes out: the Usage page or the tray panel's Allowances opened (no more than once in 30s, `quotasOpened`, #1588) or refreshed (`?asked=1`), a card's refresh (`RefreshUsage`), `magpie quota`, `magpie accounts`, `magpie quota wait` and the TUI's quotas (`Asked`). Any other read (`quotaReading` → `holdUnasked`) carries `netproxy.Hold`, so its requests fail before they leave, and every reader gives back what it last read, dated, or "not read yet" (`errNotAsked`): routing, the used-up switch, the menu bar and alerts go by that. An account refused for its quota (`StaleAllowance` → `markStaleRead`) or a key refused (`StaleKeyAllowance` → `refused`) is still read, once (`unheld`). Warm-up and check-in are not reads and are unchanged. A plugin's window may carry a prepaid wallet's `balance` in its `unit` and no share (`QuotaWindow.Balance`, #3950): the card and `magpie quota` show the figure (`BalanceText`), and routing reads it through `Allowance.Left`. | [`cards_kept.go`](../../internal/provider/cards_kept.go), [`quotas.go`](../../internal/provider/quotas.go), [`subscription_usage.go`](../../internal/provider/subscription_usage.go), [`planquota.go`](../../internal/provider/planquota.go), [`balance.go`](../../internal/provider/balance.go), [`quota_refresh.go`](../../internal/provider/quota_refresh.go), [`remote_quotas.go`](../../internal/provider/remote_quotas.go), [`remote_key_limits.go`](../../internal/provider/remote_key_limits.go), [`quota_asked.go`](../../internal/provider/quota_asked.go) || A remote magpie's prices | A local magpie asks a remote magpie's `/v1/models` with `X-Magpie-Prices` (`PricesHeader`, sent by `listHeaders`). The remote answers each model's `magpie_price`: what its own Usage page counts the model at (`EntryPriceIn`: the price its user set, else its provider's list price at its price rate; a routing group only when every member costs the same). It tells it only to a request from its own computer or one let in with a gateway key (`local` or `sharedWith`); a list that didn't ask gets no `magpie_price` (a remote request without a valid key never reaches the list: `lanGuard` refuses it); every list told to those callers also carries the same price as OpenRouter's `pricing`, for agents ([gateway routing](gateway-routing.md)). The local keeps the price with the fetched list (`catalog.Model.Price`; a value that isn't a price, or has a negative part, is dropped, the model kept) and uses it as that provider's list price (`ListPrice` → `remotePrice`). A price the local user set (`provider/model`, `provider/*`, `*/model`) still comes first, and the local provider's own price rate still applies on top. A remote from before this sends no field and the models stay priced as before; an older local sends no header and is sent nothing new. The model editor says the greyed price is the other magpie's (`remoteList`). | [`remote_magpie.go`](../../internal/provider/remote_magpie.go), [`models.go`](../../internal/provider/models.go), [`gateway.go`](../../internal/gateway/gateway.go) (`models`), [`live.go`](../../internal/catalog/live.go) || A remote magpie's service tiers | A remote magpie's `/v1/models` gives each model the `service_tiers` its own Codex is offered on it (`codexTiers` → `codexcat.ServiceTiers`, from the same `CodexCatalog` and `codexcat.Entries` as its `/v1/codex/models`: Fast on a ChatGPT account's GPT model, the tiers of Codex's own entry on a relay's, none on a model it offers none). The local keeps the ids (`catalog.Model.Tiers` → `Entry.Tiers`), `codexListed` hands them on for the remote's models, and `codexcat.Entries` offers them to the local Codex with Codex's own names (`namedTiers`). The gateway sends the tier Codex asks for to a remote magpie as it was asked (`Request.OwnTier`, as for a provider added by its address; dropped and not sent again if refused), and the remote serves it as its own Codex's turn (#1234). An agent's picker offers the bolt on a remote's model whose tiers hold `priority` (`provider.CanFast` reads them with `RemoteTiers`; Ultrafast too where they hold `ultrafast`, `UltraOn`), and a fast pick of one goes on with `service_tier` `priority` on the remote's Chat or Responses: an agent on Messages, whose fast is Claude's `speed`, has it turned into the tier the remote offers (`forwardTranslated`), so Claude Code's pick reaches the remote's vendor too (littlekk88 on Discord; `TestRemoteMagpieFastPick`, red without either half). A remote from before this sends no tiers, and its models are offered none, as before. The list gives every client the tiers, not only a magpie asking with `X-Magpie-Drawers`: Cindy shows its Fast switch on a model whose `service_tiers` hold `priority` (#1914, `TestModelsListTiersForEveryClient`). | [`codexcat.go`](../../internal/codexcat/codexcat.go), [`codex_models.go`](../../internal/provider/codex_models.go), [`codex_catalog.go`](../../internal/gateway/codex_catalog.go), [`gateway.go`](../../internal/gateway/gateway.go), [`live.go`](../../internal/catalog/live.go) || A relay's Codex entries | A provider the user added by its address with a Responses URL may list its models in Codex's own shape (`slug`, `supported_reasoning_levels`, `shell_type`, `base_instructions`: `catalog.CodexEntry`), plainly or when asked with Codex's `client_version`, as sub2api does (ctopsc on Discord: GPT-6.1 Terra was handed models.dev's 922000 window where the relay said 272000). `fetchOne` keeps such a row whole (`catalog.Model.Codex`, with its window, max window and inputs read off it), and when the plain list has none it asks the same URL once more with `client_version` (`codexEntries`): only where the list is fetched (add, key change, Refresh), never per Codex poll. The answer only adds entries to models the plain list has; one that fails or can't be read keeps the last list's entries (failed read = unknown), one that answers plainly says there are none. `codexcat.listedEntry` hands Codex the relay's entry as given, `base_instructions` included, with magpie's slug, name, priority and " via magpie" description; the user's window, compaction, levels and image setting still win (levels keep the relay's descriptions). A saved list from before is enriched at its next Refresh. `TestCodexListedEntry`, `TestCodexListedEntryInPlainList`. | [`codex_entries.go`](../../internal/provider/codex_entries.go), [`live.go`](../../internal/catalog/live.go), [`codexcat.go`](../../internal/codexcat/codexcat.go) |diff --git a/internal/cli/accounts_cli.go b/internal/cli/accounts_cli.goindex 5cbb86868..b7b8d0a8e 100644--- a/internal/cli/accounts_cli.go+++ b/internal/cli/accounts_cli.go@@ -360,7 +360,7 @@ func accountRows(ls []provider.Login, now time.Time) []accountRow {// a pool's own windows stand in for the models' drawing on it,// as the usage page shows themfor _, w := range provider.PooledWindows(q.Windows) {- s := quotaSpan{Name: w.Name, Used: w.Used, Remaining: max(0, 100-w.Used), ResetsAt: w.ResetsAt, Display: w.Display, Text: w.Text, Pool: w.Pool}+ s := quotaSpan{Name: w.Name, Used: w.Used, Remaining: max(0, 100-w.Used), ResetsAt: w.ResetsAt, Display: w.Display, Text: w.Text, Pool: w.Pool, Unit: w.Unit, Balance: w.Balance}if s.ResetsAt == nil && w.ResetSecs > 0 {t := now.Add(time.Duration(w.ResetSecs) * time.Second)s.ResetsAt = &t@@ -382,7 +382,10 @@ func quotaCell(w quotaSpan, now time.Time) string {return name + " unlimited"}cell := fmt.Sprintf("%s %.0f%%", name, w.Used)- if w.Text {+ if w.Balance != nil {+ // a wallet tells what is left, never a share (#3950)+ cell = name + " " + provider.BalanceText(*w.Balance, w.Unit)+ } else if w.Text {// a row of text alone has no share to tellcell = name + " " + w.Display} else if w.Display != "" {diff --git a/internal/cli/accounts_cli_test.go b/internal/cli/accounts_cli_test.goindex 0e3de619f..6326a20b3 100644--- a/internal/cli/accounts_cli_test.go+++ b/internal/cli/accounts_cli_test.go@@ -151,6 +151,19 @@ func TestQuotaCell(t *testing.T) {if got := statuslineCard(provider.Quota{Provider: "autoclaw-plugin", Windows: []provider.QuotaSpan{{Name: "积分余额", Display: "1,234 积分", Text: true}, {Name: "5 hours", Used: 40}}}, now); got != "autoclaw-plugin 积分余额 1,234 积分 5h 40%" {t.Fatalf("status line: %q", got)}+ // a wallet's balance is its figure in its unit, not 0% (#3950)+ bal := 6291.0+ if got := quotaCell(quotaSpan{Name: "积分", Balance: &bal, Unit: "积分"}, now); got != "积分 6,291 积分 left" {+ t.Fatalf("balance: %q", got)+ }+ if got := statuslineCard(provider.Quota{Provider: "magicrew-plugin", Windows: []provider.QuotaSpan{{Name: "Wallet", Balance: &bal, Unit: "积分"}}}, now); got != "magicrew-plugin Wallet 6,291 积分 left" {+ t.Fatalf("status line balance: %q", got)+ }+ for b, want := range map[float64]string{0: "0 pts left", 1234567.5: "1,234,567.5 pts left", 12.345: "12.35 pts left"} {+ if got := provider.BalanceText(b, "pts"); got != want {+ t.Errorf("BalanceText(%v): %q, want %q", b, got, want)+ }+ }}// accountRows shows a pool's own windows in place of its models', as thediff --git a/internal/cli/statusline_cli.go b/internal/cli/statusline_cli.goindex 6eb480354..a4afafed7 100644--- a/internal/cli/statusline_cli.go+++ b/internal/cli/statusline_cli.go@@ -155,6 +155,9 @@ func statuslineCard(q provider.Quota, now time.Time) string {switch {case w.Unlimited:cells = append(cells, n+" ∞")+ case w.Balance != nil:+ // a wallet's figure in its unit, never a share (#3950)+ cells = append(cells, n+" "+provider.BalanceText(*w.Balance, w.Unit))case w.Text:// a row of text alone (a plugin's balance) has no sharecells = append(cells, n+" "+w.Display)diff --git a/internal/gateway/routing.go b/internal/gateway/routing.goindex 7a4725cb9..602124ea6 100644--- a/internal/gateway/routing.go+++ b/internal/gateway/routing.go@@ -1618,6 +1618,11 @@ type left struct {// credits: a Codex account that goes on on its credits once its// allowance is used up (spendsCredits)credits bool+ // bal is a prepaid wallet's balance in balUnit (Allowance.Left,+ // #3950); balIn says whose wallet it is, provider and unit, and is+ // empty when no balance was told: routes.Seat.LeftIn+ bal float64+ balUnit, balIn string}// learns: c is a subscription whose allowance isn't known yet, of an agent@@ -1673,12 +1678,14 @@ func weighRouted(p provider.Provider, cs []candidate, model string, from providefor _, c := range cs {var a provider.Allowancevar ok bool+ whose := c.p.ID // whose wallet a balance is inif c.p.Account == nil {// a key that reads its own windows is weighed by them as an// account is; any other key isn't knowna, ok = keyAllowance(c.p)} else {ag := c.p.Account.UsageAgent()+ whose = agif _, had := known[ag]; !had {known[ag] = allowances(ag)}@@ -1689,8 +1696,14 @@ func weighRouted(p provider.Provider, cs []candidate, model string, from providepc, due := a.Pace(c.model, now)amt, of, unit := a.Count(c.model, now)rs := a.Restarts(now)- wg.lefts[c.allowanceKey()] = left{used: u, renews: r, fullest: a.Fullest(c.model, now), soon: a.Renewal(c.model, now), lapse: a.Lapse(c.model, now), pace: pc, due: due, amount: amt, of: of, unit: unit,+ l := left{used: u, renews: r, fullest: a.Fullest(c.model, now), soon: a.Renewal(c.model, now), lapse: a.Lapse(c.model, 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+ if b, bu, has := a.Left(c.model); 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+ }+ wg.lefts[c.allowanceKey()] = l}}if len(cs) < 2 {@@ -1711,7 +1724,8 @@ func weighRouted(p provider.Provider, cs []candidate, model string, from providepace = provider.FreshPace}seats[i] = routes.Seat{Key: c.rest, Account: c.p.Account != nil, Known: known, Learns: learns(c, wg.lefts),- Used: l.used, Soon: l.soon, Lapse: l.lapse, Pace: pace, Weight: keyWeight(c), Resting: resting(c), Tokens: routed.used[c.restKey()].now(now), Credits: l.credits}+ Used: l.used, Soon: l.soon, Lapse: l.lapse, Pace: pace, Weight: keyWeight(c), Resting: resting(c), Tokens: routed.used[c.restKey()].now(now), Credits: l.credits,+ Left: l.bal, LeftIn: l.balIn}}routed.Unlock()if st.ByUse {diff --git a/internal/gateway/trace.go b/internal/gateway/trace.goindex a837893f0..9de5ef492 100644--- a/internal/gateway/trace.go+++ b/internal/gateway/trace.go@@ -258,9 +258,12 @@ type Weighed struct {Used float64 `json:"used"` // share of the allowance counting the model, used// Amount of Limit in Unit: the count that share is of, when the// vendor counts it so (WorkBuddy's credits, #659)- Amount float64 `json:"amount,omitempty"`- Limit float64 `json:"limit,omitempty"`- Unit string `json:"unit,omitempty"`+ Amount float64 `json:"amount,omitempty"`+ Limit float64 `json:"limit,omitempty"`+ Unit string `json:"unit,omitempty"`+ // Balance is a prepaid wallet's left in Unit (left.bal, #3950): the+ // Routing page tells the figure, not a share+ Balance *float64 `json:"balance,omitempty"`Renews []time.Time `json:"renews,omitempty"` // when those windows renew, the biggest firstPace float64 `json:"pace,omitempty"` // remaining allowance per hour until its window resetsDue *time.Time `json:"due,omitempty"` // when the allowance window used for pace resets@@ -462,6 +465,10 @@ func weighed(c candidate, p provider.Provider, wg weighing, fallback bool, fromif l.of > 0 {w.Amount, w.Limit, w.Unit = l.amount, l.of, l.unit}+ if l.balIn != "" {+ b := l.bal+ w.Balance, w.Unit = &b, l.balUnit+ }if !l.due.IsZero() {due := l.duew.Due = &duediff --git a/internal/gateway/wallet_balance_test.go b/internal/gateway/wallet_balance_test.gonew file mode 100644index 000000000..8e21349d0--- /dev/null+++ b/internal/gateway/wallet_balance_test.go@@ -0,0 +1,53 @@+package gateway++import (+ "strings"+ "testing"++ "github.com/yetone/magpie/internal/provider"+)++// 墨雨藏锋 / mycf_711 (#3950): SuperMagic's accounts are prepaid wallets of+// points with no total. Under smart, pace and least used the account with+// 6,291 points left goes before one with 750, whatever their order; the+// Routing page is told each one's figure, not a share. A balance in+// another unit, or another provider's, is never weighed against it.+func TestWalletWithMoreLeftGoesFirst(t *testing.T) {+ old := allowances+ defer func() { allowances = old }()+ share := map[string]provider.Allowance{}+ allowances = func(string) map[string]provider.Allowance { return share }+ wallet := func(left float64, unit string) provider.Allowance {+ return provider.Allowance{{Name: "积分", Balance: &left, Unit: unit}}+ }+ acct := func(agent, user string) candidate {+ return candidate{p: provider.Provider{ID: agent, Account: &provider.Account{Agent: agent, User: user}}, model: "m", rest: agent + "#" + user}+ }+ for _, routing := range []string{"", provider.Pace, provider.LeastUsed} {+ p := provider.Provider{ID: "magicrew", Routing: routing}+ order := func(cs ...candidate) (string, weighing, []candidate) {+ got, wg := weigh(p, cs, "m", provider.Chat)+ var s []string+ for _, c := range got {+ s = append(s, c.p.Account.User)+ }+ return strings.Join(s, ","), wg, got+ }+ share["small"], share["big"] = wallet(750, "积分"), wallet(6291, "积分")+ got, wg, cs := order(acct("magicrew", "small"), acct("magicrew", "big"))+ if got != "big,small" {+ t.Errorf("%q: %s, want big,small", routing, got)+ }+ if w := weighed(cs[0], p, wg, false, provider.Chat); !w.Known || w.Balance == nil || *w.Balance != 6291 || w.Unit != "积分" || w.Used != 0 {+ t.Errorf("%q: the Routing page's row: %+v", routing, w)+ }+ share["big"] = wallet(6291, "credits")+ if got, _, _ := order(acct("magicrew", "small"), acct("magicrew", "big")); got != "small,big" {+ t.Errorf("%q, another unit: %s, want their order", routing, got)+ }+ share["big"] = wallet(6291, "积分")+ if got, _, _ := order(acct("magicrew", "small"), acct("othercrew", "big")); got != "small,big" {+ t.Errorf("%q, another provider: %s, want their order", routing, got)+ }+ }+}diff --git a/internal/gui/assets/app.js b/internal/gui/assets/app.jsindex c77040a6f..8cfabeda5 100644--- a/internal/gui/assets/app.js+++ b/internal/gui/assets/app.js@@ -13859,16 +13859,14 @@ async function refreshLanes() {for (const pill of document.querySelectorAll(".alane")) laneText(pill);}-// A window reads as how much of it is used, or — as the vendors' own apps-// show it — how much is left, the bar filling with that; one choice for-// every meter and the menu bar, kept in the settings (#122). The vendor's-// own count, where it gives one, stands before the percentage.+// A window reads as used or, as the vendors' apps show it, left, the bar+// filling with that: one setting for every meter and the menu bar (#122).+// The vendor's count, if any, stands before the percentage.let quotaLeft = false;function to100(v) { return Math.max(0, Math.min(100, v)); }-// quotaNoShare: the plugin didn't say how much of the window is used. Its-// text is all there is, and no percentage may be read from it: 0 is a-// reading, absent is not (#3650)-function quotaNoShare(w) { return !!w.text || w.used == null; }+// quotaNoShare: no share was said (0 is one, absent is not, #3650), or the+// window is a wallet's balance (#3950): its text or figure is all there is+function quotaNoShare(w) { return !!w.text || w.used == null || w.balance != null; }function tipLines(...a) { return a.filter(Boolean).join("\n"); }function quotaFill(w) {if (w.used == null) return 0;@@ -13877,6 +13875,7 @@ function quotaFill(w) {}function quotaText(w) {if (w.unlimited) return t("Unlimited");+ if (w.balance != null) return t("{n} left", { n: (countFormat.format(w.balance) + " " + t(w.unit || "")).trim() });if (quotaNoShare(w)) return w.display || t("No allowance reported");const used = to100(w.used);const n = quotaLeft ? 100 - used : used;@@ -13914,9 +13913,8 @@ function paceLine(w) {: t("Right on an even pace through this window");return span;}-// quotaCount: a window's own count, when its vendor counts in amounts-// (WorkBuddy's credits, #659) — "355 / 500 credits" used, or what is left-// of them, as the share beside it says; the vendor's own text otherwise.+// quotaCount: a window's own count in amounts (WorkBuddy's credits, #659),+// "355 / 500 credits" used or left as the share says; else the vendor's textconst countFormat = new Intl.NumberFormat("en-US", { maximumFractionDigits: 2 });function quotaCount(w) {if (!(w.limit > 0)) return w.display || "";diff --git a/internal/gui/assets/plugins/routing/client.js b/internal/gui/assets/plugins/routing/client.jsindex 57f6a291d..58ef04ff1 100644--- a/internal/gui/assets/plugins/routing/client.js+++ b/internal/gui/assets/plugins/routing/client.js@@ -473,7 +473,11 @@ function routingPage(part) {const share = (w) => quotaLeft ? 100 - Math.max(0, Math.min(100, w.used)) : w.used;// the account's own count before it, when its vendor counts in amounts// (WorkBuddy's credits, #659): "355 / 500 credits · 71% used"- const quota = (w, used, left, vars) => (w.limit > 0 ? quotaCount(w) + " · " : "") + t(quotaLeft ? left : used, { n: pct(share(w)), ...vars });+ // a prepaid wallet tells what it has left in its unit, no share (#3950):+ // "6,291 points left", whichever way the meters read+ const balText = (w) => (countFormat.format(w.balance) + " " + t(w.unit || "")).trim();+ const quota = (w, used, left, vars) => w.balance != null ? t(left, { n: balText(w), ...vars })+ : (w.limit > 0 ? quotaCount(w) + " · " : "") + t(quotaLeft ? left : used, { n: pct(share(w)), ...vars });const fill = (w) => Math.max(0, Math.min(100, share(w))) + "%";const FAIL = { rate: "rate limited", credit: "out of credit", quota: "quota used up", other: "failed", auth: "sign-in required", canceled: "canceled", foreign: "another account's reasoning", floor: "reply too short", verify: "needs verification", refused: "refused (safety filter)", shape: "request not understood", proxy: "proxy not reachable", effort: "reasoning effort not in its plan", overflow: "too long for its model", room: "reply asked past the window left", slow: "slow to start", prompt: "agent's prompt turned away", restricted: "account restricted by the vendor" };const failWord = (why) => t(FAIL[why] || "failed");@@ -639,6 +643,14 @@ function routingPage(part) {&& (!(x.fallback || whole) || (y.provider === x.provider && y.model === x.model && (y.fixed || "") === (x.fixed || "") && !!y.fast === !!x.fast)));}+ // walletWhy: f, a prepaid wallet, goes before the next of its+ // provider's in its unit as it has more left (routes.byLeft, #3950)+ function walletWhy(r, f) {+ const o = r.order.find((x) => x !== f && !x.fallback && !x.rest && x.balance != null && x.provider === f.provider && x.unit === f.unit);+ return f.balance != null && o && f.balance > o.balance+ ? t("{who} goes first: of those alike, its wallet has the most left — {n}, where {other} has {m}.", { who: who(f), n: balText(f), other: who(o), m: balText(o) }) : null;+ }+// why routing put the first where it didfunction firstWhy(r) {const f = r.order[0];@@ -696,10 +708,12 @@ function routingPage(part) {return t("Speed first: none has answered {model} lately, so {who}, first in the list, goes first and its answer measures it.", { who: w, model: f.model });}case "usage":+ if (f.balance != null) return walletWhy(r, f) || t("{who} goes first.", { who: w });if (f.known) return t("Least used first: {who} has the most of its allowance left — {n} used.", { who: w, n: pct(f.used) });if (f.kind === "key" && !someKnown) return t("Least used first: {who} served the fewest tokens lately — {n}.", { who: w, n: tokens(f.tokens || 0) });return t("Least used first: {who} goes first.", { who: w });case "pace":+ if (f.balance != null) return walletWhy(r, f) || t("{who} goes first.", { who: w });if (f.known) {// The allowance window used for pace, which may be shorter than a week.const left = known0(f.due) ? Math.min(100, Math.round((f.pace || 0) * Math.max(1, (at(f.due) - at(r.time)) / 36e5))) : null;@@ -732,6 +746,7 @@ function routingPage(part) {if (c < 0 && k === 0 && known0(f.restarts)) return t("{who} goes first: of those with quota to spare, its allowance starts again soonest — one of its Codex resets about to run out is used by itself in {d}, and what it has left then is lost. {other} renews later and keeps its own.", { who: w, d: dur(at(f.restarts) - at(r.time)), other: who(next) });if (c < 0 && k === 0) return t("{who} goes first: of those with quota to spare, its allowance renews soonest — in {d} — and what it has left then is lost. {other} renews later and keeps its own.", { who: w, d: dur(renews(f)[0] - at(r.time)), other: who(next) });if (c < 0) return t("{who} goes first: its allowance renews in the same hour as {other}'s, and its shorter one sooner — in {d}.", { who: w, other: who(next), d: dur(renewsBy(f)[k] - at(r.time)) });+ if (c === 0 && walletWhy(r, f)) return walletWhy(r, f);if (soon) return t("{who} and {other} renew within the same hour, so the order given stays — and the vendor's prompt cache stays warm.", { who: w, other: who(next) });return t("{who} goes first, in the order given: when its allowance renews isn't known.", { who: w });}@@ -2420,7 +2435,7 @@ function routingPage(part) {// crowd the stage. Live only, as the list's are (winsOf).const tip = [w.id, ...(day ? [] : winsOf(w))].join("\n");if (row.li.title !== tip) row.li.title = tip;- const bar = w.known && !w.free;+ const bar = w.known && !w.free && w.balance == null;row.li.classList.toggle("nobar", !bar);row.bi.style.width = bar ? fill(w) : "0";// on: the row answers or answered the request shown; flying: a@@ -3778,7 +3793,7 @@ function routingPage(part) {fix.append(go);row.append(fix);}- if (w.known) {+ if (w.known && w.balance == null) {const bar = el("div", "bar"), bi = el("i");bi.style.width = fill(w);bar.append(bi);diff --git a/internal/gui/assets/plugins/routing/i18n.js b/internal/gui/assets/plugins/routing/i18n.jsindex e80856aab..4718f63e9 100644--- a/internal/gui/assets/plugins/routing/i18n.js+++ b/internal/gui/assets/plugins/routing/i18n.js@@ -420,6 +420,7 @@ magpie.strings({"{who} goes first: its allowance renews in the same hour as {other}'s, and its shorter one sooner — in {d}.": "{who} 排第一:它与 {other} 的额度在同一小时重置,而它较短的窗口更早({d}后)。","{who} and {other} renew within the same hour, so the order given stays — and the vendor's prompt cache stays warm.": "{who} 和 {other} 在同一小时内重置,保持原顺序,厂商的提示词缓存也保持命中。","{who} goes first, in the order given: when its allowance renews isn't known.": "{who} 按原有顺序排第一:不知道它的额度何时重置。",+ "{who} goes first: of those alike, its wallet has the most left — {n}, where {other} has {m}.": "{who} 排第一:同类账号里,它的钱包剩得最多——{n},{other} 剩 {m}。","{who} is resting — {why}, {when} — so it waits at the back.": "{who} 正在休息({why},{when}),排在最后。","{who} is at {n} — all but used up, it answers only when nothing else can.": "{who} 已用 {n},几乎用尽,仅在其他都无法响应时使用。","{who} is at {n} — kept for when the others can't.": "{who} 已用 {n},其他账号都无法响应时才用。",@@ -990,6 +991,7 @@ magpie.strings({"{who} goes first: its allowance renews in the same hour as {other}'s, and its shorter one sooner — in {d}.": "{who} 排第一:它與 {other} 的額度在同一小時重置,而它較短的時段更早({d}後)。","{who} and {other} renew within the same hour, so the order given stays — and the vendor's prompt cache stays warm.": "{who} 和 {other} 在同一小時內重置,保持原順序,廠商的提示詞快取也保持命中。","{who} goes first, in the order given: when its allowance renews isn't known.": "{who} 按原有順序排第一:不知道它的額度何時重置。",+ "{who} goes first: of those alike, its wallet has the most left — {n}, where {other} has {m}.": "{who} 排第一:同類帳號裡,它的錢包剩得最多——{n},{other} 剩 {m}。","{who} is resting — {why}, {when} — so it waits at the back.": "{who} 正在休息({why},{when}),排在最後。","{who} is at {n} — all but used up, it answers only when nothing else can.": "{who} 已用 {n},幾乎用盡,僅在其他都無法回應時使用。","{who} is at {n} — kept for when the others can't.": "{who} 已用 {n},其他帳號都無法回應時才用。",@@ -1558,6 +1560,7 @@ magpie.strings({"{who} goes first: its allowance renews in the same hour as {other}'s, and its shorter one sooner — in {d}.": "{who} が先です:利用枠が {other} と同じ時間帯に更新され、短いほうの枠がより早く — {d} 後に — 更新されます。","{who} and {other} renew within the same hour, so the order given stays — and the vendor's prompt cache stays warm.": "{who} と {other} は同じ時間帯に更新されるため、設定順のままです — ベンダーのプロンプトキャッシュも温かいままです。","{who} goes first, in the order given: when its allowance renews isn't known.": "{who} が設定順で先です:利用枠がいつ更新されるか不明です。",+ "{who} goes first: of those alike, its wallet has the most left — {n}, where {other} has {m}.": "{who} が先です:同じ種類のうち、ウォレットの残りが最も多いため — {n}、{other} は {m}。","{who} is resting — {why}, {when} — so it waits at the back.": "{who} は休止中です — {why}、{when} — そのため最後尾で待ちます。","{who} is at {n} — all but used up, it answers only when nothing else can.": "{who} は {n} — ほぼ使い切っており、他に応答できる相手がいないときだけ応答します。","{who} is at {n} — kept for when the others can't.": "{who} は {n} — 他が応答できないときのために取っておきます。",@@ -2128,6 +2131,7 @@ magpie.strings({"{who} goes first: its allowance renews in the same hour as {other}'s, and its shorter one sooner — in {d}.": "{who} kommt zuerst: Sein Kontingent erneuert sich in derselben Stunde wie das von {other}, sein kürzeres aber früher – in {d}.","{who} and {other} renew within the same hour, so the order given stays — and the vendor's prompt cache stays warm.": "{who} und {other} erneuern sich in derselben Stunde, daher bleibt die vorgegebene Reihenfolge – und der Prompt-Cache des Anbieters bleibt warm.","{who} goes first, in the order given: when its allowance renews isn't known.": "{who} kommt gemäß vorgegebener Reihenfolge zuerst: Wann sich sein Kontingent erneuert, ist unbekannt.",+ "{who} goes first: of those alike, its wallet has the most left — {n}, where {other} has {m}.": "{who} kommt zuerst: Unter den gleichartigen hat sein Guthaben am meisten übrig — {n}, {other} hat {m}.","{who} is resting — {why}, {when} — so it waits at the back.": "{who} pausiert – {why}, {when} – und wartet daher hinten.","{who} is at {n} — all but used up, it answers only when nothing else can.": "{who} liegt bei {n} – fast aufgebraucht, es antwortet nur, wenn nichts anderes kann.","{who} is at {n} — kept for when the others can't.": "{who} liegt bei {n} – aufgehoben für den Fall, dass die anderen nicht können.",diff --git a/internal/gui/tests/routing-wallet-balance.test.cjs b/internal/gui/tests/routing-wallet-balance.test.cjsnew file mode 100644index 000000000..8422c7fae--- /dev/null+++ b/internal/gui/tests/routing-wallet-balance.test.cjs@@ -0,0 +1,104 @@+// Run with Node's test runner and Playwright on the module path; see README.md.+// #3950 (墨雨藏锋 / mycf_711): prepaid wallets of one provider, in one+// unit, have a balance and no share. On the Routing page each one's row+// says what it has left, "750 积分 left", with no bar (a share it was+// never told), in the live rows and in the accounts listed below; the+// story says the first went first as its wallet has the most left,+// naming both figures, under Smart, Least used and Weekly pace alike.+// Where it said "0% used" and "in the order given". Every language, at a+// window's width and at 420px, in both engines.+const assert = require("node:assert/strict");+const fs = require("node:fs/promises");+const path = require("node:path");+const { test } = require("node:test");+const { chromium, webkit } = require("playwright");++const assets = path.resolve(__dirname, "../assets");+const now = new Date();+const ago = (s) => new Date(now.getTime() - s * 1000).toISOString();+// as the gateway sends them (Weighed): known, used 0, the balance and unit+const seat = (who, balance, routing) => ({ id: `magicrew#${who}`, provider: "magicrew", name: "SuperMagic", who, kind: "account", model: "magic-1", plan: "Points",+ ...(routing ? { routing } : {}), known: true, used: 0, balance, unit: "积分", renews: ["0001-01-01T00:00:00Z"], pace: 100 / 168 });++function serve(lang, routing) {+ const order = [seat("[email protected]", 6291, routing), seat("[email protected]", 750, routing)];+ const route = {+ id: 1, seq: 1, time: ago(1), agent: "codex", model: "magic-1", provider: "magicrew", done: true, status: 200, ms: 900, tokens: 1200, order,+ tries: [{ id: order[0].id, model: "magic-1", start: ago(1), done: true, status: 200, ms: 900 }],+ };+ return async (request) => {+ const url = new URL(request.request().url());+ const json = (data) => request.fulfill({ json: data });+ if (url.pathname === "/boot.js") return request.fulfill({ contentType: "text/javascript", body: `window.bootPrefs = {lang:"${lang}",theme:"light",web:true};` });+ if (url.pathname === "/wails/runtime.js") return request.fulfill({ contentType: "text/javascript", body: "export const Window = {};" });+ if (url.pathname === "/api/state") return json({ agents: [{ id: "codex", name: "Codex", path: "/test/config.toml", fields: [] }], profiles: [], settings: { lang, theme: "light" } });+ if (url.pathname === "/api/gateway/trace") {+ if (url.searchParams.get("wait")) return new Promise(() => {}); // nothing more comes+ return json({ mine: true, now: now.toISOString(), seq: 1, totals: { requests: 1 }, routes: [route] });+ }+ if (url.pathname === "/api/gateway/history") return json({ cut: false, days: [], routes: [] });+ if (url.pathname === "/api/groups") return json({ groups: [] });+ if (url.pathname === "/api/providers") return json({ providers: [], excluded: [], gateway: { running: true, window: true } });+ if (url.pathname.startsWith("/api/")) return json({});+ const file = path.join(assets, url.pathname === "/" ? "index.html" : url.pathname);+ const contentType = { ".html": "text/html", ".js": "text/javascript", ".css": "text/css", ".svg": "image/svg+xml", ".png": "image/png" }[path.extname(file)];+ await request.fulfill({ body: await fs.readFile(file), contentType });+ };+}++const WHY = "{who} goes first: of those alike, its wallet has the most left — {n}, where {other} has {m}.";++for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {+ test(`${engine}: a wallet's row says its balance, and the story why the fuller went first`, async (t) => {+ const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" }));+ t.after(() => browser.close());+ for (const lang of ["en", "zh", "zh-TW", "ja", "de"]) {+ for (const [routing, width] of [["", 1100], ["usage", 1100], ["pace", 420]]) {+ await t.test(`${lang} ${routing || "smart"} at ${width}px`, async () => {+ const page = await browser.newPage({ viewport: { width, height: 900 }, reducedMotion: "reduce" });+ try {+ page.setDefaultTimeout(5000);+ const errors = [];+ page.on("pageerror", (error) => errors.push(error.message));+ await page.route("**/*", serve(lang, routing));+ await page.goto("http://magpie.test/?view=routing");+ const req = page.locator(".rt-req").first();+ await req.waitFor();+ if (await req.getAttribute("aria-pressed") !== "true") await req.click();+ await page.locator(".rt-steps li.why").first().waitFor();+ await page.waitForFunction(() => [...document.querySelectorAll(".rt-accts > li")].every((li) => li.querySelector("em")?.textContent.trim()));+ const tr = (key, vars) => page.evaluate(([lang, key, vars]) => {+ const s = (lang !== "en" && I18N[lang]?.[key]) || key;+ return s.replace(/\{(\w+)\}/g, (_, k) => vars[k] ?? `{${k}}`);+ }, [lang, key, vars]);+ const big = await tr("{n} left", { n: "6,291 积分" }), small = await tr("{n} left", { n: "750 积分" });+ const look = (id) => page.locator(`.rt-accts > li[title^="${id}"]`).first().evaluate((li) => ({+ st: li.querySelector("em").textContent, bar: getComputedStyle(li.querySelector(".bar")).display !== "none" && li.querySelector(".bar i").style.width !== "0px" && li.querySelector(".bar i").style.width !== "0" }));+ const b = await look("magicrew#[email protected]"), s = await look("magicrew#[email protected]");+ // the first says it answered; the one behind it, its figure+ assert.equal(s.st, small);+ assert.equal(b.bar, false, "no bar from a share never told");+ assert.equal(s.bar, false);+ // the story: the first went first by what its wallet has left+ const why = (await page.locator(".rt-steps li.why").first().textContent()).trim();+ const tpl = await tr(WHY, { n: "6,291 积分", m: "750 积分" });+ const [head, mid, tail] = tpl.split(/\{who\}|\{other\}/);+ assert.ok(why.includes(mid.trim()) && why.endsWith(tail.trim()) && (!head || why.startsWith(head)), `the story: ${why}`);+ // the accounts below: their figures, no bar+ const acts = page.locator(".rt-act");+ await acts.filter({ hasText: "6,291" }).first().waitFor();+ const list = await acts.evaluateAll((as) => as.map((a) => ({ st: a.querySelector(".st")?.textContent || "", bar: !!a.querySelector(".bar") })));+ assert.ok(list.some((a) => a.st.startsWith(big)), JSON.stringify(list));+ assert.ok(list.some((a) => a.st.startsWith(small)), JSON.stringify(list));+ assert.ok(list.every((a) => !a.bar), "no bar in the list either");+ const over = await page.evaluate(() => document.documentElement.scrollWidth - innerWidth);+ assert.ok(over <= 1, `${over}px past`);+ assert.deepEqual(errors, []);+ } finally {+ await page.close();+ }+ });+ }+ }+ });+}diff --git a/internal/gui/tests/usage-wallet-balance.test.cjs b/internal/gui/tests/usage-wallet-balance.test.cjsnew file mode 100644index 000000000..515cf3d91--- /dev/null+++ b/internal/gui/tests/usage-wallet-balance.test.cjs@@ -0,0 +1,86 @@+// Run with Node's test runner and Playwright on the module path; see README.md.+// #3950 (墨雨藏锋 / mycf_711): a prepaid wallet (SuperMagic's points) has a+// balance and no total. Its plugin sends the window's balance and unit+// with no used; the usage card says the figure, "6,291 积分 left", with no+// meter and no percentage, whether the meters read used or left, where it+// said "No allowance reported" or a 0% it was never told. A window that+// said its share beside it keeps its percentage and meter. Chromium and+// WebKit, every language, at a window's width and a phone's; no backend,+// the API is faked here.+const assert = require("node:assert/strict");+const fs = require("node:fs/promises");+const path = require("node:path");+const { test } = require("node:test");+const { chromium, webkit } = require("playwright");++const assets = path.resolve(process.env.MAGPIE_ASSETS || path.join(__dirname, "../assets"));+const left = { en: "6,291 积分 left", zh: "剩余 6,291 积分", "zh-TW": "剩餘 6,291 积分", ja: "残り 6,291 积分", de: "6,291 积分 übrig" };++const quotas = [+ // as magpie's API sends a wallet's window: its balance and unit, used 0+ // and no share (QuotaSpan.Balance)+ { provider: "magicrew-plugin", name: "SuperMagic", user: "[email protected]", windows: [+ { name: "Points", used: 0, remaining: 100, balance: 6291, unit: "积分" },+ ] },+ { provider: "claude", name: "Claude", user: "[email protected]", windows: [+ { name: "5 hours", used: 40 },+ ] },+];++function serve(lang) {+ return async (route) => {+ const url = new URL(route.request().url());+ const json = (data) => route.fulfill({ json: data });+ if (url.pathname === "/boot.js") return route.fulfill({ contentType: "text/javascript", body: `window.bootPrefs = {lang:"${lang}",theme:"light",web:true};` });+ if (url.pathname === "/wails/runtime.js") return route.fulfill({ contentType: "text/javascript", body: "export const Window = {};" });+ if (url.pathname === "/api/state") return json({ agents: [], profiles: [], settings: { lang, theme: "light" } });+ if (url.pathname === "/api/providers") return json({ providers: [], presets: [], excluded: [], gateway: { running: true, window: true } });+ if (url.pathname === "/api/usage/quotas") return json(quotas);+ if (url.pathname === "/api/groups") return json({ groups: [], models: [] });+ if (url.pathname === "/api/plugins") return json({ plugins: [] });+ if (url.pathname.startsWith("/api/")) return json({});+ const file = path.join(assets, url.pathname === "/" ? "index.html" : url.pathname);+ const contentType = { ".html": "text/html", ".js": "text/javascript", ".css": "text/css", ".svg": "image/svg+xml", ".png": "image/png" }[path.extname(file)];+ try { await route.fulfill({ body: await fs.readFile(file), contentType }); } catch { await route.fulfill({ status: 404, body: "" }); }+ };+}++async function windows(card) {+ return card.locator(".quota").evaluateAll((qs) => qs.map((q) => ({ n: q.querySelector(".quota-n")?.innerText ?? "", track: !!q.querySelector(".quota-track") })));+}++for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {+ test(`${engine}: a wallet's window says its balance, not a percentage`, async (t) => {+ const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" }));+ t.after(() => browser.close());+ for (const lang of Object.keys(left)) {+ for (const width of [900, 390]) {+ const page = await browser.newPage({ viewport: { width, height: 800 }, reducedMotion: "reduce" });+ page.setDefaultTimeout(5000);+ const errors = [];+ page.on("pageerror", (e) => errors.push(e.message));+ await page.route("**/*", serve(lang));+ await page.goto("http://magpie.test/?view=usage");+ const at = `${lang} ${width}px`;+ const wallet = page.locator(".subscription-card", { hasText: "SuperMagic" });+ const fine = page.locator(".subscription-card", { hasText: "Claude" });+ await wallet.locator(".quota-n").first().waitFor();+ await fine.locator(".quota-n").first().waitFor();+ for (const side of ["used", "left"]) {+ const w = await windows(wallet);+ assert.equal(w.length, 1, `${at} ${side}: ${JSON.stringify(w)}`);+ assert.equal(w[0].n, left[lang], `${at} ${side}: the wallet's figure`);+ assert.equal(w[0].track, false, `${at} ${side}: no meter from a share never sent`);+ const f = await windows(fine);+ assert.match(f[0].n, side === "used" ? /40\s?%/ : /60\s?%/, `${at} ${side}: ${f[0].n}`);+ assert.ok(f[0].track, `${at} ${side}: a window that said its share has its meter`);+ if (side === "used") await fine.locator(".quota-n").first().click();+ }+ const overflow = await page.evaluate(() => document.documentElement.scrollWidth - document.documentElement.clientWidth);+ assert.ok(overflow <= 0, `${at}: the page scrolls sideways by ${overflow}px`);+ assert.deepEqual(errors, [], at);+ await page.close();+ }+ }+ });+}diff --git a/internal/plugin/host.js b/internal/plugin/host.jsindex 5cf110a71..2ddda42e7 100644--- a/internal/plugin/host.js+++ b/internal/plugin/host.js@@ -2381,7 +2381,11 @@ async function load({ provider, account, proxy }) {// count as one), aside? (using it up doesn't// stop the account), runsOutAt? (ISO or ms: when the soonest// credits left in it are lost, apart from its reset, as WorkBuddy's-// packages end) / runsOut? (how many are lost then) }],+// packages end) / runsOut? (how many are lost then), balance?+// (how much is left, in unit, of a prepaid wallet with no total:+// sent without used, it is no share, yet routing knows the account+// and puts the one with the most left first among the provider's+// accounts in the same unit, #3950) }],// signIn?: "expired" | "kept" | "renewed" (what the read means for the// account's sign-in, as a model request's X-Magpie-Sign-In says;// without it an error saying to sign in again marks the account and@@ -2442,6 +2446,7 @@ async function usageOf(provider, account) {aside: !!w?.aside,runsOutAt: when(w?.runsOutAt),runsOut: Math.max(0, num(w?.runsOut)),+ balance: typeof w?.balance === "number" && isFinite(w.balance) ? Math.max(0, w.balance) : null, // null: not said})),}}diff --git a/internal/plugin/providers.go b/internal/plugin/providers.goindex 8b5c9a768..256c02e74 100644--- a/internal/plugin/providers.go+++ b/internal/plugin/providers.go@@ -1095,6 +1095,9 @@ type UsageWindow struct {// apart from the window's reset (WorkBuddy's packages)RunsOutAt string `json:"runsOutAt"`RunsOut float64 `json:"runsOut"`+ // Balance is how much is left in Unit, a prepaid wallet's reading,+ // with no share to tell (#3950); nil when the plugin didn't say.+ Balance *float64 `json:"balance"`}// Checkin is what came of an account's daily check-in, as the plugin'sdiff --git a/internal/provider/plugin_usage.go b/internal/provider/plugin_usage.goindex 8e47b025a..7bd4a2e63 100644--- a/internal/provider/plugin_usage.go+++ b/internal/provider/plugin_usage.go@@ -158,9 +158,14 @@ func quotaOfPlugin(q SubscriptionQuota, u plugin.Usage) SubscriptionQuota {w := QuotaWindow{Name: x.Name, ResetSecs: x.ResetSecs, Display: x.Display,Amount: x.Amount, Limit: x.Limit, Unit: x.Unit,Span: time.Duration(x.Span * float64(time.Second)), Model: strings.ToLower(x.Model), Aside: x.Aside}+ if x.Balance != nil {+ // a wallet's balance: a reading, though it tells no share (#3950)+ b := *x.Balance+ w.Balance = &b+ }if x.Used != nil {w.Used = *x.Used- } else if !x.Aside {+ } else if !x.Aside && x.Balance == nil {// the plugin didn't say how much of it is used: its text is all// there is, and routing has no share to count (#3650)w.Text, w.Aside = true, true@@ -168,7 +173,7 @@ func quotaOfPlugin(q SubscriptionQuota, u plugin.Usage) SubscriptionQuota {// a row set aside with text and nothing counted is that text: a// window that counts nothing yet says 0 with a count, or with no// text, and one that stops the account is a reading at 0- w.Text = w.Text || x.Aside && x.Display != "" && (x.Used == nil || *x.Used == 0) && x.Amount == 0 && x.Limit == 0+ w.Text = w.Text || x.Aside && x.Display != "" && (x.Used == nil || *x.Used == 0) && x.Amount == 0 && x.Limit == 0 && x.Balance == nilif t, err := time.Parse(time.RFC3339, x.ResetsAt); err == nil {w.ResetsAt = &t}diff --git a/internal/provider/plugin_usage_balance_test.go b/internal/provider/plugin_usage_balance_test.gonew file mode 100644index 000000000..ca5580cd3--- /dev/null+++ b/internal/provider/plugin_usage_balance_test.go@@ -0,0 +1,129 @@+package provider++import (+ "context"+ "encoding/json"+ "os"+ "path/filepath"+ "testing"+ "time"++ "github.com/yetone/magpie/internal/plugin"+ "github.com/yetone/magpie/internal/testenv"+)++// A prepaid wallet (SuperMagic's points, #3950) tells how much is left in+// its unit and nothing it is a share of. Its window keeps that figure,+// is no text row and no share, and routing knows the account by it with+// nothing used invented; an empty wallet is used up. Through the decode+// a plugin's reply takes, as host.js hands it on.+func TestPluginWalletBalanceIsAReading(t *testing.T) {+ var u plugin.Usage+ if err := json.Unmarshal([]byte(`{"windows":[{"name":"积分","balance":6291,"unit":"积分"}]}`), &u); err != nil {+ t.Fatal(err)+ }+ q := quotaOfPlugin(SubscriptionQuota{Provider: "magicrew-plugin", User: "u"}, u)+ w := q.Windows[0]+ if w.Balance == nil || *w.Balance != 6291 || w.Unit != "积分" {+ t.Fatalf("the balance: %+v", w)+ }+ if w.Text || w.Aside || w.Used != 0 {+ t.Errorf("a wallet is a reading with no share invented: Text %v, Aside %v, Used %v", w.Text, w.Aside, w.Used)+ }+ now := time.Now()+ a, ok := routedAllowance("plugin:magicrew", "u", q, now)+ if !ok {+ t.Fatal("a wallet's account is not known to routing")+ }+ if used, _ := a.For("", now); used != 0 {+ t.Errorf("used invented: %v", used)+ }+ if left, unit, ok := a.Left(""); !ok || left != 6291 || unit != "积分" {+ t.Errorf("Left: %v %q %v", left, unit, ok)+ }++ var empty plugin.Usage+ if err := json.Unmarshal([]byte(`{"windows":[{"name":"积分","balance":0,"unit":"积分"}]}`), &empty); err != nil {+ t.Fatal(err)+ }+ e, ok := routedAllowance("plugin:magicrew", "v", quotaOfPlugin(SubscriptionQuota{Provider: "magicrew-plugin", User: "v"}, empty), now)+ if !ok {+ t.Fatal("an empty wallet is not known")+ }+ if used, _ := e.For("", now); used < SpentShare {+ t.Errorf("an empty wallet is not used up: %v", used)+ }+ if left, _, ok := e.Left(""); !ok || left != 0 {+ t.Errorf("an empty wallet's Left: %v %v", left, ok)+ }+}++// Left is the least balance of the windows that count the model, and+// none when no window told one.+func TestAllowanceLeftIsTheLeastBalance(t *testing.T) {+ b := func(f float64) *float64 { return &f }+ now := time.Now()+ a := allowanceOf([]QuotaWindow{+ {Name: "Wallet", Balance: b(800), Unit: "pts"},+ {Name: "Opus wallet", Balance: b(30), Unit: "pts", Model: "opus"},+ {Name: "Daily", Used: 20, ResetSecs: 3600},+ }, now)+ if left, _, _ := a.Left("sonnet"); left != 800 {+ t.Errorf("sonnet's: %v", left)+ }+ if left, _, _ := a.Left("opus"); left != 30 {+ t.Errorf("opus's: %v", left)+ }+ if _, _, ok := allowanceOf([]QuotaWindow{{Name: "Daily", Used: 20}}, now).Left(""); ok {+ t.Error("no balance told, yet one is left")+ }+}++// Through the plugin host: a balance the plugin sends reaches magpie as+// that figure; one that isn't a number is not said.+func TestPluginHostPassesABalanceOn(t *testing.T) {+ windows := filepath.Join(t.TempDir(), "windows.json")+ if err := os.WriteFile(windows, []byte(`{+ "a@fake": [{"name": "积分", "balance": 6291, "unit": "积分"}],+ "full@fake": [{"name": "积分", "balance": "lots", "unit": "积分", "display": "lots"}]+ }`), 0o600); err != nil {+ t.Fatal(err)+ }+ u := fakePluginUsage(t, windows)+ if w := u["a@fake"].Windows; len(w) != 1 || w[0].Balance == nil || *w[0].Balance != 6291 || w[0].Text {+ t.Errorf("a balance: %+v", w)+ }+ if w := u["full@fake"].Windows; len(w) != 1 || w[0].Balance != nil || !w[0].Text {+ t.Errorf("not a number: %+v", w)+ }+}++// fakePluginUsage signs in the fake plugin's a@fake and full@fake with+// the windows file it reads (FAKE_WINDOWS) and reads their usage.+func fakePluginUsage(t *testing.T, windows string) map[string]SubscriptionQuota {+ t.Helper()+ bun := testenv.Bun(t)+ claudeHome(t)+ t.Setenv("MAGPIE_BUN", bun)+ t.Setenv("FAKE_WINDOWS", windows)+ t.Cleanup(plugin.Settle)+ ctx, cancel := context.WithTimeout(context.Background(), time.Minute)+ defer cancel()+ abs, _ := filepath.Abs("../plugin/testdata/fake/index.js")+ if _, err := plugin.Add(ctx, abs); err != nil {+ t.Fatal(err)+ }+ if _, err := plugin.Providers(ctx); err != nil {+ t.Fatal(err)+ }+ for _, team := range []string{"a", "full"} {+ st, err := StartPluginSignIn("fakeco", 1, map[string]string{"where": "work", "team": team})+ if err != nil {+ t.Fatal(err)+ }+ if err := SubmitSignInCallback(st.ID, "good"); err != nil {+ t.Fatal(err)+ }+ }+ return LoginUsage(ctx, "plugin:fakeco")+}diff --git a/internal/provider/quota_span_test.go b/internal/provider/quota_span_test.goindex f173ac215..90ad9c884 100644--- a/internal/provider/quota_span_test.go+++ b/internal/provider/quota_span_test.go@@ -83,7 +83,8 @@ func TestQuotaSpanCarriesEveryWindowField(t *testing.T) {// and what is carried is copied: a window with each set says eachat := time.Date(2026, 10, 30, 17, 0, 0, 0, time.UTC)- full := QuotaWindow{Unlimited: true, Name: "Credits", Used: 40, ResetsAt: &at, Display: "1 / 2", Text: true, Amount: 1, Limit: 2, Unit: "credits",+ bal := 6291.0+ full := QuotaWindow{Balance: &bal, Unlimited: true, Name: "Credits", Used: 40, ResetsAt: &at, Display: "1 / 2", Text: true, Amount: 1, Limit: 2, Unit: "credits",RunsOutAt: &at, RunsOut: 3, Pool: "P", Holds: &WindowHolds{}, HoldsWhy: "x"}got := quotaReport([]SubscriptionQuota{{Provider: "p", Windows: []QuotaWindow{full}}}, nil, nil, at)b, _ := json.Marshal(got[0].Windows[0])diff --git a/internal/provider/quotas.go b/internal/provider/quotas.goindex 788b3be93..158b16d3e 100644--- a/internal/provider/quotas.go+++ b/internal/provider/quotas.go@@ -4,6 +4,8 @@ import ("context""math""slices"+ "strconv"+ "strings""time")@@ -139,6 +141,9 @@ type QuotaSpan struct {// account's have no reset at all (#3762).RunsOutAt *time.Time `json:"runsOutAt,omitempty"`RunsOut float64 `json:"runsOut,omitempty"`+ // Balance is how much is left in Unit, a prepaid wallet's reading+ // (QuotaWindow.Balance, #3950): Used and Remaining are then no share.+ Balance *float64 `json:"balance,omitempty"`// Holds and HoldsWhy are the window's whole as the Usage page's card// tells it (QuotaWindow.Holds, #2333): reckoned when ReckonHolds is// set, else left out.@@ -195,7 +200,7 @@ func quotaReport(subs, plans, balances []SubscriptionQuota, now time.Time) []Quo// as the usage page shows themfor _, w := range PooledWindows(q.Windows) {s := QuotaSpan{Unlimited: w.Unlimited, Name: w.Name, Used: w.Used, Remaining: max(0, 100-w.Used), ResetsAt: w.ResetsAt, Display: w.Display, Text: w.Text,- Amount: w.Amount, Limit: w.Limit, Unit: w.Unit, Pool: w.Pool, RunsOutAt: w.RunsOutAt, RunsOut: w.RunsOut, Holds: w.Holds, HoldsWhy: w.HoldsWhy}+ Amount: w.Amount, Limit: w.Limit, Unit: w.Unit, Pool: w.Pool, RunsOutAt: w.RunsOutAt, RunsOut: w.RunsOut, Balance: w.Balance, Holds: w.Holds, HoldsWhy: w.HoldsWhy}if s.ResetsAt == nil && w.ResetSecs > 0 {t := now.Add(time.Duration(w.ResetSecs) * time.Second)s.ResetsAt = &t@@ -208,6 +213,23 @@ func quotaReport(subs, plans, balances []SubscriptionQuota, now time.Time) []Quoreturn out}+// BalanceText is a wallet's balance as told, the figure in its unit:+// "6,291 points left" (QuotaWindow.Balance).+func BalanceText(b float64, unit string) string {+ s := strconv.FormatFloat(math.Round(b*100)/100, 'f', -1, 64)+ whole, frac, _ := strings.Cut(strings.TrimPrefix(s, "-"), ".")+ for i := len(whole) - 3; i > 0; i -= 3 {+ whole = whole[:i] + "," + whole[i:]+ }+ if frac != "" {+ whole += "." + frac+ }+ if b < 0 {+ whole = "-" + whole+ }+ return strings.TrimSpace(whole+" "+unit) + " left"+}+// ResetClock is when a window starts again, on the clock: "14:30" today,// "tomorrow 09:00", "Wed 14:30" within the week, else "Oct 3 14:30".func ResetClock(at, now time.Time) string {diff --git a/internal/provider/routing.go b/internal/provider/routing.goindex 54d38fc1a..7578f9bf5 100644--- a/internal/provider/routing.go+++ b/internal/provider/routing.go@@ -189,6 +189,9 @@ type Limit struct {// Credits: the account goes on past this window on its credits// (QuotaWindow.Credits)Credits bool+ // Balance is how much is left in Unit, a wallet's reading with no+ // share (QuotaWindow.Balance); nil when not told+ Balance *float64}// OnCredits says whether the account goes on past its allowance on its@@ -366,6 +369,23 @@ func (a Allowance) Renewal(model string, now time.Time) []time.Time {return out}+// Left is how much a wallet that counts model has left, in unit+// (Limit.Balance): the least of its windows that tell a balance. ok is+// false when none does. Only balances in the same unit of one provider are+// compared (routes.Seat.Left).+func (a Allowance) Left(model string) (left float64, unit string, ok bool) {+ model = strings.ToLower(model)+ for _, l := range a {+ if l.Balance == nil || !l.applies(model) {+ continue+ }+ if !ok || *l.Balance < left {+ left, unit, ok = *l.Balance, l.Unit, true+ }+ }+ return left, unit, ok+}+// Lapse is the soonest moment credits left in a window that counts model// are lost (Limit.RunsOut), zero when none is told or all have passed.// Smart goes by it when the renewals tie: two WorkBuddy free accounts@@ -803,6 +823,15 @@ func allowanceOf(ws []QuotaWindow, now time.Time) Allowance {if w.RunsOutAt != nil {l.RunsOut = *w.RunsOutAt}+ if w.Balance != nil {+ // a wallet is known by its balance, with no share invented:+ // one with nothing left is used up, as the vendor refuses it+ b := *w.Balance+ l.Balance = &b+ if b <= 0 {+ l.Used = max(l.Used, 100)+ }+ }a = append(a, l)}return adiff --git a/internal/provider/subscription_usage.go b/internal/provider/subscription_usage.goindex f1963c748..c093a55b2 100644--- a/internal/provider/subscription_usage.go+++ b/internal/provider/subscription_usage.go@@ -52,6 +52,13 @@ type QuotaWindow struct {// day. Smart routing takes it for the window's renewal (cdredfox on X).RunsOutAt *time.Time `json:"runsOutAt,omitempty"`RunsOut float64 `json:"runsOut,omitempty"`+ // Balance is how much is left of the window in Unit, when the vendor+ // tells only that: a prepaid wallet, with no total to take a share of+ // (SuperMagic's points, #3950). Used is then no reading (0); the GUI+ // says the figure left, and routing knows the account by it and puts+ // the one with the most left first among a provider's accounts in the+ // same unit (Allowance.Left). nil when not told.+ Balance *float64 `json:"balance,omitempty"`// Family is the model family a per-model window belongs to (Antigravity's// "Gemini 3.1 Pro (High)" is Gemini's), for the GUI to show one figure a// family, the tightest; each window is still here, and routing readsdiff --git a/internal/routes/routes.go b/internal/routes/routes.goindex 738057b42..fc2ff459b 100644--- a/internal/routes/routes.go+++ b/internal/routes/routes.go@@ -60,6 +60,15 @@ type Seat struct {// TPS is how fast it wrote them, output tokens a second, 0 when not// told (a reply let go in a burst tells none). Fastest goes by them.TTFT, TPS float64+ // Left is a prepaid wallet's balance, what it has left in its unit+ // (provider.Allowance.Left, #3950), and LeftIn whose wallet that is:+ // its provider and unit, empty when no balance was told. A wallet has+ // no share and no renewal, so Used and Soon tie; Smart, Pace and+ // LeastUsed then put the one with more left first, only among seats+ // whose LeftIn is the same (byLeft): points are never weighed against+ // another provider's, or another unit.+ Left float64+ LeftIn string}// Strategy orders a pool.diff --git a/internal/routes/strategies.go b/internal/routes/strategies.goindex 2940037a4..4535a3f74 100644--- a/internal/routes/strategies.go+++ b/internal/routes/strategies.go@@ -27,6 +27,42 @@ func tier(share float64) int {return 0}+// byLeft is how a pool's wallets go by what they have left (Seat.Left):+// the one with more first, a seat that told none after those that did.+// It orders only a pool whose balances are all in one provider's one unit;+// with two kinds, nothing is weighed by them (nil), since points and+// another vendor's points don't compare.+func byLeft(seats []Seat) func(a, b Seat) int {+ in := ""+ for _, s := range seats {+ switch {+ case s.LeftIn == "":+ case in == "":+ in = s.LeftIn+ case in != s.LeftIn:+ return nil+ }+ }+ if in == "" {+ return nil+ }+ return func(a, b Seat) int {+ ha, hb := a.LeftIn != "", b.LeftIn != ""+ switch {+ case ha != hb:+ if ha {+ return -1+ }+ return 1+ case a.Left > b.Left:+ return -1+ case a.Left < b.Left:+ return 1+ }+ return 0+ }+}+func identity(n int) []int {idx := make([]int, n)for i := range idx {@@ -48,7 +84,8 @@ func identity(n int) []int {// renews, changes nothing. Renewing in the same hours, the one whose// credits left lapse first (Seat.Lapse) goes first: WorkBuddy's free// accounts all renew at the month's end, but the credits each was given-// end on their own days (zhaocai_83020 on Discord). Those alike stay in their order, keeping the+// end on their own days (zhaocai_83020 on Discord). Then, of prepaid+// wallets (Seat.Left), the one with more left (#3950). Those alike stay in their order, keeping the// vendor's prompt cache warm. Past that, whichever has the most left, and// one all but used up only when nothing else can take it, one that goes// on on its credits first of those (spentBefore). Only the windows@@ -59,6 +96,7 @@ func identity(n int) []int {// once: else, kept after those known, it would never answer and never be// known (Anthropic's usage endpoint can turn magpie away for hours).var Smart = Strategy{Order: func(_ string, seats []Seat) []int {+ left := byLeft(seats)var fine, low, spent []intfor i, s := range seats {switch tier(s.Used) {@@ -96,7 +134,8 @@ var Smart = Strategy{Order: func(_ string, seats []Seat) []int {// first, to the hour; one that tells none after those that dox, y := a.Lapse.Truncate(time.Hour), b.Lapse.Truncate(time.Hour)if x.Equal(y) {- return false+ // then a wallet with more left (#3950)+ return left != nil && left(a, b) < 0}if x.IsZero() || y.IsZero() {return y.IsZero()@@ -137,9 +176,11 @@ var Rotate = Strategy{Order: func(pool string, seats []Seat) []int {// LeastUsed puts a subscription, or a key that reads its own windows, by the// share of its allowance used, as the vendor says; then, and for other-// keys, by what magpie sent it lately. Of those all but used up, one that+// keys, by what magpie sent it lately; prepaid wallets, which have no+// share, by what they have left first (Seat.Left). Of those all but used up, one that// goes on on its credits goes first (spentBefore).var LeastUsed = Strategy{ByUse: true, Order: func(_ string, seats []Seat) []int {+ left := byLeft(seats)idx := identity(len(seats))sort.SliceStable(idx, func(a, b int) bool {sa, sb := seats[idx[a]], seats[idx[b]]@@ -149,6 +190,11 @@ var LeastUsed = Strategy{ByUse: true, Order: func(_ string, seats []Seat) []intif sa.Used != sb.Used {return sa.Used < sb.Used}+ if left != nil {+ if c := left(sa, sb); c != 0 {+ return c < 0+ }+ }return sa.Tokens < sb.Tokens})return idx@@ -166,7 +212,8 @@ var LeastUsed = Strategy{ByUse: true, Order: func(_ string, seats []Seat) []int// that goes on on its credits first (spentBefore). Among the rest, one// not known that tells what it has left as it answers goes first while it// isn't, as in Smart, else it would never be known; then the pace, those-// alike within a tenth by what magpie sent them lately, then in their+// alike within a tenth by what a wallet has left (Seat.Left), then by what+// magpie sent them lately, then in their// order, keeping the vendor's prompt cache warm. An account not known// counts as a whole week ahead of it; a key has no week, unless it reads// its own windows (a sub2api key's limits). A Codex account that spends a@@ -198,6 +245,7 @@ var Pace = Strategy{ByUse: true, Order: func(_ string, seats []Seat) []int {band[i] = band[byPace[k-1]]}}+ left := byLeft(seats)idx := identity(len(seats))sort.SliceStable(idx, func(a, b int) bool {sa, sb := seats[idx[a]], seats[idx[b]]@@ -213,6 +261,12 @@ var Pace = Strategy{ByUse: true, Order: func(_ string, seats []Seat) []int {return sa.Learns} else if band[idx[a]] != band[idx[b]] {return band[idx[a]] < band[idx[b]]+ } else if left != nil {+ // a wallet's pace is a whole week's; the one with more left+ // first (#3950)+ if c := left(sa, sb); c != 0 {+ return c < 0+ }}return sa.Tokens < sb.Tokens})diff --git a/internal/routes/wallet_test.go b/internal/routes/wallet_test.gonew file mode 100644index 000000000..75374a5f5--- /dev/null+++ b/internal/routes/wallet_test.go@@ -0,0 +1,54 @@+package routes++import (+ "slices"+ "testing"+)++// Prepaid wallets (Seat.Left, #3950) tie on everything Smart, Pace and+// Least used go by, a wallet having no share and no renewal: the one with+// more left goes first, one that told none after them. Balances in two+// providers' or two units' wallets are never weighed against each other:+// the pool keeps its order.+func TestWalletsGoByWhatTheyHaveLeft(t *testing.T) {+ const pts = "magicrew\x00积分"+ wallet := func(key string, left float64, in string) Seat {+ return Seat{Key: key, Account: true, Known: true, Pace: 100.0 / 168, Left: left, LeftIn: in}+ }+ for _, st := range []struct {+ name string+ s Strategy+ }{{"smart", Smart}, {"pace", Pace}, {"usage", LeastUsed}} {+ s := []Seat{wallet("small", 750, pts), wallet("none", 0, ""), wallet("big", 6291, pts)}+ if got, want := keys(s, Apply(st.s, "p", s)), []string{"big", "small", "none"}; !slices.Equal(got, want) {+ t.Errorf("%s: %v, want %v", st.name, got, want)+ }+ // an empty wallet is a reading of nothing left, not one not told+ s = []Seat{wallet("empty", 0, pts), wallet("some", 1, pts)}+ if got, want := keys(s, Apply(st.s, "p", s)), []string{"some", "empty"}; !slices.Equal(got, want) {+ t.Errorf("%s, empty: %v, want %v", st.name, got, want)+ }+ for _, other := range []string{"magicrew\x00credits", "other\x00积分"} {+ s = []Seat{wallet("small", 750, pts), wallet("big", 6291, other)}+ if got, want := keys(s, Apply(st.s, "p", s)), []string{"small", "big"}; !slices.Equal(got, want) {+ t.Errorf("%s across %q: %v, want %v", st.name, other, got, want)+ }+ }+ }+}++// A wallet's balance never jumps the tiers: one used up (an empty wallet+// counts as all used) or running low waits behind one with room, however+// much it says it has left.+func TestWalletLeftWithinItsTier(t *testing.T) {+ const pts = "magicrew\x00积分"+ s := []Seat{+ {Key: "low", Known: true, Used: 95, Left: 9000, LeftIn: pts},+ {Key: "room", Known: true, Used: 0, Left: 10, LeftIn: pts},+ }+ for _, st := range []Strategy{Smart, Pace, LeastUsed} {+ if got := keys(s, Apply(st, "p", s)); got[0] != "room" {+ t.Errorf("tier: %v", got)+ }+ }+}diff --git a/site/public/docs/ja/plugins.html b/site/public/docs/ja/plugins.htmlindex af8d72e64..0f209f0fc 100644--- a/site/public/docs/ja/plugins.html+++ b/site/public/docs/ja/plugins.html@@ -534,6 +534,7 @@ magpie quota <span class="c"># acme · Pro · 5h 37%models: [], notModels: [], <span class="c">// or exactly these ids, or all but these</span>aside: false, <span class="c">// true: using it up doesn't stop the account</span>runsOutAt: <span class="s">"2026-10-05T00:00:00Z"</span>, runsOut: 120, <span class="c">// when the soonest credits left are lost, and how many</span>+ balance: 6291, <span class="c">// a prepaid wallet: what is left, in unit; no used or limit</span>}],resets: { count: 2, until: <span class="s">"…"</span>, byWindow: false, fiveHour: 1, weekly: 1 }, <span class="c">// resets the account may spend</span>signIn: <span class="s">"kept"</span>, <span class="c">// as X-Magpie-Sign-In</span>diff --git a/site/public/docs/plugins.html b/site/public/docs/plugins.htmlindex a28f3a2c9..95d19c9c9 100644--- a/site/public/docs/plugins.html+++ b/site/public/docs/plugins.html@@ -534,6 +534,7 @@ magpie quota <span class="c"># acme · Pro · 5h 37%models: [], notModels: [], <span class="c">// or exactly these ids, or all but these</span>aside: false, <span class="c">// true: using it up doesn't stop the account</span>runsOutAt: <span class="s">"2026-10-05T00:00:00Z"</span>, runsOut: 120, <span class="c">// when the soonest credits left are lost, and how many</span>+ balance: 6291, <span class="c">// a prepaid wallet: what is left, in unit; no used or limit</span>}],resets: { count: 2, until: <span class="s">"…"</span>, byWindow: false, fiveHour: 1, weekly: 1 }, <span class="c">// resets the account may spend</span>signIn: <span class="s">"kept"</span>, <span class="c">// as X-Magpie-Sign-In</span>diff --git a/site/public/docs/zh/plugins.html b/site/public/docs/zh/plugins.htmlindex c73659dc4..05d5e6d9e 100644--- a/site/public/docs/zh/plugins.html+++ b/site/public/docs/zh/plugins.html@@ -534,6 +534,7 @@ magpie quota <span class="c"># acme · Pro · 5h 37%models: [], notModels: [], <span class="c">// 或恰好这些 id,或除这些外的全部</span>aside: false, <span class="c">// true:用完也不影响账号使用</span>runsOutAt: <span class="s">"2026-10-05T00:00:00Z"</span>, runsOut: 120, <span class="c">// 剩余额度中最早作废的一笔何时作废、作废多少</span>+ balance: 6291, <span class="c">// 预付钱包:剩余多少(按 unit 计),不写 used 和 limit</span>}],resets: { count: 2, until: <span class="s">"…"</span>, byWindow: false, fiveHour: 1, weekly: 1 }, <span class="c">// 账号可用的重置次数</span>signIn: <span class="s">"kept"</span>, <span class="c">// 同 X-Magpie-Sign-In</span>