diff --git a/docs/subsystems/gateway-routing.md b/docs/subsystems/gateway-routing.md index ba519c6e1..0efd79738 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) | | 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) | -| 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) 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. `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). `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. 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`). A lone key or account is weighed against nobody, but what it has left is still read into the trace (`weighRouted`), so the Routing page shows it as it does for several (#1016); all but used up, it keeps its conversation rather than being said to move (`affine`). A failure rests a candidate (`failure`, `failureOf`). | [`routing.go`](../../internal/gateway/routing.go), [`weighted.go`](../../internal/gateway/weighted.go), [`internal/routes/`](../../internal/routes), [`internal/provider/routing.go`](../../internal/provider/routing.go) | +| Order of keys and accounts | `Routing`: smart (""), `order`, `rotate`, `usage` (least used, with an `usageHalfLife` of 1h), `pace`, `weight`, `free` (free first), `fast` (speed first) 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. `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). `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. 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`). 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`); a fallback is never asked for want of either. A plugin's account sends through its own transport, so only its tries are counted, not a plugin's own extra requests. Set in the provider editor (Concurrency, Requests per minute, Queue size, Queue wait) or with `magpie provider account-concurrency`, `queue` and `rpm`; a subscription's are kept with its picks, and every account of it keeps them, those on beside the first as well (`withPicks`, called by `All` and `AlsoOn`; #1899: a second WorkBuddy AI account had none, and queued 62s with the wait set to 1s). | [`concurrency.go`](../../internal/gateway/concurrency.go), [`rpm.go`](../../internal/gateway/rpm.go), [`internal/provider/concurrency.go`](../../internal/provider/concurrency.go) | | Sink | With `Sink` on, a key or account that answers 429 while it still has quota goes to the back, behind every one not rate limited since. Held in memory until restart, or until its rest is lifted by hand (Try now, `Unrest` calls `unsink`, `UnrestAll` `unsinkAll` for the key and each of its models), which puts it back in its place (`TestTryNowPutsASunkAccountBack`, `TestUnrestAllUnsinksTheModels`). Another magpie's model rate limited there, whose rest is the model's alone (`remoteModelRest`), sinks alone too (`restID`), and `sunkAt` reads a candidate's model before its key, so the remote's other models keep their place (#2167, ggbdpq; `TestRemoteMagpieRateLimitSinksTheModel`, `TestMagpieAddedByHandRateLimitSinksTheModel`). A group in a group sinks by its own Sink, within its own order (`sinkOwn`, #2255), and the group asked for then sinks the whole by its own; `TestNestedGroupSinksItsOwnOrder`. | [`sink.go`](../../internal/gateway/sink.go) | | Image generation | `/v1/images/generations` and `/v1/images/edits` are translated to the selected model's image API. OpenRouter image-only models use its `/images` endpoint and send reference images as `input_references`; OpenRouter models that return images through chat stay on Chat Completions. Volcengine Ark (`isArk`: an `ark.*.volces.com` base, the preset's plans or one added by hand) is asked at `/images/generations` only, as its doc (https://www.volcengine.com/docs/82379/1541523) takes it (`drawArk`): `watermark: false`, since it marks every image otherwise; reference images as JSON `image` (a URL or data URL, an array for several), never a multipart edit; no `n`, so one request per image (`eachDrawing`); no ratio as `size`, so a ratio its doc lists is sent as that ratio's 2K size and any other is a 400 that says to put it in the prompt; no mask, no quality (JL on Discord, `TestArkDrawsWithoutWatermarkOncePerImage`). DashScope (`dashScope`: Qwen's, Bailian's and Qwen Cloud's presets, or one of their hosts) draws its Qwen-Image and Wan 2.7 image models (`dashScopeDraws`) on its own API, `/api/v1/services/aigc/multimodal-generation/generation` (`drawDashScope`), as docs.qwencloud.com gives it: the prompt as the user message's `text` part after an edit's images as `image` parts (a URL or data URL), `n`, `size` as `W*H` (a ratio is a 400 that says to give WxH), `watermark: false`, no mask; the images are read from every `output.choices[].message.content[].image` (`readDashScopeAnswer`), and a refusal says its `message` and `code`. A Token Plan's host serves no OpenAI images API, so the drawing went on to chat completions and "drew nothing" (judi0713 on Discord, `TestDashScopeDrawsOnItsOwnAPI`). A routing group named for a drawing or a video (`drawingGroup`: `group/`, or a bare id the group goes by that resolved to one of its members) is tried member by member in the order its routing plans for a chat (`drawingTries` over `planGroup`), each member over its own keys or accounts (`drawOnAccounts`, `startVideo`); the next member is asked while one fails as a chat's would move on (`retryable`: its vendor 5xx, out of quota, the model not served), never for a refusal of the request itself, and the call's `Fallback` names those tried first (#2005, tianxia3111: a group of two relays answered the first one's 502). Pause rules and a gateway key's group hold apply as for a chat. A failed drawing rests no member and no key. An account out of quota for the image model (`failure` reads `failQuota`) rests that model on it alone (`restDrawer`, keyed by `restID`), until the reset its refusal names (`resetsAt`: Antigravity's "Your quota will reset after 3h19m30s.") or `quotaRest`, so the next drawing asks the accounts that still have it first (`restLast`), and the account's text models stay in. Antigravity also tells a model's quota used up as a 200 whose stream is the error; `drawCodeAssist` gives such an error the status its words stand for (`saidStatus`: quota or rate 429, credit 402, else 502), as the images API's 200 with no image does, so a spent account hands the drawing to the next one as its 429 does (01huadalang on Discord: a 502 ended the drawing on the spent account; `TestAntigravityDrawingOutOfQuotaInsideTheReplyGoesOn`, `TestAntigravityDrawingQuotaRestsTheImageModel`). `TestImageGroupMovesOnToTheNextMember`, `TestVideoGroupMovesOnToTheNextMember`. Such a group may be Settings → Images → Image generation's pick (7up6666 on X): the list offers each routing group with a member among its provider's `Drawers` (`GroupDraws`), so a request naming no model, the Magpie Image MCP's included, draws on the group; a picked group none of whose members draws any more is `DrawerMissing` (`drawerMissing`), the row says so and Automatic draws in its place. `TestImageGroupPickedInSettingsDraws`, `TestImageGenOffersDrawingGroups`. An account's own list of models (#474) never bars a ChatGPT account's GPT Image, a Grok subscription's Grok Imagine or a WorkBuddy plan's image models (`listsCantName`): the list is picked from the editor's chat models, which they are never among, so a list kept for some chat models had every drawing refused as "set not to be served by any account" (heyiwei5 on X). A key's list, picked from models that include its image ones, still bars them. `TestCodexDrawsPastAccountModelLists`. A drawing is given Settings → Images → Image generation timeout (`imageTimeout`, 1 to 60 minutes, 5 when unset; neighbads on X: a slow image endpoint needed more) as its context's deadline (`drawTimeout`, `drawWithin`), and so is downloading an image answered as a link (`imageLongest`, never under `ImageLongest`). A drawing's request goes through a transport with no `ResponseHeaderTimeout` (`drawsApart`), since an images API sends its headers only once it has drawn, and every other request keeps `upstreamHeaderWait` (10 minutes). A video's submit, status and download calls keep 5 minutes each (`videoTimeout`). The `magpie mcp image` process, which may not read these settings (WSL), waits on a call up to `callLongest` (two hours and a minute), so it never cuts one the gateway still waits on. `TestLongImageTimeoutLetsASlowVendorFinish`, `TestImageTimeoutSettingReachesTheVendor`, `TestOnlyDrawingsWaitPastTheHeaderWait`. | [`draw.go`](../../internal/gateway/draw.go), [`draw_volcengine.go`](../../internal/gateway/draw_volcengine.go), [`draw_dashscope.go`](../../internal/gateway/draw_dashscope.go), [`video.go`](../../internal/gateway/video.go), [`catalog.go`](../../internal/catalog/catalog.go) | @@ -1523,6 +1523,8 @@ go test -tags nogui ./internal/gateway -run 'TestGroupAsksOneRestingMemberNotEac go test -tags nogui ./internal/gateway -run 'TestMemberTooSmallIsNotAsked|TestMemberTooSmallIsTheLastResort|TestClaudeAccountsSpentFallBackToCodex|TestConversationOutgrowingItsMemberMoves|TestRoomyLeavesWhatItCantJudge|TestPayloadTooLarge|TestOverflow|TestContextOverflow|TestRelayInputCap|TestEveryVendorsOverflow' go test -tags nogui ./internal/gateway -run 'TestPlain403|TestOrderedKeepsAnAccountAt98|TestPromptRefusalRestsNobody' go test -tags nogui ./internal/gateway -run 'TestVertex' +go test -tags nogui ./internal/gateway -run 'TestWeightedKeys|TestAccountWeightSharesRequests' +node --test internal/gui/tests/key-weight.test.cjs internal/gui/tests/account-weight.test.cjs internal/gui/tests/routing-weight-chip.test.cjs go test -tags nogui ./internal/gateway -run 'TestPreviousResponse|TestUnknownPreviousResponse|TestPrevStore' go test -tags nogui ./internal/gateway -run 'TestBedrock' go test -tags nogui ./internal/gateway -run 'TestPublicAddr|TestEditImageURL|TestPrivateDialer|TestFetchPrivateEntries|TestVendorImageURLAtPrivateAddress|TestVideoContentAtPrivateAddress' diff --git a/docs/subsystems/providers-accounts.md b/docs/subsystems/providers-accounts.md index b68438493..86f5ef5bb 100644 --- a/docs/subsystems/providers-accounts.md +++ b/docs/subsystems/providers-accounts.md @@ -284,6 +284,7 @@ and `TestHistoricalWindowHoldsUsesEachWindowsOwnReading`. - Not read for Vertex AI: the metadata server of Compute Engine, Cloud Run and GKE; workload identity federation (`external_account`, `external_account_authorized_user`, refused by name); credentials whose `universe_domain` isn't `googleapis.com`; Vertex AI's express-mode API keys (Save refuses a key). No quota project is sent: Vertex AI bills the project in the URL. - `GOOGLE_APPLICATION_CREDENTIALS` and `CLOUDSDK_CONFIG` are in `agentenv.Vars`. The desktop app takes them from the login shell when it wasn't started with them (`proc.UserPath`, macOS and Linux), and `testenv` clears both. Vertex AI reads them as set (`vertexEnvPath`), not through `appdir.Getenv`, which takes a relative value as unset: a `~/` that starts one is the home, and one that still isn't a full path is refused, naming the variable. Passed over, it would have the request signed from gcloud's own file, which may be another account's (a person's, where the variable named a service account's key). - The Vertex AI preset's `HeaderHints` are Google's Priority PayGo and Flex PayGo headers, `X-Vertex-AI-LLM-Request-Type` and `X-Vertex-AI-LLM-Shared-Request-Type`: the editor offers to add them, the values are the user's, and they go as `Headers` do. Priority PayGo couldn't be confirmed: on the project it was tried on, Vertex AI answered with `trafficType` `ON_DEMAND`. +- An account's weight under `weight` routing is kept per account too (`AccountWeights`, by the account in lower case, 2–1000; one not in it weighs 1, and nothing sets one from the plan), as a key's is (`KeyAccount.Weight`), so a Max and a Pro account can share requests by how much more one allows (rubbzha on X). `SetAccountWeight` (GUI `provider/accountweight`, the chip beside each account in use in the editor while the routing is By weight; `magpie provider account-weight [account [n|default]]`) sets it, `moveAccountSettings` carries it through a Copilot rename, and `withPicks` puts it on the accounts `All` gives, so the gateway's `keyWeight` reads it with no file read (`Provider.AccountWeight`). - A usage cap is kept per account (`AccountCaps`, 1–99) and, beside it, per window (`AccountWindowCaps`, by the account and the window's `capId`, its name in lower case: `WindowCapID`). A window's own share wins over the account's; 100 is no cap on that window. `CapsOf` gives both (`WindowCaps`), `CapHeld` and `capReached` judge each window by its own, and `SetWindowCap` (GUI `provider/windowcap`, `magpie provider account-cap --window `) sets one. A config without window caps reads as before. How a pool ends at its caps is kept with the provider (plugins#349): `CapStop` answers 429 rather than going on to the fallbacks once every account in use is at its cap, and `CapCareful` reads usage again near a cap and holds an account whose usage can't be told (both off by default; `SetCapStop`, `SetCapCareful`, GUI `provider/capstop` and `provider/capcareful`, ticks under the account list once an account has a cap). `UsageRead` says when an account's usage was last read well and whether the last try failed (a failed try keeps the good reading's time), and `ReadUsageNow` reads it again. `magpie provider pool [--accounts a,b,…] [--cap percent|off] [--stop on|off] [--careful on|off]` shows and sets the whole pool in one command: which accounts are on and in what order, each one's cap, and both settings, and names the accounts in use with no cap. - A window whose reset time has passed has started again, whatever share it was read at (`resetPassed`). That holds for a reading kept from before (`AsOf`) and for a fresh one: Claude Code's `/usage` gives a reset to the minute and can lag it, so a run just after a reset can still say 100% with that reset. `claudeWindows` hands such a window back empty on every path, and `usedPast`, `usedUp`, `BackAt` and `capReached` leave it out when they judge an account spent, for Codex, Claude Code and `magpie quota wait` alike. A card can still show a kept reading as it was read (`reported`, for a Claude card while `/usage` is unavailable); that changes what it shows, never which account is used. A reset `/usage` gives as a time alone ("resets 3pm") can be read as its next one, a day on (`claudeResetTime`), and is then not seen as passed here. - A restart to update can run two magpies for up to the old one's drain @@ -317,6 +318,8 @@ go test -tags nogui ./internal/provider -run 'TestSeat|TestPlanOfASignedInAccoun go test -tags nogui . -run TestAccountsAlias node --test internal/gui/tests/account-alias.test.cjs go test -tags nogui . -run TestAccountCapCmd +go test -tags nogui ./internal/provider ./internal/gateway ./internal/cli -run 'TestSetAccountWeight|TestAccountWeight' +node --test internal/gui/tests/account-weight.test.cjs node --test internal/gui/tests/account-cap.test.cjs internal/gui/tests/window-cap.test.cjs go test -tags nogui ./internal/provider -run 'TestRemoteMagpie' go test -tags nogui ./internal/provider -run 'TestVolc|TestQianfan|TestBedrock|TestMantleBase|TestAddCopy|TestBackupBalanceToken' diff --git a/internal/cli/account_weight_cli_test.go b/internal/cli/account_weight_cli_test.go new file mode 100644 index 000000000..a503315a1 --- /dev/null +++ b/internal/cli/account_weight_cli_test.go @@ -0,0 +1,81 @@ +package cli + +import ( + "encoding/base64" + "encoding/json" + "os" + "path/filepath" + "testing" + "time" + + "github.com/yetone/magpie/internal/provider" +) + +// magpie provider account-weight gives a subscription account its share +// of the requests under routing=weight (rubbzha on X: a Max account 5, a +// Pro one 1), default takes it back to 1; a weight out of 1–1000, an +// account the subscription hasn't, or a provider with keys is an error. +func TestAccountWeightCmd(t *testing.T) { + home := t.TempDir() + t.Setenv("HOME", home) + t.Setenv("USERPROFILE", home) + t.Setenv("XDG_CONFIG_HOME", t.TempDir()) + t.Setenv("XDG_CACHE_HOME", t.TempDir()) + t.Setenv("DSH_HOME", "") + jwt := func(m map[string]any) string { + b, _ := json.Marshal(m) + return "h." + base64.RawURLEncoding.EncodeToString(b) + ".s" + } + auth, _ := json.Marshal(map[string]any{"auth_mode": "chatgpt", "tokens": map[string]any{ + "id_token": jwt(map[string]any{"email": "me@example.com"}), + "access_token": jwt(map[string]any{"exp": time.Now().Add(time.Hour).Unix()}), + "refresh_token": "r", "account_id": "acct-1"}}) + os.MkdirAll(filepath.Join(home, ".codex"), 0o755) + if err := os.WriteFile(filepath.Join(home, ".codex", "auth.json"), auth, 0o600); err != nil { + t.Fatal(err) + } + provider.ForgetAccounts() + t.Cleanup(provider.ForgetAccounts) + weight := func() int { + p, err := provider.Find("codex") + if err != nil { + t.Fatal(err) + } + return p.AccountWeight("me@example.com") + } + + if err := providerCmd([]string{"provider", "account-weight", "codex", "Me@Example.com", "5"}); err != nil { + t.Fatal(err) + } + if w := weight(); w != 5 { + t.Fatalf("weight %d", w) + } + for _, args := range [][]string{{"provider", "account-weight", "codex"}, {"provider", "account-weight", "codex", "me@example.com"}} { + if err := providerCmd(args); err != nil { + t.Fatal(err) + } + } + for _, bad := range []string{"1.5", "1001", "-2", "lots"} { + if err := providerCmd([]string{"provider", "account-weight", "codex", "me@example.com", bad}); err == nil { + t.Fatalf("%s taken", bad) + } + } + if w := weight(); w != 5 { + t.Fatalf("a refused weight changed it to %d", w) + } + if err := providerCmd([]string{"provider", "account-weight", "codex", "nobody@example.com", "2"}); err == nil { + t.Fatal("an account it hasn't was weighed") + } + if err := providerCmd([]string{"provider", "account-weight", "codex", "me@example.com", "default"}); err != nil { + t.Fatal(err) + } + if w := weight(); w != 1 { + t.Fatalf("default left %d", w) + } + if err := provider.Save(provider.Provider{ID: "relay", Name: "Relay", Key: "k1", Chat: "http://127.0.0.1:1/v1"}); err != nil { + t.Fatal(err) + } + if err := providerCmd([]string{"provider", "account-weight", "relay", "k1", "3"}); err == nil { + t.Fatal("a key provider's account was weighed") + } +} diff --git a/internal/cli/providers_cli.go b/internal/cli/providers_cli.go index 52c33c61b..f59f98bf2 100644 --- a/internal/cli/providers_cli.go +++ b/internal/cli/providers_cli.go @@ -84,6 +84,9 @@ const providerUsage = `usage: magpie provider account-concurrency [account|key [n|off|default]] how many requests one account or key has out at once, over every model, routing group and agent: its own, off for none, default for the provider's + magpie provider account-weight [account [n|default]] + a subscription account's share of the requests with routing=weight: + one weighing 3 takes three for each one weighing 1 takes (default 1) magpie provider queue [length [seconds]] how many may wait for each account or key past its limit, and how long; past either a request is turned away with a 429 (0: no bound) @@ -621,6 +624,8 @@ func providerCmd(args []string) error { return poolCmd(rest) case "account-concurrency", "account-limit": return accountConcurrencyCmd(rest) + case "account-weight", "account-weights": + return accountWeightCmd(rest) case "queue": return queueCmd(rest) case "rpm": @@ -1707,6 +1712,57 @@ func accountConcurrencyCmd(rest []string) error { return nil } +// accountWeightCmd shows, or sets, the weight of a subscription's accounts +// under By weight routing (provider.AccountWeights): each one's share of +// the requests, 1 when none is set. +func accountWeightCmd(rest []string) error { + if len(rest) < 1 || len(rest) > 3 { + return fmt.Errorf("magpie provider account-weight [account [n|default]]") + } + p, err := provider.Find(rest[0]) + if err != nil { + return err + } + if p.Account == nil { + return fmt.Errorf("%s has keys, not subscription accounts: a key's weight is set beside it in the app", p.Name) + } + if len(rest) > 2 { + w, err := provider.ParseWeight(rest[2]) + if err != nil { + return err + } + if err := provider.SetAccountWeight(p.ID, rest[1], w); err != nil { + return err + } + if p, err = provider.Find(p.ID); err != nil { + return err + } + } + refs := p.AccountRefs() + if len(rest) > 1 { + ref, ok := p.AccountRefOf(rest[1]) + if !ok { + return fmt.Errorf("%s has no account %q", p.Name, rest[1]) + } + refs = []string{ref} + } + if len(refs) == 0 { + fmt.Println(muted.Render(p.Name + " has no account")) + return nil + } + for _, r := range refs { + if w := p.AccountWeight(r); w > 1 { + fmt.Printf("%s · weight %d\n", r, w) + } else { + fmt.Println(r, muted.Render("· weight 1")) + } + } + if p.Routing != provider.Weighted { + fmt.Println(muted.Render("Weights count with routing=weight: magpie provider set " + p.ID + " routing=weight")) + } + return nil +} + // queueCmd shows, or sets, how many requests may wait for each of a // provider's accounts or keys past its limit, and for how many seconds // (#892). diff --git a/internal/gateway/account_weight_test.go b/internal/gateway/account_weight_test.go new file mode 100644 index 000000000..bf5944afd --- /dev/null +++ b/internal/gateway/account_weight_test.go @@ -0,0 +1,40 @@ +package gateway + +import ( + "strings" + "testing" + + "github.com/yetone/magpie/internal/provider" +) + +// A subscription routed by weight spreads its requests over its accounts +// by the weight set beside each (rubbzha on X: a Max account and a Pro +// one): me@example.com weighing 3 takes three of every four requests and +// spare@example.com, with none set, the fourth. +func TestAccountWeightSharesRequests(t *testing.T) { + codexSignedIn(t, "spare@example.com") + b := newResetBackend(t) + if err := provider.SetRouting("codex", provider.Weighted); err != nil { + t.Fatal(err) + } + if err := provider.SetAffinity("codex", provider.AffinityOff); err != nil { + t.Fatal(err) + } + if err := provider.SetAccountWeight("codex", "Me@Example.com", 3); err != nil { + t.Fatal(err) + } + srv := New() + for range 8 { + if code, body := resetPost(t, srv); code != 200 || !strings.Contains(body, "pong") { + t.Fatalf("%d %s", code, body) + } + } + tried, _ := b.seen() + n := map[string]int{} + for _, a := range strings.Split(tried, ",") { + n[a]++ + } + if n["acct-1"] != 6 || n["acct-2"] != 2 { + t.Fatalf("tried %s: want acct-1 6 times, acct-2 twice", tried) + } +} diff --git a/internal/gateway/weighted.go b/internal/gateway/weighted.go index 8c6770e72..302d6e679 100644 --- a/internal/gateway/weighted.go +++ b/internal/gateway/weighted.go @@ -1,7 +1,9 @@ package gateway // Weighted routing (#841): a provider's requests spread over its keys by -// each key's weight, as NGINX's smooth weighted round robin does — keys +// each key's weight, and a subscription's over its accounts by each +// account's (provider.AccountWeights, rubbzha on X), as NGINX's smooth +// weighted round robin does — keys // weighing 3 and 1 go a, a, b, a, a, a, b, a…, the ratio held over a // handful of requests rather than only on average. A key resting after a // failure is left out of the round while it rests, so the others share @@ -21,8 +23,14 @@ import ( "github.com/yetone/magpie/internal/routes" ) -// keyWeight is a candidate's weight: its key's, 1 when none. -func keyWeight(c candidate) int { return max(c.p.KeyWeight, 1) } +// keyWeight is a candidate's weight: its account's (provider.AccountWeights, +// rubbzha on X) or its key's, 1 when none. +func keyWeight(c candidate) int { + if c.p.Account != nil { + return c.p.AccountWeight(c.p.Account.User) + } + return max(c.p.KeyWeight, 1) +} // resting says whether c rests now, as restLast will find. func resting(c candidate) bool { diff --git a/internal/gui/assets/app.js b/internal/gui/assets/app.js index e2ff7f2df..b4b927648 100644 --- a/internal/gui/assets/app.js +++ b/internal/gui/assets/app.js @@ -12047,7 +12047,7 @@ const ROUTINGS = [ ["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."], - ["weight", "By weight", "Requests spread over the keys by the weight set beside each: a key weighing 3 takes three requests for every one a key 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 its key as Stays says."], + ["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."], ]; @@ -12075,8 +12075,7 @@ function routingSegs(items, current, onPick) { }); return box; } -// weight is a key's share: offered for a provider with keys only -const routingsOf = (p) => [...(p.account ? ROUTINGS.filter(([id]) => id !== "weight") : ROUTINGS), ...jsRoutings(p.routing || "")]; +const routingsOf = (p) => [...ROUTINGS, ...jsRoutings(p.routing || "")]; // as on the Routing page's list of these (routing/client.js AFF_OPTS) const STAYS = [ ["", "Auto", "A conversation stays with the account or key that answered it while what the vendor cached of it is worth keeping — within a turn always, across turns while it's fresh."], @@ -12133,8 +12132,8 @@ function renderRouting(p) { rUnsaved.hidden = routingNow() === (p.routing || ""); // in turn and by weight go round already kLabel.hidden = kWrap.hidden = routingNow() === "rotate" || routingNow() === "weight"; - // each key's weight shows beside it while the routing is by weight - for (const l of document.querySelectorAll(".accts.keys")) if (l.dataset.provider === p.id) l.classList.toggle("weighted", routingNow() === "weight"); + // each key's or account's weight shows beside it while by weight + for (const l of document.querySelectorAll(".accts")) if (l.dataset.provider === p.id) l.classList.toggle("weighted", routingNow() === "weight"); }; const rPick = routingSegs(routingsOf(p).map(([id, name, , js]) => [id, ROUTINGS.some((r) => r[0] === id) ? t(name) : name, , js]), routingNow(), (routing) => { draft.routing = routing; drawRouting(); }); const rRow = el("div", "route-pick"); @@ -13230,24 +13229,20 @@ function renderAccounts(a, p) { const sub = subOf(a.agent); const list = el("div", "accts"); const ls = loginsInOrder(a, p); + if (p) list.dataset.provider = p.id, list.classList.toggle("weighted", (draft?.routing ?? (p.routing || "")) === "weight"); // a Claude account whose sign-in Anthropic refused, or that has none, // can't be used till it is signed in again; another subscription's lapse // shows on its quota line only, as before const unusable = (l) => a.agent === "claude" && !!l.lapsed; - // a plugin's account whose sign-in its vendor refused (#1363: Grok after - // a restart): marked lapsed, or its allowance read saying so. Whatever - // else it is (in use, the agent's own), it keeps a way to sign in again - // and its Remove, and the reason never stands in their place. - // A built-in Copilot account whose GitHub token GitHub refused (echo_ts - // on Discord: a revoked token) is the same, marked lapsed by magpie, and - // signed in again in place. So is any other built-in account whose - // sign-in its vendor revoked (#1793: ChatGPT's 401 token_revoked) or - // refused to refresh: the gateway passes over it till then. + // one whose sign-in its vendor refused (a plugin's, #1363; Copilot's + // revoked token; #1793's token_revoked) keeps Sign in again and Remove const signedOut = (l) => !unusable(l) && (sub?.plugin ? !!l.lapsed || SIGN_IN_GONE.test(quota?.[l.user]?.error || "") : (a.agent === "copilot" && !!l.lapsed) || SIGN_IN_GONE.test(l.lapsed || "")); // a Copilot account on an enterprise's GHE.com is named login@host, and // signs in again there const againSite = (l) => !sub?.plugin && a.agent === "copilot" && String(l.user).includes("@") ? String(l.user).split("@").pop() : undefined; const several = ls.filter((l) => !unusable(l) && ((l.active && !l.paused) || l.on)).length > 1; + // each one's weight (provider.AccountWeights), for its share + const isOn = (l) => !unusable(l) && !l.paused && (l.active || l.on), wOf = (l) => Math.max(p?.accountWeights?.[String(l.user).toLowerCase()] || 0, 1), weights = ls.filter(isOn).reduce((n, l) => n + wOf(l), 0); // kept signed in to one of the user's choosing (#524), the first is the // first in use in the order, which Make first sets without a sign-in const kept = keptLogin(p); @@ -13267,7 +13262,7 @@ function renderAccounts(a, p) { // it is signed back in once it has room (#408) const back = ls.find((l) => l.returns && !l.active); for (const l of ls) { - const on = !unusable(l) && !l.paused && (l.active || l.on); + const on = isOn(l); const row = el("div", "acc" + (on ? " in-use" : " off") + (l.user === justAdded ? " new" : "")); // its Remove, titled as given; true: the own account's, else the plain one const forgetOf = (title) => { @@ -13296,6 +13291,7 @@ function renderAccounts(a, p) { const line = el("div", "acc-line"); row.append(line); line.append(dot, accountNameButton(p, l.user), el("span", "plan", accountPlan({ agent: a.agent, builtin: a.builtin, plan: l.plan }))); + if (p && on && several) line.append(keyWeight(p, { name: l.user }, wOf(l), weights, "provider/accountweight", { id: p.id, account: l.user })); // its own models (#474), when there is another account to send the rest to const [amPill, amBox] = ls.length > 1 || accountModelsOf(p, l.user).length ? accountModels(p, l.user, false, l.user) : []; // what is set shows on it; the rest waits under ⋯ on a line below @@ -14566,25 +14562,25 @@ function accountModels(p, ref, isKey, name) { return [pill, box]; } -// keyWeight: a key's weight under By weight routing, and its share of the -// requests; a click edits it in place, Enter or leaving it saves it. -function keyWeight(p, k, w, total) { +// keyWeight: a key's or account's weight under By weight, and its share; +// a click edits it in place, Enter or leaving it saves it. +function keyWeight(p, k, w, total, path = "keys/weight", body = { id: p.id, ref: k.id }) { const b = el("button", "key-weight", t("Weight {n} · {share}%", { n: w, share: Math.round(100 * w / total) })); - b.title = t("Its share of the requests: a key weighing 3 takes three for every one a key weighing 1 takes"); + b.title = t("Its share of the requests: one weighing 3 takes three for every one weighing 1 takes"); b.onclick = () => { const i = input(String(w), "1"); i.type = "number"; i.min = "1"; i.max = "1000"; i.className = "key-weight-in"; - i.setAttribute("aria-label", t("Key weight")); + i.setAttribute("aria-label", t(path[0] == "k" ? "Key weight" : "Account weight")); i.title = b.title; let done = false; const save = (keep) => { if (done) return; done = true; const n = Math.round(Number(i.value)); - if (keep && n >= 1 && n <= 1000 && n !== w) accountAction("keys/weight", { id: p.id, ref: k.id, weight: n }, t("{key} weighs {n}", { key: k.name || k.masked, n })); + if (keep && n >= 1 && n <= 1000 && n !== w) accountAction(path, { ...body, weight: n }, t("{key} weighs {n}", { key: k.name || k.masked, n })); else renderProviders(); }; i.onkeydown = (e) => { e.stopPropagation(); if (e.key === "Enter") save(true); else if (e.key === "Escape") save(false); }; diff --git a/internal/gui/assets/i18n.js b/internal/gui/assets/i18n.js index 77c64f031..9adee451c 100644 --- a/internal/gui/assets/i18n.js +++ b/internal/gui/assets/i18n.js @@ -351,6 +351,7 @@ const I18N = { "Its saved configuration will be removed. Agents using it may switch to another provider or their default model.": "这将删除它的已保存配置。使用它的 Agent 可能切换到其他供应商或默认模型。", "This account or key will stop being used for requests. You will need to add it again to use it.": "此账户或密钥将不再用于请求。要再次使用,需要重新添加。", "Key weight": "密钥权重", + "Account weight": "账号权重", "Saved middleware options will be removed. The plugin will run with no options.": "已保存的中间件选项将被移除。插件将不带选项运行。", "Main navigation": "主导航", "Gateway keys": "网关密钥", @@ -1743,9 +1744,9 @@ const I18N = { "Cheapest first: no price is known for {model} on {who}, so it goes in its listed place after every one that has a price.": "最便宜优先:不知道 {model} 在 {who} 上的价格,所以它排在所有有价格的后面,按列出的位置。", "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.": "先把不花钱的用完:供应商对本订阅的额度或积分不收费的模型排在前面,按它们原来的顺序;这些都不能响应时,才用要花额度的。不花额度的一个都不剩下。", "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.": "免费优先:成员中那个模型不花订阅额度或积分的排在前面,其余在后;每个成员整体尝试,各自按其供应商的路由在自己的账号或 Key 间分配。免费的先于任何花额度的,所以不花钱的一个都不剩下。", - "Requests spread over the keys by the weight set beside each: a key weighing 3 takes three requests for every one a key 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 its key as Stays says.": "请求按每个密钥旁设置的权重分配:权重 3 的密钥每接 3 个请求,权重 1 的接 1 个,几个请求之内就均匀分开。出错的在休息期间被跳过,由其他密钥按各自权重分担;会话按「会话保持」的设置留在原来的密钥上。", + "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.": "请求按每个密钥或账号旁设置的权重分配:权重 3 的每接 3 个请求,权重 1 的接 1 个,几个请求之内就均匀分开。出错的在休息期间被跳过,由其他的按各自权重分担;会话按「会话保持」的设置留在原处。", "Weight {n} · {share}%": "权重 {n} · {share}%", - "Its share of the requests: a key weighing 3 takes three for every one a key weighing 1 takes": "它在请求中的份额:权重 3 的密钥每接 3 个请求,权重 1 的接 1 个", + "Its share of the requests: one weighing 3 takes three for every one weighing 1 takes": "它在请求中的份额:权重 3 的每接 3 个请求,权重 1 的接 1 个", "Weight {n}": "权重 {n}", "{key} weighs {n}": "{key} 的权重已设为 {n}", "Requests go to the first; the next takes over when the one before runs out of quota, hits a rate limit or fails.": "请求先发给第一个;它额度用完、被限流或出错时,由下一个接手。", @@ -4601,6 +4602,7 @@ const I18N = { "Its saved configuration will be removed. Agents using it may switch to another provider or their default model.": "這將刪除它的已儲存設定。使用它的 Agent 可能切換到其他供應商或預設模型。", "This account or key will stop being used for requests. You will need to add it again to use it.": "此帳戶或金鑰將不再用於請求。要再次使用,需要重新新增。", "Key weight": "金鑰權重", + "Account weight": "帳號權重", "Saved middleware options will be removed. The plugin will run with no options.": "已儲存的中介軟體選項將被移除。外掛將不帶選項執行。", "Main navigation": "主導航", "Gateway keys": "閘道金鑰", @@ -5975,9 +5977,9 @@ const I18N = { "Cheapest first: no price is known for {model} on {who}, so it goes in its listed place after every one that has a price.": "最便宜優先:不知道 {model} 在 {who} 上的價格,所以它排在所有有價格的後面,按列出的位置。", "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.": "先把不花錢的用完:供應商對本訂閱的額度或點數不收費的模型排在前面,按它們原本的順序;這些都不能回應時,才用要花額度的。不花額度的一個都不剩下。", "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.": "免費優先:成員中那個模型不花訂閱額度或點數的排在前面,其餘在後;每個成員整體嘗試,各自依其供應商的路由在自己的帳號或 Key 間分配。免費的先於任何花額度的,所以不花錢的一個都不剩下。", - "Requests spread over the keys by the weight set beside each: a key weighing 3 takes three requests for every one a key 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 its key as Stays says.": "請求按每個金鑰旁設定的權重分配:權重 3 的金鑰每接 3 個請求,權重 1 的接 1 個,幾個請求之內就均勻分開。出錯的在休息期間被跳過,由其他金鑰按各自權重分擔;會話按「會話保持」的設定留在原來的金鑰上。", + "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.": "請求按每個金鑰或帳號旁設定的權重分配:權重 3 的每接 3 個請求,權重 1 的接 1 個,幾個請求之內就均勻分開。出錯的在休息期間被跳過,由其他的按各自權重分擔;會話按「會話保持」的設定留在原處。", "Weight {n} · {share}%": "權重 {n} · {share}%", - "Its share of the requests: a key weighing 3 takes three for every one a key weighing 1 takes": "它在請求中的份額:權重 3 的金鑰每接 3 個請求,權重 1 的接 1 個", + "Its share of the requests: one weighing 3 takes three for every one weighing 1 takes": "它在請求中的份額:權重 3 的每接 3 個請求,權重 1 的接 1 個", "Weight {n}": "權重 {n}", "{key} weighs {n}": "{key} 的權重已設為 {n}", "Requests go to the first; the next takes over when the one before runs out of quota, hits a rate limit or fails.": "請求先發給第一個;它額度用完、被限流或出錯時,由下一個接手。", @@ -10184,9 +10186,9 @@ const I18N = { "Cheapest first: no price is known for {model} on {who}, so it goes in its listed place after every one that has a price.": "最安優先:{who} での {model} の価格が分からないため、価格のあるものすべての後ろ、設定順の位置に入ります。", "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.": "無料のものを先に使い切ります:提供元がこのサブスクリプションの利用枠やクレジットを消費しないモデルを、一覧の順に先に試し、それらが応答できないときだけ消費するものへ進みます。無料のものが残ることはありません。", "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.": "無料優先:提供元がサブスクリプションの利用枠やクレジットを消費しないモデルのメンバーを先に、残りを後に置きます。各メンバーはまとめて試され、それぞれの提供元のルーティングに従って自分のアカウントや Key に配分されます。無料のものは消費するものより先なので、無料のものは残りません。", - "Requests spread over the keys by the weight set beside each: a key weighing 3 takes three requests for every one a key 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 its key as Stays says.": "各キーの横で設定した重みでリクエストを振り分けます。重み 3 のキーは、重み 1 のキーが 1 件受けるごとに 3 件受け、数件のうちに均等に分かれます。失敗したキーは休止中は飛ばされ、他のキーがそれぞれの重みで分担します。会話は「維持」の設定どおりそのキーにとどまります。", + "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.": "各キーやアカウントの横で設定した重みでリクエストを振り分けます。重み 3 のものは、重み 1 のものが 1 件受けるごとに 3 件受け、数件のうちに均等に分かれます。失敗したものは休止中は飛ばされ、他がそれぞれの重みで分担します。会話は「維持」の設定どおりそこにとどまります。", "Weight {n} · {share}%": "重み {n} · {share}%", - "Its share of the requests: a key weighing 3 takes three for every one a key weighing 1 takes": "リクエストの取り分:重み 3 のキーは、重み 1 のキーが 1 件受けるごとに 3 件受けます", + "Its share of the requests: one weighing 3 takes three for every one weighing 1 takes": "リクエストの取り分:重み 3 のものは、重み 1 のものが 1 件受けるごとに 3 件受けます", "Weight {n}": "重み {n}", "{key} weighs {n}": "{key} の重みを {n} にしました", "Requests go to the first; the next takes over when the one before runs out of quota, hits a rate limit or fails.": "リクエストは最初のものに送られます。クォータ切れ、レート制限、エラーのときは次のものが引き継ぎます。", @@ -12450,6 +12452,7 @@ const I18N = { "Its saved configuration will be removed. Agents using it may switch to another provider or their default model.": "保存した設定が削除されます。使用中のエージェントは別のプロバイダーまたは既定のモデルに切り替わる場合があります。", "This account or key will stop being used for requests. You will need to add it again to use it.": "このアカウントまたはキーはリクエストに使用されなくなります。再び使うには追加し直してください。", "Key weight": "キーの重み", + "Account weight": "アカウントの重み", "Saved middleware options will be removed. The plugin will run with no options.": "保存したミドルウェアのオプションが削除されます。プラグインはオプションなしで実行されます。", "Main navigation": "メインナビゲーション", // agents' advice after a change (NOTICES) @@ -14423,9 +14426,9 @@ const I18N = { "Cheapest first: no price is known for {model} on {who}, so it goes in its listed place after every one that has a price.": "Günstigste zuerst: Für {model} bei {who} ist kein Preis bekannt, daher kommt es an seinem Platz in der Liste hinter alle mit Preis.", "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.": "Zuerst kommt, was nichts kostet: Modelle, die ihr Anbieter diesem Abonnement ohne Verbrauch von Kontingent oder Guthaben bereitstellt, in ihrer gelisteten Reihenfolge; erst wenn diese nicht antworten können, eines, das verbraucht. Nichts Kostenloses bleibt ungenutzt.", "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.": "Kostenlos zuerst: die Mitglieder, deren Modell ihr Anbieter dem Abonnement ohne Verbrauch von Kontingent oder Guthaben bereitstellt, kommen zuerst, dann die übrigen — jedes als Ganzes, über seine eigenen Konten oder Keys, wie es sein Anbieter routet. Die kostenlosen werden vor jedem verbrauchenden versucht, sodass nichts Kostenloses ungenutzt bleibt.", - "Requests spread over the keys by the weight set beside each: a key weighing 3 takes three requests for every one a key 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 its key as Stays says.": "Anfragen verteilen sich nach dem Gewicht neben jedem Schlüssel: Einer mit Gewicht 3 bekommt drei Anfragen für jede, die einer mit Gewicht 1 bekommt, schon über wenige Anfragen gleichmäßig. Ein fehlschlagender wird übersprungen, solange er pausiert, und die anderen teilen sich seine Anfragen; ein Gespräch bleibt bei seinem Schlüssel, wie „Bleibt“ es sagt.", + "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.": "Anfragen verteilen sich nach dem Gewicht neben jedem Schlüssel oder Konto: Eines mit Gewicht 3 bekommt drei Anfragen für jede, die eines mit Gewicht 1 bekommt, schon über wenige Anfragen gleichmäßig. Eines, das fehlschlägt, wird übersprungen, solange es pausiert, und die anderen teilen sich seine Anfragen; ein Gespräch bleibt dort, wie „Bleibt“ es sagt.", "Weight {n} · {share}%": "Gewicht {n} · {share}%", - "Its share of the requests: a key weighing 3 takes three for every one a key weighing 1 takes": "Sein Anteil an den Anfragen: Ein Schlüssel mit Gewicht 3 bekommt drei für jede, die einer mit Gewicht 1 bekommt", + "Its share of the requests: one weighing 3 takes three for every one weighing 1 takes": "Sein Anteil an den Anfragen: Eines mit Gewicht 3 bekommt drei für jede, die eines mit Gewicht 1 bekommt", "Weight {n}": "Gewicht {n}", "{key} weighs {n}": "{key} hat jetzt Gewicht {n}", "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.", @@ -16679,6 +16682,7 @@ const I18N = { "Its saved configuration will be removed. Agents using it may switch to another provider or their default model.": "Die gespeicherte Konfiguration wird entfernt. Agenten, die sie verwenden, können zu einem anderen Anbieter oder ihrem Standardmodell wechseln.", "This account or key will stop being used for requests. You will need to add it again to use it.": "Dieses Konto oder dieser Schlüssel wird nicht mehr für Anfragen verwendet. Um es erneut zu verwenden, müssen Sie es wieder hinzufügen.", "Key weight": "Schlüsselgewicht", + "Account weight": "Kontogewicht", "Saved middleware options will be removed. The plugin will run with no options.": "Die gespeicherten Middleware-Optionen werden entfernt. Das Plugin läuft ohne Optionen.", "Main navigation": "Hauptnavigation", // agents' advice after a change (NOTICES) diff --git a/internal/gui/assets/plugins/routing/client.js b/internal/gui/assets/plugins/routing/client.js index 91445713d..5277801f0 100644 --- a/internal/gui/assets/plugins/routing/client.js +++ b/internal/gui/assets/plugins/routing/client.js @@ -521,10 +521,10 @@ function routingPage(part) { 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."], manual: ["Manual", "Manual: every request goes to the model picked on the group's card, over its own accounts or keys."], - // the provider's key routing (#841); both strings as the provider - // editor's routing options say them (app.js ROUTINGS), so every - // language is already spoken - weight: ["By weight", "Requests spread over the keys by the weight set beside each: a key weighing 3 takes three requests for every one a key 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 its key as Stays says."], + // a provider's keys or a subscription's accounts by weight (#841, + // rubbzha on X); both strings as the provider editor's routing options + // say them (app.js ROUTINGS), so every language is already spoken + 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."], cheap: ["Cheapest first", "Requests go to the member whose model costs least now, by its price a million tokens in and out at this hour — DeepSeek's peak hours count double — and the cheaper cache read when two cost the same; those that cost the same keep their listed order, and one with no known price goes last."], 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."], @@ -731,7 +731,7 @@ function routingPage(part) { ? t("In order: with {rested} resting after a failure, {who} is the first that can answer.", { rested: rested.join(", "), who: w }) : t("In order: {who} is first, and answers everything while it can.", { who: w }); case "rotate": return t("In turn: it's {who}'s turn — each request starts one further along.", { who: w }); - case "weight": return t("By weight: it's {who}'s share — each key takes requests as its weight says.", { who: w }); + case "weight": return t(f.kind === "account" ? "By weight: it's {who}'s share — each account takes requests as its weight says." : "By weight: it's {who}'s share — each key takes requests as its weight says.", { who: w }); case "free": if (f.free) return restedTo(t("it costs nothing there, so it's spent first.")) || t("Free first: {model} costs nothing on {who}, so it's tried before any that spends the allowance.", { model: f.model, who: w }); @@ -7139,8 +7139,8 @@ function routingPage(part) { try { await api("provider/" + what, body); status(ok, "ok"); groups = groupsFrom(await api("groups")); load(); } catch (e) { status(e.message, "err"); } }; const lab = (s, c) => { const w = el("span", "lab"); w.append(el("small", "", s), c); return w; }; - // by weight is a key's share (#841), set beside each key in the provider's editor - const opts = withJS(p.kind === "account" ? ROUTE_OPTS : [...ROUTE_OPTS, ["weight", "By weight"]], p.routing); + // by weight: each key's or account's share (#841), set beside it in the provider's editor + const opts = withJS([...ROUTE_OPTS, ["weight", "By weight"]], p.routing); ctl.append( lab(t("Routing"), routingSegs(opts.map(([id, n, js]) => [id, t(n), , js]), p.routing || "", (v) => set("route", { id: p.provider, routing: v }, t("{name}: {routing}", { name: p.name, routing: t(opts.find(([id]) => id === v)[1]) })))), lab(t("Stays"), segs(AFF_OPTS.map(([id, n]) => [id, t(n)]), p.affinity || "", (v) => set("affinity", { id: p.provider, affinity: v }, t("{name}: {routing}", { name: p.name, routing: t(AFF_OPTS.find(([id]) => id === v)[1]) }))))); diff --git a/internal/gui/assets/plugins/routing/i18n.js b/internal/gui/assets/plugins/routing/i18n.js index 1393fdf3d..5bd94b90a 100644 --- a/internal/gui/assets/plugins/routing/i18n.js +++ b/internal/gui/assets/plugins/routing/i18n.js @@ -45,6 +45,7 @@ magpie.strings({ "{name} switched off": "已关闭 {name}", "in {groups}": "已在 {groups}", "By weight: it's {who}'s share \u2014 each key takes requests as its weight says.": "按权重:轮到 {who} 的份额——每个密钥按自己的权重接请求。", + "By weight: it's {who}'s share \u2014 each account takes requests as its weight says.": "按权重:轮到 {who} 的份额——每个账号按自己的权重接请求。", "By weight: it's {who}'s share — each model takes requests as the weight set beside it says.": "按权重:轮到 {who} 的份额——每个模型按旁边设置的权重接请求。", "By weight: each model takes its share of the requests by the weight set beside it — one weighing 3 three for every one a model weighing 1 takes, spread out rather than in bursts. One resting after a failure leaves the round and the others share its requests; the next model is the fallback when one fails.": "按权重:每个模型按旁边设置的权重分得请求——权重 3 的模型每接 3 个,权重 1 的接 1 个,均匀穿插而不是成批连发。失败后休息中的模型退出这一轮,其余模型分担它的请求;某个模型失败时,由下一个模型接替。", "Its share of the requests: a model weighing 3 takes three for every one a model weighing 1 takes": "它在请求中的份额:权重 3 的模型每接 3 个请求,权重 1 的接 1 个", @@ -660,6 +661,7 @@ magpie.strings({ "{name} switched off": "已關閉 {name}", "in {groups}": "已在 {groups}", "By weight: it's {who}'s share — each key takes requests as its weight says.": "按權重:輪到 {who} 的份額——每個金鑰按自己的權重接請求。", + "By weight: it's {who}'s share \u2014 each account takes requests as its weight says.": "按權重:輪到 {who} 的份額——每個帳號按自己的權重接請求。", "By weight: it's {who}'s share — each model takes requests as the weight set beside it says.": "按權重:輪到 {who} 的份額——每個模型按旁邊設定的權重接請求。", "By weight: each model takes its share of the requests by the weight set beside it — one weighing 3 three for every one a model weighing 1 takes, spread out rather than in bursts. One resting after a failure leaves the round and the others share its requests; the next model is the fallback when one fails.": "按權重:每個模型按旁邊設定的權重分得請求——權重 3 的模型每接 3 個,權重 1 的接 1 個,均勻穿插而不是成批連發。失敗後休息中的模型退出這一輪,其餘模型分擔它的請求;某個模型失敗時,由下一個模型接替。", "Its share of the requests: a model weighing 3 takes three for every one a model weighing 1 takes": "它在請求中的份額:權重 3 的模型每接 3 個請求,權重 1 的接 1 個", @@ -1253,6 +1255,7 @@ magpie.strings({ "{name} switched off": "{name} をオフにしました", "in {groups}": "{groups} に追加済み", "By weight: it's {who}'s share \u2014 each key takes requests as its weight says.": "重み付け:{who} の取り分です——各キーは重みどおりにリクエストを受けます。", + "By weight: it's {who}'s share \u2014 each account takes requests as its weight says.": "重み付け:{who} の取り分です——各アカウントは重みどおりにリクエストを受けます。", "By weight: it's {who}'s share — each model takes requests as the weight set beside it says.": "重み付け:{who} の取り分です——各モデルは横に設定した重みどおりにリクエストを受けます。", "By weight: each model takes its share of the requests by the weight set beside it — one weighing 3 three for every one a model weighing 1 takes, spread out rather than in bursts. One resting after a failure leaves the round and the others share its requests; the next model is the fallback when one fails.": "重み付け:各モデルは横に設定した重みに応じてリクエストを受けます。重み 3 のモデルは、重み 1 のモデルが 1 件受けるごとに 3 件受け、まとめてではなく分散して届きます。失敗して休止中のモデルは巡回から外れ、残りがその分を分け合います。あるモデルが失敗したときは次のモデルが引き継ぎます。", "Its share of the requests: a model weighing 3 takes three for every one a model weighing 1 takes": "リクエストの取り分:重み 3 のモデルは、重み 1 のモデルが 1 件受けるごとに 3 件受けます", @@ -1858,6 +1861,7 @@ magpie.strings({ "{name} switched off": "{name} ausgeschaltet", "in {groups}": "in {groups}", "By weight: it's {who}'s share \u2014 each key takes requests as its weight says.": "Nach Gewicht: {who} ist mit seinem Anteil dran — jeder Schlüssel bekommt Anfragen nach seinem Gewicht.", + "By weight: it's {who}'s share \u2014 each account takes requests as its weight says.": "Nach Gewicht: {who} ist mit seinem Anteil dran — jedes Konto bekommt Anfragen nach seinem Gewicht.", "By weight: it's {who}'s share — each model takes requests as the weight set beside it says.": "Nach Gewicht: {who} ist mit seinem Anteil dran — jedes Modell bekommt Anfragen nach dem Gewicht, das daneben eingestellt ist.", "By weight: each model takes its share of the requests by the weight set beside it — one weighing 3 three for every one a model weighing 1 takes, spread out rather than in bursts. One resting after a failure leaves the round and the others share its requests; the next model is the fallback when one fails.": "Nach Gewicht: Jedes Modell bekommt seinen Anteil an den Anfragen nach dem Gewicht daneben – eines mit Gewicht 3 drei für jede, die ein Modell mit Gewicht 1 bekommt, verteilt statt in Schüben. Eines, das nach einem Fehler pausiert, setzt aus, und die anderen teilen sich seine Anfragen; scheitert eines, springt das nächste Modell ein.", "Its share of the requests: a model weighing 3 takes three for every one a model weighing 1 takes": "Sein Anteil an den Anfragen: Ein Modell mit Gewicht 3 bekommt drei für jede, die eines mit Gewicht 1 bekommt", diff --git a/internal/gui/providers.go b/internal/gui/providers.go index 224f9b9dc..dac770855 100644 --- a/internal/gui/providers.go +++ b/internal/gui/providers.go @@ -246,6 +246,9 @@ type providerJSON struct { // each key's or account's own limit over it (#892), by its name in // lower case or its key id; 0 there is none AccountConcurrency map[string]int `json:"accountConcurrency,omitempty"` + // each subscription account's weight under By weight routing, by its + // name in lower case; one not in it weighs 1 (provider.AccountWeights) + AccountWeights map[string]int `json:"accountWeights,omitempty"` // how many may wait for each key or account, and for how many seconds // (0: no bound) QueueLimit int `json:"queueLimit,omitempty"` @@ -648,7 +651,7 @@ func providerInfoWith(p provider.Provider, agents []agentUse, desktop map[string Fallback: p.Fallback, Routing: p.Routing, Sink: p.Sink, Affinity: p.Affinity, KeepLogin: p.KeepLogin, KeepLoginAs: p.KeepLoginAs, SwitchOnly: p.SwitchOnly, CapStop: p.CapStop, CapCareful: p.CapCareful, Unlisted: p.Unlisted, NoModels: p.ServesNone(), BestInFamily: p.BestInFamily && len(p.Models) == 0 && !p.NoModels, Off: p.Off, Contexts: p.Contexts, MaxConcurrency: p.MaxConcurrency, PluginConcurrency: p.PluginConcurrency(), PriceRate: p.PriceRate, RateWindows: p.RateWindows, RateNow: rateNowOf(p, time.Now()), - AccountConcurrency: p.AccountConcurrency, QueueLimit: p.QueueLimit, QueueWait: p.QueueWait, MaxRPM: p.MaxRPM, + AccountConcurrency: p.AccountConcurrency, AccountWeights: p.AccountWeights, QueueLimit: p.QueueLimit, QueueWait: p.QueueWait, MaxRPM: p.MaxRPM, Outputs: provider.OutputsOf(p.ID), Compacts: provider.CompactsOf(p.ID), } if p.Account != nil { @@ -1357,6 +1360,9 @@ func providerRoutes(mux *http.ServeMux, w Windows) { // it follow the account's cap Cap int `json:"cap"` Window string `json:"window"` + // Weight, for accountweight: the account's share under By + // weight routing, 1 to provider.MaxKeyWeight (0 or 1: none) + Weight int `json:"weight"` // Alias, for accountname: the account's name of the user's // own, "" to take it off (#1515) Alias string `json:"alias"` @@ -1700,11 +1706,13 @@ func providerRoutes(mux *http.ServeMux, w Windows) { if old != nil { in.AccountModels = old.AccountModels } - // and their usage caps, with accountcap and windowcap, and their - // limits on requests at once, with accountconcurrency + // and their usage caps, with accountcap and windowcap, their + // limits on requests at once, with accountconcurrency, and + // their weights, with accountweight if old != nil { in.AccountCaps, in.AccountWindowCaps = old.AccountCaps, old.AccountWindowCaps in.AccountConcurrency = old.AccountConcurrency + in.AccountWeights = old.AccountWeights in.AccountNames = old.AccountNames // with accountname } // the image models unticked in its editor likewise: [] @@ -1934,6 +1942,11 @@ func providerRoutes(mux *http.ServeMux, w Windows) { fail(rw, err) return } + case "accountweight": + if err := provider.SetAccountWeight(in.ID, req.Account, req.Weight); err != nil { + fail(rw, err) + return + } case "route": if err := provider.SetRouting(in.ID, in.Routing); err != nil { fail(rw, err) diff --git a/internal/gui/tests/account-weight.test.cjs b/internal/gui/tests/account-weight.test.cjs new file mode 100644 index 000000000..7ede2a2f6 --- /dev/null +++ b/internal/gui/tests/account-weight.test.cjs @@ -0,0 +1,135 @@ +// Run with Node's test runner and Playwright on the module path; see README.md. +// A subscription's accounts by weight (rubbzha on X: a Max account and a +// Pro one, shared by how much more one allows). The provider editor's +// Routing offers By weight for accounts as it does for keys, and with it +// picked each account in use shows its weight and its share beside its +// name, as a key does; a click edits it in place and posts +// provider/accountweight. Hidden under the other routings. Each line stays +// one line, with nothing past the sheet's edge, at the window's narrowest +// and in a phone's browser, in every language, without the page scrolling. +// MAGPIE_ACC_ASSETS runs it on older assets. +const assert = require("node:assert/strict"); +const fs = require("node:fs/promises"); +const path = require("node:path"); +const { test } = require("node:test"); +const { chromium, webkit } = require("playwright"); + +const assets = path.resolve(process.env.MAGPIE_ACC_ASSETS || path.resolve(__dirname, "../assets")); +const claude = () => ({ + id: "claude", name: "Claude Code", icon: "claude-color", chat: "", responses: "", anthropic: "", catalog: "", routing: "", + models: [{ id: "claude-opus-5-5", name: "Claude Opus 5.5", on: true }], agents: [], fallback: [], headers: {}, keyList: [], + account: { + agent: "claude", agentName: "Claude Code", user: "max@example.com", plan: "max", + logins: [ + { user: "max@example.com", plan: "max", active: true, on: true }, + { user: "pro@example.com", plan: "pro", on: true }, + { user: "off@example.com", plan: "pro", on: false }, + ], + }, + accountWeights: { "max@example.com": 3 }, +}); + +function serve(lang, web, posts) { + const p = claude(); + const providers = { providers: [p], presets: [], excluded: [], gateway: { running: true, window: true } }; + return async (route) => { + const url = new URL(route.request().url()); + const json = (data) => route.fulfill({ json: data }); + if (url.pathname === "/boot.js") return route.fulfill({ contentType: "text/javascript", body: `window.bootPrefs = {lang:${JSON.stringify(lang)},theme:"light",web:${web}};` }); + if (url.pathname === "/wails/runtime.js") return route.fulfill({ contentType: "text/javascript", body: "export const Window = {};" }); + if (url.pathname === "/api/state") return json({ agents: [], profiles: [], settings: { lang, theme: "light" } }); + if (url.pathname === "/api/providers") return json(providers); + if (url.pathname === "/api/groups") return json({ groups: [] }); + if (url.pathname === "/api/plugins") return json({ plugins: [] }); + if (url.pathname === "/api/login/usage") return json({ + "max@example.com": { windows: [{ label: "5h", used: 10, limit: 100 }] }, + "pro@example.com": { windows: [{ label: "5h", used: 30, limit: 100 }] }, + }); + if (url.pathname === "/api/provider/accountweight" && route.request().method() === "POST") { + const body = route.request().postDataJSON(); + posts.push(body); + p.accountWeights = { ...p.accountWeights, [body.account.toLowerCase()]: body.weight }; + return json(providers); + } + if (url.pathname.startsWith("/api/")) return json({}); + const file = path.join(assets, url.pathname === "/" ? "index.html" : url.pathname); + const contentType = { ".html": "text/html", ".js": "text/javascript", ".css": "text/css", ".svg": "image/svg+xml", ".png": "image/png" }[path.extname(file)]; + try { await route.fulfill({ body: await fs.readFile(file), contentType }); } catch { await route.fulfill({ status: 404, body: "" }); } + }; +} + +// the app's own words, as t() gives them +const say = (page, lang, key, vars = {}) => page.evaluate(([lang, key, vars]) => ((lang !== "en" && I18N[lang]?.[key]) || key).replace(/\{(\w+)\}/g, (_, k) => vars[k]), [lang, key, vars]); + +const langs = ["en", "zh", "zh-TW", "ja", "de"]; +for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) { + test(`${engine}: By weight shows each account's weight and share, and a click sets it`, async (t) => { + const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" })); + t.after(() => browser.close()); + for (const [web, width] of [[false, 1000], [false, 560], [true, 390]]) for (const lang of langs) { + const at = `${lang} ${web ? "web " : ""}${width}`; + const context = await browser.newContext({ viewport: { width, height: 900 }, reducedMotion: "reduce" }); + const page = await context.newPage(); + page.setDefaultTimeout(5000); + const errors = []; + page.on("pageerror", (e) => errors.push(e.message)); + const posts = []; + await page.route("**/*", serve(lang, web, posts)); + await page.goto("http://magpie.test/?view=providers"); + await page.locator(".row.provider", { hasText: "Claude Code" }).first().click(); + await page.locator('.editor .acc[data-account-id="off@example.com"]').waitFor(); + const chip = (id) => page.locator(`.editor .acc[data-account-id="${id}"] .key-weight`); + const scrolled = () => page.evaluate(() => [window.scrollY, ...[...document.querySelectorAll("*")].filter((e) => e.scrollTop > 0).map((e) => `${e.className}:${e.scrollTop}`)].join(" ")); + + // Smart: no weights shown + assert.equal(await chip("max@example.com").isVisible(), false, `${at}: a weight under Smart`); + const by = page.locator(".editor").getByRole("button", { name: await say(page, lang, "By weight"), exact: true }); + await by.scrollIntoViewIfNeeded(); + const sc = await scrolled(); + await by.click(); + assert.equal(await scrolled(), sc, `${at}: a click scrolled`); + // the routing's hint names accounts too + await page.locator(".editor .hint", { hasText: (await say(page, lang, "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.")).slice(0, 20) }).first().waitFor(); + assert.equal((await chip("max@example.com").textContent()).trim(), await say(page, lang, "Weight {n} · {share}%", { n: 3, share: 75 }), at); + assert.equal((await chip("pro@example.com").textContent()).trim(), await say(page, lang, "Weight {n} · {share}%", { n: 1, share: 25 }), at); + assert.equal(await chip("off@example.com").count(), 0, `${at}: an account not in use has no share`); + + // each line one line, nothing past its row + const fit = await page.evaluate(() => [...document.querySelectorAll(".editor .accts .acc[data-account-id]")].map((r) => { + const line = r.querySelector(".acc-line"), c = r.querySelector(".key-weight"); + return { who: r.dataset.accountId, h: Math.round(line.getBoundingClientRect().height), over: line.scrollWidth - line.clientWidth, out: c ? Math.round(c.getBoundingClientRect().right - r.getBoundingClientRect().right) : -1 }; + })); + for (const f of fit) { + assert.ok(f.h <= (web ? 48 : 24), `${at}: ${f.who}'s line is one line (${f.h}px)`); + assert.ok(f.over <= 1 && f.out <= 0, `${at}: ${f.who}'s line runs past its row (${f.over}, ${f.out})`); + } + if (process.env.ARTIFACT_DIR && lang === "en") { + await fs.mkdir(process.env.ARTIFACT_DIR, { recursive: true }); + await page.locator(".editor .accts").screenshot({ path: path.join(process.env.ARTIFACT_DIR, `${engine}-${web ? "web-" : ""}${width}-account-weight.png`) }); + } + + // a click edits it in place, Enter saves it + await chip("pro@example.com").click(); + const box = page.locator('.editor .acc[data-account-id="pro@example.com"] .key-weight-in'); + await box.waitFor(); + assert.equal(await box.getAttribute("aria-label"), await say(page, lang, "Account weight"), at); + assert.equal(await scrolled(), sc, `${at}: a click scrolled`); + await box.fill("2"); + await box.press("Enter"); + for (let i = 0; i < 60 && !posts.length; i++) await new Promise((r) => setTimeout(r, 50)); + assert.deepEqual(posts.at(-1), { id: "claude", account: "pro@example.com", weight: 2 }, at); + await chip("pro@example.com").filter({ hasText: await say(page, lang, "Weight {n} · {share}%", { n: 2, share: 40 }) }).waitFor(); + assert.equal((await chip("max@example.com").textContent()).trim(), await say(page, lang, "Weight {n} · {share}%", { n: 3, share: 60 }), at); + // said once state is read again, after the chips are drawn: wait for it + const note = await say(page, lang, "{key} weighs {n}", { key: "pro@example.com", n: 2 }); + await page.waitForFunction((n) => document.querySelector("#status")?.textContent.trim() == n, note).catch(() => {}); + assert.equal((await page.locator("#status").textContent()).trim(), note, at); + + // back to Smart hides them + await page.locator(".editor").getByRole("button", { name: await say(page, lang, "Smart"), exact: true }).first().click(); + assert.equal(await chip("max@example.com").isVisible(), false, `${at}: a weight under Smart`); + assert.deepEqual(errors, [], at); + await context.close(); + } + }); +} diff --git a/internal/gui/tests/key-weight.test.cjs b/internal/gui/tests/key-weight.test.cjs index a66ff5386..c1ee9e90d 100644 --- a/internal/gui/tests/key-weight.test.cjs +++ b/internal/gui/tests/key-weight.test.cjs @@ -104,6 +104,8 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", assert.equal((await chip("aaaaaaaaaa").textContent()).trim(), w.a2); // still shown: the routing picked stays in the editor's draft assert.equal(await chip("bbbbbbbbbb").isVisible(), true); + // said once state is read again, after the chips are drawn: wait for it + await page.waitForFunction((n) => document.querySelector("#status")?.textContent.trim() == n, w.note).catch(() => {}); assert.equal((await page.locator("#status").textContent()).trim(), w.note); if (process.env.ARTIFACT_DIR) await page.locator(".editor .accts").screenshot({ path: path.join(process.env.ARTIFACT_DIR, `${engine}-${lang}-key-weight-rows.png`) }); diff --git a/internal/gui/tests/routing-weight-chip.test.cjs b/internal/gui/tests/routing-weight-chip.test.cjs index a64e7ff80..8ff19d9de 100644 --- a/internal/gui/tests/routing-weight-chip.test.cjs +++ b/internal/gui/tests/routing-weight-chip.test.cjs @@ -78,7 +78,7 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", await page.locator(".rt-prov span").filter({ hasText: chip[lang] }).first().waitFor(); const say = (key, vars = {}) => page.evaluate(([lang, key, vars]) => ((lang !== "en" && I18N[lang]?.[key]) || key).replace(/\{(\w+)\}/g, (_, k) => vars[k]), [lang, key, vars]); assert.equal((await page.locator(".rt-mode").textContent()).trim(), - await say("Requests spread over the keys by the weight set beside each: a key weighing 3 takes three requests for every one a key 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 its key as Stays says.")); + await say("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.")); // the story says whose share went first await page.locator(".rt-steps li.why").first().waitFor(); assert.equal((await page.locator(".rt-steps li.why").first().textContent()).trim(), diff --git a/internal/provider/account_weight.go b/internal/provider/account_weight.go new file mode 100644 index 000000000..70c5aa215 --- /dev/null +++ b/internal/provider/account_weight.go @@ -0,0 +1,91 @@ +package provider + +// An account's weight (rubbzha on X): a subscription routed by weight +// spreads its requests over its accounts as a provider's keys are (#841), +// each by the weight set beside it — a Max account allowing several times +// what a Pro one does takes that many requests for each the Pro one takes, +// so both are used to the end rather than the first run out mid-task. It +// is kept per account by its name in lower case (AccountWeights), as its +// other settings are; one with none weighs 1. Nothing sets one for the +// user, whatever the plan: the plans' allowances aren't told in requests. + +import ( + "fmt" + "strconv" + "strings" +) + +// AccountWeight is the weight of the account user of p under Weighted +// routing, 1 when it has none. The accounts All and AlsoOn give carry it, +// as the gateway routes them; it is read from p alone, with no file read, +// as it is asked for every account of every request weighed. +func (p Provider) AccountWeight(user string) int { + return max(p.AccountWeights[accountKey(user)], 1) +} + +// SetAccountWeight gives the account ref of the subscription id its weight +// under Weighted routing, 1 to MaxKeyWeight; 0 or 1 is the default, kept +// as none. +func SetAccountWeight(id, ref string, weight int) error { + if weight < 0 || weight > MaxKeyWeight { + return fmt.Errorf("an account's weight is 1 to %d, not %d", MaxKeyWeight, weight) + } + p, err := Find(id) + if err != nil { + return err + } + if p.Account == nil { + return fmt.Errorf("%s has keys, not subscription accounts: a key's weight is set on the key", p.Name) + } + r, ok := p.accountRef(ref) + if !ok { + return fmt.Errorf("%s has no account %q", p.Name, ref) + } + k := accountKey(r) + if max(p.AccountWeights[k], 1) == max(weight, 1) { + return nil + } + m := map[string]int{} + for u, w := range p.AccountWeights { + m[u] = w + } + if weight <= 1 { + delete(m, k) + } else { + m[k] = weight + } + p.AccountWeights = m + return Save(*p) +} + +// ParseWeight reads a weight as the CLI takes it: a whole number from 1 +// to MaxKeyWeight, or default (-, 0) for 1. +func ParseWeight(s string) (int, error) { + s = strings.ToLower(strings.TrimSpace(s)) + switch s { + case "default", "-", "0": + return 1, nil + } + n, err := strconv.Atoi(s) + if err != nil || n < 1 || n > MaxKeyWeight { + return 0, fmt.Errorf("a weight is a whole number from 1 to %d, or default, not %q", MaxKeyWeight, s) + } + return n, nil +} + +// normalAccountWeights is m as it is kept: keys in lower case, weights +// within 2–MaxKeyWeight, the default 1 left out; nil for none. +func normalAccountWeights(m map[string]int) map[string]int { + var out map[string]int + for u, w := range m { + u = accountKey(u) + if u == "" || w <= 1 { + continue + } + if out == nil { + out = map[string]int{} + } + out[u] = min(w, MaxKeyWeight) + } + return out +} diff --git a/internal/provider/account_weight_test.go b/internal/provider/account_weight_test.go new file mode 100644 index 000000000..35e9d26d6 --- /dev/null +++ b/internal/provider/account_weight_test.go @@ -0,0 +1,88 @@ +package provider + +import ( + "os" + "strings" + "testing" +) + +// An account's weight is kept by its name in lower case, 1 left out of the +// file, a weight out of 0–MaxKeyWeight or an account the subscription +// hasn't refused, a provider with keys refused (its keys have their own); +// the accounts All gives carry it, as the gateway routes them. +func TestSetAccountWeight(t *testing.T) { + signIn(t) // me@example.com on codex + if err := SetAccountWeight("codex", "Me@Example.com", 4); err != nil { + t.Fatal(err) + } + p, err := Find("codex") + if err != nil { + t.Fatal(err) + } + if w := p.AccountWeight("ME@example.com"); w != 4 { + t.Fatalf("weight %d", w) + } + if p.AccountWeights["me@example.com"] != 4 { + t.Fatalf("kept as %v", p.AccountWeights) + } + carried := false + for _, a := range All() { + if a.ID == "codex" && a.Account != nil && strings.EqualFold(a.Account.User, "me@example.com") { + carried = a.AccountWeight(a.Account.User) == 4 + } + } + if !carried { + t.Fatal("the account All gives doesn't weigh 4") + } + for _, bad := range []int{-1, MaxKeyWeight + 1} { + if err := SetAccountWeight("codex", "me@example.com", bad); err == nil { + t.Fatalf("%d taken", bad) + } + } + if err := SetAccountWeight("codex", "nobody@example.com", 2); err == nil { + t.Fatal("an account it hasn't was weighed") + } + if err := SetAccountWeight("codex", "me@example.com", 1); err != nil { + t.Fatal(err) + } + b, _ := os.ReadFile(Path()) + if strings.Contains(string(b), "accountWeights") { + t.Fatalf("1 was written: %s", b) + } + if err := Save(Provider{ID: "relay", Name: "Relay", Key: "k1", Chat: "http://127.0.0.1:1/v1"}); err != nil { + t.Fatal(err) + } + if err := SetAccountWeight("relay", "k1", 3); err == nil { + t.Fatal("a key provider's account was weighed") + } + if got := normalAccountWeights(map[string]int{" A@x ": 2, "b": 1, "c": 5000}); len(got) != 2 || got["a@x"] != 2 || got["c"] != MaxKeyWeight { + t.Fatalf("normal %v", got) + } +} + +// A Copilot account renamed on GitHub keeps its weight under its new name. +func TestAccountWeightMovesWithRename(t *testing.T) { + signIn(t) + if err := Save(Provider{ID: "copilot", Name: "Copilot", Account: &Account{}, AccountWeights: map[string]int{"old": 3}}); err != nil { + t.Fatal(err) + } + if err := moveAccountSettings("copilot", map[string]string{"Old": "New"}); err != nil { + t.Fatal(err) + } + f, err := read() + if err != nil { + t.Fatal(err) + } + found := false + for _, p := range f.Providers { + if p.ID == "copilot" { + found = true + if p.AccountWeights["new"] != 3 || p.AccountWeights["old"] != 0 { + t.Fatalf("weights after the rename %v", p.AccountWeights) + } + } + } + if !found { + t.Fatal("copilot not saved") + } +} diff --git a/internal/provider/copilot_accounts.go b/internal/provider/copilot_accounts.go index 96658c74e..8514bdfc2 100644 --- a/internal/provider/copilot_accounts.go +++ b/internal/provider/copilot_accounts.go @@ -167,6 +167,7 @@ func moveAccountSettings(id string, moves map[string]string) error { moved = moveKey(p.AccountCaps, from, to) || moved moved = moveKey(p.AccountWindowCaps, from, to) || moved moved = moveKey(p.AccountConcurrency, from, to) || moved + moved = moveKey(p.AccountWeights, from, to) || moved moved = moveKey(p.AccountNames, from, to) || moved } } diff --git a/internal/provider/provider.go b/internal/provider/provider.go index 946dc5b35..25f4e4ad8 100644 --- a/internal/provider/provider.go +++ b/internal/provider/provider.go @@ -167,6 +167,11 @@ type Provider struct { // by its KeyID; 0 there is no limit for it. One not in it takes the // provider's (see LaneLimit). AccountConcurrency map[string]int `json:"accountConcurrency,omitempty"` + // AccountWeights is, for a subscription, each account's weight under + // Weighted routing, by its name in lower case (rubbzha on X: a Max + // account and a Pro one shared by how much more one allows); one not + // in it weighs 1. A key's weight is its own (KeyAccount.Weight). + AccountWeights map[string]int `json:"accountWeights,omitempty"` // QueueLimit is how many requests may wait for a slot of each key or // account at once (#892); one more is turned away as the queue being // full. 0 is no bound. @@ -726,6 +731,7 @@ func (p Provider) clone() Provider { p.AccountWindowCaps = m } p.AccountConcurrency = maps.Clone(p.AccountConcurrency) + p.AccountWeights = maps.Clone(p.AccountWeights) p.Contexts = maps.Clone(p.Contexts) if p.AccountModels != nil { m := make(map[string][]string, len(p.AccountModels)) @@ -809,6 +815,7 @@ func withPicks(a, pk Provider) Provider { a.AccountNames = pk.AccountNames a.MaxConcurrency, a.PinUpstream = pk.MaxConcurrency, pk.PinUpstream a.AccountConcurrency, a.QueueLimit, a.QueueWait = pk.AccountConcurrency, pk.QueueLimit, pk.QueueWait + a.AccountWeights = pk.AccountWeights a.MaxRPM = pk.MaxRPM // what it bills against the official price (#819): an account's editor // sets it as a key provider's does (PaulT on Discord, Codex) @@ -952,7 +959,7 @@ func Save(p Provider) error { if p.ID == "kiro" { key = p.Key } - p = Provider{ID: p.ID, Key: key, Models: p.Models, NoModels: p.NoModels, BestInFamily: p.BestInFamily, RateWindows: p.RateWindows, PickedFrom: p.PickedFrom, Delisted: p.Delisted, Unlisted: p.Unlisted, HiddenDrawers: p.HiddenDrawers, Off: p.Off, Fallback: p.Fallback, Routing: p.Routing, Sink: p.Sink, Affinity: p.Affinity, KeepLogin: p.KeepLogin, KeepLoginAs: p.KeepLoginAs, SwitchOnly: p.SwitchOnly, Contexts: p.Contexts, Family: p.Family, Proxy: p.Proxy, AccountProxies: p.AccountProxies, AccountModels: p.AccountModels, AccountCaps: p.AccountCaps, AccountWindowCaps: p.AccountWindowCaps, CapStop: p.CapStop, CapCareful: p.CapCareful, AccountNames: p.AccountNames, MaxConcurrency: p.MaxConcurrency, AccountConcurrency: p.AccountConcurrency, QueueLimit: p.QueueLimit, QueueWait: p.QueueWait, MaxRPM: p.MaxRPM, PriceRate: p.PriceRate, CountFree: p.CountFree, QuotaRest: p.QuotaRest, QuotaResetAt: p.QuotaResetAt, RestCap: p.RestCap, PinUpstream: p.PinUpstream, NativeCompaction: p.NativeCompaction, PromptAsWritten: p.PromptAsWritten, Unredacted: p.Unredacted, Hidden: hiddenAccount(p.ID), Quiet: quietAccount(p.ID), Tucked: tuckedAccount(p.ID)} + p = Provider{ID: p.ID, Key: key, Models: p.Models, NoModels: p.NoModels, BestInFamily: p.BestInFamily, RateWindows: p.RateWindows, PickedFrom: p.PickedFrom, Delisted: p.Delisted, Unlisted: p.Unlisted, HiddenDrawers: p.HiddenDrawers, Off: p.Off, Fallback: p.Fallback, Routing: p.Routing, Sink: p.Sink, Affinity: p.Affinity, KeepLogin: p.KeepLogin, KeepLoginAs: p.KeepLoginAs, SwitchOnly: p.SwitchOnly, Contexts: p.Contexts, Family: p.Family, Proxy: p.Proxy, AccountProxies: p.AccountProxies, AccountModels: p.AccountModels, AccountCaps: p.AccountCaps, AccountWindowCaps: p.AccountWindowCaps, CapStop: p.CapStop, CapCareful: p.CapCareful, AccountNames: p.AccountNames, MaxConcurrency: p.MaxConcurrency, AccountConcurrency: p.AccountConcurrency, AccountWeights: p.AccountWeights, QueueLimit: p.QueueLimit, QueueWait: p.QueueWait, MaxRPM: p.MaxRPM, PriceRate: p.PriceRate, CountFree: p.CountFree, QuotaRest: p.QuotaRest, QuotaResetAt: p.QuotaResetAt, RestCap: p.RestCap, PinUpstream: p.PinUpstream, NativeCompaction: p.NativeCompaction, PromptAsWritten: p.PromptAsWritten, Unredacted: p.Unredacted, Hidden: hiddenAccount(p.ID), Quiet: quietAccount(p.ID), Tucked: tuckedAccount(p.ID)} } else { p.AccountProxies = keyProxies(p) // a provider of keys proxies each key apart if subscriptionID(p.ID) && !stored(p.ID) { @@ -1489,6 +1496,7 @@ func normalize(p Provider) Provider { p.MaxConcurrency = new(int) } p.AccountConcurrency = normalAccountConcurrency(p.AccountConcurrency) + p.AccountWeights = normalAccountWeights(p.AccountWeights) p.QueueLimit, p.QueueWait = min(max(p.QueueLimit, 0), MaxQueueLimit), min(max(p.QueueWait, 0), MaxQueueWait) p.MaxRPM = min(max(p.MaxRPM, 0), MaxRPMLimit) p.QuotaRest = min(max(p.QuotaRest, 0), MaxQuotaRest) diff --git a/internal/provider/routing.go b/internal/provider/routing.go index 955e4d8fa..534c7cdb1 100644 --- a/internal/provider/routing.go +++ b/internal/provider/routing.go @@ -26,7 +26,9 @@ const ( LeastUsed = "usage" Pace = "pace" // Weighted spreads a provider's requests over its keys by each key's - // weight (KeyAccount.Weight, #841), smoothly: 3 and 1 go a, a, b, a… + // weight (KeyAccount.Weight, #841), or a subscription's over its + // accounts by each account's (AccountWeights), smoothly: 3 and 1 go + // a, a, b, a… Weighted = "weight" // FreeFirst spends what costs nothing first: the models its vendor // serves at no cost to the subscription's allowance or credits, before diff --git a/site/public/docs/ja/start.html b/site/public/docs/ja/start.html index 6dd94a227..5c015f3df 100644 --- a/site/public/docs/ja/start.html +++ b/site/public/docs/ja/start.html @@ -166,7 +166,7 @@

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

-

プロバイダの行を開き、使うアカウントやキーをすべてチェックします。Routing はリクエストをそれらにどう振り分けるかを決めます:Smart(デフォルト)、In order、In turn、Least used first、Weekly pace、Speed first(最近いちばん速く応答したキーが先)。Fallback には、プロバイダのクォータ切れ、レート制限、ダウン時に代わりに使うモデルを並べます。

+

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

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

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

diff --git a/site/public/docs/start.html b/site/public/docs/start.html index 871e77e88..5299e2c89 100644 --- a/site/public/docs/start.html +++ b/site/public/docs/start.html @@ -166,7 +166,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, In turn, Least used first, Weekly pace 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, 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.

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.

diff --git a/site/public/docs/zh/start.html b/site/public/docs/zh/start.html index a440f6dec..62e17d7fd 100644 --- a/site/public/docs/zh/start.html +++ b/site/public/docs/zh/start.html @@ -166,7 +166,7 @@

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

-

展开供应商那一行,勾选要用的每个账号或密钥。路由 决定请求怎么分给它们:智能(默认)、按顺序、轮流、用量少的优先、重置前用完 或 速度优先(最近回答最快的密钥先用)。备用 里列出这个供应商额度用完、被限流或不可用时改用的模型。

+

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

跨供应商的同一个模型

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