diff --git a/docs/reference.md b/docs/reference.md index 219bf8d37..e58231441 100644 --- a/docs/reference.md +++ b/docs/reference.md @@ -1717,7 +1717,7 @@ result for every request: who went first, and why. the conversation stays on its account, resting, spent or past its cap, and its errors go to the agent. With *Stays: Session* or *Strict* under Smart, Least used first or - Weekly pace, a new conversation goes to the account the fewest other + Use before expiry, a new conversation goes to the account the fewest other conversations of the last 30 minutes are on (of those not resting and under 90%), so sessions side by side each keep an account of their own; a Claude Code subagent goes with its session's account. @@ -1726,9 +1726,9 @@ So routing decides who goes first only for a conversation nobody has answered yet. An account that has used 90% goes behind the others for new conversations, but a conversation already on it stays there until 98%. -**The routings.** Smart, Least used first and Weekly pace go by the share +**The routings.** Smart, Least used first and Use before expiry go by the share used of the fullest window that counts the model, the 5-hour window -included. Smart and Weekly pace put an account behind the others once a +included. Smart and Use before expiry put an account behind the others once a window is at 90% or more, and behind those once one is at 98% or more, each of these groups ordered by the share used. @@ -1771,11 +1771,17 @@ each of these groups ordered by the share used. - **Least used first**: the lowest share used first; then the account magpie sent the fewest tokens lately (half of them stop counting after an hour). An account not known counts as unused. -- **Weekly pace**: the account with the highest pace first. Pace is the +- **Use before expiry**: the account with the highest pace first. Pace is the share of the week left divided by the hours until the week renews (at least 1): 60% left with 20 hours to go is 3 per hour. With two weekly windows that count the model (Opus's own and the general one), the lower - pace counts. An account with no week goes by its 5 hours. Accounts whose + pace counts. An account with no week goes by its 5 hours. Credits in a + window that expire before it renews (WorkBuddy's check-in credits) count + as lost then: their share of the window, divided by the hours until they + expire (at least 1), is the window's pace when it is the higher, so 70 of + 500 credits expiring in 14 hours (1 per hour) beat a month's 100% over + 28 days. When the vendor doesn't say how much expires, all that is left + counts. Accounts whose pace is within a tenth of the highest in their band count as alike, and among them the one magpie sent the fewest tokens lately goes first. A Claude account not known goes first once, as in Smart; another unknown @@ -1829,7 +1835,7 @@ depends on the routing: | In turn | Where the rotation goes next. | | Smart | Only between accounts whose windows all renew in the same hours, or whose shares used are equal. | | Least used first | Only between accounts with the same share used and the same tokens sent lately. | -| Weekly pace | Only between accounts in the same pace band that magpie sent the same tokens lately, in practice none since magpie started. | +| Use before expiry | Only between accounts in the same pace band that magpie sent the same tokens lately, in practice none since magpie started. | | Speed first | Only between those within a tenth of each other's speed, and among those not measured lately. | | Cheapest first | Only between those that cost the same now, and among those with no known price. | diff --git a/docs/subsystems/gateway-routing.md b/docs/subsystems/gateway-routing.md index ee840894e..160a9e9b5 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-`), 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. A provider the user keeps out of found groups (Routing's "Leave out a provider", `provider.SetAutoGroupSkip`, `autoGroupSkip` in providers.json; chenxiang0010 on Discord) is in none of them, so a model one other provider serves is no group; the groups the user made or changed keep it. A request still naming a found group that took away goes to its model from a provider not kept out (`AutoStandIn`), and an agent set to it is moved there (`agent.Reseat`). 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/`: the model's id as a vendor spells it, dots kept and with no vendor prefix (`auto/claude-opus-5.5`; `provider.Group.Ref`, `spelledIn`), so a client that looks the part after the slash up on models.dev finds it (ZeroClover on X). The spelling is the one models.dev gives the model most (`catalog.Spelling`, its `normal` index: `glm-5.3-flash` whether the members serve `glm-5-3-flash`, Ark's dated id or `glm-5.3-flash`), so it no longer follows the order the providers were added in; for a model models.dev doesn't know, the first member's spelling it lists, else the first member's. The group's name comes from the same choice (`autoGroups`): the name models.dev gives that spelling (`catalog.NameOf`), else a vendor's own name for it, else the spelling itself; they were picked apart, a name of `glm-5-3-flash` beside `auto/glm-5.3-flash` (XYenon on Discord, `TestFoundGroupIDAndNameAreOneSpelling`). A found group the user changed keeps the name they saved. Every spelling it was listed by before is still the group (`CanonicalRef`), and `PublicRef` takes one to the spelling now. Its old id `group/auto-` is served forever. Inside magpie the group keeps that one id: `validateModel` takes `auto/` (with `:level` or `[1m]`) back to it with `provider.CanonicalRef` before key limits, routing, affinity and the usage log see the request, and the request body is rewritten to it, so both ids count as one group. A gateway key naming either id, `group/*` or `auto/*` passes for both (`allows` in `key_models.go`). `SaveGroup` stores a member, rule or classifier picked as `auto/` by the old id. An agent field magpie set to `group/auto-`, or to an `auto/` spelt otherwise than the group is listed now, moves to `auto/` on the next `SyncCatalog` (`agent.renameFoundGroups`, `TestFoundGroupMovedOffAnOldSpelling`), but only while its value is still what applied.json says magpie wrote; a value the user set or changed stays, and is still served. A pick of the group by its old id written now (`Agent.Apply`) is written as `auto/`. An agent's hidden, picked and ordered models saved by the old id hold for the new one (`PublicRef` in `visible.go`), and a bare model id still reaches its found group (`bareTarget`). Claude Code is given a dotted Claude version dashed, so it may send `auto/claude-sonnet-4-5`: that is the same group, and `Reseat` still moves an agent off it once the group is gone (`samePick`). `auto` is no provider id: `Save` and `Rename` refuse it for a new provider, and a plugin's `auto` is `auto-plugin` (`PluginID`). A provider of the user's saved as `auto` before keeps its models: while it exists, `auto/` is its model and found groups list as `group/auto-` (`autoRefsOn`). Hand-made groups stay `group/`. | [`internal/provider/autoref.go`](../../internal/provider/autoref.go), [`key_models.go`](../../internal/gateway/key_models.go), [`internal/agent/autoref.go`](../../internal/agent/autoref.go) | | A model's own id at a provider | A model the user lists by an id of theirs at a provider (a signed-in account's and a plugin's too; settings' `ModelIDs`, `magpie model id `, the editor's "Listed as"; [Providers and accounts](providers-accounts.md#runtime-path)) is that id everywhere the gateway names it: `/v1/models` and the lists written into agents (`Available`), `Resolve`, the routing groups and the group magpie finds for it (`auto/`, with every other provider serving that id), a gateway key's models, `X-Magpie-Model` and the usage log's `model`. Only the upstream request differs: every place that sends a wire name reads `settings.Wires()`, which is `ModelWires` with each `ModelIDs` entry turned round (`"/"` → the vendor's own id, wrapped by a `/*` wire), so the body, a Vertex path and the usage log's endpoint carry the vendor's id; an explicit `ModelWires` entry for that id wins. The vendor's reply names its own id, which the usage log, recent calls and the Routing page keep as `served`; the agent gets the id it asked for back in the reply, in every protocol, streamed or whole (`memberWriter` in [`member.go`](../../internal/gateway/member.go), `replyNamingOf`: the reply's `model`, Responses' `response.model`, Anthropic's `message.model`, Gemini's `modelVersion`; issennknight on Discord, whose agent warned that `deepseek-v4.1-flash` came back as `deepseek-v4.1-flash-1017`). The same holds for a group or a `provider/model` id the vendor knows by another name. A reply whose vendor sent the wire name as asked keeps the vendor's name (a dated `-20261017` included); `memberModel` names the group's member instead, and `X-Magpie-Response-Model: vendor` keeps the vendor's name always (`TestReplyNamesAskedModel`, `TestGeminiReplyNamesAskedModel`, `TestReplyNamesMember`). A request still naming `provider/` (an agent's file magpie didn't rewrite) resolves and goes out as it is. A key held to either id passes for both (`modelAllowed` checks the ref, then `OwnModelID`, then `ListedModelID`); a group member passes the same way. An id is given to a model of the provider's chat list or its picks; the image, video and embeddings routes send no wire name, so they are not served under one (`TestLocalModelIDOnEveryRoute`). At an account or a plugin the account's own say of the model is read by the vendor's id: a plugin's API and fetch, Claude Code's `--model`, Antigravity's variant, and which accounts list it and at what levels (`TestLocalModelIDAtAPlugin`, `TestLocalModelIDAtAClaudeAccount`, `TestLocalModelIDAtAnAntigravityAccount`). | [`internal/provider/localid.go`](../../internal/provider/localid.go), [`internal/settings/settings.go`](../../internal/settings/settings.go), [`key_models.go`](../../internal/gateway/key_models.go) | -| Candidates | `plan` lists one provider's candidates: one per key or account on, then each `Fallback` model, with resting ones last (`restLast`). A fallback the user unchecked in its own provider's model list is skipped, as a group's member is (`provider.ResolveRoute`, #3911; `fallback_unpicked_test.go`), and so is it where fallbacks are read for careful accounts, native compaction, redaction and Codex's own turns. A fallback can be a routing group (`group/`, 01huadalang on Discord): `planPaused` hands its members to `planLevel` as a request to the group would (`planFallbackGroup`), in the group's own routing and sink, its pause rules applied in `serve`, and its trace rows marked `Fallback` with the group in `Via`. Its turn rules (`ruleFor`, which may ask a classifier) are not applied: the plan is made before the primary is tried, and a classifier call on every request the primary answers costs too much. Each provider/model is tried once a round: a member that is the primary, an earlier fallback or another fallback group's is left out where it came second, so a group holding this provider is no loop (groups have no fallbacks of their own, and a member's are not followed). A group that is gone is passed over. Every place that reads fallbacks (careful accounts, native compaction, redaction, Codex's own turns, Claude's review) reads a group's members through `provider.FallbackModels`. `fallback_group_test.go`. `planGroup` and `planLevel` weigh a group's members together. A nested group plans by its own routing (#576); one left on the default (Smart) in a group that pools (Smart, In turn, Least used, 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) | +| Candidates | `plan` lists one provider's candidates: one per key or account on, then each `Fallback` model, with resting ones last (`restLast`). A fallback the user unchecked in its own provider's model list is skipped, as a group's member is (`provider.ResolveRoute`, #3911; `fallback_unpicked_test.go`), and so is it where fallbacks are read for careful accounts, native compaction, redaction and Codex's own turns. A fallback can be a routing group (`group/`, 01huadalang on Discord): `planPaused` hands its members to `planLevel` as a request to the group would (`planFallbackGroup`), in the group's own routing and sink, its pause rules applied in `serve`, and its trace rows marked `Fallback` with the group in `Via`. Its turn rules (`ruleFor`, which may ask a classifier) are not applied: the plan is made before the primary is tried, and a classifier call on every request the primary answers costs too much. Each provider/model is tried once a round: a member that is the primary, an earlier fallback or another fallback group's is left out where it came second, so a group holding this provider is no loop (groups have no fallbacks of their own, and a member's are not followed). A group that is gone is passed over. Every place that reads fallbacks (careful accounts, native compaction, redaction, Codex's own turns, Claude's review) reads a group's members through `provider.FallbackModels`. `fallback_group_test.go`. `planGroup` and `planLevel` weigh a group's members together. A nested group plans by its own routing (#576); one left on the default (Smart) in a group that pools (Smart, In turn, Least used, Use before expiry, Free first, Speed first, a plugin's) takes the outer group's, as a provider left on the default does (`provider.Group.Within`, set on `Member.Via`, so the trace's `Subs` and the Routing page read the routing that applies, #3847). In a group In order, By weight or Manual it stays Smart. `TestFreeFirstReachesAGroupInItLeftOnTheDefault`. So does a member whose provider routes other than Smart (`ownRouting`): weighed as one by its first not resting (`firstAwake`), tried whole in its own order; `leastHeld` leaves such a group's order alone too. A provider on Smart, or routed as the group is, is pooled with the group's other keys and accounts. `group_own_routing_test.go`. A member's own fallbacks are not the group's. | [`fallback.go`](../../internal/gateway/fallback.go) | | Order of keys and accounts | `Routing`: smart (""), `order`, `rotate`, `usage` (least used, with an `usageHalfLife` of 1h), `pace`, `weight`, `free` (free first), `fast` (speed first), `drain` (until used up) or, a group's only, `cheap` (cheapest first). `weighRouted` reads each candidate into a `routes.Seat` and asks the strategy serving its routing (`routes.Find`, the router strategy point of [the plugin runtime](plugin-runtime.md#gateway-extension-points-p3-router-strategy)) for the order: Smart is `routes.Smart`, the core's; the others are `routes.Builtin`, registered by the built-in plugin `rotation`. With it off a routing no strategy serves is tried in its listed order, and `routingOf` treats it as `order` wherever the core asks about a routing (a turn's mark, `goesRound`, `sinks`, a rotate group's sessions, a group's heads). Smart, `usage` and `pace` weigh a subscription by its allowance (`allowances`), and a key by its own usage windows when magpie reads them (`keyAllowance`: a sub2api key given a 5-hour, day or 7-day limit, or a key bought as a plan, such as Kimi Code's or a GLM Coding Plan's); any other key has none. Among accounts a plugin reads as prepaid wallets (a window's `balance`, #3950), Smart, `usage` and `pace` put the one with more left first where they would otherwise tie, only within one provider and unit (`routes.Seat.Left`/`LeftIn`, see [provider plugins](provider-plugins.md#a-wallets-balance)): each kind is ordered in the places its own seats take, so a group weighing several providers' accounts as one pool orders each provider's wallets too (#4095, `TestGroupWalletsGoByWhatTheyHaveLeft`). `free` weighs by what a model costs there and nothing else: only a strategy with `routes.Strategy.ByFree` set (`routes.FreeFirst` is the one) has `weighRouted` fill `routes.Seat.Free`, from `provider.FreeModel` — the user's word that the whole provider costs them nothing (`Provider.CountFree`: the editor's Free for me, `magpie provider set free=yes`; jiabubu on Discord, ModelScope's free daily quota), else the vendor's own `catalog.Model.Free` word, else a list price of $0 on every count — so a pool routed any other way never reads a model list for it, and one routed `free` spends the members whose model costs nothing before those that spend the allowance or credits, each tier in its listed order (nothing free is left behind a paid one, and a pool with no free model behaves as `order`). A group routed `free` weighs its members whole, each over its own accounts or keys as its provider routes them. Whatever a group's routing, the Routing page tags a member `provider.FreeModel` counts free "free", on the group's card and beside its provider in the editor (`groupsState`'s `memberInfo[].free`, jiabubu on Discord, `TestGroupMemberSaysFree`, `group-member-free.test.cjs`). `fast` weighs by speed lately and nothing else: only a strategy with `routes.Strategy.BySpeed` set (`routes.Fastest`) has `weighRouted` fill `routes.Seat.TTFT` and `TPS`, from `speedOf` ([`speed.go`](../../internal/gateway/speed.go)): per `restID` (account or key, and model), a decayed average (half-life 20m) of a streamed answer's ms to its first content and of its output tokens a second as `usage.DecodeOf` counts them, written once as an answer ends (`noteTrySpeed`, beside `servedCandidate`) and read with one map lookup per candidate, never from the usage history; past an hour since its last answer a seat counts as not measured, the records are capped at 4096, and a restart forgets them. `routes.Fastest` ranks the awake by their first token plus 200 tokens at their pace (a seat with no pace at the measured seats' middle pace), keeps seats within a tenth of their band's fastest in listed order, and of a pool's requests with seats both measured and not, gives every fifth to one not measured (round the unmeasured, `probes`, so one is never starved); resting seats go after the awake, used-up ones (`UsedShare`) after those, and rests and failover are as for any routing. The trace's rows carry `lateTtft`/`lateTps` for the Routing page's story ("answered fastest lately — first token in 0.8s"). A non-streamed reply tells nothing (no first token), so a pool that never streams stays in listed order bar the probes. `cheap` (a group's only: `provider.normalize` drops it from a provider, whose keys and accounts all bill one price, and the CLI refuses it there) weighs by price now and nothing else: only a strategy with `routes.Strategy.ByPrice` set (`routes.Cheapest`) has `weighRouted` fill `routes.Seat.Priced`, `Cost` and `CacheCost`, from `provider.Provider.PriceAt` at `priceClock()` — the price Usage would count a call made then (the user's `ModelPrices`, else list or maker price, at the price rate and `RateAt`'s window, a `FreeModel` at 0), doubled in its vendor's peak hours by `catalog.Price.In` (`PeakOf`: DeepSeek's API, Command Code's and OpenCode Go's DeepSeek models, each at DeepSeek's hours; Ollama Cloud's deepseek-v4.1-flash and deepseek-v4-pro, dated tags too, at its own 12:00–18:00 UTC weekdays, `catalog.PeakOllama`). `routes.Cheapest` sorts stably by a million in plus a million out, a tie (within a millionth) by cache read, and unpriced seats after every priced one in listed order; rests and failover are as for any routing. The trace's rows carry `price` (`input`, `output`, `cacheRead`, `peak`) for the Routing page's story ("costs least on Ollama now — $0.150 in, $0.600 out a million tokens"). `TestCheapestFirstGroupFollowsPeakHours` holds the clock at a peak and an off-peak hour, and `TestCheapestFirstGroupFollowsOllamaOffPeak` at each edge of Ollama Cloud's hours, a Saturday, and in far zones. A group routed `weight` (#1910) takes its members, not their keys, by smooth weighted round robin: `planLevel` makes each model member (its keys ordered by its own provider's routing) and each nested group one unit, and `weightedUnits` puts the round's pick (`routes.Round` over `group/`, keyed by the member's spelling, `Group.Weights`, 1 if unset) first and the rest in member order for failover; a unit whose head rests leaves the round, while one whose accounts are only near their limit (Smart's 90% band, not resting) keeps its share, the band ordering only its own accounts (`TestWeightedGroupGivesALowGroupItsShare`; Creat.wu on Discord read the Routing page's "kept for when the others can't" as the member passed over, so the page now tells a member behind another by a group's weights or order as such, `memberSplit` in the routing plugin's `client.js`), and a kept conversation moves the round's charge to the member that kept it (`wrrSeat`, `routes.MoveRound`). `weight` on a provider spreads its keys by each key's `Weight` and a subscription's accounts by each account's (`AccountWeights`, rubbzha on X): `keyWeight` gives a seat its `Weight`, 1 when none is set, and `routes.Weighted` takes them by smooth weighted round robin, a resting one leaving the round and a kept conversation staying as Stays says (`TestWeightedKeys`, `TestAccountWeightSharesRequests`). A lone key or account is weighed against nobody, but what it has left is still read into the trace (`weighRouted`), so the Routing page shows it as it does for several (#1016); all but used up, it keeps its conversation rather than being said to move (`affine`). `drain` (dzxx0496 on Discord: free accounts one after another, the first not taking the requests back once it renews) stays on one seat per pool (`routes.Drain`, which remembers the seat's `Key` per pool) until it is used up — a known window at 100% (`provider.SpentShareOf`, as In order) or resting out of quota or credit (`routes.Seat.Spent`, filled by `spentRest` from `restingOf`'s `failQuota`/`failCredit`) — then goes on to the next not used up in listed order and stays there, wrapping round; the others follow it in listed order for failover. A rate limit or a failure only rests the seat, tried last meanwhile, and the pool comes back to it; with every seat used up it stays put, and a seat that leaves the pool leaves it on the first not used up. A group routed `drain` pools its members' accounts and keys under `group/`, as Smart does. A restart forgets where each pool was, and it starts again at the first not used up (`TestDrainKeepsTheOneThatTookOver`). A failure rests a candidate (`failure`, `failureOf`). | [`routing.go`](../../internal/gateway/routing.go), [`weighted.go`](../../internal/gateway/weighted.go), [`internal/routes/`](../../internal/routes), [`internal/provider/routing.go`](../../internal/provider/routing.go) | | Limits | Each key or account (a candidate's `who()`) has at most `MaxConcurrency` requests out at once (its own `AccountConcurrency` over it); one more waits in its lane's queue, bounded by `QueueLimit` and `QueueWait` and turned away with a 429 past either (`lanes.take`). One with no limit still counts its requests out in a lane of `Limit` 0, which never waits, so `Lanes` (`/v1/magpie/concurrency`, the GUI's `/api/lanes`) says how many run there too and the Providers page's pill shows it (chentuoyan on Discord, `TestLanesCountWithNoLimit`); a limit set while they are out counts them. `MaxRPM` (coeo91 on Discord: OpenRouter's free models take 20 a minute) bounds how many requests it sends the vendor in any rolling 60 seconds (`rpms`), counting each for a second more (`rpmSlack`), since the vendor counts a request when it arrives and the first on a new connection arrives later by its dial: one more waits for room in the minute, in the order they came, after it has its slot and right before it is sent. A wait that would be longer than 2 minutes (or the provider's `QueueWait`, when shorter: `rpmWait`) is turned away at once with a 429 whose `Retry-After` is when the minute has room; nothing rests for it. An agent gone while it waits gives its place back. Every request that reaches the vendor counts: each try of the candidate loop (a retry, the next key, a fallback) waits in `serve`, and the requests a try makes on the way and the gateway's own asks (count_tokens, System One's decisions, embeddings, drawing, Kimi's search) are counted by `rpmTransport` on `s.client` (`metered`, `paidFor`). count_tokens never waits: a candidate with no room is skipped, and the local estimate answers. A full lane or a minute with no room gives way to a ready key or account of the provider or the group (`laneMate`, `ready`) that isn't resting: its lane is free only because nothing is sent there. A request already waiting in a lane doesn't stay bound to it: whenever a slot is given back in any lane or a rest is lifted (`lanes.freed`, signalled by the releaser, `Unrest` and `UnrestAll`), and when the soonest rest among the others runs out (at most every `laneRecheck`), it goes to the first key or account after it in the planned order that has a free slot with no queue, minute room, isn't resting and isn't a reserve now (`waitMate`, `keepAtOnce` re-derived over the provider's candidates, `errMoved`). So one that took a seat while those before it rested, then became a reserve once they were back, doesn't keep requests waiting behind its own long turns (01huadalang on Discord: three ZCode accounts at three at once, the first two back from a 405 while the waiting ones stayed on the third until its requests were cut by hand; `TestWaitingRequestGoesToAccountBackFromRest` under Smart and In turn, with Stays on and off, `TestWaitingRequestTakesSlotGivenBackElsewhere` under every routing). Strict stays leaves no other candidate, so the request waits for its own. A fallback is never asked for want of a slot or a minute (`TestFullMemberGivesWay`). A plugin's account sends through its own transport, so only its tries are counted, not a plugin's own extra requests. Set in the provider editor (Concurrency, Requests per minute, Queue size, Queue wait) or with `magpie provider account-concurrency`, `queue` and `rpm`; a subscription's are kept with its picks, and every account of it keeps them, those on beside the first as well (`withPicks`, called by `All` and `AlsoOn`; #1899: a second WorkBuddy AI account had none, and queued 62s with the wait set to 1s). | [`concurrency.go`](../../internal/gateway/concurrency.go), [`rpm.go`](../../internal/gateway/rpm.go), [`internal/provider/concurrency.go`](../../internal/provider/concurrency.go) | | Accounts at once | A provider's `MaxAccounts` (01huadalang on Discord: three ZCode accounts used at once got the exit address refused with a 405, two didn't) is how many of its keys or accounts take requests at the same time: `provider.AtOnce()` is the user's own value, else what its plugin declares (`maxAccounts` on the auth hook or in package.json's `magpie`, read by host.js `atOnceOf`; zcode says 2), else no limit; the user's 0 is no limit over the plugin's. `perKeyBarred` keeps the first N in the user's own order (`rank`, so a dragged list counts), preferring ones not resting, and hands the rest to `keepAtOnce`'s reserves: they go after everything else as asides with `candidate.reserve` set (`Weighed.Reserve`), so whatever the routing mode, a reserve is asked only once the kept ones failed or rest, and a kept one that rests gives its seat to the first reserve on the next request. Three guards keep a reserve from being reached for anything else: `laneMate` never spills a full lane onto one, a full queue (`laneErr`) drops the provider's reserves before passing on (`dropReserves`), so the request is turned away with the 429 instead, and session affinity keeps no conversation on a reserve once the kept ones can take it (`affine`'s "reserve"; Strict still holds). Leak known: a failure that rests nobody (a 5xx on one try) still passes that one request to the reserve, as it does to any next candidate. Set in the provider editor's Advanced (Accounts at once, beside Concurrency) or with `magpie provider at-once`; Routing's row says "in reserve · {n} at once" (`TestAtOnceKeepsFirstInUserOrder`, `TestAtOnceFullLaneWaitsForTheKept`, `TestAtOnceReserveTakesOverAndGivesBack`, `provider-at-once.test.cjs`). | [`fallback.go`](../../internal/gateway/fallback.go), [`concurrency.go`](../../internal/gateway/concurrency.go), [`internal/provider/concurrency.go`](../../internal/provider/concurrency.go) | @@ -204,7 +204,7 @@ recorded as a prediction failure (`noPrediction`). - A streamed reply stuck in a loop is ended, not let run to its output limit (#1359, Moody-Sin: WorkBuddy's DeepSeek v4.1 flash reasoned round "Now." "Writing." "Go." "Let me write." "OK." until max tokens while dsh and Pi waited). `holdWriter.Write` feeds every streamed try, passed through or translated, a key's, a built-in subscription's or a plugin's (a moved WorkBuddy's fetch in the plugin host, `TestLoopEndsWorkBuddysReply`), in each of the agent's protocols, to a `loopGuard` ([`loop_guard.go`](../../internal/gateway/loop_guard.go)). It cuts the reasoning and the text, each apart, into units, its lines and sentences (a list's `1.` or a decimal is no sentence's end), compared without case or a closing stop. A unit with no word in it (a letter run with no digit: not a brace, a rule, `0x00`, a hash or a row of numbers) isn't counted. When the last `loopWindow` (256) counted units of either are among no more than `loopDistinct` (24) different ones, the try is cut (`cutLoop`): what came with that write goes out, then, after a blank line (two newlines when that write stopped inside a line, `holdWriter.atLine`, #2446), the protocol's stream error (`streamError`, 502) naming the loop and quoting its units, and the vendor's request is cancelled. It falls back to nobody and rests nobody (`failLoop`); its usage record's error type is `reply_loop` (`usage.LoopErrType`), and Usage counts them per model (`Totals.Loops`), as "{n} looped" beside the model's failures in the Overview's rows and the Requests ranking (#1858, `TestLoopsCountedPerModel`, `usage-loops.test.cjs`). A reply magpie translates into the agent's protocol (`streamTranslated`) whose *reasoning* loops before it has said a text or a call, and isn't a continuation, is asked again once in place instead (`loopReasks`, through `holdWriter.onLoop`; cdredfox on X, WorkBuddy AI's DeepSeek v4 flash): the agent keeps the reasoning it has, the next try's follows it in the same stream, as an empty reply's re-ask does (#667), and only a loop on that try ends the reply with the error (`TestReasoningLoopIsAskedAgain`). A reply passed through in the agent's own protocol is asked again once too, at the fallback loop (`holdWriter.mayReloop`, `letGoLoop`; #2436, lqisgod: pi's Chat stream to WorkBuddy was cut at once): when nothing of the try has reached the agent yet, in any protocol, its held bytes are dropped; when its reasoning is already passing, only a Chat stream goes on, written up to the end of the tripping event, with the next try's chunks after it. An Anthropic or Responses stream already passing still ends with the error, since a second `message_start` or `response.created` can't follow. Each re-ask, in place or at the fallback loop, counts in the usage record's tries. A loop in the text, or after a text or call, is ended at once (`TestLoopAfterTextIsNotAskedAgain`). A cycle need not be exact. Code, tables, lists, logs, CSV and base64 differ line to line or have no words, and don't trip it (`TestLoopGuardLeavesOrdinaryRepliesAlone` feeds magpie's own sources and docs through it). A reply sent whole (no stream, or Gemini without `alt=sse`) isn't read. Settings › Models › Replies › *Stop looping replies* (`noLoopGuard`) turns it off. - A conversation going round one tool call is answered by magpie and sent nowhere (audie on Discord: Codex Desktop on WorkBuddy's deepseek-v4-pro read the same file 308 times in half an hour, and 340 times that evening, 537 credits). `stoppedToolLoop` ([`tool_loop.go`](../../internal/gateway/tool_loop.go)) runs in `serveAgent` before hooks, middleware and routing, and in the Codex backend's passthrough on Codex's own sign-in. It reads the request's own history, so it is per conversation and keeps no state: when the last `toolLoopRepeats` (8) turns are each the same calls (name and arguments, keys in any order, call ids ignored) answered with the same results (with Codex's `Wall time`, `Chunk ID` and `duration_seconds` taken out, `runNoise`) and nothing else from the user, the turn is answered in the agent's own protocol, streamed or whole (`writeLocalText` through `relayStatus`), with a notice naming the call. Any different result, or a word of the user's, starts the count again; the notice is a turn without calls, so the user's next word goes on. A body with fewer than 8 tool results isn't parsed (`mayLoop`), and only the newest 64 items of a long one are (`tailOf`, gjson), ~1ms for a 1.5MB turn (`BenchmarkToolLoopCheck`). The turn is recorded as Codex's title turns are (`answeredHere`): the Routing trace as "Tool loop stopped", and a usage row with provider `magpie`, rejected, its session and an error starting `tool loop:`. A poll that gets the same answer 8 times in a row is stopped too. Settings › Models › Replies › *Stop looping replies* (`noLoopGuard`) turns it off with the reply guard. Verification: `go test -tags nogui ./internal/gateway -run 'TestToolLoop'`. - A Chat request's earlier turns carry the assistant's thinking back in the spelling its own client used: `reasoning_content` (DeepSeek's, which OpenCode and most clients send), `reasoning` (OpenRouter's) or `reasoning_details` (OpenRouter's structured one). A request translated to a non-Chat upstream reads whichever of the three the turn has, in that order, as the turn's thinking (`messageReasoning`, `reasoningText`, read by `parseChat` in [chat.go](../../internal/gateway/chat.go)); the passthrough has read all three since `mistralThinking` (#494), which was the one place that did. Before that the parse layer read `reasoning_content` alone, so a tool-calling session whose client spelled it another way went on from its second turn without the model's own reasoning. -- The order of the steps a request's accounts go through, how much the accounts' own order (*Make first*) counts under each routing, and how often an allowance is read are described for users in [How magpie picks an account](../reference.md#how-magpie-picks-an-account). Smart compares renewals window by window, biggest first, each truncated to the hour (`weighRouted`), so the order decides only when every window falls in the same hour. A window's renewal is its reset, or, when what it has left runs out sooner or it has no reset, that moment (`Limit.RunsOut`, from `QuotaWindow.RunsOutAt`; `Allowance.Renewal`): the WorkBuddy plugin (0.1.14) sends it on its Credits window as the soonest end of a package with credits left (cdredfox on X). When the renewals tie to the hour, Smart goes by that moment once more (`Allowance.Lapse`, `Seat.Lapse`), so of accounts renewing together (WorkBuddy's free accounts all reset at the month's end, plugin 0.1.35) the one whose credits left lapse first, after that end, goes first, and one telling none goes after (zhaocai_83020 on Discord). Only Smart reads it; Weekly pace, the 90%/98% tiers and rests go by the window's share and reset as before. A row on the Routing page says the share used (the fullest window's, `Allowance.For`) with when that same window renews (`Allowance.Fullest`, the trace's `usedRenews`), not the biggest window's: a Factory account 32% into its week and 16% into its month reads "32% used · renews in 3 days" while Smart still ranks it by its month (#1778). A route from before `usedRenews` says when only for an account of one window. Affinity keeps a conversation on an account at 90–97%: only `SpentShareOf` (98%, 100% In order) stops it (`affine`), while the 90% tier (`lowShare`) orders only conversations nobody has answered. +- The order of the steps a request's accounts go through, how much the accounts' own order (*Make first*) counts under each routing, and how often an allowance is read are described for users in [How magpie picks an account](../reference.md#how-magpie-picks-an-account). Smart compares renewals window by window, biggest first, each truncated to the hour (`weighRouted`), so the order decides only when every window falls in the same hour. A window's renewal is its reset, or, when what it has left runs out sooner or it has no reset, that moment (`Limit.RunsOut`, from `QuotaWindow.RunsOutAt`; `Allowance.Renewal`): the WorkBuddy plugin (0.1.14) sends it on its Credits window as the soonest end of a package with credits left (cdredfox on X). When the renewals tie to the hour, Smart goes by that moment once more (`Allowance.Lapse`, `Seat.Lapse`), so of accounts renewing together (WorkBuddy's free accounts all reset at the month's end, plugin 0.1.35) the one whose credits left lapse first, after that end, goes first, and one telling none goes after (zhaocai_83020 on Discord). Only Smart reads it; Use before expiry, the 90%/98% tiers and rests go by the window's share and reset as before. A row on the Routing page says the share used (the fullest window's, `Allowance.For`) with when that same window renews (`Allowance.Fullest`, the trace's `usedRenews`), not the biggest window's: a Factory account 32% into its week and 16% into its month reads "32% used · renews in 3 days" while Smart still ranks it by its month (#1778). A route from before `usedRenews` says when only for an account of one window. Affinity keeps a conversation on an account at 90–97%: only `SpentShareOf` (98%, 100% In order) stops it (`affine`), while the 90% tier (`lowShare`) orders only conversations nobody has answered. - A turn's end is told to the app for the "Task done alert" notification (itieniu on X, `turndone.go`). The trace follows each agent session's turn (`turns`, keyed by agent and session): a request is of the turn unless it has a `Kind` or is a Claude Code subagent's (`agentTurnOf`), and its reply is scanned on the way to the agent for a tool call in any wire format (`toolScan`, a JSON value such as `"type":"tool_use"` or `"finish_reason":"tool_calls"`, never a key or text). The turn is done when no request of it is going, the last reply was whole, under 400 and called no tool, and nothing more came for `turnQuiet` (4s); a session idle past `turnStale` (30m) starts over. Only a turn that ran at least `settings.TurnDoneAlert` seconds is told (`TurnDone`, set by the GUI; nil under `magpie serve`, so nothing is followed). The ChatGPT backend path (`codexBackend`) is followed the same way. `TestTurnDoneSaidAtTheTurnsEnd`, `TestTurnDoneCodexBackend`, `TestToolScan`, `turn-done.test.cjs`. - A request's masking record is told to the app for the "Masking alert" notification (Must2333 on X, `OnMasked` in [`masked.go`](../../internal/gateway/masked.go), set by the GUI; nil under `magpie serve`), after `maskrec.Hold` and with its text around placeholders (`Snips`, `Back`) taken out. [`mask_alert.go`](../../internal/gui/mask_alert.go) keeps the records while `settings.MaskAlert` is on (off until turned on, in Settings → Usage, hidden with masking) and says only the values a record masked for the first time (`maskrec.Fresh`, [`first.go`](../../internal/maskrec/first.go): each placeholder by the key of the first record that had it, read from memory and the days kept, so a conversation's history sent again each turn, or after a restart, is not news; a value sent as written is not one masked). A burst is gathered for `maskGather` (3s) and said as one, and one is said at most every `maskGap` (1 minute), what came in between said after it. It says each kind with its count and up to two agents, never a value nor its hint; a click opens the Masking page on the latest record (`clickView`, `masking&key=`). A held-back request (`noteBlocked`) is not said; a value whose records have all aged out (30 days) is new again. `TestFreshOnlyTheFirstTime`, `TestMaskAlertFirstTimeOnly`, `TestMaskAlertNeverSaysTheValue`, `TestMaskAlertCoalesces`, `mask-alert.test.cjs`. - A resting candidate is tried last (`restLast`). Of the resting candidates, a request asks only the one whose rest ends soonest, the first in order on a tie (`probeOne`, #1799). The others aren't asked by that request, so a member that is down isn't asked by every request its rest was meant to spare it from, and a group that is down whole takes one upstream request per request, not one per member. Every ready candidate is still asked in its order. A lone candidate is tried even while it rests, because there is no other. The trace still lists every member, the resting ones with their rest. Only rests are read, and a failure about the request's content or its model rests no member (a model refusal rests only `restID`), so neither leaves a member out. The same applies in `count_tokens`, embeddings and rerank, image accounts and a group's System One decision models. A Codex reset (`autoReset`) still looks over every candidate. This is like AxonHub's error-aware load balancing: the rest and its backoff are the penalty that decays, and the member back soonest is the one asked to show it is back. Keys out of their allowance aren't asked even so, not even the one back soonest or a lone one (#1772: four Ollama Cloud keys out for the week, each asked again and refused on every request). The refusal given again says when they are asked again on this magpie's clock with its offset (`heldClock`: "20:12 UTC+8", "Oct 16 09:00 UTC+8"), as do the gateway's other held errors (a capped window, a spent searcher or describer): its reader may be a Remote magpie's user on another clock. When every candidate left is a key (not a subscription account, whose resets `autoReset` may spend) resting out of quota or credit after a 429 or 402, none is asked. The first one's refusal is given again (`quotaHeld`, its words kept in the rest's `said`), saying when it is asked again. A key whose rest magpie guessed the length of, the vendor and the user naming no time (`creditRest`, or `quotaRest` with no `Provider.OwnQuotaRest`), is held so only once it was refused so twice in a row (`Rest.first`): a single refusal may be a moment's, and the next request, the agent's retry first, asks it again (zoecats on Discord: a local aggregator said 429 `insufficient_quota` "quota exhausted" for the moment it switched upstreams, and every request was answered from its rest of 15 or 30 minutes, which only the provider's "Rests" switch, `LimitRestOff`, let through before). Held, it is asked again a minute on (`Rest.askAt`, `fallbackCooldown`), once, and held again if refused (`Rest.asksAt`); a time the vendor named, or the user set, holds it from the first refusal to then. The rest itself stays as long as before, so the order still passes it over for a candidate that is ready. The last key left rests too when it is refused so, as the keys before it do, and so does the last account left (a Codex or other subscription account; `quotaHeld` still holds keys alone, and `autoReset` lifts the rest of an account it spends a reset of): before, an account last in an in-order group, out of its quota, was never rested, so every request a relay ahead of it failed for a moment went on to it and ended on its 429 (dbydd on Discord; `TestGroupSpentLastAccountRests`). Any 429 that reaches the agent without a vendor `Retry-After`, while every candidate tried is resting, carries one: the seconds until the first of them is asked again (`soonestBack`, by `asksAt`), none after a key's first refusal. `TestRetryAfterALimitIsAsked`, `TestHeldLimitAskedAgainInAMinute`. A quota refusal with no word of when it is back rests `quotaRest` (15 minutes), or the provider's own `quotaRest` in minutes (`Provider.QuotaRestFor`, at most `MaxQuotaRest`, 8 days; `magpie provider quota-rest 7d`), or until the time of day the user said its allowance comes back (`QuotaResetAt`, `Provider.OwnQuotaRest`; `magpie provider quota-rest until 08:00`, or `until 00:00+08:00` on the vendor's clock; #2008, a free tier's "today's free-model token quota"). Whichever of the two was set last counts. A time the vendor names stands over it, and so does its `Retry-After`, unless that was more than `longestWait` (an hour) and so cut to it while the user's own rest is longer: then the user's stands (`TestQuotaRestsUntilTheTimeOfDaySet`). A key listed in `keys` as well as in `key` is one candidate (`KeysOn`), not asked twice. `TestAllRestingAnswersFromRest`, `TestOwnQuotaRest`, `TestQuotaHeldOnlyForKeysOutOfAllowance`, `TestFirstKeyListedTwiceAskedOnce`. @@ -219,7 +219,7 @@ recorded as a prediction failure (`noPrediction`). - A routing group set to In order is tried in the order the user put its members in, and a later member keeps a conversation only until a member ahead of it is ready again (yyhhyyyyyy on Discord: an API key first and a Claude subscription second for Opus, 8 of 10 Claude Code requests on the subscription). One failure of the first member (a 429, a 5xx, a rest) sent a conversation to the second, and Auto affinity's `cache` kept it there at every turn after, since each turn read what the last had written. Now, with Stays left on Auto, a new turn goes back to the first ready member when it is another member than the one that answered last (`backToFirst` in `affine`, `Affinity.Why` `order`; another key or account of the same member, or a group in the group, keeps its own affinity). Within a turn it stays, on the reasoning the later member sealed, as with `main`. Stays: Session and Strict are the user's own and keep the conversation where it is. The Routing page says why it moved. `TestOrderedGroupGivesTheConversationBackToItsFirstMember`, `routing-affinity-order.test.cjs`. - A group routed any other way (Smart, Least used first, By weight and the rest, In turn aside) gives back a conversation a later member took only as a stand-in (01huadalang on Discord, 11-01: Codex on two accounts first in a Smart group, a MiMo key second as the backup; after an outage of Codex's 5 hours, a session that had gone to MiMo stayed there by MiMo's cache once Codex was back, while new ones went to Codex). A member stood in when, as it answered, a member the group lists ahead of its own was resting (a 429, a 5xx: `restAfter` rests the one that failed before the try goes on) or known all but used up (`Used` at `SpentShareOf`): `standsInFor`, over the plan as it was for the request, by each candidate's `place` in the group's list (`placed` in `planGroup`; a group in the group is one member). The stick keeps it (`stick.stoodIn`, and `stoodIn` in `affinity.json`, absent from a file written before and read as no stand-in) while the same account and model answer on, so a stand-in that routing still puts first after the one ahead is back (Smart's low tier, a week at 92%) gives the conversation back once routing puts the one ahead first. At a new turn, with Stays on Auto, the conversation goes to the first ready member when that one is listed ahead of the stand-in's (`backFromStandIn`, `Affinity.Why` `back`); another key or account of the same member keeps it by its cache. A member routing put first while those ahead of it were ready and had room is no stand-in and keeps its cache as before, so peers of a Smart group don't trade conversations by renewal order. Within a turn it stays; Within a turn and Off route each new turn afresh anyway; Session and Strict keep it where it is; In turn's next turn goes round (`after`). Routing still decides who is first: Least used first and Smart put a key whose usage isn't told (counted unused) ahead of accounts at 90% or more of a window, so a conversation, and every new one, goes to such a backup while the subscription's accounts are that low (routing's own choice, not affinity's; In order keeps a backup last). `TestGroupBackupGivesTheConversationBack`, `TestGroupBackupStandingInWhileTheFirstIsBackAndBehind`, `TestGroupMemberPutFirstOnItsMeritsKeepsItsCache`, `TestGroupStandInStaysWithinATurn`, `TestGroupMemberGivesTheConversationBackOnceTheOneAheadIsBack`, `routing-affinity-order.test.cjs`. - In turn (`rotate`), a conversation nobody has answered yet goes to the key, account or model the fewest other conversations of the provider's model or the group answered in the last `heldFor` (30 minutes) are on (`leastHeld`, #946). Ties, resting ones, a provider's fallback while the provider's own leads (`standsIn`) and a group with a group in it keep routing's order. With session affinity, two sessions of one group so stay on different models. -- Stays: Session or Strict under a routing that picks by what is left (Smart, Least used first, Weekly pace: `spreadsSessions`) spreads new conversations the same way (connor_yang on Discord: three sessions over three accounts landed on two). `leastHeld` with `ready` passes over one routing keeps new conversations off (`readyForNew`: resting, a key for another protocol, a provider's fallback while its own model leads, one used past `lowShare`), counts only leads (a key without `|agent:`), and leaves the turn marks alone. A subagent's first request goes to its lead's key or account while that one is `readyForNew` (`withLead`), so a session keeps one account, its subagents included. Held is the last `heldFor` (30 minutes): a session idle longer counts no more. In order, By weight, Free first, Speed first, Cheapest, Manual and a plugin's routing keep their order. An answered conversation is kept as before; the spread only decides where a new one starts. `session_spread_test.go`. +- Stays: Session or Strict under a routing that picks by what is left (Smart, Least used first, Use before expiry: `spreadsSessions`) spreads new conversations the same way (connor_yang on Discord: three sessions over three accounts landed on two). `leastHeld` with `ready` passes over one routing keeps new conversations off (`readyForNew`: resting, a key for another protocol, a provider's fallback while its own model leads, one used past `lowShare`), counts only leads (a key without `|agent:`), and leaves the turn marks alone. A subagent's first request goes to its lead's key or account while that one is `readyForNew` (`withLead`), so a session keeps one account, its subagents included. Held is the last `heldFor` (30 minutes): a session idle longer counts no more. In order, By weight, Free first, Speed first, Cheapest, Manual and a plugin's routing keep their order. An answered conversation is kept as before; the spread only decides where a new one starts. `session_spread_test.go`. - A ChatGPT account that holds credits answers past its windows on them; the vendor spends them. That is the default. Set not to spend them (Usage card's *Use credits*, `magpie quota credits off`), the account is held at 100% of a window till it renews, by magpie's latest reading of its windows (`provider.Allowances`, refreshed about every minute), so the other accounts, groups and fallbacks take the request. A cap set on the account (1–99%) takes precedence. Unlike a cap, the hold is at the vendor's own 100%, so an account allowed to spend its resets spends one there, both when every candidate is held and after the last one is refused. A reset made forgets the account's cached allowance (`renewedNow`), so neither hold outlives the windows it started again. One let spend its credits, and holding some by its last `/wham/usage` (`credits.has_credits` with a balance over 0, or `unlimited`; `QuotaWindow.Credits`, `Limit.Credits`, `Allowance.OnCredits`), is not out when a window fills (豆子 and Zhenzhen on Discord): ChatGPT may answer the turn that uses the window up 429 `usage_limit_reached` before it spends the credits, and the next turn on them. So that 429 is asked again at once, once a request, on the same account, before a reset is looked at, on the routed path (`creditsAgain`, `creditsAsked`, `Try.Credits`) and on Codex's own sign-in's relay (`relayOnCredits`), rather than ended for the agent, which ended a running session while a new one worked. Refused again, it rests `fallbackCooldown` (`Rest.By` `credits`) and is read again, not until its window renews, and its full windows rest it nowhere else (`full` is zero for it, `spendsCredits`). Smart, Pace and Least used put such an account first of the spent tier (`routes.Seat.Credits`, `spentBefore`): after those with allowance left, ahead of those used up with nothing to go on with (`Weighed.Credits`, told on the Routing page). Switching to credits early, at a few percent left, was weighed and not done: the vendor spends credits only once the allowance is used up, so it would only waste what is left. `TestCodexCreditsAskedAgainAtTheEdge`, `TestCodexCreditsNoLongRest`, `TestCodexCreditsFirstOfTheSpent`, `TestCreditsFirstOfTheSpent`, `routing-codex-credits-again.test.cjs`. - A third way, set per account, spends the credits only after everything else (gokoshiki on Discord: a Codex subscription, then an OpenAI API key, then the subscription's credits): *Only after every other account, key and fallback* under the Usage card's *Use credits*, `magpie quota credits last`, `settings.CodexCreditsLast` (`provider.CodexCreditsLast`, `SetCodexCreditsMode`; on or off clears it, and an account never in it keeps its place, so a setting saved before keeps its order). Such an account is `creditsLast` while it goes on on its credits (`spendsCredits`) and a window for the model is used up where *off* would hold it (`Allowance.CapHeld` at `WindowCaps{Credits: true}`; a call ChatGPT counts in no window, `freeOnChatGPT`, stays). `restLast` then puts it behind every candidate of the plan, the provider's fallbacks and groups included: ready, then resting, then the credits-last ones in their own order (`Weighed.CreditsLast`). Affinity doesn't keep a conversation on one while one not on its credits leads (`Affinity.Why` `credits`, `lastBehind`), within a turn too, and In turn's next pick and Smart/Pace/Least used's spreading of new sessions never bring one forward (`after`, `leastHeld`, `readyForNew`). Strict affinity keeps it, as a rule, an `X-Magpie-Account` pin and a sealed task's lead (`leadFirst`) still put theirs first. A reset is still spent before its credits when the try reaches it (`resetBeforeCredits`). Codex's own sign-in's relay has the one account and nothing to put first, so there it is as *on*. The Routing page tells each: behind the rest, first when every one is, and the conversation moved. `TestCodexCreditsLastAfterTheOthers`, `TestCodexCreditsLastAfterTheFallback`, `TestCodexCreditsLastNotKept`, `TestCodexCreditsLastMode`, `codex-credits-last.test.cjs`. - A fourth, set per account, spends the credits before moving to another account (jojonas_xyz on X: the account ran out, magpie moved to another by itself, and no setting kept the first one's credits in use). *On* alone lets the vendor answer on credits, but Smart and Pace still put an account at `LowShare` (90%) or `SpentShare` (98%) behind every account with room (`tier`), Drain counts it used up at `SpentShareOf(Drain)`, and `NextLogin` moves Codex's own sign-in at the spent share, credits or not. *Before moving to another account* under *Use credits* (the Usage card, the menu bar panel, and the account's ⋯ in its provider's editor), `magpie quota credits first`, `settings.CodexCreditsFirst` (`provider.CodexCreditsFirst`; one of first and last at most, on or off clears it) makes an account that spends credits (`spendsCredits`) a `routes.Seat.First`: Smart, Pace and Fastest weigh it at tier 0 (`seatTier`), Drain doesn't count it spent, affinity doesn't move a conversation off it as `spent`, and `readyForNew`/`standsInFor` treat it as having room (`Weighed.CreditsFirst`). `NextLogin` keeps Codex signed in to it while one of its windows says it holds credits (`spendsFirst`); with the credits gone it moves as before. The account magpie moved Codex off says where the setting is, on its *First again once it has room* tag. `TestCodexCreditsFirstKeepsItsPlace`, `TestCodexCreditsFirstDrainStays`, `TestCodexCreditsFirstMode`, `TestCodexStaysOnAnAccountSpendingCreditsFirst`, `codex-credits-first.test.cjs`. diff --git a/internal/gateway/affinity.go b/internal/gateway/affinity.go index 53489c45f..b361bb35e 100644 --- a/internal/gateway/affinity.go +++ b/internal/gateway/affinity.go @@ -912,7 +912,7 @@ func withLead(key string, cs []candidate, pl planned) ([]candidate, planned) { // spreadsSessions says whether new conversations kept for the whole // session (Stays: Session or Strict) go to the key, account or member the // fewest others are on (leastHeld), under a routing that picks by what -// each has left: Smart, Least used first, Weekly pace. Several sessions +// each has left: Smart, Least used first, Use before expiry. Several sessions // started side by side then each keep an account of their own until its // allowance runs out, as a user picking the mode with several accounts // expects (connor_yang on Discord: three sessions on two of three diff --git a/internal/gateway/pace_expiry_test.go b/internal/gateway/pace_expiry_test.go new file mode 100644 index 000000000..d75abcdea --- /dev/null +++ b/internal/gateway/pace_expiry_test.go @@ -0,0 +1,94 @@ +package gateway + +import ( + "strings" + "testing" + "time" + + "github.com/yetone/magpie/internal/provider" +) + +// Use before expiry (Pace) takes credits that expire before their window +// renews for that window's deadline: what expires, as a share of the +// window, per hour until it does. lcyksp on Discord: a WorkBuddy month of +// 500 credits renewing in 28 days, 70.85 check-in credits in it expiring +// tomorrow morning, was billed after an account whose month had more to +// lose per hour, so the check-in credits lapsed unspent. Credits that +// expire after the window renews change nothing, nor do a few credits +// expiring when the month has more to lose; when the amount isn't told, +// all that is left is taken as lost then, as Smart's Renewal takes it. +// The trace says the deadline is the expiry. +func TestPaceGoesByCreditsExpiring(t *testing.T) { + old := allowances + defer func() { allowances = old }() + now := time.Now() + share := map[string]provider.Allowance{} + allowances = func(string) map[string]provider.Allowance { return share } + const model = "deepseek-v4.1-flash" + p := provider.Provider{ID: "workbuddy", Routing: provider.Pace, Account: &provider.Account{Agent: "workbuddy", User: "a@x.com"}} + acct := func(user string) candidate { + return candidate{p: provider.Provider{ID: "workbuddy", Account: &provider.Account{Agent: "workbuddy", User: user}}, model: model, rest: "workbuddy#" + user} + } + month := func(used float64, renews time.Duration) provider.Allowance { + return provider.Allowance{{Used: used, Amount: 500 * used / 100, Of: 500, Unit: "credits", Resets: now.Add(renews), Name: "Credits"}} + } + order := func() (string, weighing, []candidate) { + got, wg := weigh(p, []candidate{acct("b@x.com"), acct("a@x.com")}, model, provider.Chat) + var s []string + for _, c := range got { + s = append(s, c.p.Account.User[:1]) + } + return strings.Join(s, ""), wg, got + } + // B: half its month left, renewing in ten days: 50/240h ≈ 0.21 an + // hour, ahead of A's 100/672h ≈ 0.15 when nothing of A's expires + share["b@x.com"] = month(50, 10*24*time.Hour) + share["a@x.com"] = month(0, 28*24*time.Hour) + if got, _, _ := order(); got != "ba" { + t.Fatalf("nothing expiring: %s", got) + } + + // the report: 70.85 of A's credits expire in 14 hours, 14% of its + // 500 lost then, 1% an hour + share["a@x.com"][0].RunsOut, share["a@x.com"][0].RunsOutLeft = now.Add(14*time.Hour), 70.85 + got, wg, cs := order() + if got != "ab" { + t.Fatalf("credits expiring tomorrow go first: %s", got) + } + w := weighed(cs[0], p, wg, false, provider.Chat) + if w.DueBy != "expiry" || w.Due == nil || !w.Due.Equal(now.Add(14*time.Hour)) { + t.Fatalf("trace: due %v by %q", w.Due, w.DueBy) + } + if b := weighed(cs[1], p, wg, false, provider.Chat); b.DueBy != "" { + t.Fatalf("trace: B by %q", b.DueBy) + } + + // the amount not told: all A has left is taken as lost then + share["a@x.com"][0].RunsOutLeft = 0 + if got, _, _ := order(); got != "ab" { + t.Fatalf("amount not told: %s", got) + } + + // one credit expiring: 0.2% over 14h is less than A's month per hour, + // so its month decides, and B goes first + share["a@x.com"][0].RunsOutLeft = 1 + if got, wg, cs = order(); got != "ba" { + t.Fatalf("a credit expiring: %s", got) + } + if w := weighed(cs[1], p, wg, false, provider.Chat); w.DueBy != "" { + t.Fatalf("trace, month decides: by %q", w.DueBy) + } + + // expiring after the month renews: lost to the reset first, nothing + // changes + share["a@x.com"][0].RunsOut, share["a@x.com"][0].RunsOutLeft = now.Add(30*24*time.Hour), 70.85 + if got, _, _ := order(); got != "ba" { + t.Fatalf("expiring after the renewal: %s", got) + } + + // expired already: nothing changes + share["a@x.com"][0].RunsOut = now.Add(-time.Hour) + if got, _, _ := order(); got != "ba" { + t.Fatalf("expired already: %s", got) + } +} diff --git a/internal/gateway/reset_deadline_test.go b/internal/gateway/reset_deadline_test.go index 1d5c20fee..a874ae0cb 100644 --- a/internal/gateway/reset_deadline_test.go +++ b/internal/gateway/reset_deadline_test.go @@ -10,7 +10,7 @@ import ( // A Codex account that spends a reset about to run out by itself (auto-use // on, its windows used) loses what its week has left when that reset is -// spent, resetLead (half an hour unless set) before it runs out: Weekly pace and Smart take +// spent, resetLead (half an hour unless set) before it runs out: Use before expiry and Smart take // that for its deadline when it is sooner than the week renews (#717, // #718, thedavidweng: A with 80% left renewing in five days and a reset // running out that afternoon went behind B with 50% left renewing in two). diff --git a/internal/gateway/routing.go b/internal/gateway/routing.go index 3bf5ce095..02d250fc3 100644 --- a/internal/gateway/routing.go +++ b/internal/gateway/routing.go @@ -1995,9 +1995,10 @@ type left struct { due time.Time // when the window that pace went by renews; zero when not known // restarts: when an auto-used reset starts its windows again // (Allowance.Restarts), zero when none will; dueRestart: due is that, - // sooner than the window renews by itself - restarts time.Time - dueRestart bool + // sooner than the window renews by itself; dueExpiry: due is when + // credits in it expire, sooner than it renews (Allowance.Pace) + restarts time.Time + dueRestart, dueExpiry bool // the count used is the share of, when the vendor counts it so // (Allowance.Count): amount of of, in unit amount, of float64 @@ -2086,6 +2087,7 @@ func weighRouted(p provider.Provider, cs []candidate, model string, from provide rs := a.Restarts(now) 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 + l.dueExpiry = !l.dueRestart && !l.lapse.IsZero() && due.Equal(l.lapse) l.first = l.credits && provider.CodexCreditsFirst(c.p.Account.User) if b, bu, has := a.Left(c.model); has { // a wallet's figure is weighed only against the same diff --git a/internal/gateway/trace.go b/internal/gateway/trace.go index a0b33ada3..a76599d65 100644 --- a/internal/gateway/trace.go +++ b/internal/gateway/trace.go @@ -314,7 +314,9 @@ type Weighed struct { // allowance (#3749) Window int `json:"window,omitempty"` // DueBy: "reset" when Due is when an auto-used Codex reset about to - // run out starts the windows again, sooner than they renew (#717) + // run out starts the windows again, sooner than they renew (#717); + // "expiry" when it is when credits in them expire, sooner than they + // renew (Allowance.Pace) DueBy string `json:"dueBy,omitempty"` // Restarts: when that reset starts them again, set when it is sooner // than its biggest window renews — Smart goes by it then (#718) @@ -531,8 +533,11 @@ func weighed(c candidate, p provider.Provider, wg weighing, fallback bool, from if !l.due.IsZero() { due := l.due w.Due = &due - if l.dueRestart { + switch { + case l.dueRestart: w.DueBy = "reset" + case l.dueExpiry: + w.DueBy = "expiry" } } if rs := l.restarts; !rs.IsZero() && len(l.soon) > 0 && rs.Equal(l.soon[0]) { diff --git a/internal/gateway/weekly_pace_test.go b/internal/gateway/weekly_pace_test.go index a6dcc8e6b..303e1ad25 100644 --- a/internal/gateway/weekly_pace_test.go +++ b/internal/gateway/weekly_pace_test.go @@ -8,7 +8,7 @@ import ( "github.com/yetone/magpie/internal/provider" ) -// Weekly pace puts first the account with the most of its week left per +// Use before expiry puts first the account with the most of its week left per // hour until it renews — the one with the most to lose at its reset — not // the one with the most left: 20% left and an hour to go beats 60% left // and five days. Alike within a tenth go by the tokens sent lately, then diff --git a/internal/gui/assets/app.js b/internal/gui/assets/app.js index c0d570605..a34aab5e8 100644 --- a/internal/gui/assets/app.js +++ b/internal/gui/assets/app.js @@ -11893,7 +11893,7 @@ const ROUTINGS = [ ["drain", "Until used up", "Requests stay on one until it is used up, then go to the next in the list and stay there: one before it that renews meanwhile doesn't take them back. One rate limited or failing is passed over while it rests, and requests come back to it after."], ["rotate", "In turn", "Each turn of a conversation goes to the next one, spreading the load evenly; the requests within a turn stay where it began, so the prompt cache holds, and one that fails is passed over while it rests."], ["usage", "Least used first", "Each request goes to the one used least: a subscription by the share of its allowance used, a key by the tokens it served in the last hours."], - ["pace", "Weekly pace", "Each request goes to the subscription with the most of its week left per hour until it renews — the one with the most to lose at its reset — so less of each week is lost at its reset; one at 90% or more waits until the others can't answer. A key goes by the tokens it served in the last hours."], + ["pace", "Use before expiry", "Each request goes to the subscription with the most left per hour until it is lost — its week at its reset, or credits in it that expire sooner — so less is lost to resets and expiry; one at 90% or more waits until the others can't answer. A key goes by the tokens it served in the last hours."], ["weight", "By weight", "Requests spread over the keys or accounts by the weight set beside each: one weighing 3 takes three requests for every one weighing 1 takes, evenly over a few requests. One that fails is passed over while it rests, and the others share its requests; a conversation stays with it as Stays says."], ["free", "Free first", "Requests go to what costs nothing first: the models their vendor serves at no cost to this subscription's allowance or credits, in their listed order, and only when those can't answer to one that spends them. Nothing that cost nothing is left unused."], ["fast", "Speed first", "Requests go to the one that has answered this model fastest lately, by its time to the first token and how fast it writes; those within a tenth of each other keep their listed order. One not measured lately gets one request in five, so it is measured again, and one that fails is passed over while it rests."], diff --git a/internal/gui/assets/i18n.js b/internal/gui/assets/i18n.js index 8777b9d07..0fd740249 100644 --- a/internal/gui/assets/i18n.js +++ b/internal/gui/assets/i18n.js @@ -877,7 +877,7 @@ const I18N = { "Send each request's traces and metrics to an OpenTelemetry collector, such as Langfuse": "把每个请求的追踪和指标发送到 OpenTelemetry 收集器,比如 Langfuse", "Sending to a collector": "正在发送到收集器", "Routing strategies": "路由策略", - "The routings besides Smart: In order, Until used up, In turn, Least used first, Weekly pace, By weight, Free first, Speed first and Cheapest first": "智能以外的路由方式:按顺序、用完再换、轮流、用量少的优先、重置前用完、按权重、免费优先、速度优先和最便宜优先", + "The routings besides Smart: In order, Until used up, In turn, Least used first, Use before expiry, By weight, Free first, Speed first and Cheapest first": "智能以外的路由方式:按顺序、用完再换、轮流、用量少的优先、到期前用完、按权重、免费优先、速度优先和最便宜优先", "1 provider or group routed so": "1 个提供商或路由组在用", "{n} providers and groups routed so": "{n} 个提供商和路由组在用", "Run the JavaScript gateway plugins: middleware on agents' requests and replies, routings and usage observers": "运行 JavaScript 网关插件:Agent 请求和回复上的中间件、路由方式和用量观察者", @@ -1823,8 +1823,8 @@ const I18N = { "Requests go to the first; the next takes over when the one before runs out of quota, hits a rate limit or fails.": "请求先发给第一个;它额度用完、被限流或出错时,由下一个接手。", "Each turn of a conversation goes to the next one, spreading the load evenly; the requests within a turn stay where it began, so the prompt cache holds, and one that fails is passed over while it rests.": "会话每一轮轮流交给下一个,均摊负载;同一轮内的请求留在起始处,保持提示词缓存;出错的在暂停期间跳过。", "Each request goes to the one used least: a subscription by the share of its allowance used, a key by the tokens it served in the last hours.": "每个请求发给用量最少的:订阅看已用额度比例,密钥看最近几小时经它的 token 数。", - "Weekly pace": "重置前用完", - "Each request goes to the subscription with the most of its week left per hour until it renews — the one with the most to lose at its reset — so less of each week is lost at its reset; one at 90% or more waits until the others can't answer. A key goes by the tokens it served in the last hours.": "每个请求发给周剩余额度 ÷ 距重置小时数最高的订阅;用到 90% 以上的,等其他都无法响应时才用。密钥按最近几小时处理的 token 数排序。", + "Use before expiry": "到期前用完", + "Each request goes to the subscription with the most left per hour until it is lost — its week at its reset, or credits in it that expire sooner — so less is lost to resets and expiry; one at 90% or more waits until the others can't answer. A key goes by the tokens it served in the last hours.": "每个请求发给剩余额度 ÷ 距作废小时数最高的订阅——周额度在重置时作废,更早过期的积分按过期时间算;用到 90% 以上的,等其他都无法响应时才用。密钥按最近几小时处理的 token 数排序。", "The gateway now uses {user} first": "网关现在优先使用 {user}", "{agent} signs in to the first. Tick more and magpie moves on to the next when the one before it is out of quota. Sessions already running keep theirs until restarted.": "{agent} 登录首选账号;勾选多个时,前一个额度用完 magpie 自动换下一个。已在运行的会话保持原账号,重启后切换。", "{agent} is signed in to this account": "{agent} 当前登录的就是这个账号", @@ -5301,7 +5301,7 @@ const I18N = { "Send each request's traces and metrics to an OpenTelemetry collector, such as Langfuse": "把每個請求的追蹤和指標傳送到 OpenTelemetry 收集器,例如 Langfuse", "Sending to a collector": "正在傳送到收集器", "Routing strategies": "路由策略", - "The routings besides Smart: In order, Until used up, In turn, Least used first, Weekly pace, By weight, Free first, Speed first and Cheapest first": "智慧以外的路由方式:按順序、用完再換、輪流、用量少的優先、重置前用完、按權重、免費優先、速度優先和最便宜優先", + "The routings besides Smart: In order, Until used up, In turn, Least used first, Use before expiry, By weight, Free first, Speed first and Cheapest first": "智慧以外的路由方式:按順序、用完再換、輪流、用量少的優先、到期前用完、按權重、免費優先、速度優先和最便宜優先", "1 provider or group routed so": "1 個提供商或路由組在用", "{n} providers and groups routed so": "{n} 個提供商和路由組在用", "Run the JavaScript gateway plugins: middleware on agents' requests and replies, routings and usage observers": "執行 JavaScript 閘道外掛:Agent 請求和回覆上的中介軟體、路由方式和用量觀察者", @@ -6236,8 +6236,8 @@ const I18N = { "Requests go to the first; the next takes over when the one before runs out of quota, hits a rate limit or fails.": "請求先發給第一個;它額度用完、被限流或出錯時,由下一個接手。", "Each turn of a conversation goes to the next one, spreading the load evenly; the requests within a turn stay where it began, so the prompt cache holds, and one that fails is passed over while it rests.": "會話每一輪輪流交給下一個,均攤負載;同一輪內的請求留在起始處,保持提示詞快取;出錯的在暫停期間跳過。", "Each request goes to the one used least: a subscription by the share of its allowance used, a key by the tokens it served in the last hours.": "每個請求發給用量最少的:訂閱看已用額度比例,金鑰看最近幾小時經它的 token 數。", - "Weekly pace": "重置前用完", - "Each request goes to the subscription with the most of its week left per hour until it renews — the one with the most to lose at its reset — so less of each week is lost at its reset; one at 90% or more waits until the others can't answer. A key goes by the tokens it served in the last hours.": "每個請求發給週剩餘額度 ÷ 距重置小時數最高的訂閱;用到 90% 以上的,等其他都無法回應時才用。金鑰按最近幾小時處理的 token 數排序。", + "Use before expiry": "到期前用完", + "Each request goes to the subscription with the most left per hour until it is lost — its week at its reset, or credits in it that expire sooner — so less is lost to resets and expiry; one at 90% or more waits until the others can't answer. A key goes by the tokens it served in the last hours.": "每個請求發給剩餘額度 ÷ 距作廢小時數最高的訂閱——週額度在重置時作廢,更早過期的點數按過期時間算;用到 90% 以上的,等其他都無法回應時才用。金鑰按最近幾小時處理的 token 數排序。", "The gateway now uses {user} first": "閘道現在優先使用 {user}", "{agent} signs in to the first. Tick more and magpie moves on to the next when the one before it is out of quota. Sessions already running keep theirs until restarted.": "{agent} 登入首選帳號;勾選多個時,前一個額度用完 magpie 自動換下一個。已在執行的會話保持原帳號,重啟後切換。", "{agent} is signed in to this account": "{agent} 目前登入的就是這個帳號", @@ -9696,7 +9696,7 @@ const I18N = { "Send each request's traces and metrics to an OpenTelemetry collector, such as Langfuse": "各リクエストのトレースとメトリクスを Langfuse などの OpenTelemetry コレクターに送ります", "Sending to a collector": "コレクターに送信中", "Routing strategies": "ルーティング戦略", - "The routings besides Smart: In order, Until used up, In turn, Least used first, Weekly pace, By weight, Free first, Speed first and Cheapest first": "スマート以外のルーティング:順番、使い切ってから次へ、交互、使用量が最少のものを優先、週ペース、重み付け、無料優先、速度優先、最安優先", + "The routings besides Smart: In order, Until used up, In turn, Least used first, Use before expiry, By weight, Free first, Speed first and Cheapest first": "スマート以外のルーティング:順番、使い切ってから次へ、交互、使用量が最少のものを優先、期限前に使い切る、重み付け、無料優先、速度優先、最安優先", "1 provider or group routed so": "1 個のプロバイダーまたはグループが使用中", "{n} providers and groups routed so": "{n} 個のプロバイダーとグループが使用中", "Run the JavaScript gateway plugins: middleware on agents' requests and replies, routings and usage observers": "JavaScript ゲートウェイプラグインを実行します:エージェントのリクエストと応答のミドルウェア、ルーティング、使用量オブザーバー", @@ -10625,8 +10625,8 @@ const I18N = { "Requests go to the first; the next takes over when the one before runs out of quota, hits a rate limit or fails.": "リクエストは最初のものに送られます。クォータ切れ、レート制限、エラーのときは次のものが引き継ぎます。", "Each turn of a conversation goes to the next one, spreading the load evenly; the requests within a turn stay where it began, so the prompt cache holds, and one that fails is passed over while it rests.": "会話のターンごとに次のものへ送り、負荷を均等に分散します。ターン内のリクエストは開始した場所に留まるのでプロンプトキャッシュが効きます。エラーになったものは休止中スキップされます。", "Each request goes to the one used least: a subscription by the share of its allowance used, a key by the tokens it served in the last hours.": "各リクエストは使用量が最も少ないものに送られます。サブスクリプションは利用枠の使用割合、キーは直近数時間に処理したトークン数で判断します。", - "Weekly pace": "週ペース", - "Each request goes to the subscription with the most of its week left per hour until it renews — the one with the most to lose at its reset — so less of each week is lost at its reset; one at 90% or more waits until the others can't answer. A key goes by the tokens it served in the last hours.": "各リクエストは、更新までの1時間あたりの週残量が最も多いサブスクリプション(リセット時に失う分が最も多いもの)に送られ、リセット時に無駄になる週の枠を減らします。90% 以上使用したものは他が応答できないときまで待機します。キーは直近数時間に処理したトークン数で判断します。", + "Use before expiry": "期限前に使い切る", + "Each request goes to the subscription with the most left per hour until it is lost — its week at its reset, or credits in it that expire sooner — so less is lost to resets and expiry; one at 90% or more waits until the others can't answer. A key goes by the tokens it served in the last hours.": "各リクエストは、失われるまでの1時間あたりの残りが最も多いサブスクリプションに送られます — 週の枠はリセットで、それより早く期限切れになるクレジットはその期限で失われるため、リセットや期限切れで無駄になる分を減らします。90% 以上使用したものは他が応答できないときまで待機します。キーは直近数時間に処理したトークン数で判断します。", "The gateway now uses {user} first": "ゲートウェイは {user} を最初に使うようになりました", "{agent} signs in to the first. Tick more and magpie moves on to the next when the one before it is out of quota. Sessions already running keep theirs until restarted.": "{agent} は最初のアカウントにサインインします。複数チェックすると、前のアカウントのクォータが切れたときに magpie が次へ切り替えます。実行中のセッションは再起動するまで元のアカウントのままです。", "{agent} is signed in to this account": "{agent} はこのアカウントにサインインしています", @@ -14106,7 +14106,7 @@ const I18N = { "Send each request's traces and metrics to an OpenTelemetry collector, such as Langfuse": "Traces und Metriken jeder Anfrage an einen OpenTelemetry-Collector senden, etwa Langfuse", "Sending to a collector": "Sendet an einen Collector", "Routing strategies": "Routing-Strategien", - "The routings besides Smart: In order, Until used up, In turn, Least used first, Weekly pace, By weight, Free first, Speed first and Cheapest first": "Die Routings neben Intelligent: Der Reihe nach, Bis aufgebraucht, Abwechselnd, Am wenigsten genutzte zuerst, Wochentempo, Nach Gewicht, Kostenlos zuerst, Schnellste zuerst und Günstigste zuerst", + "The routings besides Smart: In order, Until used up, In turn, Least used first, Use before expiry, By weight, Free first, Speed first and Cheapest first": "Die Routings neben Intelligent: Der Reihe nach, Bis aufgebraucht, Abwechselnd, Am wenigsten genutzte zuerst, Vor Ablauf aufbrauchen, Nach Gewicht, Kostenlos zuerst, Schnellste zuerst und Günstigste zuerst", "1 provider or group routed so": "1 Anbieter oder Gruppe so geroutet", "{n} providers and groups routed so": "{n} Anbieter und Gruppen so geroutet", "Run the JavaScript gateway plugins: middleware on agents' requests and replies, routings and usage observers": "Die JavaScript-Gateway-Plugins ausführen: Middleware auf Anfragen und Antworten der Agenten, Routings und Nutzungsbeobachter", @@ -15045,8 +15045,8 @@ const I18N = { "Requests go to the first; the next takes over when the one before runs out of quota, hits a rate limit or fails.": "Anfragen gehen an das erste; das nächste übernimmt, wenn das vorherige kein Kontingent mehr hat, ein Rate-Limit erreicht oder fehlschlägt.", "Each turn of a conversation goes to the next one, spreading the load evenly; the requests within a turn stay where it began, so the prompt cache holds, and one that fails is passed over while it rests.": "Jede Runde eines Gesprächs geht an das nächste, damit sich die Last gleichmäßig verteilt; die Anfragen einer Runde bleiben dort, wo sie begann, damit der Prompt-Cache greift, und ein fehlgeschlagenes wird übersprungen, solange es pausiert.", "Each request goes to the one used least: a subscription by the share of its allowance used, a key by the tokens it served in the last hours.": "Jede Anfrage geht an das am wenigsten genutzte: ein Abo nach dem verbrauchten Anteil seines Kontingents, ein Schlüssel nach den Token, die er in den letzten Stunden geliefert hat.", - "Weekly pace": "Wochentempo", - "Each request goes to the subscription with the most of its week left per hour until it renews — the one with the most to lose at its reset — so less of each week is lost at its reset; one at 90% or more waits until the others can't answer. A key goes by the tokens it served in the last hours.": "Jede Anfrage geht an das Abo, das pro Stunde bis zur Erneuerung am meisten von seiner Woche übrig hat — also das, das beim Reset am meisten verlieren würde —, damit beim Reset weniger von jeder Woche verfällt; eines mit 90 % oder mehr wartet, bis die anderen nicht antworten können. Ein Schlüssel richtet sich nach den Token, die er in den letzten Stunden geliefert hat.", + "Use before expiry": "Vor Ablauf aufbrauchen", + "Each request goes to the subscription with the most left per hour until it is lost — its week at its reset, or credits in it that expire sooner — so less is lost to resets and expiry; one at 90% or more waits until the others can't answer. A key goes by the tokens it served in the last hours.": "Jede Anfrage geht an das Abo mit dem meisten Rest pro Stunde, bis er verfällt — seine Woche beim Reset oder Guthaben darin, das früher abläuft —, damit weniger durch Resets und Ablauf verfällt; eines mit 90 % oder mehr wartet, bis die anderen nicht antworten können. Ein Schlüssel richtet sich nach den Token, die er in den letzten Stunden geliefert hat.", "The gateway now uses {user} first": "Der Zugangspunkt verwendet jetzt zuerst {user}", "{agent} signs in to the first. Tick more and magpie moves on to the next when the one before it is out of quota. Sessions already running keep theirs until restarted.": "{agent} meldet sich beim ersten an. Haken Sie weitere an, wechselt magpie zum nächsten, sobald das vorherige kein Kontingent mehr hat. Laufende Sitzungen behalten ihres bis zum Neustart.", "{agent} is signed in to this account": "{agent} ist bei diesem Konto angemeldet", diff --git a/internal/gui/assets/plugins/routing/client.js b/internal/gui/assets/plugins/routing/client.js index b154c78e9..d9a5a3922 100644 --- a/internal/gui/assets/plugins/routing/client.js +++ b/internal/gui/assets/plugins/routing/client.js @@ -533,7 +533,7 @@ function routingPage(part) { drain: ["Until used up", "Until used up: one answers everything until its quota is used up; then the next, which keeps them even after the one before renews."], rotate: ["In turn", "In turn: each conversation's next turn goes to the account after the one that answered its last, and a new conversation starts one further along; the requests within a turn stay put, keeping the prompt cache."], usage: ["Least used", "Least used first: the account with the most of its allowance left goes first; a key by the tokens magpie sent it lately."], - pace: ["Weekly pace", "Weekly pace: the account with the most of its week left per hour until it renews goes first — the one with the most to lose at its reset; an account with five hours and no week by what its five hours have left per hour. One at 90% or more waits until the others can't answer; a key by the tokens magpie sent it lately."], + pace: ["Use before expiry", "Use before expiry: the account with the most left per hour until it is lost goes first — at its reset, or, when credits in it expire sooner, by those that expire first; an account with five hours and no week by what its five hours have left per hour. One at 90% or more waits until the others can't answer; a key by the tokens magpie sent it lately."], manual: ["Manual", "Manual: every request goes to the model picked on the group's card, over its own accounts or keys."], // a provider's keys or a subscription's accounts by weight (#841, // rubbzha on X); both strings as the provider editor's routing options @@ -789,13 +789,14 @@ function routingPage(part) { 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; - if (left !== null && f.dueBy === "reset") return t("Weekly pace: {who} has the most remaining allowance per hour until one of its Codex resets about to run out is used by itself — {n} left, used in {d}.", { who: w, n: pct(left), d: dur(at(f.due) - at(r.time)) }); + if (left !== null && f.dueBy === "expiry") return t("Use before expiry: {who} has the most credits expiring per hour until they expire — {n} of its allowance expires in {d}.", { who: w, n: pct(left), d: dur(at(f.due) - at(r.time)) }); + if (left !== null && f.dueBy === "reset") return t("Use before expiry: {who} has the most remaining allowance per hour until one of its Codex resets about to run out is used by itself — {n} left, used in {d}.", { who: w, n: pct(left), d: dur(at(f.due) - at(r.time)) }); return left !== null - ? t("Weekly pace: {who} has the most remaining allowance per hour until reset — {n} left, resets in {d}.", { who: w, n: pct(left), d: dur(at(f.due) - at(r.time)) }) - : t("Weekly pace: {who} has the most remaining allowance per hour until reset — {n} used.", { who: w, n: pct(f.used) }); + ? t("Use before expiry: {who} has the most remaining allowance per hour until reset — {n} left, resets in {d}.", { who: w, n: pct(left), d: dur(at(f.due) - at(r.time)) }) + : t("Use before expiry: {who} has the most remaining allowance per hour until reset — {n} used.", { who: w, n: pct(f.used) }); } - if (f.kind === "key" && !someKnown) return t("Weekly pace: {who} served the fewest tokens lately — {n}.", { who: w, n: tokens(f.tokens || 0) }); - return t("Weekly pace: {who} goes first.", { who: w }); + if (f.kind === "key" && !someKnown) return t("Use before expiry: {who} served the fewest tokens lately — {n}.", { who: w, n: tokens(f.tokens || 0) }); + return t("Use before expiry: {who} goes first.", { who: w }); } // keys that read their own windows (a sub2api key's limits) are // weighed by them, as accounts are, and one not read yet beside them @@ -5124,7 +5125,7 @@ function routingPage(part) { // after the requests: a request picked in the list plays on the stage, // so the list sits right under it more.append(gsec); - const ROUTE_OPTS = [["", "Smart"], ["order", "In order"], ["drain", "Until used up"], ["rotate", "In turn"], ["usage", "Least used"], ["pace", "Weekly pace"], ["free", "Free first"], ["fast", "Speed first"]]; + const ROUTE_OPTS = [["", "Smart"], ["order", "In order"], ["drain", "Until used up"], ["rotate", "In turn"], ["usage", "Least used"], ["pace", "Use before expiry"], ["free", "Free first"], ["fast", "Speed first"]]; // a group may also be routed by hand: every request to the member the // user picks on its card (provider.Manual, #317) — a provider's keys can't // and by its members' weights, as a provider's keys are (#1910) @@ -5168,7 +5169,7 @@ function routingPage(part) { drain: "Until used up: one account or key, across the members, takes every request until it is used up; then the next in the list, which keeps them even after an earlier one renews. One rate limited or failing is passed over only while it rests.", rotate: "In turn: each conversation's next turn goes to the next member's account or key, spreading the load.", usage: "Least used first: the account or key with the most of its allowance left goes first.", - pace: "Weekly pace: the account with the most of its week left per hour until it renews goes first, so less of each member's week is lost at its reset — an account with five hours and no week (Claude Enterprise) by what its five hours have left per hour until they renew, so almost always first; a key by the tokens magpie sent it lately.", + pace: "Use before expiry: the account with the most left per hour until it is lost goes first — its week at its reset, or credits in it that expire sooner — so less of each member's allowance is lost; an account with five hours and no week (Claude Enterprise) by what its five hours have left per hour until they renew, so almost always first; a key by the tokens magpie sent it lately.", weight: GROUP_WEIGHT, free: "Free first: the members whose model its vendor serves at no cost to the subscription's allowance or credits go first, then the rest — each whole, over its own accounts or keys as its provider routes them. The free ones are tried before any that spends, so nothing that costs nothing is left unused.", fast: "Speed first: the member that answered fastest lately goes first, by its time to the first token and how fast it writes, each of its accounts or keys weighed on its own; those within a tenth keep their listed order, and one not measured lately gets one request in five, so it is measured again.", diff --git a/internal/gui/assets/plugins/routing/i18n.js b/internal/gui/assets/plugins/routing/i18n.js index 2da14ab90..340d48946 100644 --- a/internal/gui/assets/plugins/routing/i18n.js +++ b/internal/gui/assets/plugins/routing/i18n.js @@ -366,7 +366,7 @@ magpie.strings({ "In order: the first model until it can't answer, then the next — each over its own accounts or keys as its provider routes them.": "按顺序:先用第一个模型,无法响应再换下一个;各成员按其供应商的路由在自己的账号或 Key 间分配。", "In turn: each conversation's next turn goes to the next member's account or key, spreading the load.": "轮流:会话的每一轮交给下一个成员的账号或 Key,均摊负载。", "Least used first: the account or key with the most of its allowance left goes first.": "最少使用优先:剩余额度最多的账号或 Key 排第一。", - "Weekly pace: the account with the most of its week left per hour until it renews goes first, so less of each member's week is lost at its reset — an account with five hours and no week (Claude Enterprise) by what its five hours have left per hour until they renew, so almost always first; a key by the tokens magpie sent it lately.": "重置前用完:按周剩余额度 ÷ 距重置小时数排序,越高越先用。只有 5 小时额度的账号(如 Claude Enterprise)按 5 小时窗口计算,几乎总排第一;Key 按最近发给它的 token 数排。", + "Use before expiry: the account with the most left per hour until it is lost goes first — its week at its reset, or credits in it that expire sooner — so less of each member's allowance is lost; an account with five hours and no week (Claude Enterprise) by what its five hours have left per hour until they renew, so almost always first; a key by the tokens magpie sent it lately.": "到期前用完:按剩余额度 ÷ 距作废小时数排序,越高越先用——周额度在重置时作废,更早过期的积分按过期时间算。只有 5 小时额度的账号(如 Claude Enterprise)按 5 小时窗口计算,几乎总排第一;Key 按最近发给它的 token 数排。", "A group among the models, and a model whose provider routes its accounts or keys other than Smart, keeps its own routing: this group only picks between it and the others, weighing it by the account or key it would try first, then tries it whole in its own order. A group among the models left on Smart is routed as this group is, unless this one goes In order, By weight or Manual.": "成员中的路由组,以及服务商路由不是“智能”的模型,都保留自己的路由:本组只在它与其他成员间选择(按它会先用的账号或 Key 比较),选中后按其自身顺序整体尝试。成员中路由留在“智能”的路由组,按本组的路由走,除非本组是“按顺序”“按权重”或“手动”。", "errors your agent saw": "Agent 收到的错误", "It said: {error}": "原话:{error}", @@ -432,7 +432,7 @@ magpie.strings({ "In order: the first answers everything until it can't; then the next.": "按顺序:第一个处理所有请求,无法响应时再换下一个。", "In turn: each conversation's next turn goes to the account after the one that answered its last, and a new conversation starts one further along; the requests within a turn stay put, keeping the prompt cache.": "轮流:会话的下一轮交给上一轮回答者的下一个账号,新会话再往后一个;一轮之内不换账号,保持提示词缓存。", "Least used first: the account with the most of its allowance left goes first; a key by the tokens magpie sent it lately.": "最少使用优先:剩余额度最多的账号排第一;Key 按 magpie 最近发给它的 token 数排。", - "Weekly pace: the account with the most of its week left per hour until it renews goes first — the one with the most to lose at its reset; an account with five hours and no week by what its five hours have left per hour. One at 90% or more waits until the others can't answer; a key by the tokens magpie sent it lately.": "重置前用完:按周剩余额度 ÷ 距重置小时数排序,越高越先用;只有 5 小时额度的账号按 5 小时窗口计算。用到 90% 以上的,等其他都无法响应时才用;Key 按最近发给它的 token 数排。", + "Use before expiry: the account with the most left per hour until it is lost goes first — at its reset, or, when credits in it expire sooner, by those that expire first; an account with five hours and no week by what its five hours have left per hour. One at 90% or more waits until the others can't answer; a key by the tokens magpie sent it lately.": "到期前用完:按剩余额度 ÷ 距作废小时数排序,越高越先用——额度在重置时作废,有积分更早过期的按最先过期的那部分算;只有 5 小时额度的账号按 5 小时窗口计算。用到 90% 以上的,等其他都无法响应时才用;Key 按最近发给它的 token 数排。", "Nothing could take {model}.": "没有谁能处理 {model}。", "{who} is the only one, so it's tried though it is resting.": "只有 {who} 一个,虽在休息仍会尝试。", "{who} is the only account on for {model} — nothing to choose between.": "{who} 是 {model} 唯一启用的账号,无需选择。", @@ -447,11 +447,12 @@ magpie.strings({ "Least used first: {who} has the most of its allowance left — {n} used.": "最少使用优先:{who} 剩余额度最多,已用 {n}。", "Least used first: {who} served the fewest tokens lately — {n}.": "最少使用优先:{who} 最近处理的 token 最少({n})。", "Least used first: {who} goes first.": "最少使用优先:{who} 排第一。", - "Weekly pace: {who} has the most remaining allowance per hour until reset — {n} left, resets in {d}.": "重置前用完:{who} 的剩余额度 ÷ 距重置小时数最高,剩余 {n},{d} 后重置。", - "Weekly pace: {who} has the most remaining allowance per hour until one of its Codex resets about to run out is used by itself — {n} left, used in {d}.": "重置前用完:{who} 的剩余额度 ÷ 距自动使用快到期 Codex 重置卡的小时数最高,剩余 {n},{d} 后自动使用。", - "Weekly pace: {who} has the most remaining allowance per hour until reset — {n} used.": "重置前用完:{who} 的剩余额度 ÷ 距重置小时数最高,已用 {n}。", - "Weekly pace: {who} served the fewest tokens lately — {n}.": "重置前用完:{who} 最近处理的 token 最少({n})。", - "Weekly pace: {who} goes first.": "重置前用完:{who} 排第一。", + "Use before expiry: {who} has the most remaining allowance per hour until reset — {n} left, resets in {d}.": "到期前用完:{who} 的剩余额度 ÷ 距重置小时数最高,剩余 {n},{d} 后重置。", + "Use before expiry: {who} has the most remaining allowance per hour until one of its Codex resets about to run out is used by itself — {n} left, used in {d}.": "到期前用完:{who} 的剩余额度 ÷ 距自动使用快到期 Codex 重置卡的小时数最高,剩余 {n},{d} 后自动使用。", + "Use before expiry: {who} has the most credits expiring per hour until they expire — {n} of its allowance expires in {d}.": "到期前用完:{who} 快过期的积分 ÷ 距过期小时数最高,额度的 {n} 将在 {d} 后过期。", + "Use before expiry: {who} has the most remaining allowance per hour until reset — {n} used.": "到期前用完:{who} 的剩余额度 ÷ 距重置小时数最高,已用 {n}。", + "Use before expiry: {who} served the fewest tokens lately — {n}.": "到期前用完:{who} 最近处理的 token 最少({n})。", + "Use before expiry: {who} goes first.": "到期前用完:{who} 排第一。", "{who} goes first: it's made for {api}, the API {model} is at home in, so nothing is translated.": "{who} 排第一:它专为 {api} 而设,正是 {model} 的原生 API,无需转换。", "{who} goes first: keys go in their order, those that suit the request first.": "{who} 排第一:Key 按顺序排,适合此请求的在前。", "{who} goes first.": "{who} 排第一。", @@ -1019,7 +1020,7 @@ magpie.strings({ "In order: the first model until it can't answer, then the next — each over its own accounts or keys as its provider routes them.": "按順序:先用第一個模型,無法回應再換下一個;各成員按其供應商的路由在自己的帳號或 Key 間分配。", "In turn: each conversation's next turn goes to the next member's account or key, spreading the load.": "輪流:會話的每一輪交給下一個成員的帳號或 Key,均攤負載。", "Least used first: the account or key with the most of its allowance left goes first.": "最少使用優先:剩餘額度最多的帳號或 Key 排第一。", - "Weekly pace: the account with the most of its week left per hour until it renews goes first, so less of each member's week is lost at its reset — an account with five hours and no week (Claude Enterprise) by what its five hours have left per hour until they renew, so almost always first; a key by the tokens magpie sent it lately.": "重置前用完:按週剩餘額度 ÷ 距重置小時數排序,越高越先用。只有 5 小時額度的帳號(如 Claude Enterprise)按 5 小時時段計算,幾乎總排第一;Key 按最近發給它的 token 數排。", + "Use before expiry: the account with the most left per hour until it is lost goes first — its week at its reset, or credits in it that expire sooner — so less of each member's allowance is lost; an account with five hours and no week (Claude Enterprise) by what its five hours have left per hour until they renew, so almost always first; a key by the tokens magpie sent it lately.": "到期前用完:按剩餘額度 ÷ 距作廢小時數排序,越高越先用——週額度在重置時作廢,更早過期的點數按過期時間算。只有 5 小時額度的帳號(如 Claude Enterprise)按 5 小時時段計算,幾乎總排第一;Key 按最近發給它的 token 數排。", "A group among the models, and a model whose provider routes its accounts or keys other than Smart, keeps its own routing: this group only picks between it and the others, weighing it by the account or key it would try first, then tries it whole in its own order. A group among the models left on Smart is routed as this group is, unless this one goes In order, By weight or Manual.": "成員中的路由組,以及服務商路由不是「智慧」的模型,都保留自己的路由:本組只在它與其他成員間選擇(按它會先用的帳號或 Key 比較),選中後按其自身順序整體嘗試。成員中路由留在「智慧」的路由組,按本組的路由走,除非本組是「按順序」「按權重」或「手動」。", "errors your agent saw": "Agent 收到的錯誤", "It said: {error}": "原話:{error}", @@ -1085,7 +1086,7 @@ magpie.strings({ "In order: the first answers everything until it can't; then the next.": "按順序:第一個處理所有請求,無法回應時再換下一個。", "In turn: each conversation's next turn goes to the account after the one that answered its last, and a new conversation starts one further along; the requests within a turn stay put, keeping the prompt cache.": "輪流:會話的下一輪交給上一輪迴答者的下一個帳號,新會話再往後一個;一輪之內不換帳號,保持提示詞快取。", "Least used first: the account with the most of its allowance left goes first; a key by the tokens magpie sent it lately.": "最少使用優先:剩餘額度最多的帳號排第一;Key 按 magpie 最近發給它的 token 數排。", - "Weekly pace: the account with the most of its week left per hour until it renews goes first — the one with the most to lose at its reset; an account with five hours and no week by what its five hours have left per hour. One at 90% or more waits until the others can't answer; a key by the tokens magpie sent it lately.": "重置前用完:按週剩餘額度 ÷ 距重置小時數排序,越高越先用;只有 5 小時額度的帳號按 5 小時時段計算。用到 90% 以上的,等其他都無法回應時才用;Key 按最近發給它的 token 數排。", + "Use before expiry: the account with the most left per hour until it is lost goes first — at its reset, or, when credits in it expire sooner, by those that expire first; an account with five hours and no week by what its five hours have left per hour. One at 90% or more waits until the others can't answer; a key by the tokens magpie sent it lately.": "到期前用完:按剩餘額度 ÷ 距作廢小時數排序,越高越先用——額度在重置時作廢,有點數更早過期的按最先過期的那部分算;只有 5 小時額度的帳號按 5 小時時段計算。用到 90% 以上的,等其他都無法回應時才用;Key 按最近發給它的 token 數排。", "Nothing could take {model}.": "沒有誰能處理 {model}。", "{who} is the only one, so it's tried though it is resting.": "只有 {who} 一個,雖在休息仍會嘗試。", "{who} is the only account on for {model} — nothing to choose between.": "{who} 是 {model} 唯一啟用的帳號,無需選擇。", @@ -1100,11 +1101,12 @@ magpie.strings({ "Least used first: {who} has the most of its allowance left — {n} used.": "最少使用優先:{who} 剩餘額度最多,已用 {n}。", "Least used first: {who} served the fewest tokens lately — {n}.": "最少使用優先:{who} 最近處理的 token 最少({n})。", "Least used first: {who} goes first.": "最少使用優先:{who} 排第一。", - "Weekly pace: {who} has the most remaining allowance per hour until reset — {n} left, resets in {d}.": "重置前用完:{who} 的剩餘額度 ÷ 距重置小時數最高,剩餘 {n},{d} 後重置。", - "Weekly pace: {who} has the most remaining allowance per hour until one of its Codex resets about to run out is used by itself — {n} left, used in {d}.": "重置前用完:{who} 的剩餘額度 ÷ 距自動使用快到期 Codex 重置卡的小時數最高,剩餘 {n},{d} 後自動使用。", - "Weekly pace: {who} has the most remaining allowance per hour until reset — {n} used.": "重置前用完:{who} 的剩餘額度 ÷ 距重置小時數最高,已用 {n}。", - "Weekly pace: {who} served the fewest tokens lately — {n}.": "重置前用完:{who} 最近處理的 token 最少({n})。", - "Weekly pace: {who} goes first.": "重置前用完:{who} 排第一。", + "Use before expiry: {who} has the most remaining allowance per hour until reset — {n} left, resets in {d}.": "到期前用完:{who} 的剩餘額度 ÷ 距重置小時數最高,剩餘 {n},{d} 後重置。", + "Use before expiry: {who} has the most remaining allowance per hour until one of its Codex resets about to run out is used by itself — {n} left, used in {d}.": "到期前用完:{who} 的剩餘額度 ÷ 距自動使用快到期 Codex 重置卡的小時數最高,剩餘 {n},{d} 後自動使用。", + "Use before expiry: {who} has the most credits expiring per hour until they expire — {n} of its allowance expires in {d}.": "到期前用完:{who} 快過期的點數 ÷ 距過期小時數最高,額度的 {n} 將在 {d} 後過期。", + "Use before expiry: {who} has the most remaining allowance per hour until reset — {n} used.": "到期前用完:{who} 的剩餘額度 ÷ 距重置小時數最高,已用 {n}。", + "Use before expiry: {who} served the fewest tokens lately — {n}.": "到期前用完:{who} 最近處理的 token 最少({n})。", + "Use before expiry: {who} goes first.": "到期前用完:{who} 排第一。", "{who} goes first: it's made for {api}, the API {model} is at home in, so nothing is translated.": "{who} 排第一:它專為 {api} 而設,正是 {model} 的原生 API,無需轉換。", "{who} goes first: keys go in their order, those that suit the request first.": "{who} 排第一:Key 按順序排,適合此請求的在前。", "{who} goes first.": "{who} 排第一。", @@ -1670,7 +1672,7 @@ magpie.strings({ "In order: the first model until it can't answer, then the next — each over its own accounts or keys as its provider routes them.": "順番:先頭のモデルが応答できなくなるまで使い、その後次へ。各モデルはそのプロバイダのルーティングに従って自身のアカウントやキーを使います。", "In turn: each conversation's next turn goes to the next member's account or key, spreading the load.": "交互:各会話の次のターンを次のメンバーのアカウントやキーに送り、負荷を分散します。", "Least used first: the account or key with the most of its allowance left goes first.": "使用量が最少を優先:利用枠の残りが最も多いアカウントやキーが先頭です。", - "Weekly pace: the account with the most of its week left per hour until it renews goes first, so less of each member's week is lost at its reset — an account with five hours and no week (Claude Enterprise) by what its five hours have left per hour until they renew, so almost always first; a key by the tokens magpie sent it lately.": "週ペース:リセットまでの 1 時間あたりの週の残りが最も多いアカウントが先頭になるため、各メンバーの週の枠がリセットで失われる分が減ります。5 時間枠のみで週の枠がないアカウント(Claude Enterprise)は、リセットまでの 1 時間あたりの 5 時間枠の残りで判断するため、ほぼ常に先頭です。キーは magpie が最近送ったトークン数で判断します。", + "Use before expiry: the account with the most left per hour until it is lost goes first — its week at its reset, or credits in it that expire sooner — so less of each member's allowance is lost; an account with five hours and no week (Claude Enterprise) by what its five hours have left per hour until they renew, so almost always first; a key by the tokens magpie sent it lately.": "期限前に使い切る:失われるまでの 1 時間あたりの残りが最も多いアカウントが先頭になり、各メンバーの枠が失われる分が減ります — 週の枠はリセットで、それより早く期限切れになるクレジットはその期限で失われます。5 時間枠のみで週の枠がないアカウント(Claude Enterprise)は、リセットまでの 1 時間あたりの 5 時間枠の残りで判断するため、ほぼ常に先頭です。キーは magpie が最近送ったトークン数で判断します。", "A group among the models, and a model whose provider routes its accounts or keys other than Smart, keeps its own routing: this group only picks between it and the others, weighing it by the account or key it would try first, then tries it whole in its own order. A group among the models left on Smart is routed as this group is, unless this one goes In order, By weight or Manual.": "モデルの中のグループと、プロバイダーのルーティングがスマート以外のモデルは、独自のルーティングを保ちます。このグループはそれと他のメンバーの間で選ぶだけで、そのグループが最初に試すアカウントやキーで比較し、選ばれたらそのグループ全体を独自の順番で試します。ルーティングをスマートのままにしたモデルの中のグループは、このグループのルーティングに従います。ただし、このグループが順番、重み付け、手動の場合を除きます。", "errors your agent saw": "エージェントが受けたエラー", "It said: {error}": "メッセージ:{error}", @@ -1736,7 +1738,7 @@ magpie.strings({ "In order: the first answers everything until it can't; then the next.": "順番:最初の 1 つが応答できなくなるまですべてに応答し、その後は次へ。", "In turn: each conversation's next turn goes to the account after the one that answered its last, and a new conversation starts one further along; the requests within a turn stay put, keeping the prompt cache.": "交互:各会話の次のターンは前回応答したアカウントの次のアカウントへ、新しい会話はさらにその次から始まります。ターン内のリクエストは同じアカウントのままで、プロンプトキャッシュを保ちます。", "Least used first: the account with the most of its allowance left goes first; a key by the tokens magpie sent it lately.": "使用量が最少:利用枠の残りが最も多いアカウントが先です。キーは magpie が最近送ったトークン数で決まります。", - "Weekly pace: the account with the most of its week left per hour until it renews goes first — the one with the most to lose at its reset; an account with five hours and no week by what its five hours have left per hour. One at 90% or more waits until the others can't answer; a key by the tokens magpie sent it lately.": "週ペース:更新までの 1 時間あたりの週の残りが最も多いアカウントが先です — リセットで失うものが最も多いアカウントです。5 時間枠だけで週の枠がないアカウントは 5 時間枠の 1 時間あたりの残りで決まります。90% 以上使ったアカウントは他が応答できなくなるまで待ち、キーは magpie が最近送ったトークン数で決まります。", + "Use before expiry: the account with the most left per hour until it is lost goes first — at its reset, or, when credits in it expire sooner, by those that expire first; an account with five hours and no week by what its five hours have left per hour. One at 90% or more waits until the others can't answer; a key by the tokens magpie sent it lately.": "期限前に使い切る:失われるまでの 1 時間あたりの残りが最も多いアカウントが先です — 残りはリセットで失われ、それより早く期限切れになるクレジットがあれば最初に期限切れになる分で決まります。5 時間枠だけで週の枠がないアカウントは 5 時間枠の 1 時間あたりの残りで決まります。90% 以上使ったアカウントは他が応答できなくなるまで待ち、キーは magpie が最近送ったトークン数で決まります。", "Nothing could take {model}.": "{model} を処理できる相手がいませんでした。", "{who} is the only one, so it's tried though it is resting.": "{who} しかいないため、休止中ですが試します。", "{who} is the only account on for {model} — nothing to choose between.": "{model} で有効なアカウントは {who} だけです — 選ぶ余地はありません。", @@ -1751,11 +1753,12 @@ magpie.strings({ "Least used first: {who} has the most of its allowance left — {n} used.": "使用量が最少:{who} は利用枠の残りが最も多いです — 使用済み {n}。", "Least used first: {who} served the fewest tokens lately — {n}.": "使用量が最少:{who} は最近処理したトークンが最も少ないです — {n}。", "Least used first: {who} goes first.": "使用量が最少:{who} が先です。", - "Weekly pace: {who} has the most remaining allowance per hour until reset — {n} left, resets in {d}.": "週ペース:{who} はリセットまでの 1 時間あたりの残り利用枠が最も多いです — 残り {n}、{d} 後にリセット。", - "Weekly pace: {who} has the most remaining allowance per hour until one of its Codex resets about to run out is used by itself — {n} left, used in {d}.": "週ペース:{who} は、期限切れ間近の Codex リセットが自動で使われるまでの 1 時間あたりの残り利用枠が最も多いです — 残り {n}、{d} 後に使用。", - "Weekly pace: {who} has the most remaining allowance per hour until reset — {n} used.": "週ペース:{who} はリセットまでの 1 時間あたりの残り利用枠が最も多いです — 使用済み {n}。", - "Weekly pace: {who} served the fewest tokens lately — {n}.": "週ペース:{who} は最近処理したトークンが最も少ないです — {n}。", - "Weekly pace: {who} goes first.": "週ペース:{who} が先です。", + "Use before expiry: {who} has the most remaining allowance per hour until reset — {n} left, resets in {d}.": "期限前に使い切る:{who} はリセットまでの 1 時間あたりの残り利用枠が最も多いです — 残り {n}、{d} 後にリセット。", + "Use before expiry: {who} has the most remaining allowance per hour until one of its Codex resets about to run out is used by itself — {n} left, used in {d}.": "期限前に使い切る:{who} は、期限切れ間近の Codex リセットが自動で使われるまでの 1 時間あたりの残り利用枠が最も多いです — 残り {n}、{d} 後に使用。", + "Use before expiry: {who} has the most credits expiring per hour until they expire — {n} of its allowance expires in {d}.": "期限前に使い切る:{who} は期限切れまでの 1 時間あたりの期限切れ間近のクレジットが最も多いです — 枠の {n} が {d} 後に期限切れ。", + "Use before expiry: {who} has the most remaining allowance per hour until reset — {n} used.": "期限前に使い切る:{who} はリセットまでの 1 時間あたりの残り利用枠が最も多いです — 使用済み {n}。", + "Use before expiry: {who} served the fewest tokens lately — {n}.": "期限前に使い切る:{who} は最近処理したトークンが最も少ないです — {n}。", + "Use before expiry: {who} goes first.": "期限前に使い切る:{who} が先です。", "{who} goes first: it's made for {api}, the API {model} is at home in, so nothing is translated.": "{who} が先です:{model} 本来の API である {api} 用なので、変換は不要です。", "{who} goes first: keys go in their order, those that suit the request first.": "{who} が先です:キーは設定順で、リクエストに合うものが先です。", "{who} goes first.": "{who} が先です。", @@ -2323,7 +2326,7 @@ magpie.strings({ "In order: the first model until it can't answer, then the next — each over its own accounts or keys as its provider routes them.": "Der Reihe nach: das erste Modell, bis es nicht mehr antworten kann, dann das nächste – jedes über seine eigenen Konten oder Schlüssel, wie sein Anbieter sie weiterleitet.", "In turn: each conversation's next turn goes to the next member's account or key, spreading the load.": "Abwechselnd: Die nächste Runde jeder Unterhaltung geht an Konto oder Schlüssel des nächsten Mitglieds und verteilt so die Last.", "Least used first: the account or key with the most of its allowance left goes first.": "Am wenigsten genutzt zuerst: Das Konto oder der Schlüssel mit dem größten Restkontingent kommt zuerst.", - "Weekly pace: the account with the most of its week left per hour until it renews goes first, so less of each member's week is lost at its reset — an account with five hours and no week (Claude Enterprise) by what its five hours have left per hour until they renew, so almost always first; a key by the tokens magpie sent it lately.": "Wochentempo: Das Konto mit dem meisten Wochenrest pro Stunde bis zur Erneuerung kommt zuerst, damit beim Zurücksetzen weniger von der Woche jedes Mitglieds verfällt – ein Konto mit fünf Stunden und ohne Woche (Claude Enterprise) nach dem Rest seiner fünf Stunden pro Stunde bis zur Erneuerung, also fast immer zuerst; ein Schlüssel nach den Token, die magpie ihm zuletzt gesendet hat.", + "Use before expiry: the account with the most left per hour until it is lost goes first — its week at its reset, or credits in it that expire sooner — so less of each member's allowance is lost; an account with five hours and no week (Claude Enterprise) by what its five hours have left per hour until they renew, so almost always first; a key by the tokens magpie sent it lately.": "Vor Ablauf aufbrauchen: Das Konto mit dem meisten Rest pro Stunde, bis er verfällt, kommt zuerst – seine Woche beim Zurücksetzen oder Guthaben darin, das früher abläuft –, damit von jedem Mitglied weniger verfällt; ein Konto mit fünf Stunden und ohne Woche (Claude Enterprise) nach dem Rest seiner fünf Stunden pro Stunde bis zur Erneuerung, also fast immer zuerst; ein Schlüssel nach den Token, die magpie ihm zuletzt gesendet hat.", "A group among the models, and a model whose provider routes its accounts or keys other than Smart, keeps its own routing: this group only picks between it and the others, weighing it by the account or key it would try first, then tries it whole in its own order. A group among the models left on Smart is routed as this group is, unless this one goes In order, By weight or Manual.": "Eine Gruppe unter den Modellen und ein Modell, dessen Anbieter seine Konten oder Schlüssel anders als „Intelligent“ weiterleitet, behalten ihre eigene Weiterleitung: Diese Gruppe wählt nur zwischen ihr und den anderen, gewichtet nach dem Konto oder Schlüssel, den sie zuerst versuchen würde, und versucht sie dann als Ganzes in ihrer eigenen Reihenfolge. Eine Gruppe unter den Modellen, deren Weiterleitung auf „Intelligent“ steht, wird wie diese Gruppe weitergeleitet, außer diese geht „Der Reihe nach“, „Nach Gewicht“ oder „Manuell“.", "errors your agent saw": "Fehler, die Ihr Agent sah", "It said: {error}": "Meldung: {error}", @@ -2389,7 +2392,7 @@ magpie.strings({ "In order: the first answers everything until it can't; then the next.": "Der Reihe nach: Der erste beantwortet alles, bis er nicht mehr kann; dann der nächste.", "In turn: each conversation's next turn goes to the account after the one that answered its last, and a new conversation starts one further along; the requests within a turn stay put, keeping the prompt cache.": "Abwechselnd: Die nächste Runde jeder Unterhaltung geht an das Konto nach dem, das die letzte beantwortet hat, und eine neue Unterhaltung beginnt eines weiter; die Anfragen innerhalb einer Runde bleiben, sodass der Prompt-Cache erhalten bleibt.", "Least used first: the account with the most of its allowance left goes first; a key by the tokens magpie sent it lately.": "Am wenigsten genutzt zuerst: Das Konto mit dem größten Restkontingent kommt zuerst; ein Schlüssel nach den Token, die magpie ihm zuletzt gesendet hat.", - "Weekly pace: the account with the most of its week left per hour until it renews goes first — the one with the most to lose at its reset; an account with five hours and no week by what its five hours have left per hour. One at 90% or more waits until the others can't answer; a key by the tokens magpie sent it lately.": "Wochentempo: Das Konto mit dem meisten Wochenrest pro Stunde bis zur Erneuerung kommt zuerst – das, bei dem beim Zurücksetzen am meisten verfällt; ein Konto mit fünf Stunden und ohne Woche nach dem Rest seiner fünf Stunden pro Stunde. Eines ab 90 % wartet, bis die anderen nicht antworten können; ein Schlüssel nach den Token, die magpie ihm zuletzt gesendet hat.", + "Use before expiry: the account with the most left per hour until it is lost goes first — at its reset, or, when credits in it expire sooner, by those that expire first; an account with five hours and no week by what its five hours have left per hour. One at 90% or more waits until the others can't answer; a key by the tokens magpie sent it lately.": "Vor Ablauf aufbrauchen: Das Konto mit dem meisten Rest pro Stunde, bis er verfällt, kommt zuerst – beim Zurücksetzen oder, wenn Guthaben darin früher abläuft, nach dem, das zuerst abläuft; ein Konto mit fünf Stunden und ohne Woche nach dem Rest seiner fünf Stunden pro Stunde. Eines ab 90 % wartet, bis die anderen nicht antworten können; ein Schlüssel nach den Token, die magpie ihm zuletzt gesendet hat.", "Nothing could take {model}.": "Nichts konnte {model} übernehmen.", "{who} is the only one, so it's tried though it is resting.": "{who} ist das einzige und wird daher versucht, obwohl es pausiert.", "{who} is the only account on for {model} — nothing to choose between.": "{who} ist das einzige aktive Konto für {model} – nichts zu wählen.", @@ -2404,11 +2407,12 @@ magpie.strings({ "Least used first: {who} has the most of its allowance left — {n} used.": "Am wenigsten genutzt zuerst: {who} hat das größte Restkontingent – {n} verbraucht.", "Least used first: {who} served the fewest tokens lately — {n}.": "Am wenigsten genutzt zuerst: {who} hat zuletzt die wenigsten Token verarbeitet – {n}.", "Least used first: {who} goes first.": "Am wenigsten genutzt zuerst: {who} kommt zuerst.", - "Weekly pace: {who} has the most remaining allowance per hour until reset — {n} left, resets in {d}.": "Wochentempo: {who} hat das meiste Restkontingent pro Stunde bis zum Zurücksetzen – {n} übrig, Zurücksetzen in {d}.", - "Weekly pace: {who} has the most remaining allowance per hour until one of its Codex resets about to run out is used by itself — {n} left, used in {d}.": "Wochentempo: {who} hat das meiste Restkontingent pro Stunde, bis einer seiner bald verfallenden Codex-Resets von selbst eingelöst wird – {n} übrig, eingelöst in {d}.", - "Weekly pace: {who} has the most remaining allowance per hour until reset — {n} used.": "Wochentempo: {who} hat das meiste Restkontingent pro Stunde bis zum Zurücksetzen – {n} verbraucht.", - "Weekly pace: {who} served the fewest tokens lately — {n}.": "Wochentempo: {who} hat zuletzt die wenigsten Token verarbeitet – {n}.", - "Weekly pace: {who} goes first.": "Wochentempo: {who} kommt zuerst.", + "Use before expiry: {who} has the most remaining allowance per hour until reset — {n} left, resets in {d}.": "Vor Ablauf aufbrauchen: {who} hat das meiste Restkontingent pro Stunde bis zum Zurücksetzen – {n} übrig, Zurücksetzen in {d}.", + "Use before expiry: {who} has the most remaining allowance per hour until one of its Codex resets about to run out is used by itself — {n} left, used in {d}.": "Vor Ablauf aufbrauchen: {who} hat das meiste Restkontingent pro Stunde, bis einer seiner bald verfallenden Codex-Resets von selbst eingelöst wird – {n} übrig, eingelöst in {d}.", + "Use before expiry: {who} has the most credits expiring per hour until they expire — {n} of its allowance expires in {d}.": "Vor Ablauf aufbrauchen: {who} hat pro Stunde bis zum Ablauf das meiste ablaufende Guthaben – {n} seines Kontingents läuft in {d} ab.", + "Use before expiry: {who} has the most remaining allowance per hour until reset — {n} used.": "Vor Ablauf aufbrauchen: {who} hat das meiste Restkontingent pro Stunde bis zum Zurücksetzen – {n} verbraucht.", + "Use before expiry: {who} served the fewest tokens lately — {n}.": "Vor Ablauf aufbrauchen: {who} hat zuletzt die wenigsten Token verarbeitet – {n}.", + "Use before expiry: {who} goes first.": "Vor Ablauf aufbrauchen: {who} kommt zuerst.", "{who} goes first: it's made for {api}, the API {model} is at home in, so nothing is translated.": "{who} kommt zuerst: Es ist für {api} gedacht, die native API von {model}, daher wird nichts übersetzt.", "{who} goes first: keys go in their order, those that suit the request first.": "{who} kommt zuerst: Schlüssel gehen in ihrer Reihenfolge, die zur Anfrage passenden zuerst.", "{who} goes first.": "{who} kommt zuerst.", diff --git a/internal/gui/tests/builtins.test.cjs b/internal/gui/tests/builtins.test.cjs index f6045a454..80a2c4c50 100644 --- a/internal/gui/tests/builtins.test.cjs +++ b/internal/gui/tests/builtins.test.cjs @@ -26,7 +26,7 @@ const PLUGINS = [ { id: "middleware", name: "JS gateway plugins", sub: "Run the JavaScript gateway plugins: middleware on agents' requests and replies, routings and usage observers", one: "1 gateway plugin on", many: "{n} gateway plugins on" }, { id: "otel", name: "Observability", sub: "Send each request's traces and metrics to an OpenTelemetry collector, such as Langfuse", one: "Sending to a collector", many: "Sending to a collector" }, { id: "redact", name: "Privacy masking", sub: "Secrets, personal data and your own words go to vendors as placeholders, and come back as they were", one: "Masking is on", many: "Masking is on" }, - { id: "rotation", name: "Routing strategies", sub: "The routings besides Smart: In order, Until used up, In turn, Least used first, Weekly pace, By weight, Free first, Speed first and Cheapest first", one: "1 provider or group routed so", many: "{n} providers and groups routed so" }, + { id: "rotation", name: "Routing strategies", sub: "The routings besides Smart: In order, Until used up, In turn, Least used first, Use before expiry, By weight, Free first, Speed first and Cheapest first", one: "1 provider or group routed so", many: "{n} providers and groups routed so" }, { id: "routing", name: "Routing", sub: "Each request as the gateway routes it, the accounts it weighed and what each answered, and your routing groups", one: "1 group in use", many: "{n} groups in use" }, { id: "search", name: "Web search", sub: "Models that can't search the web search with a provider that can, or a search API", one: "1 search source set up", many: "{n} search sources set up" }, { id: "sessions", name: "Sessions", sub: "Your agents' past conversations: read, search, resume and export them", one: "Recording gateway conversations", many: "Recording gateway conversations" }, diff --git a/internal/gui/tests/routing-group-strategy.test.cjs b/internal/gui/tests/routing-group-strategy.test.cjs index da56196b5..d633befda 100644 --- a/internal/gui/tests/routing-group-strategy.test.cjs +++ b/internal/gui/tests/routing-group-strategy.test.cjs @@ -26,7 +26,7 @@ const base = { members: ["a/sol", "b/flash", "c/luna"], ready: true, memberInfo: const words = { en: { order: "In order", manual: "Manual", weight: "By weight", smart: "Smart", head: "Routing", edit: "Edit", - names: ["Smart", "In order", "Until used up", "In turn", "Least used", "Weekly pace", "Free first", "Speed first", "Cheapest first", "By weight", "Manual"], + names: ["Smart", "In order", "Until used up", "In turn", "Least used", "Use before expiry", "Free first", "Speed first", "Cheapest first", "By weight", "Manual"], tip: "How Auto routes: click to change it", saved: "Auto: Manual" }, zh: { order: "按顺序", manual: "手动", weight: "按权重", smart: "智能", head: "路由", edit: "编辑", tip: "Auto 的路由方式:点击更改", saved: "Auto:手动" }, diff --git a/internal/gui/tests/routing-pace-expiry.test.cjs b/internal/gui/tests/routing-pace-expiry.test.cjs new file mode 100644 index 000000000..f12b8b595 --- /dev/null +++ b/internal/gui/tests/routing-pace-expiry.test.cjs @@ -0,0 +1,96 @@ +// Run with Node's test runner and Playwright on the module path; see README.md. +// Use before expiry (pace): a WorkBuddy account whose check-in credits +// expire before its month renews goes first, and the Routing page's story +// says the credits' expiry set its deadline, not its reset (lcyksp on +// Discord). An account whose month decides is told as before. In every +// language, wide and narrow. +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 = (minutes) => new Date(now.getTime() - minutes * 60e3).toISOString(); +const ahead = (hours) => new Date(now.getTime() + hours * 36e5).toISOString(); +const base = { provider: "workbuddy", name: "WorkBuddy", kind: "account", agent: "workbuddy", model: "deepseek-v4.1-flash", known: true }; +// A: its month untouched, renewing in 28 days, 70.85 of its 500 credits +// expiring in 14 hours: 14% lost then, 1% an hour +const a = (fields) => ({ ...base, id: "workbuddy#a", who: "a@example.com", routing: "pace", used: 0, renews: [ahead(672)], ...fields }); +const b = () => ({ ...base, id: "workbuddy#b", who: "b@example.com", routing: "pace", used: 50, renews: [ahead(240)], pace: 50 / 240, due: ahead(240) }); +const route = (id, order) => ({ + id, seq: id, time: ago(1), agent: "workbuddy", model: "deepseek-v4.1-flash", provider: "workbuddy", done: true, status: 200, ms: 900, tokens: 1200, + order, tries: [{ id: order[0].id, model: "deepseek-v4.1-flash", start: ago(1), done: true, status: 200, ms: 900 }], +}); +const routes = [ + route(2, [a({ pace: 70.85 / 500 * 100 / 14, due: ahead(14), dueBy: "expiry", lapse: ahead(14) }), b()]), + route(1, [b(), a({ pace: 100 / 672, due: ahead(672) })]), +]; + +function serve(lang) { + 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: "workbuddy", name: "WorkBuddy", 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: 4, totals: { requests: routes.length }, routes }); + } + 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 }); + }; +} + +// expiry: the credits that expire, 14% of A's month, in 14 hours; week: +// the reason an account whose reset decides is told by +const words = { + en: { expiry: /most credits expiring per hour until they expire — 14\s?% of its allowance expires in/, week: /per hour until reset/ }, + zh: { expiry: /快过期的积分 ÷ 距过期小时数最高,额度的 14\s?% 将在/, week: /÷ 距重置小时数最高/ }, + "zh-TW": { expiry: /快過期的點數 ÷ 距過期小時數最高,額度的 14\s?% 將在/, week: /÷ 距重置小時數最高/ }, + ja: { expiry: /期限切れ間近のクレジットが最も多いです — 枠の 14\s?% が/, week: /リセットまでの 1 時間あたりの残り利用枠/ }, + de: { expiry: /das meiste ablaufende Guthaben – 14\s?% seines Kontingents läuft in/, week: /Restkontingent pro Stunde bis zum Zurücksetzen/ }, +}; + +for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) { + for (const lang of Object.keys(words)) { + for (const width of [1100, 420]) { + test(`${engine} ${lang} ${width}px: credits expiring before the month renews are told as the deadline`, async (t) => { + const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" })); + t.after(() => browser.close()); + const page = await browser.newPage({ viewport: { width, height: 1200 }, reducedMotion: "reduce" }); + page.setDefaultTimeout(5000); + page.setDefaultNavigationTimeout(60000); + const errors = []; + page.on("pageerror", (error) => errors.push(error.message)); + await page.route("**/*", serve(lang)); + await page.goto("http://magpie.test/?view=routing"); + await page.locator(".rt-req").nth(routes.length - 1).waitFor(); + const w = words[lang]; + const why = () => page.locator(".rt-steps li.why").first().textContent(); + const open = async (n, who, want) => { + await page.locator(".rt-req").nth(n).click(); + await page.waitForFunction(([who, src]) => { + const li = document.querySelector(".rt-steps li.why"); + return li && li.textContent.includes(who) && new RegExp(src).test(li.textContent); + }, [who, want.source]); + }; + await open(0, "a@example.com", w.expiry); + assert.doesNotMatch(await why(), w.week); + // the month decides: as before + await open(1, "b@example.com", w.week); + assert.doesNotMatch(await why(), w.expiry); + const wide = await page.evaluate(() => document.documentElement.scrollWidth - window.innerWidth); + assert.ok(wide <= 0, `the page scrolls sideways by ${wide}px`); + assert.deepEqual(errors, []); + }); + } + } +} diff --git a/internal/gui/tests/routing-reset-deadline.test.cjs b/internal/gui/tests/routing-reset-deadline.test.cjs index 5a20c74f4..1e5784697 100644 --- a/internal/gui/tests/routing-reset-deadline.test.cjs +++ b/internal/gui/tests/routing-reset-deadline.test.cjs @@ -1,6 +1,6 @@ // Run with Node's test runner and Playwright on the module path; see README.md. // #717, #718: a Codex account that spends a reset about to run out by -// itself goes first, in Weekly pace and Smart, when that reset is spent +// itself goes first, in Use before expiry and Smart, when that reset is spent // before its week renews — and the Routing page's story says the reset // set its deadline, not its week. An account whose week decides is told // as before. In English and Chinese. diff --git a/internal/gui/tests/routing-save.test.cjs b/internal/gui/tests/routing-save.test.cjs index e88fbc6f5..8f8a8d058 100644 --- a/internal/gui/tests/routing-save.test.cjs +++ b/internal/gui/tests/routing-save.test.cjs @@ -56,7 +56,7 @@ function serve(lang, posts, off = []) { const ROUTINGS = [ ["", "Smart", "智能"], ["order", "In order", "按顺序"], ["drain", "Until used up", "用完再换"], ["rotate", "In turn", "轮流"], - ["usage", "Least used first", "用量少的优先"], ["pace", "Weekly pace", "重置前用完"], + ["usage", "Least used first", "用量少的优先"], ["pace", "Use before expiry", "到期前用完"], ]; const STAYS = [["", "Auto", "自动"], ["session", "Session", "整个会话"], ["turn", "Within a turn", "一轮之内"], ["off", "Off", "关闭"]]; diff --git a/internal/gui/tests/routing-wallet-balance.test.cjs b/internal/gui/tests/routing-wallet-balance.test.cjs index 7048007a9..395730c32 100644 --- a/internal/gui/tests/routing-wallet-balance.test.cjs +++ b/internal/gui/tests/routing-wallet-balance.test.cjs @@ -4,7 +4,7 @@ // 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. +// naming both figures, under Smart, Least used and Use before expiry 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"); diff --git a/internal/provider/codex_reset_deadline_test.go b/internal/provider/codex_reset_deadline_test.go index cdbbe4a05..088f68dd1 100644 --- a/internal/provider/codex_reset_deadline_test.go +++ b/internal/provider/codex_reset_deadline_test.go @@ -8,7 +8,7 @@ import ( // An account that spends a Codex reset about to run out by itself has its // windows started again then, resetLead before the reset runs out: -// Weekly pace goes by the hours until that, when it is sooner than the week +// Use before expiry goes by the hours until that, when it is sooner than the week // renews, and Smart's renewals do too (#717, #718). A reset that runs out // after the week renews, or has run out, changes nothing. func TestPaceUntilAutoUsedReset(t *testing.T) { diff --git a/internal/provider/pace_expiry_test.go b/internal/provider/pace_expiry_test.go new file mode 100644 index 000000000..8f1dec998 --- /dev/null +++ b/internal/provider/pace_expiry_test.go @@ -0,0 +1,55 @@ +package provider + +import ( + "math" + "testing" + "time" +) + +// Pace takes credits expiring before a budget window renews for its +// deadline when they make the more per hour (lcyksp on Discord): the share +// that expires (RunsOutLeft of Of, at most all), else all that is left, +// per hour until they expire, never fewer than one. +func TestPaceCreditsExpiring(t *testing.T) { + now := time.Now() + month := now.Add(28 * 24 * time.Hour) + l := Limit{Used: 20, Of: 500, Resets: month} + near := func(got, want float64) bool { return math.Abs(got-want) < 1e-9 } + + if got, due := (Allowance{l}).Pace("m", now); !near(got, 80/(28*24.0)) || !due.Equal(month) { + t.Fatalf("nothing expiring: %v by %v", got, due) + } + l.RunsOut, l.RunsOutLeft = now.Add(10*time.Hour), 50 // 10% in 10h + if got, due := (Allowance{l}).Pace("m", now); !near(got, 1) || !due.Equal(l.RunsOut) { + t.Fatalf("expiring: %v by %v", got, due) + } + l.RunsOutLeft = 0 // not told: the 80% left + if got, _ := (Allowance{l}).Pace("m", now); !near(got, 8) { + t.Fatalf("amount not told: %v", got) + } + l.RunsOutLeft = 5000 // more than the window: all of it + if got, _ := (Allowance{l}).Pace("m", now); !near(got, 10) { + t.Fatalf("capped: %v", got) + } + l.RunsOut, l.RunsOutLeft = now.Add(10*time.Minute), 50 // an hour at least + if got, _ := (Allowance{l}).Pace("m", now); !near(got, 10) { + t.Fatalf("within the hour: %v", got) + } + l.RunsOut, l.RunsOutLeft = now.Add(14*time.Hour), 0.5 // too little to matter + if got, due := (Allowance{l}).Pace("m", now); !near(got, 80/(28*24.0)) || !due.Equal(month) { + t.Fatalf("a little expiring: %v by %v", got, due) + } + l.RunsOut = month.Add(time.Hour) // after the renewal + if got, due := (Allowance{l}).Pace("m", now); !near(got, 80/(28*24.0)) || !due.Equal(month) { + t.Fatalf("after the renewal: %v by %v", got, due) + } +} + +// allowanceOf carries how much expires with when (QuotaWindow.RunsOut). +func TestAllowanceCarriesRunsOutLeft(t *testing.T) { + at := time.Now().Add(14 * time.Hour) + a := allowanceOf([]QuotaWindow{{Name: "Credits", Used: 0, Limit: 500, RunsOutAt: &at, RunsOut: 70.85}}, time.Now()) + if len(a) != 1 || !a[0].RunsOut.Equal(at) || a[0].RunsOutLeft != 70.85 { + t.Fatalf("allowance %+v", a) + } +} diff --git a/internal/provider/routing.go b/internal/provider/routing.go index 03307b028..795909ff2 100644 --- a/internal/provider/routing.go +++ b/internal/provider/routing.go @@ -258,6 +258,9 @@ type Limit struct { // RunsOut is when the soonest of what the window has left is lost, // apart from its reset (QuotaWindow.RunsOutAt): zero when not known. RunsOut time.Time + // RunsOutLeft is how much, in Unit, is lost at RunsOut + // (QuotaWindow.RunsOut): zero when not told + RunsOutLeft float64 // Credits: the account goes on past this window on its credits // (QuotaWindow.Credits) Credits bool @@ -295,7 +298,7 @@ func (a Allowance) WeekUsedUp(now time.Time) bool { // as the Codex reset about to run out is spent (expiringResetSpent): // resetLead before it runs out, or now when the account is held up // past then. What they have left then is lost, as at their own reset, so -// Weekly pace and Smart take it for their renewal when it comes sooner +// Use before expiry and Smart take it for their renewal when it comes sooner // (#717, #718). Zero when none will be. func (a Allowance) Restarts(now time.Time) time.Time { for _, l := range a { @@ -563,7 +566,14 @@ const FreshPace = 100 / (7 * 24.0) // go by what they have used, among the rest as the fresh are. An // account whose windows an auto-used reset starts again sooner than they // renew (Restarts) goes by that instead, and due is then that time: what -// it has left is lost there. +// it has left is lost there. Credits in a budget window that expire +// before it renews (Limit.RunsOut) are lost sooner still: the window goes +// by those that expire first, per hour until they do, when that is the +// more — what expires as a share of the window (RunsOutLeft of Of), or +// all it has left when the amount isn't told, as Renewal takes it. A +// WorkBuddy account whose check-in credits expire tomorrow goes ahead of +// one whose month has more left but nothing expiring (lcyksp on +// Discord); due is then the expiry. func (a Allowance) Pace(model string, now time.Time) (pace float64, due time.Time) { model = strings.ToLower(model) restart := a.Restarts(now) @@ -606,7 +616,11 @@ func (a Allowance) Pace(model string, now time.Time) (pace float64, due time.Tim until, renews = l.Resets.Sub(now), l.Resets } until, renews = cut(until, renews) - if p := (100 - u) / max(until, time.Hour).Hours(); !any || p < pace { + p := (100 - u) / max(until, time.Hour).Hours() + if q, at, ok := l.expiring(u, now, now.Add(until)); ok && q > p { + p, renews = q, at + } + if !any || p < pace { pace, due, any = p, renews, true } } @@ -619,6 +633,21 @@ func (a Allowance) Pace(model string, now time.Time) (pace float64, due time.Tim return pace, due } +// expiring is the pace of what a window loses at RunsOut, when that +// comes after now and before ends, the window's renewal: the share that +// expires (RunsOutLeft of Of, at most all), else all it has left (100-u), +// per hour until then, never fewer than one. +func (l Limit) expiring(u float64, now, ends time.Time) (pace float64, at time.Time, ok bool) { + if !l.RunsOut.After(now) || !l.RunsOut.Before(ends) { + return 0, time.Time{}, false + } + share := 100 - u + if l.RunsOutLeft > 0 && l.Of > 0 { + share = min(100, 100*l.RunsOutLeft/l.Of) + } + return share / max(l.RunsOut.Sub(now), time.Hour).Hours(), l.RunsOut, true +} + // Allowances is each of an agent's accounts' allowance by user, as last // known, asked for again in the background when that was over a minute // ago. Only the very first ask waits, and not for long. An account @@ -996,7 +1025,7 @@ func allowanceOf(ws []QuotaWindow, now time.Time) Allowance { l.Resets = now.Add(time.Duration(w.ResetSecs) * time.Second) } if w.RunsOutAt != nil { - l.RunsOut = *w.RunsOutAt + l.RunsOut, l.RunsOutLeft = *w.RunsOutAt, w.RunsOut } if w.Balance != nil { // a wallet is known by its balance, with no share invented: diff --git a/internal/routes/routes_test.go b/internal/routes/routes_test.go index 40ecb2599..f783cf36c 100644 --- a/internal/routes/routes_test.go +++ b/internal/routes/routes_test.go @@ -165,7 +165,7 @@ func TestLeastUsedSeatsWithNoShare(t *testing.T) { } } -// Weekly pace: the most of a week left per hour first; one running low +// Use before expiry: the most of a week left per hour first; one running low // after, whatever its pace. func TestPace(t *testing.T) { s := []Seat{{Key: "slow", Pace: 1}, {Key: "low", Used: 95, Pace: 50}, {Key: "fast", Pace: 10}} @@ -195,7 +195,7 @@ func TestWeighted(t *testing.T) { // Of those all but used up, one that goes on on its credits (a Codex // account holding them) goes before those with nothing left, though it -// has used more, in Smart, Weekly pace and Least used alike; still after +// has used more, in Smart, Use before expiry and Least used alike; still after // every one with room or running low, its allowance spent before its // credits are. func TestCreditsFirstOfTheSpent(t *testing.T) { diff --git a/plugins/rotation/rotation.go b/plugins/rotation/rotation.go index 77800462e..7a1e345c6 100644 --- a/plugins/rotation/rotation.go +++ b/plugins/rotation/rotation.go @@ -1,6 +1,6 @@ // Package rotation is the routings a provider or group can be set to // besides Smart: In order, Until used up, In turn, Least used first, -// Weekly pace, By weight, Free first, Speed first and Cheapest first (a +// Use before expiry, By weight, Free first, Speed first and Cheapest first (a // group's). While a provider or group is routed by one, it // stays on. // @@ -19,7 +19,7 @@ import ( func init() { pluginrt.Register(pluginrt.Manifest{ ID: "rotation", API: "^1", Requires: []string{"providers", "gateway"}, Essential: true, - Name: "Routing strategies", Sub: "The routings besides Smart: In order, Until used up, In turn, Least used first, Weekly pace, By weight, Free first, Speed first and Cheapest first", + Name: "Routing strategies", Sub: "The routings besides Smart: In order, Until used up, In turn, Least used first, Use before expiry, By weight, Free first, Speed first and Cheapest first", One: "1 provider or group routed so", Many: "{n} providers and groups routed so", InUse: inUse, Parts: []pluginrt.Part{{Slot: "part", Key: "rotation"}}, diff --git a/site/public/docs/ja/start.html b/site/public/docs/ja/start.html index 2f3a06973..19802e718 100644 --- a/site/public/docs/ja/start.html +++ b/site/public/docs/ja/start.html @@ -171,7 +171,7 @@

1 つのプロバイダに複数のアカウントやキー

-

プロバイダの行を開き、使うアカウントやキーをすべてチェックします。Routing はリクエストをそれらにどう振り分けるかを決めます:Smart(デフォルト)、In order、Until used up(使い切ったら次へ移り、前のものが回復しても戻りません)、In turn、Least used first、Weekly pace、By weight(各アカウントやキーが横で設定した重みで取り分を受けます。たとえば Max アカウントは 5、Pro は 1)、Speed first(最近いちばん速く応答したキーが先)。Fallback には、プロバイダのクォータ切れ、レート制限、ダウン時に代わりに使うモデルを並べます。

+

プロバイダの行を開き、使うアカウントやキーをすべてチェックします。Routing はリクエストをそれらにどう振り分けるかを決めます:Smart(デフォルト)、In order、Until used up(使い切ったら次へ移り、前のものが回復しても戻りません)、In turn、Least used first、Use before expiry、By weight(各アカウントやキーが横で設定した重みで取り分を受けます。たとえば Max アカウントは 5、Pro は 1)、Speed first(最近いちばん速く応答したキーが先)。Fallback には、プロバイダのクォータ切れ、レート制限、ダウン時に代わりに使うモデルを並べます。

1 つのモデルを複数のプロバイダで

グループとは、1 つまたは複数のプロバイダのモデルを、エージェントが 1 つとして選べるようにまとめたものです。ピッカーの Routing groups の下に group/<id> として表示されます。2 つのプロバイダが同じ名前で提供しているモデルは、それだけでグループになります。Routing タブの New group では、好きなモデルを組み合わせてグループを作れます。グループで何ができるかは、最初のモデルが基準になります。

@@ -184,7 +184,7 @@ 使い切ってから次へ drain1 つのアカウントやキーを使い切るまで使い、その後は次へ移ってそのまま使い続けます。その間に前のものが回復しても戻りません。レート制限やエラーのものは休止中だけ飛ばします。 持ち回り rotate各会話の次のターンを、次のメンバーのアカウントやキーに送り、負荷を分散します。 使用量の少ない順 usage利用枠の残りが最も多いアカウントやキー。 - 週のペース pace更新までの 1 時間あたりの週の枠の残りが最も多いアカウント、つまりリセット時に失う分が最も多いもの。これにより各メンバーの週の枠がリセットで無駄になりにくくなります。週の枠がなく 5 時間枠だけのアカウント(Claude Enterprise)は、更新までの 1 時間あたりの 5 時間枠の残りで判断されるので、ほぼ常に最初になります。使用率が 90% 以上のものは、他が応答できなくなるまで待ちます。キーは最近送ったトークン数で判断します。 + 期限前に使い切る pace更新までの 1 時間あたりの週の枠の残りが最も多いアカウント、つまりリセット時に失う分が最も多いもの。これにより各メンバーの週の枠がリセットで無駄になりにくくなります。週の枠がなく 5 時間枠だけのアカウント(Claude Enterprise)は、更新までの 1 時間あたりの 5 時間枠の残りで判断されるので、ほぼ常に最初になります。リセットより早く期限切れになるクレジットがあるアカウントは、最初に期限切れになる分を期限までの 1 時間あたりで数え、そのほうが多ければそれで判断します(WorkBuddy のチェックインで得たクレジットなど)。使用率が 90% 以上のものは、他が応答できなくなるまで待ちます。キーは最近送ったトークン数で判断します。 重み順 weightグループ編集画面で各モデルの横に設定した重み(1〜1000、未設定は 1)に応じてリクエストを分けます。重み 3 のモデルは重み 1 のモデルが 1 件受けるごとに 3 件受け、まとめてではなく均等に散らします。各モデルは自分のプロバイダーのルーティングで自分のアカウントやキーを使い、グループ内のグループは 1 つとして数えます。失敗して休んでいるものはその回から外れ、失敗したときは次のモデルが代わりに答えます。 速度優先 fastこのモデルに最近いちばん速く応答したメンバー、アカウント、キーが先です。最初のトークンまでの時間と出力の速さで比べ、新しい応答ほど重く数えます。差が 1 割以内のものは並び順のままです。1 時間測っていないものには 5 件に 1 件を回すので、一度遅かったチャネルもまた試されます。失敗して休んでいるものは最後です。測るのはストリーミングの応答だけで、再起動すると測り直します。 最安優先 cheapルーティンググループのみ。いまモデルが最も安いメンバーが先です。Usage が数えるのと同じく、この時間帯の入力・出力 100 万トークンあたりの価格で比べます:自分で設定した価格、なければ定価に、プロバイダの価格倍率と時間帯倍率をかけたもの。DeepSeek 公式 API、Command Code と OpenCode Go の DeepSeek モデルはピーク時間帯(平日 UTC 01:00–04:00 と 06:00–10:00)に、Ollama Cloud の DeepSeek V4.1 Flash と V4 Pro は自社のピーク時間帯(平日 UTC 12:00–18:00、それ以外は半額)に 2 倍になるので、2 つのプロバイダにある同じ DeepSeek モデルはその時間に安い方へ送られます。同じ価格のものは順番どおり、価格が分からないものは最後です。 @@ -192,7 +192,7 @@
- + @@ -214,8 +214,8 @@

グループのモデルには別のグループも含められます。Add a model の Routing groups の下から選ぶか、ターミナルで models+=group/<id> を使います。中に入ったグループは順序の中でその位置を占め、自分のモデルの間では自分のルーティングとルールに従って振り分けます。たとえば Coder を deepseek-v4-pro、次に Fast とし、Fast は安いモデルを独自の順序で並べる、といった構成ができます。Coder のルールでターンを group/fast に送れば、どのモデルを先にするかは Fast 自身のルールが決めます。

  • ループは不可。 グループは、直接でも中のグループ経由でも、自分自身を含められません。Coder が Fast を含んでいるときに、Coder を含む Fast を保存しようとすると拒否され、ピッカーにもそのようなグループは表示されません。入れ子は最大 8 階層です。他のグループに含まれているグループは削除できないので、先にそちらから外してください。
  • -
  • 各グループは自分のルーティングに従います。 外側のグループのルーティングが何であれ、内側のグループの中には及びません。スマート、持ち回り、使用量の少ない順、週のペースは、内側のグループを 1 つのメンバーとして、内側のグループが最初に試すアカウントやキーで評価します。そこが選ばれると、内側のグループが丸ごと、自分の順序で試されます。Claude(順番どおり)と GPT(順番どおり)を含むスマートの Coder は、両者のアカウントをすべてまとめて比べるのではなく、Claude の先頭と GPT の先頭を比べます。
  • -
  • 独自のルーティングを持つプロバイダーも同じです。 プロバイダーのアカウントやキーのルーティングを順番どおり、持ち回り、使用量の少ない順、週のペース、重みにしたモデルは、どのグループの中でもそれを保ちます。グループはそれが最初に試すアカウントやキーで比べ、選ばれたら自分の順序で丸ごと試します。既定のスマートのままのプロバイダーは、アカウントがグループの他のものとまとめて比べられ、どのプロバイダーのものでも枠が最も早くリセットされるものが先になります。
  • +
  • 各グループは自分のルーティングに従います。 外側のグループのルーティングが何であれ、内側のグループの中には及びません。スマート、持ち回り、使用量の少ない順、期限前に使い切るは、内側のグループを 1 つのメンバーとして、内側のグループが最初に試すアカウントやキーで評価します。そこが選ばれると、内側のグループが丸ごと、自分の順序で試されます。Claude(順番どおり)と GPT(順番どおり)を含むスマートの Coder は、両者のアカウントをすべてまとめて比べるのではなく、Claude の先頭と GPT の先頭を比べます。
  • +
  • 独自のルーティングを持つプロバイダーも同じです。 プロバイダーのアカウントやキーのルーティングを順番どおり、持ち回り、使用量の少ない順、期限前に使い切る、重みにしたモデルは、どのグループの中でもそれを保ちます。グループはそれが最初に試すアカウントやキーで比べ、選ばれたら自分の順序で丸ごと試します。既定のスマートのままのプロバイダーは、アカウントがグループの他のものとまとめて比べられ、どのプロバイダーのものでも枠が最も早くリセットされるものが先になります。
  • フェイルオーバーは通ります。 内側のグループのモデルがすべて失敗すると、他のメンバーと同様に、外側のグループの次のメンバーが応答します。
  • 2 回現れるモデル(単独と、中のグループ内)は、最初の位置で一度だけ問い合わせます。
diff --git a/site/public/docs/start.html b/site/public/docs/start.html index e49f6c330..99e5eea5a 100644 --- a/site/public/docs/start.html +++ b/site/public/docs/start.html @@ -171,7 +171,7 @@

Several accounts or keys in one provider

-

Open the provider’s row and tick every account or key to use. Routing says how requests spread over them: Smart (the default), In order, Until used up, staying on the next once one is used up even after the first renews, In turn, Least used first, Weekly pace, By weight, each account or key taking its share by the weight set beside it (a Max account 5, a Pro one 1), or Speed first, the key that answered fastest lately first. Fallback lists models to use instead when the provider is out of quota, rate limited or down.

+

Open the provider’s row and tick every account or key to use. Routing says how requests spread over them: Smart (the default), In order, Until used up, staying on the next once one is used up even after the first renews, In turn, Least used first, Use before expiry, By weight, each account or key taking its share by the weight set beside it (a Max account 5, a Pro one 1), or Speed first, the key that answered fastest lately first. Fallback lists models to use instead when the provider is out of quota, rate limited or down.

One model over several providers

A group is several models, from one provider or many, that an agent picks as one: group/<id>, under Routing groups in the picker. A model two of your providers serve under the same name becomes a group on its own; New group in the Routing tab makes one of any models you like. The first model answers for what the group can do.

@@ -184,7 +184,7 @@ - + @@ -192,7 +192,7 @@
維持会話が、応答したアカウントやキーに留まる期間
自動 autoデフォルトです。ターン内では常に、ターンをまたいでは、ベンダーがキャッシュした内容が保持する価値のある間。
セッション session応答できる限り、セッション全体。ルーティングがスマート、使用量の少ない順、週のペースのとき、新しいセッションは他のセッションが最も少ないアカウントやキーに割り当てられ、同時に開いたセッションはそれぞれ別のものを使います。
セッション session応答できる限り、セッション全体。ルーティングがスマート、使用量の少ない順、「期限前に使い切る」のとき、新しいセッションは他のセッションが最も少ないアカウントやキーに割り当てられ、同時に開いたセッションはそれぞれ別のものを使います。
ターン内 turnエージェントがツールの結果を返している間。あなたが再び発言すると、ルーティングが改めて決めます。
オフ offリクエストごとに改めてルーティングします。
厳格 strict使用量上限を超えても、他のアカウントやキーへは移りません。レート制限や割り当て切れのときは、エラーがそのままエージェントに渡ります。新しい会話は「セッション」と同じく分散されます。
Until used up drainOne account or key until it is used up, then the next, which keeps the requests: one before it that renews meanwhile doesn’t take them back. One rate limited or failing is passed over only while it rests.
In turn rotateEach conversation’s next turn goes to the next member’s account or key, spreading the load.
Least used usageThe account or key with the most of its allowance left.
Weekly pace paceThe account with the most of its week left per hour until it renews — the one with the most to lose at its reset — so less of each member’s week is lost at its reset; an account with five hours and no week (Claude Enterprise) by what its five hours have left per hour until they renew, so almost always first. One at 90% or more waits until the others can’t answer. A key by the tokens sent it lately.
Use before expiry paceThe account with the most of its week left per hour until it renews — the one with the most to lose at its reset — so less of each member’s week is lost at its reset; an account with five hours and no week (Claude Enterprise) by what its five hours have left per hour until they renew, so almost always first. Credits in an account that expire before it resets count too: those that expire first, per hour until they do, when that is the more (WorkBuddy’s check-in credits). One at 90% or more waits until the others can’t answer. A key by the tokens sent it lately.
By weight weightEach model takes its share of the requests by the weight set beside it in the group editor (1 to 1000, 1 if unset): one weighing 3 takes three for every one a model weighing 1 takes, spread out rather than in bursts. Each model is tried whole over its own accounts or keys, as its provider routes them, and a group in the group counts as one. One resting after a failure leaves the round; the next model is the fallback when one fails.
Speed first fastThe member, account or key that answered this model fastest lately: the time to its first token and how fast it writes, newer answers counting more. Those within a tenth of each other keep their order. One not measured in the last hour gets one request in five, so a channel that was slow once is tried again; one resting after a failure goes last. Only streamed replies are measured, and a restart measures again from scratch.
Cheapest first cheapGroups only. The member whose model costs least now, by its price a million tokens in and out at this hour as Usage counts it: your own price for it, else its list price, at the provider’s price rate and rate windows. DeepSeek’s own API, Command Code’s and OpenCode Go’s DeepSeek models cost double in their peak hours (weekdays 01:00–04:00 and 06:00–10:00 UTC), and Ollama Cloud’s DeepSeek V4.1 Flash and V4 Pro in its own (weekdays 12:00–18:00 UTC, half price the rest of the time), so a DeepSeek model listed on two providers goes to the one cheaper at that hour. Members that cost the same keep their order; one with no known price goes last.
- + @@ -214,8 +214,8 @@

A group’s models can include another group: pick it under Routing groups in Add a model, or models+=group/<id> from a terminal. The group in it takes its place in the order and routes among its own models by its own routing and rules. So Coder can be deepseek-v4-pro then Fast, and Fast its own order of cheap models. A Coder rule can send a turn to group/fast, and Fast’s own rules then pick which of its models goes first.

  • No loops. A group can’t be in itself, directly or through the groups in it. Saving Fast with Coder in it, while Coder has Fast, is refused, and the picker doesn’t offer such a group. Groups go at most 8 deep. A group can’t be removed while another has it: take it out there first.
  • -
  • Each group routes by its own routing. Whatever the outer group’s routing, it never reaches inside a group in it: Smart, In turn, Least used or Weekly pace weighs the inner group as one member, by the account or key the inner group would try first, and where it lands the inner group is tried whole, in its own order. Coder on Smart with Claude (In order) and GPT (In order) in it compares Claude’s first with GPT’s first, not all of their accounts together.
  • -
  • So does a provider routed its own way. A model whose provider routes its accounts or keys In order, In turn, by Least used, Weekly pace or Weight keeps that inside any group, weighed as one by the account or key it would try first and tried whole in its own order. One left on Smart, the default, has its accounts weighed with the group’s others as one pool, so the one whose allowance renews soonest goes first whichever provider it is of.
  • +
  • Each group routes by its own routing. Whatever the outer group’s routing, it never reaches inside a group in it: Smart, In turn, Least used or Use before expiry weighs the inner group as one member, by the account or key the inner group would try first, and where it lands the inner group is tried whole, in its own order. Coder on Smart with Claude (In order) and GPT (In order) in it compares Claude’s first with GPT’s first, not all of their accounts together.
  • +
  • So does a provider routed its own way. A model whose provider routes its accounts or keys In order, In turn, by Least used, Use before expiry or Weight keeps that inside any group, weighed as one by the account or key it would try first and tried whole in its own order. One left on Smart, the default, has its accounts weighed with the group’s others as one pool, so the one whose allowance renews soonest goes first whichever provider it is of.
  • Failover goes through. If every model in the inner group fails, the outer group’s next member answers, as with any member.
  • A model that appears twice (on its own and in a group in it) is asked once, at its first place.
diff --git a/site/public/docs/zh/start.html b/site/public/docs/zh/start.html index b37d72248..8c466b111 100644 --- a/site/public/docs/zh/start.html +++ b/site/public/docs/zh/start.html @@ -171,7 +171,7 @@

一个供应商里的多个账号或密钥

-

展开供应商那一行,勾选要用的每个账号或密钥。路由 决定请求怎么分给它们:智能(默认)、按顺序、用完再换(一个用完再换下一个,前面的恢复了也不切回去)、轮流、用量少的优先、重置前用完、按权重(每个账号或密钥按旁边设的权重分得请求,比如 Max 账号设 5、Pro 账号设 1)或 速度优先(最近回答最快的密钥先用)。备用 里列出这个供应商额度用完、被限流或不可用时改用的模型。

+

展开供应商那一行,勾选要用的每个账号或密钥。路由 决定请求怎么分给它们:智能(默认)、按顺序、用完再换(一个用完再换下一个,前面的恢复了也不切回去)、轮流、用量少的优先、到期前用完、按权重(每个账号或密钥按旁边设的权重分得请求,比如 Max 账号设 5、Pro 账号设 1)或 速度优先(最近回答最快的密钥先用)。备用 里列出这个供应商额度用完、被限流或不可用时改用的模型。

跨供应商的同一个模型

路由组是几个模型(来自一个或多个供应商),Agent 把它当作一个来选:group/<id>,在选择列表的 路由组 下面。两个供应商用同一个名字提供的模型会自动成组;在 路由 标签页点 新建组 可以把任意模型组到一起。排第一的模型决定这个组对外的能力。

@@ -184,7 +184,7 @@ - + @@ -192,7 +192,7 @@
StaysHow long a conversation stays with the account or key that answered it
Auto autoThe default. Within a turn always, across turns while what the vendor cached of it is worth keeping.
Session sessionThe whole session, while it can answer. With Smart, Least used first or Weekly pace, a new session goes to the account or key the fewest other sessions are on, so sessions side by side each keep one of their own.
Session sessionThe whole session, while it can answer. With Smart, Least used first or Use before expiry, a new session goes to the account or key the fewest other sessions are on, so sessions side by side each keep one of their own.
Within a turn turnWhile the agent sends tool results back; when you speak again, routing decides afresh.
Off offEvery request is routed afresh.
Strict strictNever moves to another account or key, even past its usage cap: when that one is rate limited or out of quota, the error goes to the agent. New conversations are spread as with Session.
用完再换 drain一个账号或 Key 用到额度用完,再换下一个,并一直用它:前面的额度恢复了也不会切回去。被限流或出错的只在休息期间跳过。
轮流 rotate会话的每一轮交给下一个成员的账号或 Key,均摊负载。
最少使用 usage剩余额度最多的账号或 Key 排第一。
重置前用完 pace每周剩余额度除以距重置的小时数,最高的账号排第一——重置时损失最多的那个——少让成员的周额度到重置时作废;只有 5 小时额度、没有周额度的账号(如 Claude Enterprise)按 5 小时窗口的剩余额度除以距它重置的小时数算,所以几乎总排第一。用到 90% 以上的等其他账号都答不了时才用。Key 按最近发给它的 token 数排。
到期前用完 pace每周剩余额度除以距重置的小时数,最高的账号排第一——重置时损失最多的那个——少让成员的周额度到重置时作废;只有 5 小时额度、没有周额度的账号(如 Claude Enterprise)按 5 小时窗口的剩余额度除以距它重置的小时数算,所以几乎总排第一。账号里有比重置更早过期的积分时(如 WorkBuddy 签到得的积分),按最先过期的那部分除以距过期的小时数算,比周额度的更高就按它排。用到 90% 以上的等其他账号都答不了时才用。Key 按最近发给它的 token 数排。
按权重 weight每个模型按群组编辑器里它旁边设的权重(1 到 1000,不设为 1)分得请求:权重 3 的模型每拿三个,权重 1 的拿一个,均匀穿插而不是成批。每个模型按它自己提供方的路由用自己的账号或 Key,群组里的群组算一个成员。失败后歇着的那个退出这一轮;一个失败时,下一个模型接上。
速度优先 fast最近回答这个模型最快的成员、账号或 Key 先用:看首字时间和输出速度,越新的回答算得越重。相差不到一成的保持原来的顺序。一小时内没测过的每五个请求分到一个,慢过一次的渠道还会再试;失败后歇着的排最后。只测流式回复,重启后重新测。
最便宜优先 cheap仅限路由组。此刻模型最便宜的成员先用,按 Usage 计费的方式算这个时段每百万输入、输出 token 的价格:你自己设的价格,否则用标价,再乘以提供方的价格倍率和分时倍率。DeepSeek 官方 API、Command Code 和 OpenCode Go 的 DeepSeek 模型在高峰时段(工作日 UTC 01:00–04:00 和 06:00–10:00)双倍计价,Ollama Cloud 的 DeepSeek V4.1 Flash 和 V4 Pro 则按它自己的高峰时段(工作日 UTC 12:00–18:00,其余时间半价),所以同一个 DeepSeek 模型挂在两个提供方上时,会交给这个时段更便宜的那个。价格相同的保持原来的顺序;不知道价格的排最后。
- + @@ -214,8 +214,8 @@

路由组的成员也可以是另一个路由组:在 添加模型 的 路由组 分类里选它,或者在终端里用 models+=group/<id>。子组占据它在顺序里的位置,在自己的模型之间按自己的路由方式和规则分配。比如 Coder 可以是 deepseek-v4-pro,然后是 Fast,而 Fast 是几个便宜模型的顺序。Coder 的规则可以把一轮对话交给 group/fast,再由 Fast 自己的规则决定它里面哪个模型排第一。

  • 不会无限递归。一个组不能包含它自己,无论是直接包含,还是经由它里面的组间接包含。Coder 已经包含 Fast 时,再把 Coder 放进 Fast 会被拒绝,选择器里也不会列出这样的组。最多嵌套 8 层。一个组被别的组包含时不能删除,要先从那个组里移除它。
  • -
  • 每一层按自己的路由。外层组不管用什么路由,都不会伸进它里面的组:智能、轮流、最少使用、重置前用完都把子组当作一个成员,拿子组自己会先用的那个账号或 Key 来比;排到它时,子组按自己的顺序整体尝试。Coder 设为智能、里面放 Claude(按顺序)和 GPT(按顺序)两个组时,比较的是 Claude 组的第一个和 GPT 组的第一个,不会把两组的账号混在一起排。
  • -
  • 服务商自己的路由也一样。一个模型的服务商把账号或 Key 设为按顺序、轮流、用量少的优先、重置前用完或按权重时,在任何路由组里都保持这个路由:组拿它会先用的那个账号或 Key 来比,排到它时按它自己的顺序整体尝试。保持默认“智能”的服务商,它的账号和组里其他账号放在一起排,额度最先重置的排第一,不管属于哪个服务商。
  • +
  • 每一层按自己的路由。外层组不管用什么路由,都不会伸进它里面的组:智能、轮流、最少使用、到期前用完都把子组当作一个成员,拿子组自己会先用的那个账号或 Key 来比;排到它时,子组按自己的顺序整体尝试。Coder 设为智能、里面放 Claude(按顺序)和 GPT(按顺序)两个组时,比较的是 Claude 组的第一个和 GPT 组的第一个,不会把两组的账号混在一起排。
  • +
  • 服务商自己的路由也一样。一个模型的服务商把账号或 Key 设为按顺序、轮流、用量少的优先、到期前用完或按权重时,在任何路由组里都保持这个路由:组拿它会先用的那个账号或 Key 来比,排到它时按它自己的顺序整体尝试。保持默认“智能”的服务商,它的账号和组里其他账号放在一起排,额度最先重置的排第一,不管属于哪个服务商。
  • 故障转移照常。子组里的模型全部失败时,由外层组的下一个成员接手,和其他成员一样。
  • 同一个模型出现两次(单独一次,子组里一次)时只问一次,按它第一次出现的位置。
会话保持会话在回答过它的账号或 Key 上留多久
自动 auto默认。一轮之内总是保持,跨轮则在厂商缓存还值得保留时保持。
整个会话 session整个会话,只要它还能回答。路由为智能、最少使用或重置前用完时,新会话交给当前会话最少的账号或 Key,同时开的几个会话各占一个。
整个会话 session整个会话,只要它还能回答。路由为智能、最少使用或到期前用完时,新会话交给当前会话最少的账号或 Key,同时开的几个会话各占一个。
一轮之内 turnAgent 回传工具结果时不换;你再次发言时,路由重新决定。
关闭 off每个请求都重新路由。
严格 strict绝不换到别的账号或密钥,即使超过其用量上限也一样:它被限流或额度用完时,错误直接交给 Agent。新会话像“整个会话”一样分开。