diff --git a/docs/subsystems/gateway-routing.md b/docs/subsystems/gateway-routing.md index 0e6ee0999..a7e99784f 100644 --- a/docs/subsystems/gateway-routing.md +++ b/docs/subsystems/gateway-routing.md @@ -36,6 +36,7 @@ backfilled; see [Gateway Session Aggregation](gateway-sessions.md). | 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`). `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) | +| Accounts at once | A provider's `MaxAccounts` (01huadalang on Discord: three ZCode accounts used at once got the exit address refused with a 405, two didn't) is how many of its keys or accounts take requests at the same time: `provider.AtOnce()` is the user's own value, else what its plugin declares (`maxAccounts` on the auth hook or in package.json's `magpie`, read by host.js `atOnceOf`; zcode says 2), else no limit; the user's 0 is no limit over the plugin's. `perKeyBarred` keeps the first N in the user's own order (`rank`, so a dragged list counts), preferring ones not resting, and hands the rest to `keepAtOnce`'s reserves: they go after everything else as asides with `candidate.reserve` set (`Weighed.Reserve`), so whatever the routing mode, a reserve is asked only once the kept ones failed or rest, and a kept one that rests gives its seat to the first reserve on the next request. Three guards keep a reserve from being reached for anything else: `laneMate` never spills a full lane onto one, a full queue (`laneErr`) drops the provider's reserves before passing on (`dropReserves`), so the request is turned away with the 429 instead, and session affinity keeps no conversation on a reserve once the kept ones can take it (`affine`'s "reserve"; Strict still holds). Leak known: a failure that rests nobody (a 5xx on one try) still passes that one request to the reserve, as it does to any next candidate. Set in the provider editor's Advanced (Accounts at once, beside Concurrency) or with `magpie provider at-once`; Routing's row says "in reserve · {n} at once" (`TestAtOnceKeepsFirstInUserOrder`, `TestAtOnceFullLaneWaitsForTheKept`, `TestAtOnceReserveTakesOverAndGivesBack`, `provider-at-once.test.cjs`). | [`fallback.go`](../../internal/gateway/fallback.go), [`concurrency.go`](../../internal/gateway/concurrency.go), [`internal/provider/concurrency.go`](../../internal/provider/concurrency.go) | | Sink | With `Sink` on, a key or account that answers 429 while it still has quota goes to the back, behind every one not rate limited since. Held in memory until restart, or until its rest is lifted by hand (Try now, `Unrest` calls `unsink`, `UnrestAll` `unsinkAll` for the key and each of its models), which puts it back in its place (`TestTryNowPutsASunkAccountBack`, `TestUnrestAllUnsinksTheModels`). Another magpie's model rate limited there, whose rest is the model's alone (`remoteModelRest`), sinks alone too (`restID`), and `sunkAt` reads a candidate's model before its key, so the remote's other models keep their place (#2167, ggbdpq; `TestRemoteMagpieRateLimitSinksTheModel`, `TestMagpieAddedByHandRateLimitSinksTheModel`). A group in a group sinks by its own Sink, within its own order (`sinkOwn`, #2255), and the group asked for then sinks the whole by its own; `TestNestedGroupSinksItsOwnOrder`. | [`sink.go`](../../internal/gateway/sink.go) | | 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) | | Affinity | A conversation stays with the key or account that answered it, so the vendor's prompt cache is read again. Modes: auto (""), `session`, `turn`, `off`, `strict`. Stored in `affinity.json` next to `providers.json`. A conversation is kept by its id (`conversationID`), and a Claude Code subagent's apart from its lead's by `x-claude-code-agent-id` (`stickKey`): Claude Code sends the session's id with its subagents' requests too, and a subagent's answer took the lead's stick over, so the lead's next turn was judged by the subagent's cache and moved to another account, where its whole conversation was written again (slkassinthehood on X, `TestClaudeConversationKeepsItsAccountsCache`). Behind a remote magpie, the key or account is the remote's key and the provider there that serves the model, its id's first part (`remoteUpstream`, `candidate.vendor`, `sameVendor`): the remote is one key here, but each of its providers keeps its own cache and seals, so a conversation is kept, held strictly, told its sealed reasoning was refused and given its native compaction's reader by that pair, as the same group on the remote does (fremontdango on Discord: a group of one model from two of the remote's providers kept a conversation on the second as the same account when the first was gone, and a strict one failed over to it; `TestRemoteMagpieStrictKeepsTheRemotesProvider`, `TestRemoteMagpieOtherProviderIsNotTheSameAccount`). A remote's group is one vendor by its whole id, its own routing deciding inside it; a model named without a provider is the key alone. Lanes and requests a minute still go by the key here, the limits the user set on it. | [`affinity.go`](../../internal/gateway/affinity.go) | diff --git a/docs/subsystems/providers-accounts.md b/docs/subsystems/providers-accounts.md index 761b5cace..e4dfc5eaf 100644 --- a/docs/subsystems/providers-accounts.md +++ b/docs/subsystems/providers-accounts.md @@ -33,6 +33,7 @@ keys and accounts per request is in [Gateway routing and fallback](gateway-routi | Model picks | `Models` are the models the user picked for agents; none means the vendor's list, up to 24 (`Exposed`), unless the user chose Select none (`NoModels`, `magpie provider models none`): then none of its models is served, not to agents, not to any routing group (auto groups included), not by a `provider/model` id, not as a classifier, while its balance and usage are still read (`ServesNone`, #1818). Codex's own list at `/backend-api/codex/models` drops the ChatGPT account's visible models too, as spawn_agent's list of them does, and the list's ETag changes so a running Codex asks again (`CodexNativePicked` in [`codex_models.go`](../../internal/provider/codex_models.go), #2530); the hidden ones Codex runs jobs of its own on (codex-auto-review, gpt-reserve) and other providers' models stay. The editor's serves control names it Usage only, beside Vendor's list and Picked only, and the card says "usage only" (#2068); Picked only from there picks the models the vendor's list serves, to unpick from. A file without `noModels` reads as before, and a pick clears it. With nothing picked and Select none off, Best in family (`BestInFamily`, `magpie provider models best`, the editor's fourth option, Steven on Discord) serves only the newest model of each family the vendor lists, up to 24: the family is the id with its version numbers taken out, a dated snapshot counts as its alias, and sizes and suffixes (-mini, -pro, -8b) stay in the name (`FamilyOf`, `BestInFamily` in [`family.go`](../../internal/catalog/family.go)). A newer one the vendor lists later takes the old one's place with nothing saved. Codex's own list narrows the same way (`CodexNativePicked`). An older one named by its `provider/model` id is still served, as an unpicked one is under Picked only. A pick or Select none clears it, and a file without `bestInFamily` reads as before. `Save` keeps beside new picks the models listed then (`PickedFrom`, `listedWith`), and the same picks saved again keep it. When the picks held every model listed then, one the vendor lists since is served first beside them (`withNewlyListed`, `Picks`); one listed then and left unpicked stays out. Picks saved before `PickedFrom` was kept are taken to hold every model when they hold every one released up to the newest of them (models.dev's `release_date`), so a Claude account whose user picked them all is served Haiku 5.5 (wakaka). The editor and the TUI start from `Picks`, so a later Save keeps the new model. While some picks are set aside (the list is known to be short), a save with new picks keeps the models the earlier `PickedFrom` had beside those listed now, so a model the user saw and left unpicked isn't new when that list has it again; a list short of no pick is taken as it is. A pick a list fetched again stops listing (`Refetch`, `KeepListsFresh`, and a plugin's hourly `KeepPluginsListed`) leaves `Models` for `Delisted` (`dropGonePicks`), not served, and goes back among the picks when a later list has it (`relistPicks`): Our Free Model's plugin lists its account channels' models only once its service has read them after a restart, and its free pools only while they answer, so each magpie update had its user pick every model again (多喝热水 on Discord). Every save keeps `Delisted` but for what it picks again (`delistedWith`); Select none clears it. A provider whose every pick is in `Delisted` serves none of its models (`waitsForPicks`), not the vendor's list. `KeepPluginsListed` asks again after `relistSoon` (5 minutes) when a list left a pick out. `TestPluginPicksComeBackWithTheirList`, `TestEveryPickDelistedServesNone` and `TestRelayPicksComeBackWithTheirList` cover it. | [`models.go`](../../internal/provider/models.go), [`provider.go`](../../internal/provider/provider.go) | | List schedule and rules | A provider of the user's own (not an account, a plugin's or a decision-only one) can set `RefreshEvery` (`magpie provider refresh-every 6h`, or 1d, or off, at least 10m) and `AutoInclude` (`magpie provider auto-include 'gpt-*' 're:claude-.*'`, or none; a glob with `*`, or `re:` matching the whole id, both in any case (`compilePattern`; `(?-i)` inside a `re:` makes case matter); a plain id is refused) (#2135). The gateway (`magpie serve` or the app) looks each minute and fetches a list once `Fetched` is that old, through the same `Refetch` as Fetch models (`KeepListsFresh`); a failed fetch waits `min(every, 15m)`. `RefetchTaking` adds to the picks a model the fetch newly lists that a rule matches (`takeMatching`), starting from what is served now (`Exposed`), so nothing served is taken away and a model the user unticks stays out (it is not new to the next fetch). Setting the rules takes the current list's matches. Every save that doesn't set them keeps them, the window's editor among them; the editor has no fields for them yet. A Remote magpie with no `RefreshEvery` is fetched every 10m (`RemoteMagpieEvery`, `RefreshSchedule`), so a model the other magpie lists later (ZCode's GLM-5.3-Trial once its plugin read the gift, 6igsteven on Discord) is served without Fetch models; `off` set on it is kept as `"off"` and asks it only when told (`TestRemoteMagpieListFollowsTheOtherMagpie`). | [`autolist.go`](../../internal/provider/autolist.go), [`models.go`](../../internal/provider/models.go), [`providers_cli.go`](../../internal/cli/providers_cli.go) | | Keys | Several keys per provider. Requests go to the first key that is on; the gateway moves on when it is out or rate limited. `Key` stays the first, so other code reads it as before. A key can be made for one protocol (`KeyProtocol`). A key made for a protocol its provider has no URL for is skipped (`perKeyBarred`); when every key is, the provider is still tried whole on the URLs it has, and the candidate carries `noURL` so it isn't quiet: Routing's row (`Weighed.NoURL`) says "key set to {api} only, no {api} URL · sent on the others", and the editor's key row shows a "No {api} URL" chip (`keyLacksURL`; #1702, `TestKeyForAProtocolWithNoURLIsSaid`, `key-nourl.test.cjs`). A key's value can be replaced in place (`ReplaceKey`, #1869: a key rotated at the vendor): it keeps its name, place, protocol, weight and on or off, and what was set for it by its fingerprint (`AccountModels`, `AccountProxies`, `AccountConcurrency`) and the gateway keys held to it (`access.ReplaceAccount`) move to the new one; the GUI's `keys/replace` also lifts its rests (`UnrestAll`). Its past requests stay under the old fingerprint, by the same name. A provider may hold thousands of keys (@NetRozee on X: a thousand froze magpie). Nothing goes over its keys once for each key: `KeysOn` drops a repeat by a set, a row's rest keys come from `RestKeys` (whether several are on, found once), and whether each key serves a model from `Serving`, which reads the lists once and keeps each model's keys as a set until the lists are read anew (`keyLists`). `KeysListed` and `ListsRead` count them for the tests (`TestProviderInfoListsKeysOnce`, `TestPerKeyReadsListsOnce`). A provider's keys have their balances, plans and remote limits read `keyReadsAtOnce` (8) at a time (`keySlots`); other providers' beside them. The editor's per-key proxy lines fold as its Accounts list does (`proxyLines`, `provider-many-keys-proxy.test.cjs`). Asking a key's models (`fetchPerKey`) still goes one key after another. | [`keys.go`](../../internal/provider/keys.go) | +| Accounts at once | `MaxAccounts *int` is the user's own count of keys or accounts taking requests at the same time: nil takes the plugin's (`PluginAtOnce`: `maxAccounts` on the plugin's auth hook or package.json `magpie`, host.js `atOnceOf`), 0 is no limit, saved clamped to 0..`MaxLimit`; a subscription's is kept with its picks (`withPicks`). `AtOnce()` answers the one in force, `SetAtOnce` sets it (`magpie provider at-once`, the editor's Accounts at once; GUI save leaves it as it was when the body has none). The gateway's use is in [gateway routing](gateway-routing.md) (`TestAtOnce`, `TestAtOnceSave`, `TestAtOnceCmd`). | [`concurrency.go`](../../internal/provider/concurrency.go) | | A provider with no key | A provider of the user's own saves, imports and is `Ready` with no key when it is a preset with `NoKey` or its host is on this computer or the user's own network (`keyOptional`, `ownNetwork`): localhost, a loopback, private, link-local or carrier-grade NAT (Tailscale's 100.64/10) address, or a `.local` name, read from the URL alone with no lookup. A company's keyless relay at a LAN address is taken as a local server is (iSnow_999 on X: a Codex relay at http://:8080 was left out of a CC Switch import as "it has no API key"); a keyless address on the internet still needs its key. With no key it is asked as one on 127.0.0.1 is: a Responses request carries no `Authorization`. | [`provider.go`](../../internal/provider/provider.go), [`importapps.go`](../../internal/provider/importapps.go), [`import_lan_test.go`](../../internal/provider/import_lan_test.go) | | A key a provider | One vendor's keys saved a provider each — an app that keeps an entry a key, as CC Switch does, imported (yuluo_yx on X: "NVIDIA #001" to "#600" at one address, "Mistral #0001"…) — are folded into one provider with those keys (`FoldCopies` at start-up, `foldAdded` after `ImportFromApps`): hundreds of copies listed every model hundreds of times in every agent's picker and found group, and 3,000 made `/api/state` 86 MB. At start-up only copies by name are folded: a base name and that name with a number after it (`copyBase`: " #12", or `freeName`'s " 2"), one at least numbered; an import folds what it added whatever their names. Either way they must be alike in all but their key (`foldShape`: the provider with its id, name, keys and on/off left out), what the settings say of their models (`modelPrefs`) and where they are named (`foldRefs`: Visible, the agents' picked, hidden and ordered models, the groups, the providers falling back to them), so one key shown to one agent and another to another stays apart. Not folded: a subscription's, a hidden one, one without a key, Vertex, one with a StepFun sign-in of its own. The first on, in the providers' order, takes the rest in; its name becomes the base and its key is named its old name. Each other is a key in order, named its name, off if it was off (all off: the provider is off, its keys on); its id goes in `Was`, so its calls count with the provider by their key (`ProviderKeyID` is the key's fingerprint, unchanged) and a model picked by the old id still reaches it. Group members, rules, weights and fallbacks naming them name the provider once; their per-model settings and fetched lists go; balance and window history kept by their id moves to their key's name (`foldHistories`). A providers.json that doesn't parse is left alone. It runs at every start and writes nothing when there is nothing to fold. `TestFoldCopies`, `TestFoldCopiesIntoOneOn`, `TestFoldCopiesUnreadable`, `TestImportFoldsAKeyAnEntry`. | [`fold.go`](../../internal/provider/fold.go), [`importapps.go`](../../internal/provider/importapps.go), [`main.go`](../../internal/cli/main.go) | | A key's plan | A vendor whose plans take keys of their own (`PresetDef.KeyPlans`: zhipu, zai, stepfun, stepfun-cn, xiaomi, baidu-qianfan, tencent-cloud, huaweicloud, volcengine, siliconflow) lets each key say which of the preset's Regions it is for (`KeyAccount.Plan`, `Provider.KeyPlan` for the first; yckonnnn on X: a Volcengine pay-as-you-go key and an Agent Plan key in one provider). No plan, or the provider's own, is the provider's plan, as every key was before, and is stored as none (`SetKeyPlan`, the GUI's `keys/plan`). `WithKey` moves a key's copy to its plan's endpoints (`atKeyPlan`: chat, Responses, Anthropic, decide, key page, docs and catalog; a provider at a host of its own, a mirror or a test's fake vendor, keeps that host) and marks it a key's view (`keyView`), so nothing judges plans on it again. Only when the keys in use are on more than one plan (`PlansMixed`) does anything differ: the model list is each key's plan's (`fetch` goes to `fetchPerKey`; a plan with no list of its own, `planOnly`, is its preset list without a request, so Ark's Coding and Agent Plans ask nothing while pay as you go asks `/api/v3/models` with its own key); plan media (`planMedia`) are every plan's; each key serves its plan's models alone (`PlanServing`, read by the gateway's `perKeyBarred`; a model set for the key in `AccountModels` it serves); plan windows (`PlanQuotas`), Volcengine's and Tencent Cloud's access-key windows (`planViews`) and balances (`balance.go`) are read at each key's plan. Volcengine's keys carry nothing that says their plan, so none is guessed; Xiaomi's `tp-`, Tencent's `sk-tp-`, MiniMax's `sk-cp-` and Bailian's `sk-sp-` prefixes are documented in code but not used to set a plan. The editor's key row has a plan chip (`planPicker`, the app's own menu) while the provider has several keys or the key has a plan. Not done: a gateway key held to some keys of a mixed provider's video (`videoAsker`) may pick another key's plan; a mixed provider whose own plan has no balance source while a key's plan has is not read; StepFun's plan windows are a sign-in per site, unchanged. `TestKeyPlanEndpoints`, `TestKeyPlanServing`, `TestKeyPlanOldConfigsUnchanged`, `TestSetKeyPlan`, `TestKeyPlanModelList`, `TestKeyPlanViews`, `key-plan.test.cjs`. | [`key_plans.go`](../../internal/provider/key_plans.go), [`keys.go`](../../internal/provider/keys.go), [`models.go`](../../internal/provider/models.go) | diff --git a/internal/cli/account_concurrency_cli_test.go b/internal/cli/account_concurrency_cli_test.go index 8d3de974a..1cab941d6 100644 --- a/internal/cli/account_concurrency_cli_test.go +++ b/internal/cli/account_concurrency_cli_test.go @@ -127,3 +127,54 @@ func TestRPMCmd(t *testing.T) { t.Fatalf("off: %d", n) } } + +// magpie provider at-once sets how many of a provider's keys take requests +// at the same time (01huadalang on Discord, ZCode), off for no limit and +// default for the plugin's; a number out of range is an error. +func TestAtOnceCmd(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", "") + if err := provider.Save(provider.Provider{ID: "zc", Name: "ZC", Key: "k1", Chat: "http://127.0.0.1:1/v1"}); err != nil { + t.Fatal(err) + } + set := func() *int { + p, err := provider.Find("zc") + if err != nil { + t.Fatal(err) + } + return p.MaxAccounts + } + if err := providerCmd([]string{"provider", "at-once", "zc", "2"}); err != nil { + t.Fatal(err) + } + if n := set(); n == nil || *n != 2 { + t.Fatalf("set: %v, want 2", n) + } + if err := providerCmd([]string{"provider", "at-once", "zc"}); err != nil { + t.Fatal(err) + } + for _, bad := range [][]string{{"-1"}, {"20000"}, {"x"}, {"2", "3"}} { + if err := providerCmd(append([]string{"provider", "at-once", "zc"}, bad...)); err == nil { + t.Fatalf("%v taken", bad) + } + } + if n := set(); n == nil || *n != 2 { + t.Fatalf("after refused ones: %v, want 2", n) + } + if err := providerCmd([]string{"provider", "at-once", "zc", "off"}); err != nil { + t.Fatal(err) + } + if n := set(); n == nil || *n != 0 { + t.Fatalf("off: %v, want 0 kept as the user's own", n) + } + if err := providerCmd([]string{"provider", "at-once", "zc", "default"}); err != nil { + t.Fatal(err) + } + if n := set(); n != nil { + t.Fatalf("default: %v, want none of the user's own", *n) + } +} diff --git a/internal/cli/providers_cli.go b/internal/cli/providers_cli.go index 401234392..cdca22d70 100644 --- a/internal/cli/providers_cli.go +++ b/internal/cli/providers_cli.go @@ -92,6 +92,10 @@ const providerUsage = `usage: past either a request is turned away with a 429 (0: no bound) magpie provider rpm [n|off] how many requests each account or key sends the vendor in any minute; one more waits for room, up to 2 minutes, then is turned away with a 429 + magpie provider at-once [n|off|default] + how many of its accounts or keys take requests at the same time, the first + in the list; the next takes over when one runs out or fails (off: no limit, + default: what its plugin says) magpie provider quota-rest [30m|6h|7d|until 08:00|until 00:00+08:00|default] how long a key sits out once the vendor says it is out of its allowance without saying when it is back (default: 15 minutes; at most 8 days), @@ -630,6 +634,8 @@ func providerCmd(args []string) error { return queueCmd(rest) case "rpm": return rpmCmd(rest) + case "at-once", "accounts-at-once": + return atOnceCmd(rest) case "refresh-every": return refreshEveryCmd(rest) case "auto-include": @@ -1850,6 +1856,47 @@ func rpmCmd(rest []string) error { return nil } +// atOnceCmd shows, or sets, how many of a provider's accounts or keys take +// requests at the same time (01huadalang on Discord: three ZCode accounts +// at once got the address refused with a 405, two didn't). The others wait +// in reserve, in the list's order. +func atOnceCmd(rest []string) error { + usage := fmt.Errorf("magpie provider at-once [n|off|default]") + if len(rest) < 1 || len(rest) > 2 { + return usage + } + p, err := provider.Find(rest[0]) + if err != nil { + return err + } + if len(rest) > 1 { + var n *int + switch s := strings.ToLower(strings.TrimSpace(rest[1])); s { + case "default", "plugin": + case "off", "none", "no", "-": + n = new(int) + default: + v, err := strconv.Atoi(s) + if err != nil { + return fmt.Errorf("accounts at once is a whole number, off or default, not %q", rest[1]) + } + n = &v + } + if err := provider.SetAtOnce(p.ID, n); err != nil { + return err + } + if p, err = provider.Find(p.ID); err != nil { + return err + } + } + if n := p.AtOnce(); n > 0 { + fmt.Printf("%s · %d of its accounts or keys take requests at once, the first in the list; the others wait in reserve\n", p.Name, n) + } else { + fmt.Printf("%s · every account or key takes requests\n", p.Name) + } + return nil +} + // quotaRestCmd shows, or sets, how long a provider's keys sit out once the // vendor says one is out of its allowance without saying when it is back // (#1772: Ollama Cloud's weekly limit, asked again every 15 minutes). diff --git a/internal/gateway/accounts_at_once_test.go b/internal/gateway/accounts_at_once_test.go new file mode 100644 index 000000000..2f6add4b4 --- /dev/null +++ b/internal/gateway/accounts_at_once_test.go @@ -0,0 +1,230 @@ +package gateway + +import ( + "context" + "fmt" + "io" + "net/http" + "net/http/httptest" + "slices" + "strings" + "sync" + "testing" + "time" + + "github.com/yetone/magpie/internal/provider" +) + +// 01huadalang on Discord: ZCode bans the address three of its accounts are +// used from at once, while two are let be. A provider's accounts at once +// (provider.AtOnce) keeps the first that many in the user's own order, +// whatever routing then weighs them by, and holds the rest back as +// reserves, after them; one resting gives its seat to the next. +func TestAtOnceKeepsFirstInUserOrder(t *testing.T) { + fresh(t) + two := 2 + for _, mode := range []string{"", provider.Ordered, provider.Rotate, provider.LeastUsed} { + p := provider.Provider{ID: "once" + mode, Name: "Once", Chat: "https://example.invalid/v1", Key: "first", Keys: []provider.KeyAccount{{Key: "second"}, {Key: "third"}}, Routing: mode, MaxAccounts: &two} + if err := provider.Save(p); err != nil { + t.Fatal(err) + } + if err := provider.SetAccountOrder(p.ID, []string{provider.KeyID("third"), provider.KeyID("first"), provider.KeyID("second")}); err != nil { + t.Fatal(err) + } + got, err := provider.Find(p.ID) + if err != nil { + t.Fatal(err) + } + split := func() (kept []string, reserve string) { + t.Helper() + cs, pl := (&Server{}).plan(*got, "model", provider.Chat) + if len(cs) != 3 || len(pl.order) != 3 { + t.Fatalf("mode=%q: %d candidates, order %+v", mode, len(cs), pl.order) + } + for i, w := range pl.order { + id := w.ID[len(p.ID)+1:] + switch { + case w.Reserve == 0 && cs[i].reserve == 0: + if reserve != "" { + t.Fatalf("mode=%q: %s kept after the reserve %s", mode, id, reserve) + } + kept = append(kept, id) + case w.Reserve == 2 && cs[i].reserve == 2 && w.Aside: + reserve = id + default: + t.Fatalf("mode=%q: %s reserve %d/%d aside %v", mode, id, w.Reserve, cs[i].reserve, w.Aside) + } + } + slices.Sort(kept) + return kept, reserve + } + want := []string{provider.KeyID("first"), provider.KeyID("third")} + slices.Sort(want) + if kept, reserve := split(); !slices.Equal(kept, want) || reserve != provider.KeyID("second") { + t.Fatalf("mode=%q: kept %v, reserve %s; want the first two as dragged, third and first", mode, kept, reserve) + } + // the first in the list resting: the next takes its seat + restingUntil.Lock() + k := p.ID + "#" + provider.KeyID("third") + restingUntil.m[k] = time.Now().Add(time.Hour) + restingUntil.note[k] = Rest{Why: failOther, Status: 500, Key: k} + restingUntil.Unlock() + want = []string{provider.KeyID("first"), provider.KeyID("second")} + slices.Sort(want) + if kept, reserve := split(); !slices.Equal(kept, want) || reserve != provider.KeyID("third") { + t.Fatalf("mode=%q, third resting: kept %v, reserve %s", mode, kept, reserve) + } + restingUntil.Lock() + delete(restingUntil.m, k) + restingUntil.Unlock() + } + // with no limit, every one is routed over + p := provider.Provider{ID: "every", Name: "Every", Chat: "https://example.invalid/v1", Key: "first", Keys: []provider.KeyAccount{{Key: "second"}, {Key: "third"}}} + if _, pl := (&Server{}).plan(p, "model", provider.Chat); len(pl.order) != 3 || slices.ContainsFunc(pl.order, func(w Weighed) bool { return w.Reserve > 0 || w.Aside }) { + t.Fatalf("no limit: %+v", pl.order) + } +} + +// atOnceKeys records which key each request came with, and lets a slowVendor +// answer it. +type atOnceKeys struct { + mu sync.Mutex + keys []string + next http.Handler +} + +func (b *atOnceKeys) ServeHTTP(w http.ResponseWriter, r *http.Request) { + b.mu.Lock() + b.keys = append(b.keys, strings.TrimPrefix(r.Header.Get("Authorization"), "Bearer ")) + b.mu.Unlock() + b.next.ServeHTTP(w, r) +} + +func (b *atOnceKeys) seen() []string { + b.mu.Lock() + defer b.mu.Unlock() + return slices.Clone(b.keys) +} + +// A full lane never hands a request to a reserve: with one request at once +// on each key and two keys at once, a third request waits for a slot of +// the two rather than going to the third key (laneMate gave way to it, so +// In order still spread over every account under load), and once both +// queues are full too the next is turned away, not sent to the third. +func TestAtOnceFullLaneWaitsForTheKept(t *testing.T) { + fresh(t) + v := &slowVendor{release: map[string]chan struct{}{}, quit: make(chan struct{})} + rec := &atOnceKeys{next: v} + up := httptest.NewServer(rec) + t.Cleanup(up.Close) + t.Cleanup(func() { close(v.quit) }) + one, two := 1, 2 + if err := provider.Save(provider.Provider{ID: "zc", Name: "ZC", Key: "k1", Keys: []provider.KeyAccount{{Key: "k2"}, {Key: "k3"}}, Models: []string{"m"}, Chat: up.URL + "/v1", + Routing: provider.Ordered, MaxConcurrency: &one, MaxAccounts: &two, QueueLimit: 1}); err != nil { + t.Fatal(err) + } + g := newLaneRig(t) + waiting := func() int { + n := 0 + for _, l := range g.s.Lanes() { + n += l.Waiting + } + return n + } + g.send(context.Background(), "/v1/chat/completions", "zc/m", "a") + within(t, "a at the vendor", func() bool { return len(v.seen()) == 1 }) + g.send(context.Background(), "/v1/chat/completions", "zc/m", "b") + within(t, "b at the vendor", func() bool { return len(v.seen()) == 2 }) + g.send(context.Background(), "/v1/chat/completions", "zc/m", "c") + within(t, "c waiting for a slot", func() bool { return waiting() == 1 }) + if got := rec.seen(); slices.Contains(got, "k3") { + t.Fatalf("keys asked %v: the reserve k3 was sent a request for want of a slot", got) + } + // k1's queue full, d waits in k2's + g.send(context.Background(), "/v1/chat/completions", "zc/m", "d") + within(t, "d waiting for a slot", func() bool { return waiting() == 2 }) + // both full: e is turned away, never sent to the reserve + g.send(context.Background(), "/v1/chat/completions", "zc/m", "e") + if r := g.reply(); r.tag != "e" || r.status != http.StatusTooManyRequests { + t.Fatalf("e = %+v, want turned away with a 429", r) + } + if got := rec.seen(); slices.Contains(got, "k3") { + t.Fatalf("keys asked %v: the reserve k3 was sent a request turned away by a full queue", got) + } + for _, tag := range []string{"a", "b", "c", "d"} { + close(v.gate(tag)) + } + for range 4 { + if r := g.reply(); r.err != nil || !strings.Contains(r.body, "[DONE]") { + t.Fatalf("reply %+v", r) + } + } + if v.most != 2 { + t.Fatalf("most out at once = %d, want 2", v.most) + } + if got := rec.seen(); slices.Contains(got, "k3") || len(got) != 4 { + t.Fatalf("keys asked %v, want k1 and k2 only", got) + } + within(t, "every slot given back", func() bool { return len(g.s.Lanes()) == 0 }) +} + +// atOnceVendor answers each request by its key: 429 for those in fail, +// else a reply naming the key. +type atOnceVendor struct { + mu sync.Mutex + fail map[string]bool + asked []string +} + +func (v *atOnceVendor) ServeHTTP(w http.ResponseWriter, r *http.Request) { + io.Copy(io.Discard, r.Body) + k := strings.TrimPrefix(r.Header.Get("Authorization"), "Bearer ") + v.mu.Lock() + v.asked = append(v.asked, k) + fail := v.fail[k] + v.mu.Unlock() + w.Header().Set("Content-Type", "application/json") + if fail { + w.WriteHeader(http.StatusTooManyRequests) + io.WriteString(w, `{"error":{"message":"rate limited","type":"rate_limit"}}`) + return + } + fmt.Fprintf(w, `{"id":"x","object":"chat.completion","model":"m","choices":[{"index":0,"message":{"role":"assistant","content":"from %s"},"finish_reason":"stop"}]}`, k) +} + +// A reserve takes the request once every key kept has failed, and keeps +// no conversation: once the kept are back, the conversation's next turn +// goes back to the first of them, even under Stays: Session, which keeps +// a conversation on whoever answered it. +func TestAtOnceReserveTakesOverAndGivesBack(t *testing.T) { + fresh(t) + v := &atOnceVendor{fail: map[string]bool{"k1": true, "k2": true}} + up := httptest.NewServer(v) + t.Cleanup(up.Close) + two := 2 + if err := provider.Save(provider.Provider{ID: "zc", Name: "ZC", Key: "k1", Keys: []provider.KeyAccount{{Key: "k2"}, {Key: "k3"}}, Models: []string{"m"}, Chat: up.URL + "/v1", + Routing: provider.Ordered, Affinity: provider.AffinitySession, MaxAccounts: &two}); err != nil { + t.Fatal(err) + } + s := New() + msgs := `{"role":"user","content":"hi"}` + code, body := postAs(t, s, "s1", `{"model":"zc/m","messages":[`+msgs+`]}`) + if code != 200 || !strings.Contains(body, "from k3") { + t.Fatalf("with k1 and k2 refusing: %d %s", code, body) + } + // the kept two are back, their rests over + v.mu.Lock() + v.fail = nil + v.mu.Unlock() + restingUntil.Lock() + restingUntil.m = map[string]time.Time{} + restingUntil.Unlock() + msgs += `,{"role":"assistant","content":"from k3"},{"role":"user","content":"more"}` + code, body = postAs(t, s, "s1", `{"model":"zc/m","messages":[`+msgs+`]}`) + if code != 200 || !strings.Contains(body, "from k1") { + t.Fatalf("next turn, the kept back: %d %s; want k1, not kept on the reserve k3", code, body) + } + if r := s.trace.routes[len(s.trace.routes)-1]; r.Affinity == nil || r.Affinity.Why != "reserve" { + t.Fatalf("affinity %+v, want reserve", r.Affinity) + } +} diff --git a/internal/gateway/affinity.go b/internal/gateway/affinity.go index aa10cfe99..948ff6266 100644 --- a/internal/gateway/affinity.go +++ b/internal/gateway/affinity.go @@ -579,6 +579,13 @@ func affine(scope, mode string, rotate, spread, inOrder bool, in http.Header, fr m := pl.order[0] a.Main = &m } + case at < len(pl.order) && pl.order[at].Reserve > 0: + // held back, its provider's accounts at once taken by those + // before it (keepAtOnce): asked when they all failed, it keeps no + // conversation, which goes back to them whatever it cached + // (01huadalang on Discord: a third ZCode account in use at once + // had the address banned). Strict, the user's own, keeps it + a.Why = "reserve" case pl.order[at].Rest != nil: a.Why = "resting" case !a.Within && backToMain(pl.order, at): diff --git a/internal/gateway/concurrency.go b/internal/gateway/concurrency.go index 2de646e41..582e5f8af 100644 --- a/internal/gateway/concurrency.go +++ b/internal/gateway/concurrency.go @@ -5,6 +5,7 @@ import ( "errors" "fmt" "net/http" + "slices" "sync" "time" @@ -162,7 +163,9 @@ func (l *lanes) free(who string, limit int) bool { // and room in its minute — another key or account of cands[i]'s provider, // or in a routing group any member — when cands[i]'s key or account is // full, or has sent its MaxRPM in the last minute; -1 when it isn't -// full, gave way once already, or none has room. +// full, gave way once already, or none has room. A reserve is never one +// (keepAtOnce): it is held back for its provider not to be used from more +// accounts at once than it lets be, and a full lane is not a failure. func (s *Server) laneMate(cands []candidate, i int, group bool, gave map[string]bool) int { c := cands[i] who := c.who() @@ -171,7 +174,7 @@ func (s *Server) laneMate(cands []candidate, i int, group bool, gave map[string] } for j := i + 1; j < len(cands); j++ { m := cands[j] - if m.who() == who || !group && m.p.ID != c.p.ID { + if m.who() == who || !group && m.p.ID != c.p.ID || m.reserve > 0 { continue } if s.ready(m) { @@ -181,6 +184,13 @@ func (s *Server) laneMate(cands []candidate, i int, group bool, gave map[string] return -1 } +// dropReserves leaves out, of the candidates after i, the reserves of +// provider id (keepAtOnce). +func dropReserves(cands []candidate, i int, id string) []candidate { + tail := slices.DeleteFunc(slices.Clone(cands[i+1:]), func(m candidate) bool { return m.reserve > 0 && m.p.ID == id }) + return append(slices.Clone(cands[:i+1]), tail...) +} + // ready is whether c's request would go at once: a slot free in its lane, // and room in its minute (rpm.go). func (s *Server) ready(c candidate) bool { diff --git a/internal/gateway/fallback.go b/internal/gateway/fallback.go index dbf46c857..637f0b7f3 100644 --- a/internal/gateway/fallback.go +++ b/internal/gateway/fallback.go @@ -79,6 +79,11 @@ type candidate struct { // what a member listed after it stands in for (standsInFor) member string place int + // reserve is set, to the provider's AtOnce, on an account or key held + // back past the first that many (keepAtOnce): tried after them, never + // given a request for want of a slot (laneMate) nor kept on by a + // conversation (affine) + reserve int } // capHold is how an account is held at its usage cap: the cap of the @@ -230,6 +235,71 @@ func perKeyOf(p provider.Provider, model string, from provider.Protocol) (out, a // serve the model (provider.AccountModels, #474): never tried, whatever // else there is — none, when every one of them is. func perKeyBarred(p provider.Provider, model string, from provider.Protocol) (out, aside, left, barred []candidate) { + out, aside, left, barred = perKeyEvery(p, model, from) + out, aside = keepAtOnce(p.AtOnce(), out, aside) + return out, aside, left, barred +} + +// keepAtOnce keeps, of a provider's accounts or keys routed over, the +// first n in the user's own order (rank, the order the provider's page +// shows and a drag sets), and holds the rest back as reserves: tried after +// them, the way a key for another protocol is (aside), and marked so +// (candidate.reserve). 01huadalang on Discord: ZCode bans the address +// that three of its accounts are used from at once, while two are let +// be, and In order alone still spread over all three under load (a full +// lane gave way to the next account, laneMate, and every busy refusal +// rested one). The ones kept are those not resting first, so an account +// at the end of its quota hands its seat to the next in the list, and +// gets it back once it is back; those resting fill seats only when fewer +// than n are not. The user's order, not routing's, says who is first, so +// the set stays the same request to request under In turn or By usage. +// n of 0 keeps them all. +func keepAtOnce(n int, out, aside []candidate) ([]candidate, []candidate) { + if n <= 0 || len(out)+len(aside) <= n { + return out, aside + } + all := append(slices.Clone(out), aside...) + byRank := make([]int, len(all)) + for i := range byRank { + byRank[i] = i + } + slices.SortStableFunc(byRank, func(a, b int) int { return all[a].rank - all[b].rank }) + resting := make([]bool, len(all)) + for i, c := range all { + _, resting[i] = restingOf(c) + } + keep := make([]bool, len(all)) + kept := 0 + for _, rested := range []bool{false, true} { + for _, i := range byRank { + if kept < n && resting[i] == rested && !keep[i] { + keep[i], kept = true, kept+1 + } + } + } + var reserves []candidate + for _, i := range byRank { + if !keep[i] { + c := all[i] + c.reserve = n + reserves = append(reserves, c) + } + } + keptOf := func(cs []candidate, from int) []candidate { + var o []candidate + for i, c := range cs { + if keep[from+i] { + o = append(o, c) + } + } + return o + } + return keptOf(out, 0), append(keptOf(aside, len(out)), reserves...) +} + +// perKeyEvery is perKeyBarred with every account or key routed over, the +// provider's AtOnce aside. +func perKeyEvery(p provider.Provider, model string, from provider.Protocol) (out, aside, left, barred []candidate) { if _, off := provider.ModelDisabled(p.ID, model); off || provider.DisabledUnknown() { return nil, nil, nil, nil // the user disabled it (#1867): never planned, a fallback no more than the model asked } diff --git a/internal/gateway/gateway.go b/internal/gateway/gateway.go index a4f88bb0d..6968a7cf6 100644 --- a/internal/gateway/gateway.go +++ b/internal/gateway/gateway.go @@ -3237,6 +3237,13 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro tt.Done, tt.Status, tt.Error, tt.Queued, tt.Millis = true, call.Status, call.Error, queued, time.Since(began).Milliseconds() }) if !last { + // a reserve of its provider is not asked in its place: a + // full lane fails nobody, and the reserve is held back for + // the provider not to be used from one account more at + // once (keepAtOnce) + cands = dropReserves(cands, i, c.p.ID) + } + if i < len(cands)-1 { skipped = append(skipped, c.label()+": "+call.Error) continue } diff --git a/internal/gateway/trace.go b/internal/gateway/trace.go index dcb5da4e7..e3d34e530 100644 --- a/internal/gateway/trace.go +++ b/internal/gateway/trace.go @@ -348,6 +348,10 @@ type Weighed struct { // Aside: a key made for another protocol than the keys routed over, // tried only after them Aside bool `json:"aside,omitempty"` + // Reserve: an account or key held back, its provider's accounts at + // once (provider.AtOnce, this many) taken by those before it in the + // user's order: tried, aside, only after they all failed + Reserve int `json:"reserve,omitempty"` // NoURL: its keys are all set to this protocol, which its provider has // no URL for, so it was tried on the URLs it has (#1702) NoURL provider.Protocol `json:"noURL,omitempty"` @@ -479,7 +483,7 @@ type planned struct { func weighed(c candidate, p provider.Provider, wg weighing, fallback bool, from provider.Protocol) Weighed { w := Weighed{ID: c.rest, Provider: p.ID, Name: p.Name, Icon: p.Icon, Preset: p.Preset, Model: c.model, Fixed: c.effort, Fast: c.fast, - Routing: p.Routing, Fallback: fallback, Shared: c.rest != p.ID, Rank: c.rank, NoURL: c.noURL} + Routing: p.Routing, Fallback: fallback, Shared: c.rest != p.ID, Rank: c.rank, NoURL: c.noURL, Reserve: c.reserve} switch { case c.p.Account != nil: w.Kind, w.Who, w.Agent, w.Plan = "account", c.p.Account.User, c.p.Account.Agent, c.p.Account.Plan diff --git a/internal/gui/assets/app.js b/internal/gui/assets/app.js index 85dc7ea88..6bc0df9d0 100644 --- a/internal/gui/assets/app.js +++ b/internal/gui/assets/app.js @@ -7596,9 +7596,8 @@ window.addEventListener("beforeunload", (e) => { } }); -// priceTypedError: a model with no list price given only part of its -// price in Names & levels (its input and output both needed) holds the -// Save, its empty box focused, rather than the part typed being dropped. +// priceTypedError: a model with no list price given half a price in Names & +// levels holds the Save, its empty box focused, rather than drop the half. function priceTypedError(ed) { const id = Object.keys(draft?.priceTyped || {}).find((x) => !draft.chosen?.length || draft.chosen.includes(x)); if (id === undefined) return false; @@ -7636,9 +7635,7 @@ function proxyPicker() { hint.textContent = t(PROXY_HINT[v]); }); seg.classList.add("proxy-mode"); - // the address sits beside the options, its room kept while it is not - // asked for, so picking one never changes the dialog's height (a - // centred dialog would move under the pointer) + // its room kept while not asked for: a pick never moves the dialog const row = el("div", "proxy-row"); row.append(seg, addr); box.append(row, login, hint); @@ -7651,23 +7648,18 @@ function concurrencyField(p) { const plugin = p?.pluginConcurrency || 0; const box = input(draft.concurrency ?? "", plugin ? t("{n}, as its plugin says", { n: plugin }) : t("No limit"), "number"); box.classList.add("concurrency"); - box.min = "0"; - box.max = "1000"; - box.step = "1"; - box.inputMode = "numeric"; - box.oninput = () => { draft.concurrency = box.value; }; - // the queue each key or account has past it (#892): how many may wait, - // and how long; past either, a request is turned away with a 429 + // the queue past it (#892): past either, a request is turned away (429) const queue = input(draft.queueLimit ?? "", t("No bound"), "number"); queue.classList.add("queue-limit"); const wait = input(draft.queueWait ?? "", t("As long as it takes"), "number"); wait.classList.add("queue-wait"); - // how many requests each key or account sends the vendor in any minute - // (coeo91 on Discord: OpenRouter's free models take 20); one more waits - // for room in the minute + // requests a minute (coeo91: OpenRouter's free models take 20) const rpm = input(draft.maxRPM ?? "", t("No limit"), "number"); rpm.classList.add("rpm"); - for (const [b, max, k] of [[queue, 10000, "queueLimit"], [wait, 3600, "queueWait"], [rpm, 10000, "maxRPM"]]) { + // the rest wait in reserve (01huadalang: ZCode bans 3 per IP) + const accounts = input(draft.maxAccounts ?? "", p?.pluginAccounts ? t("{n}, as its plugin says", { n: p.pluginAccounts }) : t("No limit"), "number"); + accounts.classList.add("max-accounts"); + for (const [b, max, k] of [[box, 1000, "concurrency"], [queue, 10000, "queueLimit"], [wait, 3600, "queueWait"], [rpm, 10000, "maxRPM"], [accounts, 1000, "maxAccounts"]]) { b.min = "0"; b.max = String(max); b.step = "1"; @@ -7676,6 +7668,7 @@ function concurrencyField(p) { } return [ ...field(t("Concurrency"), box, (plugin ? t("Over it, requests queue and go out in order; empty takes the plugin's {n}, 0 is no limit", { n: plugin }) : t("Over it, requests queue and go out in order; 0 or empty is no limit"))), + ...field(t("Accounts at once"), accounts, t("How many of its accounts or keys take requests at once, the first in the list; the next takes over when one runs out or fails. 0 is no limit")), ...field(t("Requests per minute"), rpm, t("How many requests each key or account sends in any minute, retries included; one more waits for room, up to 2 minutes. 0 or empty is no limit")), ...field(t("Queue size"), queue, t("How many requests may wait for each key or account; one more is turned away at once. 0 or empty is no bound")), ...field(t("Queue wait"), wait, t("Seconds a request waits for a free slot before it is turned away. 0 or empty waits as long as it takes")), @@ -7736,8 +7729,7 @@ function pluginOptionsField(sub) { } return field(t("Plugin options"), box, t("{plugin} declares these and reads them as it works; nothing runs on its own when one changes.", { plugin: sub.plugin.name || sub.plugin.pid })); } -// savePluginOptions saves the plugin options changed in the draft, by the -// plugin's own provider id. +// savePluginOptions saves the draft's changed plugin options, by its own id. async function savePluginOptions(sub) { const pid = sub?.plugin?.pid; if (!pid) return; @@ -7745,8 +7737,7 @@ async function savePluginOptions(sub) { prefs = await writingPrefs(api("settings/plugin-option", { provider: pid, key, on })); } } -// priceRateOfDraft is the draft's rate as it is saved — null for none, -// else the number — or undefined when what is typed isn't one. +// priceRateOfDraft: as saved, null for none, undefined if typed wrong function priceRateOfDraft() { const v = String(draft.priceRate ?? "").trim(); if (!v) return null; @@ -7760,13 +7751,9 @@ function shown(x) { for (let d = x?.closest("details"); d; d = d.parentElement?.closest("details")) d.open = true; return x; } -// An editor's fold (Advanced, Server address, More endpoints) opens and -// closes as a disclosure does on iOS: its content grows out of the line -// on a spring, its rows coming in one after another, and the dialog round -// it grows or shrinks on the same curve — so the change shows even where -// the fold is taller than the dialog and goes on out of sight below. Its -// arrow turns. At once with Reduce motion, and for a fold a Save opens -// (shown). A click while it moves turns it back from where it is. +// An editor's fold opens as an iOS disclosure: it and the dialog grow on one +// spring, rows in one by one; at once with Reduce motion or for a Save +// (shown). A click while it moves turns it back. const foldMoves = new WeakMap(); document.addEventListener("click", (e) => { const sum = e.target.closest?.(".editor details.more > summary"); @@ -7829,7 +7816,7 @@ document.addEventListener("click", (e) => { function advancedSet(d, p) { return (d.headers || []).some(([k]) => (k || "").trim()) || !!(d.extraBody || "").trim() || !!(d.replyHeaders || "").trim() || !!d.proxyMode || Object.values(d.accountProxies || {}).some((x) => x?.mode) || - [d.concurrency, d.queueLimit, d.queueWait, d.maxRPM, d.priceRate, d.contexts, d.outputs, d.compacts].some((v) => String(v ?? "").trim()) || + [d.concurrency, d.maxAccounts, d.queueLimit, d.queueWait, d.maxRPM, d.priceRate, d.contexts, d.outputs, d.compacts].some((v) => String(v ?? "").trim()) || !!d.rateWindows?.length || !!(d.searches || d.authHeader || d.passUserAgent || d.unredacted || d.countFree || d.pinUpstream || d.nativeCompaction || d.balanceToken || d.limitRestOff) || !!d.fallback?.length || !!p?.balanceToken?.set; @@ -7841,11 +7828,9 @@ function priceRateError(ed) { function concurrencyDraft(p) { return { concurrency: p?.maxConcurrency == null ? "" : String(p.maxConcurrency), priceRate: p?.priceRate ? String(p.priceRate) : "", queueLimit: p?.queueLimit ? String(p.queueLimit) : "", queueWait: p?.queueWait ? String(p.queueWait) : "", - maxRPM: p?.maxRPM ? String(p.maxRPM) : "" }; + maxRPM: p?.maxRPM ? String(p.maxRPM) : "", maxAccounts: p?.maxAccounts == null ? "" : String(p.maxAccounts) }; } -// queueOfDraft is the draft's queue and limit a minute as they are saved, -// { queueLimit, queueWait, maxRPM } with 0 for none, or { bad } naming the -// field typed wrong. +// queueOfDraft: { queueLimit, queueWait, maxRPM } as saved, 0 for none, or { bad } function queueOfDraft() { const out = {}; for (const [k, max] of [["queueLimit", 10000], ["queueWait", 3600], ["maxRPM", 10000]]) { @@ -7864,18 +7849,18 @@ function queueError(ed, bad) { shown(ed.querySelector(bad === "queueLimit" ? "input.queue-limit" : "input.queue-wait"))?.focus(NO_SCROLL); return editorError(bad === "queueLimit" ? t("Queue size: a whole number from 0 to 10000") : t("Queue wait: a whole number of seconds from 0 to 3600"), "warn"); } -// concurrencyOfDraft is the draft's limit as it is saved — null for none -// set, else the number — or undefined when what is typed isn't one. -function concurrencyOfDraft() { - const v = String(draft.concurrency ?? "").trim(); +// concurrencyOfDraft: draft[k] as saved, null for none, undefined if typed wrong +function concurrencyOfDraft(k = "concurrency") { + const v = String(draft[k] ?? "").trim(); if (!v) return null; if (!/^\d+$/.test(v) || +v > 1000) return undefined; return +v; } -function concurrencyError(ed) { - shown(ed.querySelector("input.concurrency"))?.focus(NO_SCROLL); - return editorError(t("Concurrency: a whole number from 0 to 1000"), "warn"); +function concurrencyError(ed, c = "concurrency", m = t("Concurrency: a whole number from 0 to 1000")) { + shown(ed.querySelector("input." + c))?.focus(NO_SCROLL); + return editorError(m, "warn"); } +const accountsError = (ed) => concurrencyError(ed, "max-accounts", t("Accounts at once: a whole number from 0 to 1000")); function proxyDraft(p) { const v = (p?.proxy || "").trim(); // each account's own (accountProxies), by its name in lower case @@ -9384,6 +9369,8 @@ function drawEditor(p, presetID) { } const maxConcurrency = concurrencyOfDraft(); if (maxConcurrency === undefined) return concurrencyError(ed); + const maxAccounts = concurrencyOfDraft("maxAccounts"); + if (maxAccounts === undefined) return accountsError(ed); const queue = queueOfDraft(); if (queue.bad) return queueError(ed, queue.bad); const priceRate = priceRateOfDraft(); @@ -9393,7 +9380,7 @@ function drawEditor(p, presetID) { if (priceTypedError(ed)) return; const picked = accountModelsDraft(p); if (picked === false) return pickError(); - const body = { id: p.id, models: chosenIds(), noModels: noneChosen(), bestInFamily: bestChosen(), unlisted: draft.unlisted, hiddenDrawers: draft.hiddenDrawers, fallback: draft.fallback, contexts: cx.map, outputs: ox.map, compacts: cpx.map, proxy, accountProxies: own.map, maxConcurrency, ...queue, priceRate, rateWindows, modelPrefs: modelPrefsOfDraft(), pinUpstream: !!draft.pinUpstream, unredacted: !!draft.unredacted, countFree: !!draft.countFree, ...(p.carriesCompaction ? { nativeCompaction: !!draft.nativeCompaction } : {}), ...routingOfDraft(p) }; + const body = { id: p.id, models: chosenIds(), noModels: noneChosen(), bestInFamily: bestChosen(), unlisted: draft.unlisted, hiddenDrawers: draft.hiddenDrawers, fallback: draft.fallback, contexts: cx.map, outputs: ox.map, compacts: cpx.map, proxy, accountProxies: own.map, maxConcurrency, maxAccounts, ...queue, priceRate, rateWindows, modelPrefs: modelPrefsOfDraft(), pinUpstream: !!draft.pinUpstream, unredacted: !!draft.unredacted, countFree: !!draft.countFree, ...(p.carriesCompaction ? { nativeCompaction: !!draft.nativeCompaction } : {}), ...routingOfDraft(p) }; saving(saveBtn, t("Saving…")); saveAccountModelsDraft(picked).then(() => savePluginOptions(subOf(a.agent))).then(() => providerAction("save", body, t("{name} saved", { name: p.name })), (e) => { doneSaving(saveBtn); editorError(e.message || String(e)); }); }; bar.append(cancel, saveBtn); @@ -10023,6 +10010,8 @@ function drawEditor(p, presetID) { } body.maxConcurrency = concurrencyOfDraft(); if (body.maxConcurrency === undefined) return concurrencyError(ed); + body.maxAccounts = concurrencyOfDraft("maxAccounts"); + if (body.maxAccounts === undefined) return accountsError(ed); const queue = queueOfDraft(); if (queue.bad) return queueError(ed, queue.bad); Object.assign(body, queue); diff --git a/internal/gui/assets/i18n.js b/internal/gui/assets/i18n.js index 89131eedb..e82745a55 100644 --- a/internal/gui/assets/i18n.js +++ b/internal/gui/assets/i18n.js @@ -2345,6 +2345,9 @@ const I18N = { "Price rate: a number from 0 to 1000, at most three decimals": "价格倍率:0 到 1000 之间的数字,最多三位小数", "{n}, as its plugin says": "{n}(插件的默认值)", "Over it, requests queue and go out in order; 0 or empty is no limit": "超出时排队,按顺序发出;0 或留空为不限制", + "Accounts at once": "同时使用的账号数", + "How many of its accounts or keys take requests at once, the first in the list; the next takes over when one runs out or fails. 0 is no limit": "同时接请求的账号或 Key 数量,按列表顺序取前几个;其中一个额度用完或失败时,由下一个接替。0 为不限制", + "Accounts at once: a whole number from 0 to 1000": "同时使用的账号数:0 到 1000 的整数", "Over it, requests queue and go out in order; empty takes the plugin's {n}, 0 is no limit": "超出时排队,按顺序发出;留空则用插件的默认值 {n},0 为不限制", "Concurrency: a whole number from 0 to 1000": "并发上限:请填写 0 到 1000 之间的整数", "Add another {name}": "再添加一个 {name}", @@ -6641,6 +6644,9 @@ const I18N = { "Price rate: a number from 0 to 1000, at most three decimals": "價格倍率:0 到 1000 之間的數字,最多三位小數", "{n}, as its plugin says": "{n}(外掛的預設值)", "Over it, requests queue and go out in order; 0 or empty is no limit": "超出時排隊,按順序發出;0 或留空為不限制", + "Accounts at once": "同時使用的帳號數", + "How many of its accounts or keys take requests at once, the first in the list; the next takes over when one runs out or fails. 0 is no limit": "同時接請求的帳號或 Key 數量,依清單順序取前幾個;其中一個額度用完或失敗時,由下一個接替。0 為不限制", + "Accounts at once: a whole number from 0 to 1000": "同時使用的帳號數:0 到 1000 的整數", "Over it, requests queue and go out in order; empty takes the plugin's {n}, 0 is no limit": "超出時排隊,按順序發出;留空則用外掛的預設值 {n},0 為不限制", "Concurrency: a whole number from 0 to 1000": "並行上限:請填寫 0 到 1000 之間的整數", "Add another {name}": "再新增一個 {name}", @@ -10915,6 +10921,9 @@ const I18N = { "Price rate: a number from 0 to 1000, at most three decimals": "価格倍率: 0〜1000 の数値、小数点以下 3 桁まで", "{n}, as its plugin says": "{n}(プラグインの既定値)", "Over it, requests queue and go out in order; 0 or empty is no limit": "超えたリクエストはキューに入り、順番に送られます。0 または空欄で上限なし", + "Accounts at once": "同時に使うアカウント数", + "How many of its accounts or keys take requests at once, the first in the list; the next takes over when one runs out or fails. 0 is no limit": "同時にリクエストを受けるアカウントやキーの数で、一覧の先頭から選ばれます。どれかが使い切るか失敗すると次が引き継ぎます。0 で上限なし", + "Accounts at once: a whole number from 0 to 1000": "同時に使うアカウント数:0〜1000 の整数", "Over it, requests queue and go out in order; empty takes the plugin's {n}, 0 is no limit": "超えたリクエストはキューに入り、順番に送られます。空欄ならプラグインの {n}、0 で上限なし", "Concurrency: a whole number from 0 to 1000": "同時実行数:0〜1000 の整数を入力してください", "Add another {name}": "{name} をもう1つ追加", @@ -15220,6 +15229,9 @@ const I18N = { "Price rate: a number from 0 to 1000, at most three decimals": "Preisfaktor: eine Zahl von 0 bis 1000, höchstens drei Nachkommastellen", "{n}, as its plugin says": "{n}, laut Erweiterung", "Over it, requests queue and go out in order; 0 or empty is no limit": "Darüber hinaus warten Anfragen in einer Warteschlange und gehen der Reihe nach raus; 0 oder leer heißt kein Limit", + "Accounts at once": "Konten gleichzeitig", + "How many of its accounts or keys take requests at once, the first in the list; the next takes over when one runs out or fails. 0 is no limit": "Wie viele seiner Konten oder Schlüssel gleichzeitig Anfragen annehmen, die ersten der Liste; ist eines aufgebraucht oder schlägt fehl, übernimmt das nächste. 0 heißt kein Limit", + "Accounts at once: a whole number from 0 to 1000": "Konten gleichzeitig: eine ganze Zahl von 0 bis 1000", "Over it, requests queue and go out in order; empty takes the plugin's {n}, 0 is no limit": "Darüber hinaus warten Anfragen in einer Warteschlange und gehen der Reihe nach raus; leer übernimmt den Wert {n} der Erweiterung, 0 heißt kein Limit", "Concurrency: a whole number from 0 to 1000": "Parallelität: eine ganze Zahl von 0 bis 1000", "Add another {name}": "{name} noch einmal hinzufügen", diff --git a/internal/gui/assets/plugins/routing/client.js b/internal/gui/assets/plugins/routing/client.js index 878227e3f..ed341c9a8 100644 --- a/internal/gui/assets/plugins/routing/client.js +++ b/internal/gui/assets/plugins/routing/client.js @@ -927,7 +927,10 @@ function routingPage(part) { else if (smart(x) && !x.known && someKnown(x)) out.push(t("{who}: what it has left isn't known yet, so it goes after those known.", { who: who(x) })); } const pooled = r.order.find((x) => !x.aside && x.kind === "key"); - for (const x of r.order.filter((x) => x.aside)) out.push(t("{who} is made for {api}, not {other} as the keys routed over are, so it isn't one of them: it's tried after them.", { who: who(x), api: API[x.speaks] || x.speaks || t("any API"), other: API[pooled?.speaks] || pooled?.speaks || t("any API") })); + // held back, the provider's accounts at once taken by those before it + // in the list (01huadalang on Discord, ZCode) + for (const x of r.order.filter((x) => x.reserve)) out.push(t("{who} is in reserve: {n} of its provider's accounts or keys take requests at once, the first in the list, so it's tried only once they have all failed.", { who: who(x), n: x.reserve })); + for (const x of r.order.filter((x) => x.aside && !x.reserve)) out.push(t("{who} is made for {api}, not {other} as the keys routed over are, so it isn't one of them: it's tried after them.", { who: who(x), api: API[x.speaks] || x.speaks || t("any API"), other: API[pooled?.speaks] || pooled?.speaks || t("any API") })); for (const x of r.left || []) out.push(leftWhy(x)); return out; } @@ -954,6 +957,7 @@ function routingPage(part) { switch (a.why) { case "resting": return t("{who} answered this conversation last, but it is resting, so the conversation moves.", { who: last }); case "spent": return t("{who} answered this conversation last, but its allowance is all but used up, so the conversation moves.", { who: last }); + case "reserve": return t("{who} answered this conversation last, but it is in reserve while those before it in the list can take requests, so the conversation moves back to them.", { who: last }); case "gone": return t("{who} answered this conversation last, but it is no longer one to route to.", { who: last }); case "order": return t("{who} answered this conversation last, but the group goes in order and {first}, ahead of it, is ready again, so turn {n} goes back to {first}.", { who: last, first: who(r.order[0]), n: a.turn }); case "main": return t("{who}, a fallback, answered this conversation last, but the provider's own {first} is ready again, so turn {n} goes back to it.", { who: last, first: who(r.order[0]), n: a.turn }); @@ -2610,6 +2614,7 @@ function routingPage(part) { else if (gave.has(id)) s = t("{status} · {fail} · passed to {agent}", { status: gave.get(id).status, fail: failWord(gave.get(id).fail), agent: agentName(r.agent) }); else if (went.has(id)) s = t("{status} · {fail} · went on to the next", { status: went.get(id).status, fail: failWord(went.get(id).fail) }); else if (w.noURL) s = noURLWord(w); + else if (w.reserve) s = t("in reserve · {n} at once", { n: w.reserve }); else if (w.sunk && !lifted(sunkKey(w), at(w.sunk))) s = t("rate limited at {time} · at the back", { time: clock(w.sunk) }); // the row smart routing's intent put first says the intent instead else if (said) s = said; diff --git a/internal/gui/assets/plugins/routing/i18n.js b/internal/gui/assets/plugins/routing/i18n.js index c3f2215d2..d16ac3bf2 100644 --- a/internal/gui/assets/plugins/routing/i18n.js +++ b/internal/gui/assets/plugins/routing/i18n.js @@ -129,6 +129,9 @@ magpie.strings({ "{pattern} is not a regular expression magpie can read": "{pattern} 不是 magpie 能识别的正则表达式", "Every model a pattern matches is in the group, now and as providers list new ones, after the models above: * is any run of characters in provider/model, re: starts a regular expression.": "模式匹配的模型均入组(含供应商日后新增的),排在上方模型之后:* 匹配 provider/model 中任意字符,re: 开头表示正则表达式。", "{api} only · after the others": "仅 {api} · 排在其他之后", + "{who} is in reserve: {n} of its provider's accounts or keys take requests at once, the first in the list, so it's tried only once they have all failed.": "{who} 是备用的:其提供商同时只用列表中前 {n} 个账号或 Key,所以只有它们都失败后才会试它。", + "{who} answered this conversation last, but it is in reserve while those before it in the list can take requests, so the conversation moves back to them.": "{who} 上次回答了这个对话,但列表中排在它前面的账号能接请求时它只作备用,所以对话回到它们那里。", + "in reserve · {n} at once": "备用 · 同时 {n} 个", "key set to {api} only, no {api} URL · sent on the others": "key 只用 {api},没有 {api} 地址 · 改走其他地址", "{who} is made for {api}, not {other} as the keys routed over are, so it isn't one of them: it's tried after them.": "{who} 用于 {api},与参与路由的 {other} 密钥不同,不算其中一员,排在它们之后尝试。", "{n} keys for {api}": "{n} 个 {api} 密钥", @@ -767,6 +770,9 @@ magpie.strings({ "{pattern} is not a regular expression magpie can read": "{pattern} 不是 magpie 能識別的正規表示式", "Every model a pattern matches is in the group, now and as providers list new ones, after the models above: * is any run of characters in provider/model, re: starts a regular expression.": "模式匹配的模型均入組(含供應商日後新增的),排在上方模型之後:* 匹配 provider/model 中任意字元,re: 開頭表示正規表示式。", "{api} only · after the others": "僅 {api} · 排在其他之後", + "{who} is in reserve: {n} of its provider's accounts or keys take requests at once, the first in the list, so it's tried only once they have all failed.": "{who} 是備用的:其供應商同時只用清單中前 {n} 個帳號或 Key,所以只有它們都失敗後才會試它。", + "{who} answered this conversation last, but it is in reserve while those before it in the list can take requests, so the conversation moves back to them.": "{who} 上次回答了這個對話,但清單中排在它前面的帳號能接請求時它只作備用,所以對話回到它們那裡。", + "in reserve · {n} at once": "備用 · 同時 {n} 個", "key set to {api} only, no {api} URL · sent on the others": "key 只用 {api},沒有 {api} 位址 · 改走其他位址", "{who} is made for {api}, not {other} as the keys routed over are, so it isn't one of them: it's tried after them.": "{who} 用於 {api},與參與路由的 {other} 金鑰不同,不算其中一員,排在它們之後嘗試。", "{n} keys for {api}": "{n} 個 {api} 金鑰", @@ -1383,6 +1389,9 @@ magpie.strings({ "{pattern} is not a regular expression magpie can read": "{pattern} は magpie が読める正規表現ではありません", "Every model a pattern matches is in the group, now and as providers list new ones, after the models above: * is any run of characters in provider/model, re: starts a regular expression.": "パターンに一致するモデルは、プロバイダが今後追加するものも含めてすべて、上のモデルの後にグループに入ります。* は provider/model の任意の文字列、re: で始めると正規表現です。", "{api} only · after the others": "{api} のみ · 他の後", + "{who} is in reserve: {n} of its provider's accounts or keys take requests at once, the first in the list, so it's tried only once they have all failed.": "{who} は予備です。このプロバイダーは一覧の先頭から {n} 個のアカウントやキーだけを同時に使うので、それらがすべて失敗したときだけ試されます。", + "{who} answered this conversation last, but it is in reserve while those before it in the list can take requests, so the conversation moves back to them.": "{who} がこの会話に前回答えましたが、一覧でその前にあるアカウントがリクエストを受けられる間は予備なので、会話はそちらに戻ります。", + "in reserve · {n} at once": "予備 · 同時に {n} 個", "key set to {api} only, no {api} URL · sent on the others": "キーは {api} 専用、{api} の URL なし · 他の URL で送信", "{who} is made for {api}, not {other} as the keys routed over are, so it isn't one of them: it's tried after them.": "{who} は {api} 用で、ルーティング対象のキーのような {other} 用ではないため、その一員にはなりません。それらの後に試されます。", "{n} keys for {api}": "{api} 用のキー {n} 個", @@ -2011,6 +2020,9 @@ magpie.strings({ "{pattern} is not a regular expression magpie can read": "{pattern} ist kein regulärer Ausdruck, den magpie lesen kann", "Every model a pattern matches is in the group, now and as providers list new ones, after the models above: * is any run of characters in provider/model, re: starts a regular expression.": "Jedes Modell, auf das ein Muster passt, ist in der Gruppe, jetzt und sobald Anbieter neue auflisten, nach den Modellen oben: * steht für beliebige Zeichen in provider/model, re: leitet einen regulären Ausdruck ein.", "{api} only · after the others": "nur {api} · nach den anderen", + "{who} is in reserve: {n} of its provider's accounts or keys take requests at once, the first in the list, so it's tried only once they have all failed.": "{who} ist in Reserve: Von seinem Anbieter nehmen nur die ersten {n} Konten oder Schlüssel der Liste gleichzeitig Anfragen an, also wird es erst versucht, wenn sie alle fehlgeschlagen sind.", + "{who} answered this conversation last, but it is in reserve while those before it in the list can take requests, so the conversation moves back to them.": "{who} hat diese Unterhaltung zuletzt beantwortet, ist aber in Reserve, solange die Konten davor in der Liste Anfragen annehmen können, also geht die Unterhaltung zu ihnen zurück.", + "in reserve · {n} at once": "in Reserve · {n} gleichzeitig", "key set to {api} only, no {api} URL · sent on the others": "Schlüssel nur für {api}, keine {api}-URL · über die anderen gesendet", "{who} is made for {api}, not {other} as the keys routed over are, so it isn't one of them: it's tried after them.": "{who} ist für {api} gedacht, nicht für {other} wie die Schlüssel der Weiterleitung, und gehört daher nicht zu ihnen: Es wird nach ihnen versucht.", "{n} keys for {api}": "{n} Schlüssel für {api}", diff --git a/internal/gui/lane_limit_test.go b/internal/gui/lane_limit_test.go index 543af3631..68277bc2c 100644 --- a/internal/gui/lane_limit_test.go +++ b/internal/gui/lane_limit_test.go @@ -180,3 +180,78 @@ func TestRPMSave(t *testing.T) { t.Fatalf("null: %d %s, limit %d", w.Code, w.Body, rpm()) } } + +// The editor's save sets how many of a provider's keys or accounts take +// requests at once (01huadalang on Discord: ZCode bans an address three of +// its accounts are used from at once), shows it in the providers' state, +// keeps it when a save leaves it out, takes null for the plugin's and 0 +// for no limit, and refuses one out of range. +func TestAtOnceSave(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()) + if err := provider.Save(provider.Provider{ID: "once", Name: "Once", Chat: "https://example.invalid/v1", Key: "a", Keys: []provider.KeyAccount{{Key: "b"}, {Key: "c"}}}); err != nil { + t.Fatal(err) + } + mux := http.NewServeMux() + providerRoutes(mux, nil) + post := func(body string) *httptest.ResponseRecorder { + w := httptest.NewRecorder() + mux.ServeHTTP(w, httptest.NewRequest("POST", "/api/provider/save", strings.NewReader(body))) + return w + } + set := func() *int { + got, err := provider.Find("once") + if err != nil { + t.Fatal(err) + } + return got.MaxAccounts + } + const form = `{"id":"once","name":"Once","chat":"https://example.invalid/v1"` + if w := post(form + `,"maxAccounts":2}`); w.Code != 200 { + t.Fatalf("%d %s", w.Code, w.Body) + } + if n := set(); n == nil || *n != 2 { + t.Fatalf("set to 2: %v", n) + } + w := httptest.NewRecorder() + mux.ServeHTTP(w, httptest.NewRequest("GET", "/api/providers", nil)) + var state providersJSON + if err := json.Unmarshal(w.Body.Bytes(), &state); err != nil { + t.Fatal(err) + } + shown := false + for _, q := range state.Providers { + if q.ID == "once" { + shown = q.MaxAccounts != nil && *q.MaxAccounts == 2 + } + } + if !shown { + t.Fatalf("the providers' state doesn't tell it: %s", w.Body) + } + if w := post(form + `}`); w.Code != 200 { + t.Fatalf("%d %s", w.Code, w.Body) + } + if n := set(); n == nil || *n != 2 { + t.Fatalf("a save leaving it out lost it: %v", n) + } + if w := post(form + `,"maxAccounts":0}`); w.Code != 200 { + t.Fatalf("%d %s", w.Code, w.Body) + } + if n := set(); n == nil || *n != 0 { + t.Fatalf("set to no limit: %v", n) + } + if w := post(form + `,"maxAccounts":null}`); w.Code != 200 { + t.Fatalf("%d %s", w.Code, w.Body) + } + if n := set(); n != nil { + t.Fatalf("null kept %d", *n) + } + for _, bad := range []string{`-1`, `1001`, `"x"`, `1.5`} { + if w := post(form + `,"maxAccounts":` + bad + `}`); w.Code == 200 { + t.Fatalf("maxAccounts %s taken", bad) + } + } +} diff --git a/internal/gui/providers.go b/internal/gui/providers.go index cc84d2909..9fc8c3fb9 100644 --- a/internal/gui/providers.go +++ b/internal/gui/providers.go @@ -248,6 +248,12 @@ type providerJSON struct { // when the user set none (provider.Concurrency) MaxConcurrency *int `json:"maxConcurrency"` PluginConcurrency int `json:"pluginConcurrency,omitempty"` + // how many of its keys or accounts take requests at once, the rest + // held back as reserves: the user's (null: not set), and what its + // plugin says when the user set none (provider.AtOnce; 01huadalang + // on Discord, ZCode) + MaxAccounts *int `json:"maxAccounts"` + PluginAccounts int `json:"pluginAccounts,omitempty"` // 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"` @@ -669,7 +675,7 @@ func providerInfoWith(p provider.Provider, ls provider.Listing, agents []agentUs Proxy: p.Proxy, AccountProxies: p.AccountProxies, AccountModels: p.AccountModels, AccountCaps: p.AccountCaps, AccountWindowCaps: p.AccountWindowCaps, AccountNames: p.AccountNames, Headers: p.Headers, ExtraBody: p.ExtraBody, ReplyHeaders: p.ReplyHeaders, Searches: p.Searches, Cline: p.ClinePinnable(), PinUpstream: p.PinUpstream, Unredacted: p.Unredacted, CountFree: p.CountFree, InsecureTLS: p.InsecureTLS, TakesInsecureTLS: p.TakesInsecureTLS(), LimitRestOff: p.LimitRestOff, NativeCompaction: p.NativeCompaction, CarriesCompaction: p.CarriesCompaction(), PassUserAgent: p.PassUserAgent, OwnClient: p.OwnClient(), AuthHeader: p.AuthHeader, BothAuth: p.BothAuth(), BalanceURL: p.BalanceURL, BalancePath: p.BalancePath, BalanceMethod: p.BalanceMethod, ModelsURL: p.ModelsURL, Ready: p.Ready(), Chosen: p.PicksOf(avail), Agents: make([]providerAgent, 0, len(agents)), 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, + MaxConcurrency: p.MaxConcurrency, PluginConcurrency: p.PluginConcurrency(), MaxAccounts: p.MaxAccounts, PluginAccounts: p.PluginAtOnce(), PriceRate: p.PriceRate, RateWindows: p.RateWindows, RateNow: rateNowOf(p, time.Now()), 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), @@ -1324,6 +1330,10 @@ func providerRoutes(mux *http.ServeMux, w Windows) { // accounts has out at once: a number (0 none), null for what // its plugin says or none; a save that leaves it out keeps it MaxConcurrency json.RawMessage `json:"maxConcurrency"` + // MaxAccounts is how many of its keys or accounts take + // requests at once: a number (0 none), null for what its + // plugin says or none; a save that leaves it out keeps it + MaxAccounts json.RawMessage `json:"maxAccounts"` // QueueLimit and QueueWait are how many may wait for each key // or account and for how many seconds (#892): numbers, 0 or // null for no bound; a save that leaves them out keeps them @@ -1605,6 +1615,12 @@ func providerRoutes(mux *http.ServeMux, w Windows) { return } in.MaxConcurrency = cc + ma, keepMA, err := limitOf(req.MaxAccounts, "accounts at once") + if err != nil { + fail(rw, err) + return + } + in.MaxAccounts = ma ql, keepQL, err := queueOf(req.QueueLimit, "queue length") if err != nil { fail(rw, err) @@ -1718,6 +1734,9 @@ func providerRoutes(mux *http.ServeMux, w Windows) { if keepCC && old != nil { in.MaxConcurrency = old.MaxConcurrency } + if keepMA && old != nil { + in.MaxAccounts = old.MaxAccounts + } if keepQL && old != nil { in.QueueLimit = old.QueueLimit } @@ -2788,14 +2807,20 @@ func rateNowOf(p provider.Provider, t time.Time) float64 { // concurrencyOf is a save's maxConcurrency: keep when the save left it // out, nil for null (the plugin's, or none), else the number, 0 for none. func concurrencyOf(raw json.RawMessage) (n *int, keep bool, err error) { + return limitOf(raw, "max concurrent requests") +} + +// limitOf is a save's limit named what, read as concurrencyOf reads +// maxConcurrency: keep when left out, nil for null, else 0 to 1000. +func limitOf(raw json.RawMessage, what string) (n *int, keep bool, err error) { if len(raw) == 0 { return nil, true, nil } if err := json.Unmarshal(raw, &n); err != nil { - return nil, false, fmt.Errorf("max concurrent requests must be a whole number, not %s", raw) + return nil, false, fmt.Errorf("%s must be a whole number, not %s", what, raw) } if n != nil && (*n < 0 || *n > 1000) { - return nil, false, fmt.Errorf("max concurrent requests must be from 0 to 1000, not %d", *n) + return nil, false, fmt.Errorf("%s must be from 0 to 1000, not %d", what, *n) } return n, false, nil } diff --git a/internal/gui/tests/provider-at-once.test.cjs b/internal/gui/tests/provider-at-once.test.cjs new file mode 100644 index 000000000..586855204 --- /dev/null +++ b/internal/gui/tests/provider-at-once.test.cjs @@ -0,0 +1,206 @@ +// Run with Node's test runner and Playwright on the module path; see README.md. +// A provider's Accounts at once (01huadalang on Discord: three ZCode +// accounts used at once got the address refused with a 405, two didn't): +// its editor has the field beside Concurrency, empty for none set, a +// plugin's own count as the placeholder; Save posts the number typed (0 for +// no limit), null when it is empty, and refuses one that isn't a whole +// number before anything is posted. On Routing a key held back says it is +// in reserve, on its row and in the request's story. In every language. +const assert = require("node:assert/strict"); +const fs = require("node:fs/promises"); +const path = require("node:path"); +const { test } = require("node:test"); +const { chromium, webkit } = require("playwright"); + +const assets = path.resolve(__dirname, "../assets"); +const unfold = async (page) => { + const adv = page.locator(".editor details.advanced"); + await adv.waitFor({ state: "attached" }); + if (!(await adv.evaluate((d) => d.open))) await adv.locator(":scope > summary").click(); +}; +const keys = [1, 2, 3].map((n, i) => ({ id: `key-${n}`, name: `Key ${n}`, masked: `k${n}`, active: i === 0, on: true })); +const relay = { + id: "relay", name: "Relay", icon: "generic", chat: "https://relay.example.invalid/v1", responses: "", anthropic: "", catalog: "", + models: [{ id: "m", name: "M", on: true }], agents: [], fallback: [], headers: {}, + key: { set: true, masked: "k1" }, keyList: keys, balanceToken: { takes: false, set: false }, proxy: "", maxConcurrency: null, maxAccounts: null, +}; +const lemon = { + id: "lemon", name: "Lemon", icon: "generic", chat: "plugin://lemon/v1", responses: "", anthropic: "", catalog: "", + models: [{ id: "m1", name: "M1", on: true }], agents: [], fallback: [], headers: {}, keyList: [], + account: { agent: "plugin", agentName: "Lemon", user: "lemon@example.invalid", plan: "" }, + proxy: "", maxConcurrency: null, maxAccounts: null, pluginAccounts: 2, +}; +// one request as the gateway traces it: Key 1 and Key 2 kept, Key 3 in +// reserve after them +const seat = (k, rank, extra) => ({ id: `relay#${k.id}`, provider: "relay", name: "Relay", who: k.name, kind: "key", model: "m", rank, shared: true, ...extra }); +const t0 = Date.now() - 2000; +const order = [seat(keys[0], 0), seat(keys[1], 1), seat(keys[2], 2, { aside: true, reserve: 2 })]; +const route = { id: 100, seq: 1, time: new Date(t0).toISOString(), agent: "claude", model: "relay/m", provider: "relay", order, + tries: [{ id: order[0].id, model: "m", start: new Date(t0 + 10).toISOString(), done: true, status: 200, ms: 300 }], done: true, status: 200, ms: 320, tokens: 100 }; + +function serve(lang, posts, wait) { + const providers = { providers: [relay, lemon], presets: [], excluded: [], gateway: { running: true, window: true } }; + const state = { agents: [{ id: "claude", name: "Claude", icon: "generic", path: "/fixture", fields: [] }], profiles: [], settings: { lang, theme: "light" } }; + return async (r) => { + const url = new URL(r.request().url()); + const json = (data) => r.fulfill({ json: data }); + if (url.pathname === "/boot.js") return r.fulfill({ contentType: "text/javascript", body: `window.bootPrefs = {lang:"${lang}",theme:"light",web:true};` }); + if (url.pathname === "/wails/runtime.js") return r.fulfill({ contentType: "text/javascript", body: "export const Window = {};" }); + if (url.pathname === "/api/state") return json(state); + if (url.pathname === "/api/providers") return json(providers); + if (url.pathname === "/api/plugins") return json({ plugins: [] }); + if (url.pathname === "/api/groups") return json({ models: [], groups: [], pools: [] }); + if (url.pathname === "/api/gateway/trace") { + const out = (routes) => json({ mine: true, now: new Date().toISOString(), seq: 1, totals: { requests: 1, rerouted: 0, errors: 0 }, routes }); + if (!url.searchParams.get("wait")) return out([route]); + return new Promise((res) => wait.push(() => res(out([])))); + } + if (url.pathname === "/api/gateway/history") return json({ cut: false, days: [], routes: [] }); + if (url.pathname.startsWith("/api/provider/") && r.request().method() === "POST") { + posts.push({ action: url.pathname.slice("/api/provider/".length), body: r.request().postDataJSON() }); + 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)]; + await r.fulfill({ body: await fs.readFile(file), contentType }); + }; +} + +const words = { + en: { label: "Accounts at once", save: "Save", none: "No limit", plugin: "2, as its plugin says", + hint: "How many of its accounts or keys take requests at once, the first in the list; the next takes over when one runs out or fails. 0 is no limit", + bad: "Accounts at once: a whole number from 0 to 1000", row: "in reserve · 2 at once", + why: "Key 3 is in reserve: 2 of its provider's accounts or keys take requests at once, the first in the list, so it's tried only once they have all failed." }, + zh: { label: "同时使用的账号数", save: "保存", none: "不限制", plugin: "2(插件的默认值)", + hint: "同时接请求的账号或 Key 数量,按列表顺序取前几个;其中一个额度用完或失败时,由下一个接替。0 为不限制", + bad: "同时使用的账号数:0 到 1000 的整数", row: "备用 · 同时 2 个", why: "是备用的:其提供商同时只用列表中前 2 个账号或 Key" }, + "zh-TW": { label: "同時使用的帳號數", row: "備用 · 同時 2 個", why: "是備用的:其供應商同時只用清單中前 2 個帳號或 Key" }, + ja: { label: "同時に使うアカウント数", row: "予備 · 同時に 2 個", why: "は予備です。このプロバイダーは一覧の先頭から 2 個" }, + de: { label: "Konten gleichzeitig", row: "in Reserve · 2 gleichzeitig", why: "ist in Reserve: Von seinem Anbieter nehmen nur die ersten 2 Konten" }, +}; + +for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) { + for (const lang of Object.keys(words)) { + const w = words[lang]; + const open = async (t, view, width = 900) => { + const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" })); + const wait = []; + const page = await (await browser.newContext({ viewport: { width, height: 760 }, reducedMotion: "reduce" })).newPage(); + t.after(async () => { + if (process.env.ARTIFACT_DIR) { + await fs.mkdir(process.env.ARTIFACT_DIR, { recursive: true }); + await page.screenshot({ path: path.join(process.env.ARTIFACT_DIR, `${engine}-${lang}-${view}-${width}-at-once.png`) }); + } + for (const f of wait) f(); + await browser.close(); + }); + page.setDefaultTimeout(5000); + page.setDefaultNavigationTimeout(60000); + const errors = []; + page.on("pageerror", (e) => errors.push(e.message)); + const posts = []; + await page.route("**/*", serve(lang, posts, wait)); + await page.goto(`http://magpie.test/?view=${view}`); + return { page, errors, posts }; + }; + const box = (page) => page.locator(".editor input.max-accounts"); + const edit = async (page, name) => { + await page.locator(".row.provider", { hasText: name }).click(); + await unfold(page); + await box(page).waitFor(); + await page.waitForTimeout(300); // the editor drawn again as what it asked for comes in + }; + const save = async (page, posts) => { + const n = posts.length; + await page.locator(".editor .bar").getByRole("button", { name: w.save, exact: true }).click(); + for (let i = 0; i < 50 && posts.length === n; i++) await page.waitForTimeout(50); + return posts.at(-1); + }; + + for (const width of [900, 360]) { + test(`${engine} ${lang} ${width}px: Accounts at once sits beside Concurrency, its label on one line`, async (t) => { + const { page, errors } = await open(t, "providers", width); + await edit(page, "Relay"); + const label = page.locator(".editor label", { hasText: w.label }); + assert.equal(await label.count(), 1); + // right after Concurrency, in the same column of fields + const next = await page.locator(".editor input.concurrency").evaluate((c) => { + const all = [...document.querySelectorAll(".editor input")]; + return all[all.indexOf(c) + 1]?.className; + }); + assert.match(next, /max-accounts/); + const look = (e) => { const s = getComputedStyle(e); return { bg: s.backgroundColor, border: s.borderTopColor, radius: s.borderTopLeftRadius, height: s.height }; }; + assert.deepEqual(await box(page).evaluate(look), await page.locator(".editor input.concurrency").evaluate(look), "styled as Concurrency is"); + const h = await label.evaluate((e) => e.getBoundingClientRect().height); + const one = await page.locator(".editor label").first().evaluate((e) => e.getBoundingClientRect().height); + assert(h <= one + 1, `the label takes ${h}px, one line is ${one}px`); + const stripes = await box(page).evaluate((e) => { const s = getComputedStyle(e); return parseFloat(s.borderLeftWidth) > parseFloat(s.borderRightWidth) || (parseFloat(s.borderLeftWidth) > 0 && s.borderLeftColor !== s.borderRightColor); }); + assert.equal(stripes, false, "no border stripe"); + assert(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth), "no sideways scroll"); + assert.deepEqual(errors, []); + }); + } + + test(`${engine} ${lang}: a key held back says it is in reserve on Routing`, async (t) => { + const { page, errors } = await open(t, "routing", 1100); + const fold = page.locator(".rt-accts > li.rt-fold:not(.open)"); + await page.locator(".rt-accts > li").first().waitFor(); + if (await fold.count()) await fold.first().click(); + const k3 = page.locator('.rt-accts > li[title^="relay#key-3"]'); + await k3.waitFor(); + await page.waitForFunction((want) => document.querySelector('.rt-accts > li[title^="relay#key-3"]')?.textContent.includes(want), w.row); + const k2 = await page.locator('.rt-accts > li[title^="relay#key-2"]').textContent(); + assert(!k2.includes(w.row), `a kept key isn't in reserve: ${k2}`); + await page.locator(".rt-req").first().click(); + await page.waitForTimeout(400); + const story = await page.locator(".rt-steps li").allTextContents(); + assert(story.some((s) => s.includes(w.why)), JSON.stringify(story)); + assert.deepEqual(errors, []); + }); + + if (!w.save) continue; + + test(`${engine} ${lang}: accounts at once are typed and saved`, async (t) => { + const { page, errors, posts } = await open(t, "providers"); + await edit(page, "Relay"); + assert.equal(await box(page).inputValue(), "", "none set"); + assert.equal(await box(page).getAttribute("placeholder"), w.none); + assert.equal(await box(page).evaluate((e) => e.parentElement.querySelector(".hint")?.textContent), w.hint); + + // not a whole number: refused, nothing posted + await box(page).fill("1.5"); + await page.locator(".editor .bar").getByRole("button", { name: w.save, exact: true }).click(); + await page.locator(".editor .editor-error").waitFor(); + assert.equal(await page.locator(".editor .editor-error").textContent(), w.bad); + assert.equal(posts.length, 0); + + await box(page).fill("2"); + let saved = await save(page, posts); + assert.equal(saved.body.id, "relay"); + assert.equal(saved.body.maxAccounts, 2); + assert.equal(saved.body.maxConcurrency, null, "Concurrency left as it was"); + + await edit(page, "Relay"); + await box(page).fill(""); + saved = await save(page, posts); + assert(Object.hasOwn(saved.body, "maxAccounts"), "an empty field is saved as none, not left out"); + assert.equal(saved.body.maxAccounts, null); + assert.deepEqual(errors, []); + }); + + test(`${engine} ${lang}: a plugin's provider shows its plugin's count, and 0 is no limit`, async (t) => { + const { page, errors, posts } = await open(t, "providers"); + await edit(page, "Lemon"); + assert.equal(await box(page).inputValue(), ""); + assert.equal(await box(page).getAttribute("placeholder"), w.plugin); + let saved = await save(page, posts); + assert.equal(saved.body.maxAccounts, null, "empty follows the plugin"); + await edit(page, "Lemon"); + await box(page).fill("0"); + saved = await save(page, posts); + assert.equal(saved.body.maxAccounts, 0, "0 is the user's own no limit, saved as such"); + assert.deepEqual(errors, []); + }); + } +} diff --git a/internal/plugin/host.js b/internal/plugin/host.js index a4b02e2f8..28b0aa872 100644 --- a/internal/plugin/host.js +++ b/internal/plugin/host.js @@ -1970,11 +1970,25 @@ function iconOf(a) { // package.json's magpie.maxConcurrency. A whole number over 0, else none // (0); the user's setting on the provider goes over it. function concurrencyOf(a) { + return declared(a, "maxConcurrency") +} + +// atOnceOf is how many of its accounts the plugin says may take requests +// at the same time, magpie's own field: the auth hook's maxAccounts, else +// package.json's magpie.maxAccounts, as concurrencyOf reads its own. The +// user's setting on the provider goes over it. +function atOnceOf(a) { + return declared(a, "maxAccounts") +} + +// declared is a whole number over 0 the plugin declares under key, on its +// auth hook or else in its package.json's magpie, at most 1000; else 0. +function declared(a, key) { const ok = (v) => (Number.isInteger(v) && v > 0 ? Math.min(v, 1000) : 0) - const own = ok(a.auth.maxConcurrency) + const own = ok(a.auth[key]) if (own || !a.target) return own const dir = fs.statSync(a.target, { throwIfNoEntry: false })?.isDirectory() ? a.target : path.dirname(a.target) - return ok(readJSON(path.join(dir, "package.json"))?.magpie?.maxConcurrency) + return ok(readJSON(path.join(dir, "package.json"))?.magpie?.[key]) } // rateOf reads a model's credit rate as a plugin gives it: a number (0.5) @@ -2040,6 +2054,7 @@ async function providers({ proxies } = {}) { decide: p.decide === true, searches: p.searches === true, maxConcurrency: concurrencyOf(a), + maxAccounts: atOnceOf(a), signedIn: keys.length > 0, authType: first?.type ?? "", accountId: whoOf(first), diff --git a/internal/plugin/plugin_icon_test.go b/internal/plugin/plugin_icon_test.go index f2810f4be..5cca7c7b1 100644 --- a/internal/plugin/plugin_icon_test.go +++ b/internal/plugin/plugin_icon_test.go @@ -41,6 +41,12 @@ func TestPluginOwnIconAndKeyHint(t *testing.T) { if lemon.MaxConcurrency != 3 || lime.MaxConcurrency != 5 { t.Errorf("maxConcurrency = %d, %d, want 3, 5", lemon.MaxConcurrency, lime.MaxConcurrency) } + // how many of its accounts take requests at once (01huadalang on + // Discord: ZCode bans an address three accounts are used from at once): + // read the same way + if lemon.MaxAccounts != 4 || lime.MaxAccounts != 2 { + t.Errorf("maxAccounts = %d, %d, want 4, 2", lemon.MaxAccounts, lime.MaxAccounts) + } if len(lemon.Methods) != 2 || lemon.Methods[0] != (Method{Type: "api", Label: "Lemon API key (from lemon.example/keys)", Placeholder: "sk-lemon-…"}) || lemon.Methods[1].Placeholder != "" { t.Fatalf("lemon's methods = %+v", lemon.Methods) } diff --git a/internal/plugin/providers.go b/internal/plugin/providers.go index 88a04f3d0..fbdd7c233 100644 --- a/internal/plugin/providers.go +++ b/internal/plugin/providers.go @@ -170,6 +170,12 @@ type Provider struct { // magpie.maxConcurrency); 0 for none said. The user's setting on the // provider goes over it. MaxConcurrency int `json:"maxConcurrency,omitempty"` + // MaxAccounts is how many of its accounts the plugin says may take + // requests at the same time (the auth hook's maxAccounts, else + // package.json's magpie.maxAccounts: a vendor that blocks an address + // asking for more accounts at once); 0 for none said. The user's + // setting on the provider goes over it. + MaxAccounts int `json:"maxAccounts,omitempty"` } // Option is a switch a plugin declares for its provider (auth.options, diff --git a/internal/plugin/testdata/ownicon/index.js b/internal/plugin/testdata/ownicon/index.js index 8a07f7c74..7f1a00985 100644 --- a/internal/plugin/testdata/ownicon/index.js +++ b/internal/plugin/testdata/ownicon/index.js @@ -1,6 +1,6 @@ // A plugin giving its providers their own icons and its key a title and a // hint: the auth hook's icon (magpie's own field), else package.json's -// magpie.icon (and so maxConcurrency); an "api" method's label and placeholder. +// magpie.icon (and so maxConcurrency and maxAccounts); an "api" method's label and placeholder. const svg = "data:image/svg+xml;base64," + btoa('') export const Lemon = async () => ({ @@ -8,6 +8,7 @@ export const Lemon = async () => ({ provider: "lemon", icon: svg, maxConcurrency: 3, // how many each account takes at once + maxAccounts: 4, // how many of its accounts take requests at once methods: [ { type: "api", label: "Lemon API key (from lemon.example/keys)", placeholder: "sk-lemon-…" }, { type: "oauth", label: "Browser", placeholder: "not a key's", authorize: async () => ({ url: "https://lemon.invalid", instructions: "", method: "auto", callback: async () => ({ type: "failed" }) }) }, @@ -20,6 +21,7 @@ export const Lime = async () => ({ provider: "lime", icon: "javascript:alert(1)", // refused: package.json's instead maxConcurrency: 2.5, // not a whole number: package.json's instead + maxAccounts: "3", // not a number: package.json's instead methods: [{ type: "api", label: "API key", placeholder: 42 }], }, }) diff --git a/internal/plugin/testdata/ownicon/package.json b/internal/plugin/testdata/ownicon/package.json index 2a42d9d81..51c781477 100644 --- a/internal/plugin/testdata/ownicon/package.json +++ b/internal/plugin/testdata/ownicon/package.json @@ -3,5 +3,5 @@ "version": "1.0.0", "type": "module", "main": "index.js", - "magpie": { "icon": "https://ownicon.example/icon.png", "maxConcurrency": 5 } + "magpie": { "icon": "https://ownicon.example/icon.png", "maxConcurrency": 5, "maxAccounts": 2 } } diff --git a/internal/provider/accounts_at_once_test.go b/internal/provider/accounts_at_once_test.go new file mode 100644 index 000000000..ee1657ddc --- /dev/null +++ b/internal/provider/accounts_at_once_test.go @@ -0,0 +1,78 @@ +package provider + +import ( + "testing" + + "github.com/yetone/magpie/internal/plugin" + "github.com/yetone/magpie/internal/testenv" +) + +// How many of a provider's accounts or keys take requests at once +// (01huadalang on Discord: ZCode bans an address three of its accounts are +// used from at once): the user's own MaxAccounts, 0 for no limit, over +// what the plugin giving the provider says, which goes for nil; none for a +// provider no plugin gives. The save keeps it in range and keeps it when +// set, and SetAtOnce refuses one out of range. +func TestAtOnce(t *testing.T) { + testenv.SetHome(t, t.TempDir()) + t.Setenv("XDG_CONFIG_HOME", t.TempDir()) + plug := Provider{ID: "zc", Account: &Account{plugin: &plugin.Provider{ID: "zc", MaxAccounts: 2}}} + if n := plug.AtOnce(); n != 2 { + t.Fatalf("the plugin's own = %d, want 2", n) + } + if n := plug.PluginAtOnce(); n != 2 { + t.Fatalf("PluginAtOnce = %d, want 2", n) + } + three, none := 3, 0 + plug.MaxAccounts = &three + if n := plug.AtOnce(); n != 3 { + t.Fatalf("the user's 3 over the plugin's 2 = %d", n) + } + plug.MaxAccounts = &none + if n := plug.AtOnce(); n != 0 { + t.Fatalf("the user's no limit over the plugin's 2 = %d", n) + } + if n := (Provider{ID: "keys", Key: "k"}).AtOnce(); n != 0 { + t.Fatalf("no plugin, nothing set = %d", n) + } + + p := Provider{ID: "at-once", Name: "At once", Chat: "https://example.invalid/v1", Key: "a", Keys: []KeyAccount{{Key: "b"}, {Key: "c"}}} + if err := Save(p); err != nil { + t.Fatal(err) + } + two := 2 + if err := SetAtOnce(p.ID, &two); err != nil { + t.Fatal(err) + } + got, err := Find(p.ID) + if err != nil { + t.Fatal(err) + } + if got.AtOnce() != 2 || got.MaxAccounts == nil || *got.MaxAccounts != 2 { + t.Fatalf("set to 2: %d %v", got.AtOnce(), got.MaxAccounts) + } + if err := SetAtOnce(p.ID, new(int)); err != nil { + t.Fatal(err) + } + if got, _ = Find(p.ID); got.AtOnce() != 0 || got.MaxAccounts == nil { + t.Fatalf("set to no limit: %d %v", got.AtOnce(), got.MaxAccounts) + } + if err := SetAtOnce(p.ID, nil); err != nil { + t.Fatal(err) + } + if got, _ = Find(p.ID); got.MaxAccounts != nil { + t.Fatalf("given back to the plugin's: %v", *got.MaxAccounts) + } + big := MaxLimit + 1 + if err := SetAtOnce(p.ID, &big); err == nil { + t.Fatal("a limit past MaxLimit was taken") + } + neg := -1 + got.MaxAccounts = &neg + if err := Save(*got); err != nil { + t.Fatal(err) + } + if got, _ = Find(p.ID); got.MaxAccounts == nil || *got.MaxAccounts != 0 { + t.Fatalf("a save of -1 kept %v, want 0", got.MaxAccounts) + } +} diff --git a/internal/provider/concurrency.go b/internal/provider/concurrency.go index b801ef3dc..fe1ab5320 100644 --- a/internal/provider/concurrency.go +++ b/internal/provider/concurrency.go @@ -32,6 +32,52 @@ func (p Provider) PluginConcurrency() int { return max(p.Account.plugin.MaxConcurrency, 0) } +// AtOnce is how many of the provider's accounts or keys take requests at +// the same time, 0 for no limit: the user's MaxAccounts when they set one, +// else what the plugin giving the provider says (its auth hook's +// maxAccounts, or its package.json's magpie.maxAccounts), else none. An +// account not had from All or AlsoOn carries none of the provider's +// settings: they are read from providers.json then. +func (p Provider) AtOnce() int { + n := p.MaxAccounts + if n == nil && p.Account != nil { + if s, ok := storedPicks(p.ID); ok { + n = s.MaxAccounts + } + } + if n != nil { + return min(max(*n, 0), MaxLimit) + } + return p.PluginAtOnce() +} + +// PluginAtOnce is how many of its accounts the plugin giving the provider +// says may take requests at the same time, as it lists it now; 0 for none, +// or for a provider no plugin gives. +func (p Provider) PluginAtOnce() int { + if !p.IsPlugin() { + return 0 + } + if cur, ok := PluginOf(p.ID); ok { + return min(max(cur.MaxAccounts, 0), MaxLimit) + } + return min(max(p.Account.plugin.MaxAccounts, 0), MaxLimit) +} + +// SetAtOnce sets how many of the provider's accounts or keys take requests +// at the same time: 0 for no limit, nil for what its plugin says. +func SetAtOnce(id string, n *int) error { + if n != nil && (*n < 0 || *n > MaxLimit) { + return fmt.Errorf("accounts at once is from 0 (no limit) to %d, not %d", MaxLimit, *n) + } + p, err := Find(id) + if err != nil { + return err + } + p.MaxAccounts = n + return Save(*p) +} + // One account's or key's own limit (#892: a Claude account kept to two // at once while the provider's others take more), the queue's bound and // how long a request waits in it. The limit is the lane's — the account diff --git a/internal/provider/provider.go b/internal/provider/provider.go index 8af7739e0..c09d1856e 100644 --- a/internal/provider/provider.go +++ b/internal/provider/provider.go @@ -163,6 +163,14 @@ type Provider struct { // in the order they came (see Concurrency). nil follows what a // plugin's provider says it takes, else none; 0 is no limit. MaxConcurrency *int `json:"maxConcurrency,omitempty"` + // MaxAccounts is how many of its accounts or keys take requests at + // the same time (01huadalang on Discord: ZCode's firewall blocks the + // address that three of its accounts ask from at once, and two are + // fine). Routing goes over the first that many it would ask, in its + // order and not resting; the others wait as reserves until one of + // those rests (out of quota, rate limited, failing). nil follows what + // a plugin's provider says, else none; 0 is no limit (see AtOnce). + MaxAccounts *int `json:"maxAccounts,omitempty"` // AccountConcurrency is, for one account or key, its own limit over // MaxConcurrency (#892): an account by its name in lower case, a key // by its KeyID; 0 there is no limit for it. One not in it takes the @@ -767,6 +775,10 @@ func (p Provider) clone() Provider { v := *p.MaxConcurrency p.MaxConcurrency = &v } + if p.MaxAccounts != nil { + v := *p.MaxAccounts + p.MaxAccounts = &v + } if p.ZhipuTeam != nil { v := *p.ZhipuTeam p.ZhipuTeam = &v @@ -837,6 +849,7 @@ func withPicks(a, pk Provider) Provider { a.CapStop, a.CapCareful = pk.CapStop, pk.CapCareful a.AccountNames = pk.AccountNames a.MaxConcurrency, a.PinUpstream = pk.MaxConcurrency, pk.PinUpstream + a.MaxAccounts = pk.MaxAccounts a.AccountConcurrency, a.QueueLimit, a.QueueWait = pk.AccountConcurrency, pk.QueueLimit, pk.QueueWait a.AccountWeights = pk.AccountWeights a.MaxRPM = pk.MaxRPM @@ -985,7 +998,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, 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)} + 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, MaxAccounts: p.MaxAccounts, 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) { @@ -1521,6 +1534,10 @@ func normalize(p Provider) Provider { if p.MaxConcurrency != nil && *p.MaxConcurrency < 0 { p.MaxConcurrency = new(int) } + if p.MaxAccounts != nil { + v := min(max(*p.MaxAccounts, 0), MaxLimit) + p.MaxAccounts = &v + } 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)