diff --git a/docs/subsystems/gateway-routing.md b/docs/subsystems/gateway-routing.md index 5618edf76..232e8d0ae 100644 --- a/docs/subsystems/gateway-routing.md +++ b/docs/subsystems/gateway-routing.md @@ -196,7 +196,7 @@ recorded as a prediction failure (`noPrediction`). - A rule by agent (`Rule.Agents`, `agents=codex,sillytavern`) matches the agent the gateway names the request's (`agentOf` in [`gateway.go`](../../internal/gateway/gateway.go): its `magpie-` key, else its User-Agent), in lower case (`cleanRules`, `MatchesBesidesIntent`, `Pauses`). A client magpie doesn't know is named by its User-Agent's product name, before the first `/` or space (`usage.AgentOf`), so a rule can hold SillyTavern or one's own app (raikyou on Discord). The editor's agent picker lists the agents magpie knows, then those `/api/usage?period=30d` heard from that it doesn't (not `other`, nor `magpie`), and takes a name typed in its filter as the gateway reads a User-Agent (`uaName` in [`plugins/routing/client.js`](../../internal/gui/assets/plugins/routing/client.js), through the picker's `field.typed`): "MyApp/2.0 (Linux)" is `myapp`. `routing-rule-agent-typed.test.cjs`. - A pause rule (`Rule.Pause`, `pause=`; John on Discord: a model of the group paused in its vendor's peak hours) leaves the model it names out of the group while it holds (`provider.PausedOut`, on `ruleClock`): the group's own rules and each nested group's on the way down to a member, a group named taking all its models, and a model named taking it wherever a group in the group has it (#625). It runs before planning, on every request rather than once a turn, so the model is not first, not a failover, and not kept by affinity, and comes back as soon as the hours end. It holds by hours, days, agents and folders only (`cleanRules` refuses another condition), and is not a send-to rule: `Matches`, `MatchRule`, `ThenUses`, `Ruled` and the compaction rules leave it out. A send-to rule naming a paused model finds it unready and the group routes as without it. The trace keeps what was paused (`GroupRef.Paused`), and the Routing page says so. Every model paused answers 503 (`pausedError`) naming each rule. Embeddings go by the same pauses; manual groups have no rules (`Live`), so none pause there. A pause by folder (#1606, Ti800: a subscription's quota kept for the long task in one folder, `pause= except-folders=~/big-task`) reads the folder only when such a pause is on the way (`provider.PausesByFolder`, then `workDir`): outside its except-folders, which includes a request that says no folder (a subagent's or a small model's that doesn't), the model is left out; with `folders=`, only requests known to be in them. Embeddings and System One's decision calls have no folder. `Paused.Folder`/`ByFolder` carry what was read, and the Routing page says the folder or that none was said. `rules_pause_test.go`, `TestPauseByFolder`, `TestPauseByFolderRule`, `TestParsePauseByFolder`, `routing-pause-folder.test.cjs`. - A rule's hours and days (`Rule.Time`, `provider.TimeWindow`) are read on `ruleClock` in the zone they were set in (`TimeWindow.Zone`, an IANA name; gaubeebangeel on X: magpie on a cloud server in UTC, its user in Beijing, the hours 8 off). The GUI saves the browser's zone when the hours or days are changed in the editor and leaves a rule's zone alone otherwise; the CLI (`magpie group rule add … time=09:00-18:00@Asia/Shanghai` or `tz=`) and the TUI save the one typed, or this computer's (`provider.LocalZone`: `$TZ`, `time.Local`, the `/etc/localtime` link) when it has an IANA name. A window with no zone, every one saved before zones were kept, stays on magpie's own clock. A zone magpie doesn't know is refused on save (`TimeWindow.clean`), and one in a file edited by hand makes the window never hold (`zoneOf`): the rule is as if absent, never always on and never hours off. Zones come from Go's embedded tzdata, so Windows knows them too. `/api/groups` gives magpie's clock (`clock`: its zone and offset in seconds), and when it differs from the hours' zone the Routing groups page tells the zone beside them, on the group's rules and in the editor (`zoneNote` in [`plugins/routing/client.js`](../../internal/gui/assets/plugins/routing/client.js)): the zone's name, or the server's offset for hours with none. `TestRuleTimeWindowInItsZone`, `TestRuleTimeWindowInItsZoneAtTurnStart`, `TestRuleTimeWindowUnknownZone`, `TestParseRuleTimeZone`, `TestGroupRuleTimeZoneCmd`, `routing-time-zone.test.cjs`. -3. Candidates come from `planGroup` for a group or `plan` for a provider. They are filtered by `sealedReaders` and `allowedCandidates`. An account past its share is held out of the candidates (`capHeld`): a usage cap's share, each window at its own where the account gives it one (`AccountWindowCaps`, willz on Discord: 50% of the five hours, 40% of the week) and at the account's cap otherwise, or 100% of a window for a Codex account set not to spend its credits (`provider.HoldCaps`, `WindowCaps.Of`, `CodexNoCredits`). A ChatGPT account's call on `codex-auto-review`, which OpenAI counts in no window, is held by no usage cap, only by credits it may not spend (`freeOnChatGPT`, #1593, `TestAccountCapLetsAutoReviewThrough`); a Free plan's call is capped as any other (`TestAccountCapHoldsAutoReviewOnAFreePlan`). The account is held while any window is past its own share, and `cappedError` and the trace name the fullest such window's share and cap. When every candidate is held and one held for its credits spends its resets by itself, `autoReset` spends a reset on it and it is tried (`planned.held`). A Codex account let spend its credits is never held or refused for its week, so before a try goes to one whose week its last reading says is used up and that spends a reset when its week runs out, `resetBeforeCredits` spends one first, one a week at most, in routing and in the relay (`resetBeforeCreditsOn`); a reset is free and credits cost money (tongzhenbao on X, `TestCodexResetBeforeCredits`). Otherwise a capped or barred set returns `cappedError` or `barredError`. A provider with Stop at the caps on (`CapStop`, plugins#349) answers that 429 instead of going on to its fallbacks when every primary account is held (`plan`, `TestCapStopSkipsTheFallbacks`); off, the default, the fallbacks take it as before. With every account held and no fallback left to take it, a request for a model the user put in routing groups of their own goes on to those groups, in the user's order, each as its own routing orders it (`provider.GroupsAfter`, `groupsAfter`, planned again in serve with them after the fallbacks; a group magpie found, hidden or switched off, or one with no other member, is none). The Codex app signed in to ChatGPT asks Codex's own model, never the group built around it, so its capped account answered 429 though a group had two APIs after it (adorable_piglet on Discord, v0.1.3354; `TestCappedCodexOwnModelGoesToItsGroup`). `CapStop` still answers the 429, and a request for the group itself was routed so before (`TestCappedSubscriptionGivesWayInGroup`). A careful provider (`CapCareful`, plugins#349, off by default, `cap_careful.go`) has `readCareful` read a capped account's usage again before planning when its reading is over 15s old within 5 points of a cap, or over 5m old at all, waiting at most 10s and asking a failed account again at most every 15s; `capHold` then holds an account whose usage was never read, whose last read failed or whose reading is still that old (`carefulDoubt`, `Weighed.Unread` in the trace), as one at its cap is: unknown is not spent (`TestCarefulHoldsWhatItCantTell`, `TestCarefulReadsAgainNearTheCap`, `TestCarefulEveryAccountUnread`, `TestCarefulOffByDefault`). Planning goes by the last reading, so turns sent together were each planned on the same one: an account a point under its cap took all of them and went past it by what they used between them (dyzdyz010 on Discord: capped at 90%, used to 100%). In serve's walk an account within 5 points of a usage cap (`nearCapOf`, `nearCapPoints`, `cap_near.go`) takes one turn at a time (`Server.nearCap`, its turn held until the try ends): a turn that finds it busy goes to the next candidate first, the account moved behind them once (`nearBehind`); the last candidate waits. Once its turn comes `capHeld` judges it again, by what the reply before it left (Codex's `codex.rate_limits`, Claude's `rate_limit_event`), or, when that reply said nothing of the account's usage, by a reading taken again then (`nearCapAgain`, at most `carefulWait`); held, it is passed over, and when it was the last the agent gets `cappedError`'s 429. The cap is passed by one turn at most, as a gateway key's limit is, Claude Code accounts as Codex's (`TestNearCapTakesOneTurnAtATime`, `TestNearCapWaitsThenHolds`, `TestNearCapReadsAgainAfterASilentReply`, `TestFarFromCapTurnsGoTogether`, `TestNearCapClaudeAccountsTakeOneTurnEach`). A conversation kept on its account by Stays: Strict goes on past the cap as `strictKeep` keeps it, and takes no turn there (`TestStrictAffinityGoesPastTheCap`). Then `affine` moves the conversation's last answerer first, unless it is resting or nearly used up. An `X-Magpie-Account` header (`AccountHeader`) pins the request to one account: only that account is tried, and when it can't answer the caller is told why. A header value is ASCII on the wire and fetch refuses one that isn't, so an account whose user isn't ASCII (北冥, plugins#615) is named percent-encoded; `pinnedName` decodes it, the value as written matches too, and the trace and the call's record name it decoded (`TestAccountPinnedPercentEncoded`). +3. Candidates come from `planGroup` for a group or `plan` for a provider. They are filtered by `sealedReaders` and `allowedCandidates`. An account past its share is held out of the candidates (`capHeld`): a usage cap's share, each window at its own where the account gives it one (`AccountWindowCaps`, willz on Discord: 50% of the five hours, 40% of the week), or at a fixed amount of a window counted in a unit with its total (`AccountWindowAmounts`, 9won_25273 on Discord: 300 of a day's 1000 credits; held once the window's count reaches it, `WindowCaps.limitShare`, `TestWindowAmountHoldsTheAccount`), and at the account's cap otherwise, or 100% of a window for a Codex account set not to spend its credits (`provider.HoldCaps`, `WindowCaps.Of`, `CodexNoCredits`). A ChatGPT account's call on `codex-auto-review`, which OpenAI counts in no window, is held by no usage cap, only by credits it may not spend (`freeOnChatGPT`, #1593, `TestAccountCapLetsAutoReviewThrough`); a Free plan's call is capped as any other (`TestAccountCapHoldsAutoReviewOnAFreePlan`). The account is held while any window is past its own share, and `cappedError` and the trace name the fullest such window's share and cap. When every candidate is held and one held for its credits spends its resets by itself, `autoReset` spends a reset on it and it is tried (`planned.held`). A Codex account let spend its credits is never held or refused for its week, so before a try goes to one whose week its last reading says is used up and that spends a reset when its week runs out, `resetBeforeCredits` spends one first, one a week at most, in routing and in the relay (`resetBeforeCreditsOn`); a reset is free and credits cost money (tongzhenbao on X, `TestCodexResetBeforeCredits`). Otherwise a capped or barred set returns `cappedError` or `barredError`. A provider with Stop at the caps on (`CapStop`, plugins#349) answers that 429 instead of going on to its fallbacks when every primary account is held (`plan`, `TestCapStopSkipsTheFallbacks`); off, the default, the fallbacks take it as before. With every account held and no fallback left to take it, a request for a model the user put in routing groups of their own goes on to those groups, in the user's order, each as its own routing orders it (`provider.GroupsAfter`, `groupsAfter`, planned again in serve with them after the fallbacks; a group magpie found, hidden or switched off, or one with no other member, is none). The Codex app signed in to ChatGPT asks Codex's own model, never the group built around it, so its capped account answered 429 though a group had two APIs after it (adorable_piglet on Discord, v0.1.3354; `TestCappedCodexOwnModelGoesToItsGroup`). `CapStop` still answers the 429, and a request for the group itself was routed so before (`TestCappedSubscriptionGivesWayInGroup`). A careful provider (`CapCareful`, plugins#349, off by default, `cap_careful.go`) has `readCareful` read a capped account's usage again before planning when its reading is over 15s old within 5 points of a cap, or over 5m old at all, waiting at most 10s and asking a failed account again at most every 15s; `capHold` then holds an account whose usage was never read, whose last read failed or whose reading is still that old (`carefulDoubt`, `Weighed.Unread` in the trace), as one at its cap is: unknown is not spent (`TestCarefulHoldsWhatItCantTell`, `TestCarefulReadsAgainNearTheCap`, `TestCarefulEveryAccountUnread`, `TestCarefulOffByDefault`). Planning goes by the last reading, so turns sent together were each planned on the same one: an account a point under its cap took all of them and went past it by what they used between them (dyzdyz010 on Discord: capped at 90%, used to 100%). In serve's walk an account within 5 points of a usage cap (`nearCapOf`, `nearCapPoints`, `cap_near.go`) takes one turn at a time (`Server.nearCap`, its turn held until the try ends): a turn that finds it busy goes to the next candidate first, the account moved behind them once (`nearBehind`); the last candidate waits. Once its turn comes `capHeld` judges it again, by what the reply before it left (Codex's `codex.rate_limits`, Claude's `rate_limit_event`), or, when that reply said nothing of the account's usage, by a reading taken again then (`nearCapAgain`, at most `carefulWait`); held, it is passed over, and when it was the last the agent gets `cappedError`'s 429. The cap is passed by one turn at most, as a gateway key's limit is, Claude Code accounts as Codex's (`TestNearCapTakesOneTurnAtATime`, `TestNearCapWaitsThenHolds`, `TestNearCapReadsAgainAfterASilentReply`, `TestFarFromCapTurnsGoTogether`, `TestNearCapClaudeAccountsTakeOneTurnEach`). A conversation kept on its account by Stays: Strict goes on past the cap as `strictKeep` keeps it, and takes no turn there (`TestStrictAffinityGoesPastTheCap`). Then `affine` moves the conversation's last answerer first, unless it is resting or nearly used up. An `X-Magpie-Account` header (`AccountHeader`) pins the request to one account: only that account is tried, and when it can't answer the caller is told why. A header value is ASCII on the wire and fetch refuses one that isn't, so an account whose user isn't ASCII (北冥, plugins#615) is named percent-encoded; `pinnedName` decodes it, the value as written matches too, and the trace and the call's record name it decoded (`TestAccountPinnedPercentEncoded`). 4. The candidate loop calls `attempt` on each candidate in turn, through a `holdWriter`. The writer holds the reply until it is clearly passing. A candidate that fails before anything is sent rests (`failure`): out of credit for 30 minutes (a key longer each time it is refused so again once its rest has ended: 30 minutes, 2 hours, 8 hours, a day, 3 days, then a week (`creditLadder`, `creditBackoff`), the same rung while a rest still runs, a new run after "Try now" (`Unrest`) or an answer; each such rest, its rung and when it ends, is kept in `rests.json` beside `providers.json` (written through a renamed temp file whenever one is set or dropped, `saveRests`) and read once as the gateway starts to listen (`loadRests`), so a restart rests out what is left and climbs on from the rung: an ended rest keeps its rung there as in memory, unless it ended over `restsKeep` (35 days) ago, a key no longer in `providers.json` is let go, and a file or `providers.json` that can't be read or parsed adds no rest (PaulT on Discord, `TestKeyCreditRestOutlivesRestart`, `TestKeyCreditRestFileCorrupt`); a refusal that names its reset rests till then, and one that says it can pass soon (a `Retry-After`, OpenRouter's in-flight budget or "can only afford", a "try again in 30 seconds", `creditSoon`) rests 30 minutes or less and doesn't climb; a remote magpie's model rests 30 minutes as before: PaulT on Discord, `TestKeyOutOfCreditRestsLongerEachTime`; a ChatGPT account until the reset its refusal names, else until its full window renews, else 5 hours, `chatgptCreditRest`, and a reading finding its window renewed has it back: PaulT on Discord, `TestChatGPTOutOfCreditsRestsLong`), out of quota until reset, rate limited until retry-after, otherwise a minute and longer on repeats: doubled each time, up to `longestRetry` (10 minutes) for a failure and `longestRateRest` (30 minutes) for a rate limit back as soon as its rest is over, or up to the provider's own `restCap` in minutes (`Provider.RestCapOr`, at most `MaxQuotaRest`; `magpie provider rest-cap 4h`, #2008: a free key down for hours was asked every 10 minutes). A time the vendor names stands over it as before (`TestOwnRestCap`). An error `failure` reads as out of credit is `retryable` at any 4xx, so the next account or member is asked and this one rests as credit; before, a 400 or 422 counted only by `quotaWords`, and SuperMagic's 400 「您的可用积分已不足…通过「充值」通道补充积分」 went to the agent with another account of 6,467 points unasked, the empty one never rested (#4095, mycf_711; `TestCredit400MovesToTheNextAccount`). A shape refusal that also says so (`creditWords` in `shapeRefused`) is the credit it says. The failure count is kept per key or account (`restKey`), and any of its models' answers clears it (`served`). Each model's own count (`restID`) is kept beside it and cleared only by that model's answer (`servedCandidate`): once it is past the account's, a sibling model answered since it last did, so the failure is the model's and it climbs its own ladder and rests alone, its siblings still served (#2241, weizsw: an Antigravity seat's gemini-3.5-flash-lite rested a minute 41 times of 43 while gemini-3.8-flash kept answering; `TestModelLadderClimbsPastSiblingAnswers`). Every model failing with no answer between still climbs the account's ladder and rests the account, and a candidate naming no model has the account's count alone. `rest-cap off` (`provider.RestCapOff`, `restCap: -1`) is for a relay or account pool whose unknown errors come now and then and pass by the next request (Kismet Alan on Discord): a failure that says nothing of why (`failOther`: a 5xx, a dropped connection) then rests nobody and isn't counted, its trace rest `by: "off"` with no time left. A 401 or 403, a model not served, an account's window full, a rate limit (magpie's own 30-minute cap), quota, credit and a restriction still rest it as before (`TestRestCapOff`). A provider the user added can be set never to rest for a limit instead (`provider.LimitRestOff`, `limitRestOff` in providers.json; the editor's Advanced fold, "Set it aside when out of quota or rate limited", ticked by default): a refusal `restAfterMarked` reads as out of quota, out of credit or rate limited, and any 429, then rests nothing, isn't counted or sunk, and is `by: "off"`; `restDrawer` rests no image model of it. The next request is sent to it as usual. It is for a relay whose limits pass in a moment (zoecats on Discord: a local aggregator said "quota exhausted" while it switched upstreams, and magpie answered itself for 30 minutes; `TestLimitRestOffKeepsAsking`, `TestLimitRestOffRestsNothingForALimit`). A 401, a model not served and a plain failure still rest it. The shortest cap otherwise is a minute, the first rest; `rest-cap 30s` is turned away and names `off`. A 400, 403, 404 or 422 that says the model isn't served (`unservedWords`) and says nothing of quota, credit or a rate limit rests only that key's or account's model (`modelRefused`, keyed by `restID`, its backoff counted apart): its other models are still served first in order (#1235, SenseNova's 403 "model is not available in the current token plan"). A Google account's Code Assist (the Antigravity and Gemini CLI built-ins) answering 404 `NOT_FOUND` ("Requested entity was not found.") rests its model the same way, as its endpoint is the same for every model (`codeAssistModelMissing`; Packing1 on Discord: Argon, listed for a Google AI Pro account, answered 404 and rested the whole account; `TestCodeAssistMissingModelRestsTheModel`). A refusal for want of quota, credit or rate, for an account its vendor restricted, or for a verify it asks of its account there, from another computer's magpie (a Remote magpie provider, LAN share) rests only the model it was about (`remoteModelRest`, keyed by `restID`, in `restAfterMarked` and `rateRest`): that magpie serves each of its models from its own providers and rests them itself, so one out of quota there says nothing of the others (bigsteven on Discord: a 429 for one model rested every model on the remote for the 3 hours it named, so a group never moved on to the remote's other models; `TestRemoteMagpieQuotaRestsTheModel`, `TestRemoteMagpieRestrictedRestsTheModel`). Such a rest out of quota or credit (`Rest.there`) still puts the model behind the others, but is never given again without asking (`quotaHeld` passes it by): that magpie holds its own rests and answers from them at once, and what it serves under a name may have changed there since (zaidu259434 on X: a routing group there moved off a spent Open Design, and this magpie gave Open Design's 402 again until the time it named, never asking; `TestRemoteMagpieQuotaIsAskedNotReplayed`, `TestHandAddedMagpieQuotaIsAskedNotReplayed`). Another magpie added by hand, as an OpenAI-compatible provider of the user's own name rather than the preset, is read as one by its reply: a magpie names the provider that answered or held it (`X-Magpie-Provider`, `providerHeader`; `noteMember`, also on a `quotaHeld` or `verifyHeld` answer), as no vendor does, and `keepRetry` notes it as `answeredThereHeader`, since this magpie writes its own provider into the same header of its reply and the note is kept from the client (lagrangepoint1813 on Discord: "Remote Magpie: Claude Code: You've hit your session limit" answered every model of it, from `quotaHeld`, for the five hours it named; `TestAnotherMagpieAddedByHandRestsTheModel`, asked there and held there). Its key refused, the computer unreachable, or the key's own limit there (`keyLimited`'s 429, which carries `X-Magpie-Limit-Reset`, `remoteKeyLimitHeader`), still rests it whole: #2077's reporter had a Claude Code session limit on the other magpie refuse its Qoder models here (`TestRemoteMagpieRestsTheModel`, two gateways over HTTP; `TestRemoteMagpieKeyLimitRestsTheKey`). The held try keeps that marker only as a note of magpie's own (`keepRetry` sets `keyLimitThereHeader`, which `holdWriter` never passes on), so the rest is whole however the 429 came, and the marker never reaches the agent or a magpie this one answers, which would read it as this magpie's own key limit (#2791, ggbdpq; `TestRemoteMagpieKeyLimitRestsTheRemote`, `TestRemoteMagpieKeyLimitMarkerStaysHere`). A 400, 404, 410 or 422 that says the model is retired (`retiredWords`: OpenCode Zen's 410 `ModelDeprecated` "Model exo-free has been deprecated.", whose own model list still names it; MOMO on Discord) rests only that model the same way, is retryable so a group's next member or another provider of it is asked, and is remembered (`provider.Retire`, `retired.json` beside `providers.json`): the model leaves that provider's entries in the catalog (`buildEntries`), so /v1/models, every agent's model list and the found groups go without it, until a request on it is answered again (`Unretire` in `servedCandidate`) or a week has passed. A refresh of the vendor's list doesn't bring it back early, since that list is where it still is. A `provider/model` request for it is still sent. A 400 or 422 that says this upstream's API can't take the request's shape (`shapeWords`: xAI's 422 "unknown item type" (#350), OpenAI's "Unknown parameter", and a limit of a model's own on tool schemas, OpenCode Go's 400 "JSON schema exceeds the maximum nesting depth of 10 levels" on muse-spark-1.3-contributor, #1870), or that it is served on another API than the one asked (`wrongEndpoint`, once the member has tried every API it has a URL for: #2670, a relay with a Chat URL alone refusing tools with reasoning and `none` too), rests nobody: the next candidate is asked once (`shapeRefused`, `failShape`), and the last one's error reaches the agent. A request missing what every API requires ("field required") isn't one, nor is a 200 that mentions it. A model asking for an earlier reply's reasoning the history doesn't have (`reasoningBackRefused` in `thinking_back.go`: Command Code's Beam answering "Missing required parameter: 'messages[1].reasoning_content'" to a second turn, DeepSeek's and Kimi's words for their tool turns) is one too, after any refill `refuseThinkingBack` makes: the request is whole, and another member's model may not ask for it (EDwinpzy on Discord, `TestGroupFailsOverAMissingReasoning`); a missing `messages` or `model` still stops (`TestMissingReasoningIsNotABadRequest`). Command Code's Provider API turning a request away with nothing but a trace id (`unsaidWords`: `{"message":"invalid request error trace_id: ","type":"invalid_request_error"}`, a 400, or a 422 before) is handled the same way: it turns away a request whose history and asked-for output together are over a limit below the model's listed context (the reporter's A/B: one ~748K-token agent conversation answered 200 with `max_completion_tokens` 64000 and this 400 with 384000, the model's listed max output), which another member's model may take, and the key is fine (#2313, `TestGroupFailsOverCommandCodesBare400`). Its overflow, which names the model's context length before the trace id, and an error that names a `param`, aren't one. A relay's own cap on one request's input that says so (`tooLongRe`: B.ai's 400 "Input token exceed the limit", on a 380K request under the model's 1M window; #2445, worksyang) is taken as an overflow (`overflowed`), which no word list of `retryable` matched: a group's next member that may hold the request is asked (`withRoom`, `failOverflow`), nobody rests, another account of the same model isn't asked, and with no member left the agent is told the conversation is too long, so it compacts. The conversation remembers the refusal (`noteOverflow` in [`affinity.go`](../../internal/gateway/affinity.go), by its stick key and the member's provider and model, with the request's size): its next request at least as large asks that member after the others (`behindOverflow`, after `roomy`, so after a rule that named it), behind and not out, until the member answers one (`forgetOverflow`) or the conversation shrinks below the refused size. Another conversation, and a 413 byte cap, are not affected (#3453, `TestOverflowRefusedOnceIsAskedLast`). A rate limit worded with input tokens (`paceWords`) isn't one, and a plain bad request is still asked of nobody else (`TestRelayInputCapGoesToTheNextMember`). Chinese that names the input rather than the context is one too (`tooLongRe`'s third line: a group member's 400 「内容太长了,请精简输入或开启新对话」, z.ai's 「Prompt 超长」, iFlytek Spark's 「…字数太多,需要精简输入」, 「输入长度超过限制」); before, it was a plain failure that rested the member and asked no other (#4420, MYCF711; `TestChineseInputTooLongGoesToTheNextMember`). Each names what was sent beside its length, so a field's or the reply's length isn't one, and Chinese pace words (速率, 频繁, 并发, 每分钟…, in `paceWords`) beside them make it a rate limit, not a size (`TestChineseNotTooLong`). A 400 or 422 whose message speaks only of length, without naming what is long (`lengthWords` in `fallback.go`: 太长, 过长, 精简, 开启新对话, "too long", "too large", "shorten"), with no pace word and no part of the request named (`partWords`: a picture, a file, the reply, a field), is the request too long for that member once the request is past half its window (`saysLength`, `lengthMargin` 0.5 in `tooLongUnsaid`), not the 1.2 margin a refusal that says nothing needs: a vendor whose own ceiling is under the window it declares answered 「内容太长了…」 at ~730K of a declared 1M (#4420, MYCF711). It then goes as an unsaid overflow goes: to a member with room, nobody resting, else to the agent as "prompt is too long" (`TestLengthWordsPastHalfTheWindowGoToTheNextMember`). A refusal that says nothing of length is read as an overflow only from the vendors seen to answer one so, by the plugin that serves them (`unsaidStatus` in `fallback.go`: Devin's 5xx, Qoder's, Qoder CN's, WorkBuddy's and WorkBuddy AI's 400/413/422, Factory's 413), once the request is 1.2 times past the window (`unsaidMargin`), the window no less than the most the model has answered here or its list's `max_context_window`; any other provider's failure, a custom relay's, OpenAI's or Anthropic's, reaches the agent with its own status and words, as does a transport failure from any vendor (#5486, NEKO-CwC; `TestRelayFailureKeepsItsOwnWords`, `TestUnsaidVendorsStillOverflow`, `TestTransportFailureIsNotTooLong`). Under half the window the same words are left as the vendor's error. A subscription account that fails any other way with a window full, by magpie's latest reading of its windows, rests until that window renews; when every full window that counts the model counts some models only (`Allowance.Pooled`), only that model rests (`restID`), and its siblings in their own windows still answer (plugins#817: ZCode's GLM-5.3 gift bucket spent left GLM-5.3-Flash's; `TestScopedWindowFullRestsTheModelOnly`). A 401 or 403 is the exception: one that names a quota is out of quota already (`usedUpWords`), and one that doesn't is about the key or the request, so it rests on the backoff ladder whatever the reading says (plugins#243, zygs1083-dotcom: a Factory account read at 98% sat out its week over one plain 403; `TestPlain403DoesNotRestUntilTheWindow`). A plain 403 (`plainForbidden`: no quota, credit, rate, verification, restriction or model not served) from a second key or account of the same provider, model and reasoning in one request is the request refused, not each account: neither rests, the first one's rest and counted failure are taken back (`forbiddenAlike`, `unforbid`), and the provider's other mates are asked last (`matesLast`). Before, that one request walked every account of the provider into backoff (`TestPlain403OnTwoMatesRestsNeither`). One account's plain 403 alone still rests it. A 500, 502 or 503 that says nothing of why (`plainUnavailable`: no quota, credit, rate, overload, proxy down, ChatGPT reset or protection refusal, and some words) is read the same way when a second account of the same provider, model and reasoning gives it in the same words and status, ids left out (`refusalWords`), and the provider answered another request within `answeringLately` (5 minutes, `answeredLately`, noted in `servedCandidate`): neither rests, and the last one left isn't asked again after a moment (`sameRefusal`). Before, one agent's request an upstream always refused (mycf_711 on Discord: 127 of a provider's 128 503s were "AIError AI服务异常", for an empty tool schema) walked every account into backoff and the other agents found them all resting. One account's 503 alone, 503s in other words, and alike 503s from a provider that answered nothing lately (an outage) still rest as before, so an outage is backed off once 5 minutes have passed since its last answer (`TestPlain5xxOnTwoMatesRestsNeither`). Both quota rests and window rests are held to `longestQuota` (8 days), so a reset time read wrong (a year off) doesn't bench the account for that long. The next candidate is then tried. A failed provider waits `fallbackCooldown` (1 minute) at the back. An overload is no failure of the account's (`vendorOverloaded`: a 529, the ChatGPT backend's `server_is_overloaded` and Anthropic's `overloaded_error` among them, or a 5xx whose words say overloaded, as Gemini's 503 does): its model rests on that account `overloadRest` (30 seconds), or as long as a Retry-After asks up to `overloadRestMost` (a minute), every time alike, and no failure is counted on the backoff ladder (celestial_eagle_99230 on Discord: eight Codex accounts each rested up to the 10-minute cap for ChatGPT's overload, "failed 5 times in a row", leaving nothing to answer). A WorkBuddy account the vendor restricted (#1849: 403 `{"code":11140,"msg":"request illegal","displayMsg":{"en":"Your account has been restricted due to unusual activity",…}}`) rests `restrictedRest` (2 hours) as `restricted` (`failRestricted`), not the minutes of an unknown failure: only WorkBuddy lifting the restriction, after the user's appeal, brings it back. Both shapes are known: the built-in's `wbExplain` and the plugin's `explained()` (0.1.17, the mover's `min`) end the error with `provider.WBRestrictedHint` (`restrictedSaid`), and the vendor's own body, its code 11140 or its words (`provider.WBRestricted`), counts only from a WorkBuddy candidate (`restrictedRefused`, `isWorkBuddy`), as another vendor's 11140 is its own. Bare "request illegal" isn't matched. A vendor's risk control reads the request as well as the account, so a restricted account (`failRestricted`, ZCode's 3012 too) walls its provider off for the rest of the request (`riskRefused`, `elsewhere`; `busyNow` and `roomy`'s left-out list too): none of the provider's other accounts is sent it, a group's other provider is asked, and with none left the agent is told and the account rests, the last one left too. Before, one request was sent on from account to account and each was restricted in turn (_teamtaylor_ on Discord; `TestRiskRefusalNotSentToTheProvidersOtherAccounts`, `TestRiskRefusalAloneIsToldAndRests`). The next request still goes to the provider's next account. A remote magpie's restriction walls off nothing (`remoteModelRest`). WorkBuddy's 11128 channel refusal stays `promptRefused` and rests nobody. The Routing page names it "account restricted by the vendor", says the appeal is the way back, and gives the account's row a button that lifts the rest (`/api/gateway/unrest`) once the vendor has. Every other rest a key or account takes (quota, rate limit, retry-after, a failure's backoff) can be lifted by hand the same way (#1869): "Try now" on its row on the Routing page and beside its rest note in the provider's key list. It ends the rest, and with Sink on puts the key back from the back of the order; the backoff count stays, and a refusal after it rests the key again the usual way. Every lift before its time (Try now, `UnrestAll` for a replaced key, `renewed` for windows that renewed) is noted by its rest key (`restingUntil.lifted`) and handed to the Routing page in the trace (`TraceState.Lifted`, `lifted` in `/api/gateway/trace`), and a lift wakes a page waiting on the trace though no route changed (`trace.lifted`). The page stops showing a rest or a sink found before its lift, wherever the lift was asked for (zoecats on Discord: Try now in the provider's editor left Routing at 429 until a restart; `TestTryNowToldToTheRoutingPage`, `routing-lifted-elsewhere.test.cjs`). With another magpie serving the gateway, Try now lifts nothing (#3555). The vendor's safety filter refusing a reply rests nobody, whether it refuses the turn before any of the reply is said or once some of it has been said (`refused`, `refusedAfter`). So does one said in a stream a client is answered whole from (a Codex account is streamed upstream for a `stream:false` Responses, Chat or Messages request): each decoder gives the refusal's error event status 400 and its code (`filterRefused`), a whole reply it cut is answered the refusal rather than its words so far, and Anthropic's error shape, which has no code, carries it in `refusedHeader`; before, it was answered 502 `api_error`, asked again, and each account rested (#3274). `restAfterMarked` itself rests nobody, and counts no failure, for a 400 whose error object `policyRefusal` reads as a refusal, by its code, never by words a body may echo of the request. A refusal after the reasoning went through as it came (a vendor whose reasoning is never held, a trusted DeepSeek member, a hold that timed out) but before a word of the answer or a call is handed over (`refusalHandover`, `refusal_handover.go`): when the agent streams Anthropic Messages, Chat Completions or Responses, another candidate is left and `refusalAsksAgain` allows one more (`handsOver`), what passes is read event by event (`passOver`); the refusal's event and everything after it are not sent, an Anthropic block still open gets its `content_block_stop`, the try fails as a refusal with nothing said (`failRefused`, nobody rests, `matesFirst`), and the next try writes through `spliceAfter`, so its stream is the same reply: Anthropic's `message_start` is dropped and its block indexes go after those sent; Responses' `response.created`/`in_progress`/`queued` are dropped, `output_index` goes after the items sent and `sequence_number` goes on from the last one sent; Chat chunks go as they come. Once text or a call has gone, a refusal is the agent's as before (`refusalAfter`). Without another candidate nothing changes. A Gemini stream is not handed over, the reasoning item of a Responses stream handed over gets no `output_item.done`, and the next reply's `response.completed` lists only its own output (#4604). Zhipu's `finish_reason` `"sensitive"` and error 1301 (敏感), DashScope's `data_inspection_failed` and Volcengine Ark's `*SensitiveContentDetected` are refusals (`filterReasons`, `sensitiveCode`). Its note on the try (and in the error the agent gets when nobody is left) is the vendor's reason, with Anthropic's `stop_details` category and explanation when it gave them (`refusedDetail`, #1768: "safety filter: refusal (category cyber)"); none is made up when it gave none. `stop_details` is carried through the IR (`Event.StopDetails`), so a Claude subscription run through the claude CLI and a translated Anthropic route keep it for an Anthropic client too. How many more candidates a refusal before any of the reply is asked of is Settings' `RefusalRetries` (`refusalAsksAgain`, counted per request in the candidate loop; a group's other members count too): unset, every one left (#248); 0, none (#1925, DD on Discord). A Claude subscription account's refusal of a conversation of `retellMost` (100K) tokens or more leaves the subscription's other accounts out (`tooBigToRetell`, `otherThanClaudeAccounts`): each would be a new Claude Code told the whole conversation, all of it written to that account's cache again, for a refusal about the content it most likely gives too (Aisiverto on X: a 900K conversation refused and told again cost a Pro account most of its 5 hours). The size is the larger of what the account counted and `estimate`; other members are still asked, and a smaller conversation still goes to the next account (`TestClaudeSubscriptionBigRefusalNotToldAgain`, `TestClaudeSubscriptionRefusalMovesToNextAccount`). When nobody is left, an agent on Anthropic's Messages API gets the held refusal itself, the vendor's 200 with `stop_reason` `refusal` and its `stop_details`, streamed or whole (`holdWriter.handBack`), since that is what Claude Code switches to its fallback model on; a 400 is only an API error to it. Codex and Chat clients still get `failTo`'s 400 (`refusedStatus`), which they don't ask again for. `TestRefusalRetries*` in [`refusal_retries_test.go`](../../internal/gateway/refusal_retries_test.go) cover keys, a group and the Claude subscription. The ChatGPT backend's 502 "response protection is unavailable" is about the request's content, not the account: the same history fails the same on each of its accounts and models. It rests nobody, isn't tried again after a moment, and isn't asked of the provider's other accounts or models; another provider left in a group is asked once (`protectionRefused`, `elsewhere`). One cause is known (#1270): a history that replays the backend's own `web_search_call` in a request that doesn't declare the `web_search` tool is refused so, whatever the account, model or turn (a plain turn, a thread's description, a compaction, Codex's own text compaction for a custom provider with `tools: []`). Every request to the ChatGPT backend with such a history therefore declares cached-only search (`{"type":"web_search","external_web_access":false}`, `provider.DeclareSearch`): an account's in `codexBody`, Codex's own sign-in relayed in `codexUpstreamOn`. It goes in the tools, or for Responses Lite (its header, `reasoning.context` `all_turns`, or an `additional_tools` item already there), which refuses a top-level `web_search`, in the `additional_tools` item. A request that offered no tools gets `tool_choice` `none` so the model can't search; one with a forced choice keeps it. A history without a search, or a request that declares search already, is relayed unchanged; Codex's own `web.run` (a function in the `web` namespace, which Codex offers in place of the hosted tool on a Responses Lite model or with its standalone web search on, and runs through `/alpha/search`) counts as declaring it, since the backend refuses a request carrying both `web.run` and the hosted `web_search` (Savin on Discord, Codex 0.163.0-alpha; `TestSearchedConversationUnderWebRun`). siwc, API-key requests to openai.com and the legacy `/responses/compact` are left as they were. The ChatGPT backend also turns a whole request away when one tool name in it, a call's in the input or a tool's in `tools`, is outside `^[a-zA-Z0-9_.-]+\z` (400 "Invalid 'input[83].name': string does not match pattern"; wing3556 on Discord, on a compaction): a call another provider's model wrote with a space, a colon or non-ASCII in its name, kept in the history beside its "no such tool", failed every later turn on Codex. Every request to it sends each such name as `provider.CodexToolName` makes it (each refused byte `_`, cut to 55, `_` and 8 hex of its sha256, the same on every request), a valid one unchanged and a body with none byte for byte (`CodexToolNames`): an account's in `codexBody`, Codex's own sign-in's in `codexUpstreamOn` (`/responses/compact` too). A tool the agent declared under such a name is called back by its own: a translated reply through `decoderFor` (`codexNamesBack`), a relayed Responses reply through `nsTidy.back` (`codexRenamedIn`; `TestCodexToolNamesTheBackendTakes`). Namespaces, the OpenAI API, Azure and Copilot are not covered (#4875). Command Code turning a model away for its Zero Data Retention setting (its plugin's switch, 0.1.14, which sends `x-cmd-zdr: 1`; magpie-community/plugins#246) is a refusal of that request's setting, not of the model or the account: the Provider API's 422 with `"code":"cmd_zdr_no_providers"` and the 400 the plugin makes of Go's error line with `"type":"cmd_zdr_no_providers"` (`zdrCoded`, matched as the error's code or type, never by its words, whose "…a different model.","type":"invalid_request_error" read as a model unserved and rested the model on the account). `keepRetry` notes it beside the error (`zdrHeader`), since the error the agent gets may keep no code (Anthropic's shape, or the 400's numeric code). It rests nobody, anywhere (`restAfterMarked` returns `by: "off"`), so the model answers as soon as the switch is off; it isn't asked of the provider's other accounts at that model, which carry the same header (`notMates`), nor again after a moment; another member, the provider's other models among them, is asked once, and with none left the agent gets Command Code's words (`TestCommandCodeZDRRefusalRestsNothing`, `TestZDRRefusalNeverRests`). Another vendor's refusal in the same words, without the code, still rests the model (`TestZDRRefusalIsCommandCodesCodeOnly`). 5. The last candidate's error reaches the agent, with one exception for a group (#1418, `patience.go`), which a plain provider shares once its same-one retries are spent (below). When every member has failed in a way that passes (`busy`, its statuses `busyStatus`: 408, 500, 502, 503, 504, 529, or Cloudflare's 520 to 524, which a relay behind it answers with now and then (`TestCloudflareErrorIsTriedAgain`; the same-one retries of `passing` read the same list), that isn't a proxy, a quota, response protection, or an upstream that answered a stream request with a whole reply, which fails the same however often it is asked (`didNotStream`; the same-one retries of `passing` leave it alone too, `TestStreamlessMemberIsAskedOnce`), or a 429 that is a short rate limit, not a plan or credit, nor an account's token wall: a vendor code in `wallCodes`, Raccoon's `user_model_rate_limited`, which rests as a rate limit but is asked again neither here nor by the same-one retries, as each ask draws on the bucket it waits for; plugins#512, `TestTokenWallFailsFast`), and nothing of the reply has been sent, the members that failed so are asked again in turn after a pause (`replan`). The pause is `retryPause` doubled each round up to `replanLongest()` (30 times `retryPause`, 30s), and never shorter than the soonest Retry-After; a member whose Retry-After ends past the pause is asked after the others. This goes on while the group's `Patience` lasts. A member of a group in the group uses the innermost that sets `Patience` (`innerPatience`, #2410), as FirstToken (#2246) and Sink (#2255) do; unset falls back to the group asked for, and an inner `PatienceOff` skips replan for that member (`TestNestedGroupPatienceThroughOuter`, `TestNestedGroupPatienceInnerOff`, `TestNestedGroupPatienceFallsBackToOuter`). `replanRounds` (12) is only a backstop that never comes first: the pauses alone add up to `PatienceLongest` in 11 rounds (with 6, a group set to 240s gave up after 90s of pauses, real-jacket on #1418; `TestPatienceIsUsedUp`). The budget is the group's `Patience`, counted from the first time every member had failed, when the agent would have had the error (`waitFrom`; `Group.Waits`: 0 follows the default for every group, `groupPatience`, itself 0 for `PatienceDefault`, 60s; -1, `PatienceOff`, turns it off; at most `PatienceLongest`, 240s). A pause that would end past the budget isn't taken, and the agent gets the error; a member the vendor said is back within a second past its budget (read in whole seconds) is asked as the budget ends (`TestReporterResetFitsTheDefaultPatience`). The last member out of its quota or credit (not `busy`), after an earlier member failed in a way that passes, has those earlier ones asked again the same way, and rests as they did (`lastSpent`): before, the agent had the relay's moment of 503 while the relay would answer a moment on (`TestGroupRelayBlipDoesNotEndOnSpentLast`). While another member is busy too, the last one isn't first tried again alone (`passing`): the members take turns, and once the budget has begun, the same-one retries aren't taken either. While the budget lasts, the last candidate's failure is held (`newHoldWriter`), and a streaming agent is kept alive through the pause with SSE comments (`pauseAlive`). The try is traced with `Again` (the pause), `Replan` (how many are asked again) and `Patience` (the budget in seconds). The group editor's "Every member busy" row sets it. A plain provider (a `provider/model` request, its accounts and fallbacks the candidates) first takes the same-one retries `passing` gives the last one left: `lastRetries` for a busy vendor, `rateRetries` for a rate limit, each pause `retryPause< patience=2m|off|default`; the provider editor shows no row for it and its save keeps it, `TestProviderSaveKeepsPatience`), unset `singlePatience` (`PatienceDefault`, 60s), counted from when the agent would have had the error, so it works with no setting and the user's value wins either way (`TestSingleProviderOwnPatienceWins`; ChatGPT's reset of a large request, `codexReset`, is left out: Codex is told it at its 503 with what may help, as `codexBusy` leaves it). A provider's own Patience is for a request to it alone: a group it is in, set or unset, keeps the group's (zoecats on Discord: a local relay's short 429 went straight to Claude Code once the few retries were spent). So a 429 whose Retry-After is 20s is waited out, the stream kept alive past `keepHeldAfter`; one of an hour, a quota, credit or plan limit, a 401 or 403, a refusal, response protection's 502 and `didNotStream` are not `busy` or don't fit the budget, and reach the agent at once as the vendor said them. Its tries are traced with `Again` alone, no `Replan` or `Patience`, so the Routing page tells it as the last one left asked again rather than as a group's members (`TestSingleProviderWaitsOutAShortRateLimit`, `TestSingleProviderPassesALongLimitThrough`, `TestSingleProviderAgentGoneInTheWait` in [`single_busy_test.go`](../../internal/gateway/single_busy_test.go)). Codex's own one-account relay (`codexUpstreamOn`, below) doesn't join it: its request is relayed unchanged outside the candidate loop, and the backend's 429 is always the plan's usage limit (`codexBusy` never retries one), so the short rate limit this waits out doesn't arise there; its overloads keep their `lastRetries` and then the subscription's fallbacks. A client that says how long it waits, in seconds (`provider.WaitHeader`, `X-Magpie-Wait`: a model test asking a remote magpie sends its own wait, `pluginTestWait`, 60s, since the remote serves plugins' models), takes neither pause when it would end within `clientRoom` (10s) of that wait (`keptAlive.outlives`), and has the error while it still waits; before, the test gave up at 20s on a 502 the remote held through its 60s patience (plugins#827, `TestClientWaitBoundsPatience`, `TestRemoteMagpieProbeWait`). Like every `X-Magpie-` header it goes no further upstream. An agent that goes away in either pause (the same-one retry's or a group's replan) ends the request there with 499: nobody is asked again, and the try whose pause it was is marked `Gone` (#1894, heng91: a relay down while its proxy was off, the agent's window closed). The Routing page says the agent canceled the request before the retry and lists it as canceled, rather than ending its story on "tried again in 2s", a retry that never came (`TestAgentGoneInTheRetryPause`, `routing-agent-gone.test.cjs`). A request its agent cancels, in such a pause or while a try is out (a person stopped the reply, or sent the next message while it came and the agent asked again), is logged 499 "the agent canceled the request" (`usage.CanceledBy`), with the error type `agent_canceled` (`usage.CanceledErrType`), which a middleware's usage rows carry too, so a module tells it from magpie's own limit below without the message. It is no failure: the agent saw no error (#2398). The Requests card and the totals line over the Requests list count it apart (`Totals.Canceled`); its success share, the Failed filter, the CSV's `error` column, the Routing page's errors and the Context page's error rate leave it out; the Requests list, the Routing page and Recent calls show it muted, in neither the failed nor the answered colour, from `canceled` on the row, route and call; and the OTLP export sends its span and its try's with status code 499, no error and no error type (`TestAgentCanceledIsNoError`, `TestAgentCanceledIsNoFailure`, `TestLedgerTellsCanceledRows`, `TestContextLeavesCanceledOutOfErrors`, `TestOTelWaterfallFailureAndCancellation`). Codex signed in to ChatGPT, its turn relayed to the backend as it came, gone mid-reply is logged the same 499 (#4866) and counted the same way (`TestCodexGoneMidReplyIsNoFailure`). magpie's own limit running out on a request it asked of itself is logged 499 too, and stays a failure (#2318, `TestCanceledTellsTheAgentFromMagpiesLimit`). A record logged before the error type, and a day's history kept before routes said `canceled`, are read the same way, by status and message (`TestHistoryTellsCanceledRoutes`). A try that answered is recorded (`served`, `answered`) for routing, affinity and usage. A try is added to the route's `Tries` only as it is asked, so a later try is the record that the gateway went on from this one, and the Routing page tells what came of a try from that, never from where it stood in the order (#2281, xishuchkui-code: an Antigravity 502 empty reply that went on to the next account was told as "an error another account wouldn't fix, so Claude Code gets it"). The one case the record can't show is the last try left out of its allowance after an earlier failure that wasn't one, where the agent is told the earlier error: that try is marked `Earlier` (`routing-went-on.test.cjs`). diff --git a/docs/subsystems/providers-accounts.md b/docs/subsystems/providers-accounts.md index 639868615..adca00446 100644 --- a/docs/subsystems/providers-accounts.md +++ b/docs/subsystems/providers-accounts.md @@ -374,7 +374,7 @@ and `TestHistoricalWindowHoldsUsesEachWindowsOwnReading`. - `GOOGLE_APPLICATION_CREDENTIALS` and `CLOUDSDK_CONFIG` are in `agentenv.Vars`. The desktop app takes them from the login shell when it wasn't started with them (`proc.UserPath`, macOS and Linux), and `testenv` clears both. Vertex AI reads them as set (`vertexEnvPath`), not through `appdir.Getenv`, which takes a relative value as unset: a `~/` that starts one is the home, and one that still isn't a full path is refused, naming the variable. Passed over, it would have the request signed from gcloud's own file, which may be another account's (a person's, where the variable named a service account's key). - The Vertex AI preset's `HeaderHints` are Google's Priority PayGo and Flex PayGo headers, `X-Vertex-AI-LLM-Request-Type` and `X-Vertex-AI-LLM-Shared-Request-Type`: the editor offers to add them, the values are the user's, and they go as `Headers` do. Priority PayGo couldn't be confirmed: on the project it was tried on, Vertex AI answered with `trafficType` `ON_DEMAND`. - An account's weight under `weight` routing is kept per account too (`AccountWeights`, by the account in lower case, 2–1000; one not in it weighs 1, and nothing sets one from the plan), as a key's is (`KeyAccount.Weight`), so a Max and a Pro account can share requests by how much more one allows (rubbzha on X). `SetAccountWeight` (GUI `provider/accountweight`, the chip beside each account in use in the editor while the routing is By weight; `magpie provider account-weight [account [n|default]]`) sets it, `moveAccountSettings` carries it through a Copilot rename, and `withPicks` puts it on the accounts `All` gives, so the gateway's `keyWeight` reads it with no file read (`Provider.AccountWeight`). -- A usage cap is kept per account (`AccountCaps`, 1–99) and, beside it, per window (`AccountWindowCaps`, by the account and the window's `capId`, its name in lower case: `WindowCapID`). A window's own share wins over the account's; 100 is no cap on that window. `CapsOf` gives both (`WindowCaps`), `CapHeld` and `capReached` judge each window by its own, and `SetWindowCap` (GUI `provider/windowcap`, `magpie provider account-cap --window `) sets one; `SetWindowCaps` sets several at once, as the GUI's meter for a family of models (Antigravity's Gemini 3.1 Pro, High and Low) posts its models' windows in `windows`. An Antigravity pool's own windows ("Gemini · 7 days") are set aside for routing but capped (`WithCapped`, `capId` the pool's name and its own, as `LineName`): `allowanceOf` hangs each on its members' windows (`Limit.pool`), and `CapHeld` and `NearCap` count them through `capLimits`, so a cap on one holds that pool's models only (pluviophile714 on Discord, `TestPoolWindowCapHeld`). A config without window caps reads as before. How a pool ends at its caps is kept with the provider (plugins#349): `CapStop` answers 429 rather than going on to the fallbacks once every account in use is at its cap, and `CapCareful` reads usage again near a cap and holds an account whose usage can't be told (both off by default; within 5 points of its cap an account takes one turn at a time whatever they say, [gateway routing](gateway-routing.md); `SetCapStop`, `SetCapCareful`, GUI `provider/capstop` and `provider/capcareful`, ticks under the account list once an account has a cap). `UsageRead` says when an account's usage was last read well and whether the last try failed (a failed try keeps the good reading's time), and `ReadUsageNow` reads it again. `magpie provider pool [--accounts a,b,…] [--cap percent|off] [--stop on|off] [--careful on|off]` shows and sets the whole pool in one command: which accounts are on and in what order, each one's cap, and both settings, and names the accounts in use with no cap. +- A usage cap is kept per account (`AccountCaps`, 1–99) and, beside it, per window (`AccountWindowCaps`, by the account and the window's `capId`, its name in lower case: `WindowCapID`). A window's own share wins over the account's; 100 is no cap on that window. `CapsOf` gives both (`WindowCaps`), `CapHeld` and `capReached` judge each window by its own, and `SetWindowCap` (GUI `provider/windowcap`, `magpie provider account-cap --window `) sets one; `SetWindowCaps` sets several at once, as the GUI's meter for a family of models (Antigravity's Gemini 3.1 Pro, High and Low) posts its models' windows in `windows`. An Antigravity pool's own windows ("Gemini · 7 days") are set aside for routing but capped (`WithCapped`, `capId` the pool's name and its own, as `LineName`): `allowanceOf` hangs each on its members' windows (`Limit.pool`), and `CapHeld` and `NearCap` count them through `capLimits`, so a cap on one holds that pool's models only (pluviophile714 on Discord, `TestPoolWindowCapHeld`). A window counted in a unit with its total (`QuotaWindow.Amount`, `Limit`, `Unit`: WorkBuddy's credits, a plan's requests) can instead be capped at a fixed amount of that unit (`AccountWindowAmounts`, by account and `capId`; 9won_25273 on Discord). `SetWindowAmount` (GUI `provider/windowcap` with `amount` in place of `cap`, the meter's menu's Amount…, typed in place) sets it, 0 lifts it; a window has a share of its own or an amount, never both, and setting one clears the other. `limitShare` makes the amount a share of the window's total for marks and `NearCap`, while `CapHeld` and `capReached` hold the account once the count reaches the amount (`past`); `CapHold` and the trace carry `Amount`, `Count` and `Unit`, and `cappedError` says "has used 300 credits … past its cap of 300". A reading with no total leaves the amount aside and the account's share applies. Every cap reads the vendor's own count of the window, so what the account spent outside magpie (the vendor's app, another machine) counts toward it as the vendor reports it, from the next reading on; magpie can only hold back its own requests (`TestWindowAmountCapHeld`, `TestSetWindowAmount`, `window-cap.test.cjs`). A config without window caps reads as before. How a pool ends at its caps is kept with the provider (plugins#349): `CapStop` answers 429 rather than going on to the fallbacks once every account in use is at its cap, and `CapCareful` reads usage again near a cap and holds an account whose usage can't be told (both off by default; within 5 points of its cap an account takes one turn at a time whatever they say, [gateway routing](gateway-routing.md); `SetCapStop`, `SetCapCareful`, GUI `provider/capstop` and `provider/capcareful`, ticks under the account list once an account has a cap). `UsageRead` says when an account's usage was last read well and whether the last try failed (a failed try keeps the good reading's time), and `ReadUsageNow` reads it again. `magpie provider pool [--accounts a,b,…] [--cap percent|off] [--stop on|off] [--careful on|off]` shows and sets the whole pool in one command: which accounts are on and in what order, each one's cap, and both settings, and names the accounts in use with no cap. - A key's spend cap (`KeySpendCaps`, by the key's fingerprint, [`key_spend.go`](../../internal/provider/key_spend.go); sparkling_lemur_62868 on Discord: a team's OpenAI key whose granted credits other services spend from too) is how much magpie may spend on an API key, in USD, per calendar day or month in local time, or in all since it was set (`Since`, kept while the cap stays one in all, its amount changed or not). What counts is what the Usage page prices magpie's own calls on the key at (`usage.KeySpent`: records whose `ProviderKeyID` is the key, not turned away, not reported by an app; the log is read once and each new call added by `Append`, read again after 5 minutes), not the vendor's bill: a model with no known price counts nothing, and requests under way when it is reached still finish, so the key can go a little past it. At or past the cap the gateway passes the key over ([gateway routing](gateway-routing.md)). Only a key has one: `SetKeySpendCap` refuses a subscription, an amount not above 0 or over `MaxSpendCap` (1,000,000) and a period it doesn't know. `ReplaceKey` carries it to the new value. Set from the key's row in the editor (a pill: "$7.50 of $20.00 today", the app's menu, then the amount typed in place, drawn by `keyspend.js`, which app.js imports when it draws a key's row; GUI `provider/keyspendcap`, `key-spend-cap.test.cjs`) or `magpie provider spend-cap [key [usd [day|month|total]|off]]`, which also lists each key's spend. `TestKeySpendCapSet`, `TestSpendCapWindow`, `TestParseSpendCap`, `TestKeySpentCountsTheKeysCalls`, `TestSpendCapCmd`. - A key's balance typed by hand (`KeyOwnBalances`, by the key's fingerprint: `{usd | cny, at, refill, expirings}`, [`key_balance_own.go`](../../internal/provider/key_balance_own.go); tenacious_eagle on Discord) is for a key whose vendor tells no balance magpie can read (`TakesOwnBalance`: an API key with no balance source, not Cline's or OpenCode Zen's, not on a plan's windows). The user types what the vendor's page says is left; the key's card on the Usage page and the tray then shows it less what the Usage page prices magpie's own calls on the key at since then (`usage.KeySpent` from `at`, through the `provider.KeySpent` hook usage sets), as `≈$12.50` with `Estimate` (`set`, `at`, `spent`) and below nothing as `≈$-2.00`. Typing it again counts from then. It is an estimate, not a reading: it is kept out of the balance history (no trend or runs-out), is never shared, and routing reads nothing from it; a low-balance alert reads its number. A balance the vendor tells always wins: with a Balance URL or a source magpie knows the card is the vendor's, and a relay whose query is looked for shows the typed one only when none is found (`errNoBalance`); the typed value stays saved as the user left it. `SetKeyOwnBalance` (GUI `provider/keyownbalance`, a pill in the key's row, "≈$12.50 left" or "Set balance", drawn by `keybalance.js` while `takesOwnBalance` and no balance was found; `magpie provider key-balance [key [usd|¥cny|off] [--refill …]]`) refuses a subscription, an amount outside 0 to `MaxOwnBalance` (1,000,000) in either currency, and any currency but USD and CNY; nil takes it off, `ReplaceKey` carries it to the new value, and saving the editor keeps it. It may be typed in yuan (`cny`, "¥100", or a bare number with ¥ CNY picked in the currency button beside the field, which starts at the balance's own currency, else Settings' one; picking keeps the number typed and posts nothing until the field is left or Enter is pressed, so a balance's currency changes without clearing it or going to Settings, tenacious_eagle on Discord): what is spent is counted in USD and turned into yuan at `fx.Known()`, the rate `internal/fx` last fetched (cached 12h in `fxrate.json`, fetched again in the background, never on the request path); `fx.Known` never hands out `fx.Fallback`, so with no rate fetched yet and something spent the left is unknown (`left` null, the card's `Error` says why) rather than a guess. It may refill (`refill`: `{every: month, day: 1–31}`, a day past the month's end meaning its last, or `{every: week, day: 1 Monday–7 Sunday}`), at midnight in the user's local time: nothing is stored on a refill; the spend is counted from the last refill boundary after `at` (`From`), and `Next` is the next one. Typing the amount again keeps the refill. `SetKeyBalanceRefill` (GUI `provider/keybalancerefill`, the pill's menu: Refills each month…, Refills each week…, Never refills; CLI `--refill monthly[:day]|weekly[:mon…sun]|off`) refuses a key with no balance. Part of it may expire, in grants (`expirings`: a list of `{amount, until, at}`, up to `MaxExpiring` (20), each amount in the balance's currency, `until` the last day it counts as 2006-01-02, `at` when it was typed; tenacious_eagle_96548 on Discord: money that stays and promotional credit twice, one good until tomorrow and one the day after). Grants are spent first, as DeepSeek spends its granted balance before the money topped up, and of them the one that ends soonest first (`spendGrants`): the spend is taken piece by piece over the times between `From`, now, and each grant's `at` and end (midnight after `until`, local time), each piece going to the live grant that ends first, and only what grants took after `From` is off the rest, so a refill or typing the balance again doesn't count it twice. `left` is the whole balance, the grants' remainders included; from a grant's end its remainder counts no more (`expired`, the latest such end), and unspent credit is simply gone. A grant whose end is at or before `From` is dropped on the next write (`liveGrants`). `AddKeyExpiring` (GUI `provider/keyexpiring` `{expiring: {amount, until}}`), `RemoveKeyExpiring` (`{expiring: {at, until}, remove: true}`, matched by `at`, else by `until` and the amount when given; nothing matched is an error) and `ClearKeyExpiring` (`{expiring: null}`) edit them. The pill's menu has Add credit that expires…, which opens one small form (`.abal-form`, the app's popover, no native control but the date field) with the amount, in the balance's currency, and the last day, a month ahead to begin with: Add or Enter saves, Escape or a click outside leaves it, an amount in the other currency or a day gone by is refused with the form kept; then a Remove {amount} for each grant with when it goes beside it, and No credit that expires with two or more, or one that expired. The CLI takes `--expiring amount@yyyy-mm-dd` and `--expiring-remove [amount@]yyyy-mm-dd`, each as often as wanted and applied in order after the balance, every value read before anything is written; `--expiring off` takes every grant off. Each refuses a key with no balance typed (type the rest first, 0 when all of it expires), an amount not above 0 or past `MaxOwnBalance`, and a date that isn't one. A v0.1.3305 balance's one `expiring` object is read as the first grant (`UnmarshalJSON`) and saved as `expirings` on the next write; a magpie before this reads `expirings` as no grant, so going back loses them from the estimate, not from the file until it writes. Typing the balance again keeps the grants in the same currency and drops them in the other, where its amount would mean another sum. A balance saved before has none and is counted as it was. The estimate's `expiring`, one per grant soonest first (`set`, `at`, `until`, `left`, `ends`), is the pill's "≈$60.00 left · $5.00 expires tomorrow · $20.00 expires in 30 days" (wrapping at a grant on a narrow row), and the card's `BalanceSplit` a line each with `expires`, which the Usage page and the panel label "Expires in 30 days" (`expiresIn` in app.js), amber from a week; the TUI and CLI quota say "$20.00 until Dec 31" (`SplitWords`). Each key with one gets `balance` in `/api/providers`' `keyList` (`set`, `at`, `spent`, `currency`, `rate`, `left`, `from`, `refill`, `next`, `expiring`, `expired`). `TestTypedBalanceExpires`, `TestTypedBalanceSavedBeforeExpiring`, `TestTypedBalanceGrantsSoonestFirst`, `TestTypedBalanceGrantsEdited`, `TestTypedBalanceOneGrantMigrated`, `TestExpiringParsed`, `TestExpiringDayParsed`, `TestKeyBalanceCmd`, `key-balance-expiring.test.cjs`, `TestKnownIsNeverAGuess`, `TestTypedBalanceInYuan`, `TestTypedBalanceRefills`, `TestRefillDays`, `TestTypedBalanceCountsDown`, `TestToldBalanceWinsOverTyped`, `TestOwnBalanceParsed`, `TestKeyOwnBalanceRoutes`, `key-own-balance.test.cjs`. - A window whose reset time has passed has started again, whatever share it was read at (`resetPassed`). That holds for a reading kept from before (`AsOf`) and for a fresh one: Claude Code's `/usage` gives a reset to the minute and can lag it, so a run just after a reset can still say 100% with that reset. `claudeWindows` hands such a window back empty on every path, and `usedPast`, `usedUp`, `BackAt` and `capReached` leave it out when they judge an account spent, for Codex, Claude Code and `magpie quota wait` alike. A card can still show a kept reading as it was read (`reported`, for a Claude card while `/usage` is unavailable); that changes what it shows, never which account is used. A reset `/usage` gives as a time alone ("resets 3pm") can be read as its next one, a day on (`claudeResetTime`), and is then not seen as passed here. diff --git a/internal/cli/account_cap_cli_test.go b/internal/cli/account_cap_cli_test.go index 13de33e46..3c755bf90 100644 --- a/internal/cli/account_cap_cli_test.go +++ b/internal/cli/account_cap_cli_test.go @@ -94,6 +94,28 @@ func TestAccountCapCmd(t *testing.T) { if c := provider.AccountCapsOf("codex", "me@example.com"); c.Windows != nil { t.Fatalf("default left %+v", c) } + // a fixed amount of a window's unit (9won_25273 on Discord): 300 + // credits a day, then off; a bad amount, or one with no window, refused + if err := providerCmd([]string{"provider", "account-cap", "codex", "me@example.com", "--window", "Daily credits", "--amount", "1,000"}); err != nil { + t.Fatal(err) + } + if c := provider.AccountCapsOf("codex", "me@example.com"); c.Amounts["daily credits"] != 1000 { + t.Fatalf("amount %+v", c) + } + for _, bad := range [][]string{{"--window", "Daily credits", "--amount", "-3"}, {"--window", "Daily credits", "--amount", "lots"}, {"--amount", "300"}, {"--window", "Daily credits", "--amount", "300", "50"}} { + if err := providerCmd(append([]string{"provider", "account-cap", "codex", "me@example.com"}, bad...)); err == nil { + t.Errorf("%q taken", bad) + } + } + if c := provider.AccountCapsOf("codex", "me@example.com"); c.Amounts["daily credits"] != 1000 { + t.Fatalf("a refused amount changed it: %+v", c) + } + if err := providerCmd([]string{"provider", "account-cap", "codex", "me@example.com", "--window=Daily credits", "--amount=off"}); err != nil { + t.Fatal(err) + } + if c := provider.AccountCapsOf("codex", "me@example.com"); c.Amounts != nil { + t.Fatalf("off left %+v", c) + } if err := provider.Save(provider.Provider{ID: "relay", Name: "Relay", Key: "k1", Chat: "http://127.0.0.1:1/v1"}); err != nil { t.Fatal(err) } diff --git a/internal/cli/providers_cli.go b/internal/cli/providers_cli.go index b2216454a..c4d012e09 100644 --- a/internal/cli/providers_cli.go +++ b/internal/cli/providers_cli.go @@ -7,6 +7,7 @@ import ( "fmt" "log" "maps" + "math" "os" "path/filepath" "slices" @@ -87,6 +88,9 @@ const providerUsage = `usage: magpie provider account-cap --window [percent|none|default] a share for one window alone (e.g. "5 hours" 50): none is no cap on it, default has it follow the account's cap + magpie provider account-cap --window --amount + a fixed amount of a window counted in a unit (e.g. "Daily credits" 300), + by the vendor's count, spending outside magpie included magpie provider pool [--accounts a,b,…] [--cap percent|off] [--stop on|off] [--careful on|off] a subscription's accounts as one pool: which are in use and in what order, each one's cap, --stop: answer 429 at the caps rather than go on to the @@ -1665,28 +1669,37 @@ func accountModelsCmd(rest []string) error { // accountCapCmd shows, or sets with a share or off, the usage cap of a // subscription's accounts: the share of each window one is used to at most // (provider.AccountCaps); with --window , the share of that window -// alone (provider.AccountWindowCaps). +// alone (provider.AccountWindowCaps); with --amount too, a fixed amount of +// that window's own unit, credits or requests (provider.AccountWindowAmounts). func accountCapCmd(rest []string) error { - usage := fmt.Errorf("magpie provider account-cap [account [percent|off]]\n magpie provider account-cap --window [percent|none|default]") + usage := fmt.Errorf("magpie provider account-cap [account [percent|off]]\n magpie provider account-cap --window [percent|none|default]\n magpie provider account-cap --window --amount ") window, windowSet := "", false + amount, amountSet := "", false for i := 0; i < len(rest); i++ { a := rest[i] - if v, ok := strings.CutPrefix(a, "--window="); ok { - window, windowSet = v, true - rest = slices.Delete(slices.Clone(rest), i, i+1) - i-- - continue - } - if a == "--window" { - if i+1 >= len(rest) { - return usage + for _, f := range []struct { + name string + v *string + set *bool + }{{"--window", &window, &windowSet}, {"--amount", &amount, &amountSet}} { + if v, ok := strings.CutPrefix(a, f.name+"="); ok { + *f.v, *f.set = v, true + rest = slices.Delete(slices.Clone(rest), i, i+1) + i-- + break + } + if a == f.name { + if i+1 >= len(rest) { + return usage + } + *f.v, *f.set = rest[i+1], true + rest = slices.Delete(slices.Clone(rest), i, i+2) + i-- + break } - window, windowSet = rest[i+1], true - rest = slices.Delete(slices.Clone(rest), i, i+2) - i-- } } - if len(rest) < 1 || windowSet && (len(rest) < 2 || strings.TrimSpace(window) == "") { + if len(rest) < 1 || windowSet && (len(rest) < 2 || strings.TrimSpace(window) == "") || amountSet && (!windowSet || len(rest) != 2) { return usage } p, err := provider.Find(rest[0]) @@ -1696,6 +1709,18 @@ func accountCapCmd(rest []string) error { if p.Account == nil { return fmt.Errorf("%s has keys, not subscription accounts with usage windows to cap", p.Name) } + if amountSet { + n, err := parseWindowAmount(amount) + if err != nil { + return err + } + if err := provider.SetWindowAmount(p.ID, rest[1], []string{window}, n); err != nil { + return err + } + if p, err = provider.Find(p.ID); err != nil { + return err + } + } if len(rest) > 2 { if windowSet { cap, err := parseWindowCap(rest[2]) @@ -1736,7 +1761,7 @@ func accountCapCmd(rest []string) error { caps := p.CapsOf(r) if caps.All > 0 { fmt.Printf("%s · capped at %d%% of each usage window\n", r, caps.All) - } else if len(caps.Windows) > 0 { + } else if len(caps.Windows) > 0 || len(caps.Amounts) > 0 { fmt.Println(r, muted.Render("· no cap on its other windows: used to 100%")) } else { fmt.Println(r, muted.Render("· no cap: used to 100%")) @@ -1748,10 +1773,27 @@ func accountCapCmd(rest []string) error { fmt.Printf(" %s · capped at %d%%\n", w, c) } } + for _, w := range slices.Sorted(maps.Keys(caps.Amounts)) { + fmt.Printf(" %s · capped at %s of its unit\n", w, strconv.FormatFloat(caps.Amounts[w], 'f', -1, 64)) + } } return nil } +// parseWindowAmount reads a window's fixed amount as the CLI takes it: a +// number above 0, "300" or "1,000", or off (0) to lift it. +func parseWindowAmount(s string) (float64, error) { + t := strings.ToLower(strings.TrimSpace(s)) + if t == "off" || t == "none" || t == "default" || t == "0" { + return 0, nil + } + n, err := strconv.ParseFloat(strings.ReplaceAll(t, ",", ""), 64) + if err != nil || !(n > 0) || math.IsInf(n, 0) { + return 0, fmt.Errorf("a window's amount is a number above 0, in the window's own unit, or off, not %q", s) + } + return n, nil +} + // parseWindowCap reads a window's own share as the CLI takes it: "50", // "50%", none (off, 100) for no cap on that window, default (-) to follow // the account's cap. diff --git a/internal/gateway/account_cap_amount_test.go b/internal/gateway/account_cap_amount_test.go new file mode 100644 index 000000000..3e83a8cdd --- /dev/null +++ b/internal/gateway/account_cap_amount_test.go @@ -0,0 +1,77 @@ +package gateway + +import ( + "fmt" + "strings" + "testing" + "time" + + "github.com/yetone/magpie/internal/provider" +) + +// 9won_25273 on Discord: an account capped at 300 of a day's 1000 credits +// is held once the vendor's count of the day reaches 300, and the request +// goes to the next account; under it, it is used; every account at its +// cap is refused, named with the count and the amount. +func TestWindowAmountHoldsTheAccount(t *testing.T) { + codexSignedIn(t, "spare@example.com") + b := newResetBackend(t) + if err := provider.SetRouting("codex", provider.Ordered); err != nil { + t.Fatal(err) + } + for _, u := range []string{"me@example.com", "spare@example.com"} { + if err := provider.SetWindowAmount("codex", u, []string{"Daily credits"}, 300); err != nil { + t.Fatal(err) + } + } + try := func(count map[string]float64) (int, string, string, *Server) { + t.Helper() + old := allowances + t.Cleanup(func() { allowances = old }) + day := time.Now().Add(5 * time.Hour) + allowances = func(string) map[string]provider.Allowance { + out := map[string]provider.Allowance{} + for u, n := range count { + out[u] = provider.Allowance{{Name: "Daily credits", Used: n / 10, Amount: n, Of: 1000, Unit: "credits", Resets: day, Span: 24 * time.Hour}} + } + return out + } + b.mu.Lock() + b.tried = nil + b.mu.Unlock() + srv := New() + code, body := resetPost(t, srv) + tried, _ := b.seen() + return code, body, tried, srv + } + + code, body, tried, srv := try(map[string]float64{"me@example.com": 320, "spare@example.com": 40}) + if code != 200 || tried != "acct-2" { + t.Fatalf("320 of 300 credits: %d %s tried %s", code, body, tried) + } + var left []string + for _, r := range srv.Trace(t.Context(), 0, 0).Routes { + for _, w := range r.Left { + if w.Capped > 0 && !w.Barred { + left = append(left, fmt.Sprintf("%s %g/%g %s", w.Who, w.CapCount, w.CapAmount, w.CapUnit)) + } + } + } + if len(left) != 1 || left[0] != "me@example.com 320/300 credits" { + t.Fatalf("traced as capped: %v", left) + } + + if code, body, tried, _ := try(map[string]float64{"me@example.com": 299, "spare@example.com": 40}); code != 200 || tried != "acct-1" { + t.Fatalf("299 of 300 credits: %d %s tried %s", code, body, tried) + } + + code, body, tried, _ = try(map[string]float64{"me@example.com": 300, "spare@example.com": 412.5}) + if code != 429 || tried != "" { + t.Fatalf("both at their amount: %d tried %q", code, tried) + } + for _, want := range []string{"usage cap reached", "(me@example.com) has used 300 credits", "(spare@example.com) has used 412.5 credits", "past its cap of 300"} { + if !strings.Contains(body, want) { + t.Errorf("no %q in %s", want, body) + } + } +} diff --git a/internal/gateway/affinity.go b/internal/gateway/affinity.go index ccd3e226e..c6385061c 100644 --- a/internal/gateway/affinity.go +++ b/internal/gateway/affinity.go @@ -462,6 +462,7 @@ func strictKeep(scope, mode string, in http.Header, body []byte, cs []candidate, } w := pl.left[i] w.Unlisted, w.Capped, w.CapBack = false, 0, nil + w.CapAmount, w.CapCount, w.CapUnit = 0, 0, "" pl.left = slices.Delete(slices.Clone(pl.left), i, i+1) back, order = append(back, c), append(order, w) } diff --git a/internal/gateway/codex_autoreset.go b/internal/gateway/codex_autoreset.go index da5482b61..6612c56cd 100644 --- a/internal/gateway/codex_autoreset.go +++ b/internal/gateway/codex_autoreset.go @@ -96,6 +96,7 @@ func unhold(order, left []Weighed, c candidate) ([]Weighed, []Weighed) { } w := left[i] w.Unlisted, w.Capped, w.CapBack, w.NoCredits = false, 0, nil, false + w.CapAmount, w.CapCount, w.CapUnit = 0, 0, "" return append(slices.Clip(order), w), slices.Delete(slices.Clone(left), i, i+1) } diff --git a/internal/gateway/fallback.go b/internal/gateway/fallback.go index 732f9a83b..f2cef2e93 100644 --- a/internal/gateway/fallback.go +++ b/internal/gateway/fallback.go @@ -107,10 +107,14 @@ type candidate struct { // renews (zero when one doesn't say). noCredits: it is a Codex account // held at 100% as it is set not to spend its credits (cap is 100 then). type capHold struct { - cap int - used float64 - back time.Time - noCredits bool + cap int + used float64 + // amount: held at a window's fixed amount (provider.CapHold.Amount), + // count of it used, in unit + amount, count float64 + unit string + back time.Time + noCredits bool // unread: held by a careful provider as its usage can't be told, why // (carefulDoubt), cap then the account's own unread string @@ -954,7 +958,7 @@ func capHeld(p, acct provider.Provider, model string, now time.Time) *capHold { } return nil } - return &capHold{cap: h.Cap, used: h.Used, back: h.Back, noCredits: h.Credits} + return &capHold{cap: h.Cap, used: h.Used, back: h.Back, noCredits: h.Credits, amount: h.Amount, count: h.Count, unit: h.Unit} } // cappedError says why a request for model went nowhere when every account @@ -1013,6 +1017,9 @@ func heldReasons(ws []Weighed, now time.Time) ([]string, time.Time) { continue } s := fmt.Sprintf("%s (%s) is at %.0f%% of a usage window, past its %d%% cap", w.Name, w.Who, w.Used, w.Capped) + if w.CapAmount > 0 { + s = fmt.Sprintf("%s (%s) has used %s %s of a usage window, past its cap of %s", w.Name, w.Who, amountText(w.CapCount), w.CapUnit, amountText(w.CapAmount)) + } if w.SpendCap > 0 { s = fmt.Sprintf("%s (%s) has spent %s of the %s spend cap set on it %s, as magpie's usage prices its calls", w.Name, w.Who, usd(w.Spent), usd(w.SpendCap), spendPeriod(w.SpendPeriod, w.SpendSince, now)) } @@ -1052,6 +1059,12 @@ func spendOnly(ws []Weighed) bool { return n > 0 } +// amountText is a window's count as a cap at a fixed amount says it: whole +// when it is, else to two places. +func amountText(v float64) string { + return strconv.FormatFloat(math.Round(v*100)/100, 'f', -1, 64) +} + // usd is an amount in dollars as a spend cap is told: cents kept. func usd(v float64) string { return "$" + strconv.FormatFloat(math.Floor(v*100+0.5)/100, 'f', 2, 64) @@ -1170,6 +1183,7 @@ func barredOf(cs []candidate, q provider.Provider, fallback bool, from provider. w.Unlisted, w.Via = true, via if h := c.capped; h != nil { w.Capped, w.Used, w.NoCredits, w.Unread = h.cap, h.used, h.noCredits, h.unread + w.CapAmount, w.CapCount, w.CapUnit = h.amount, h.count, h.unit if sp := h.spend; sp != nil { w.SpendCap, w.Spent, w.SpendPeriod = sp.usd, sp.spent, sp.period if sp.period == provider.SpendTotal { diff --git a/internal/gateway/trace.go b/internal/gateway/trace.go index 6d6a6eba7..d0c512ac5 100644 --- a/internal/gateway/trace.go +++ b/internal/gateway/trace.go @@ -401,6 +401,11 @@ type Weighed struct { // share, CapBack when the last window at or past it renews Capped int `json:"capped,omitempty"` CapBack *time.Time `json:"capBack,omitempty"` + // CapAmount: held (Capped) at a window's fixed amount of its own unit + // rather than a share: CapCount of it used, in CapUnit + CapAmount float64 `json:"capAmount,omitempty"` + CapCount float64 `json:"capCount,omitempty"` + CapUnit string `json:"capUnit,omitempty"` // NoCredits: held at 100% (Capped), a Codex account the user set not // to spend its credits once its allowance is used up NoCredits bool `json:"noCredits,omitempty"` diff --git a/internal/gui/assets/app.js b/internal/gui/assets/app.js index 9255db9f5..b6efbed53 100644 --- a/internal/gui/assets/app.js +++ b/internal/gui/assets/app.js @@ -14125,9 +14125,18 @@ function accountCapOf(p, user) { return p?.accountCaps?.[String(user).toLowerCas function windowOwnCapOf(p, user, w) { return (w?.capId && p?.accountWindowCaps?.[String(user).toLowerCase()]?.[w.capId]) || 0; } -function windowCapsOf(p, user) { return Object.keys(p?.accountWindowCaps?.[String(user).toLowerCase()] || {}).length; } -// windowCapOf: the share the window holds the account at, 0 for none +function windowCapsOf(p, user) { const k = String(user).toLowerCase(); return Object.keys({ ...p?.accountWindowCaps?.[k], ...p?.accountWindowAmounts?.[k] }).length; } +// A window's cap at a fixed amount of its own unit (provider.AccountWindowAmounts, +// 9won_25273 on Discord), by capId: 0 when it has none. +function windowAmountOf(p, user, w) { + return (w?.capId && p?.accountWindowAmounts?.[String(user).toLowerCase()]?.[w.capId]) || 0; +} +// windowCapOf: the share the window holds the account at, 0 for none; an +// amount as a share of the window's total, which a window read without one +// leaves aside function windowCapOf(p, user, w) { + const amount = windowAmountOf(p, user, w); + if (amount && w?.limit > 0) return amount / w.limit * 100; const own = windowOwnCapOf(p, user, w); if (own) return own >= 100 ? 0 : own; return w?.ownCap ? 0 : accountCapOf(p, user); @@ -14156,7 +14165,7 @@ function capHeldOf(q, capFor) { if (!r) h.unknown = true; else h.back = Math.max(h.back, r); } const h = all.n ? all : some.n ? some : null; - return h && { used: h.used, cap: h.cap, back: h.unknown ? 0 : h.back, all: h === all, some: some.names }; + return h && { used: h.used, cap: Math.ceil(h.cap), back: h.unknown ? 0 : h.back, all: h === all, some: some.names }; } // directNote: why the cap can't stop agent, signed in to the account and // asking its vendor itself, with no other account on to move it to @@ -14192,7 +14201,7 @@ function capMark(track, w, cap) { if (!cap || !w.capped) return; const mk = el("span", "aq-cap"); mk.style.left = (quotaLeft ? 100 - cap : cap) + "%"; - mk.title = t("Usage cap {n}%", { n: cap }); + mk.title = t("Usage cap {n}%", { n: Math.round(cap) }); track.classList.add("capped"); track.append(mk); } @@ -14223,14 +14232,22 @@ function pillNumber(at, val, ph, cls, label, parse, bad, own, set) { // sets the window's own cap, a family's its models' (tiers); not on-demand's. function windowCapMeter(m, p, user, w) { const ids = (w.tiers || [w]).map((x) => x.capId), owns = ids.map((capId) => windowOwnCapOf(p, user, { capId })); - if (!ids.every(Boolean) || w.ownCap && !(owns[0] % 100)) return m; + const amounts = ids.map((capId) => windowAmountOf(p, user, { capId })); + const amount = new Set(amounts).size > 1 ? 0 : amounts[0]; + if (!ids.every(Boolean) || w.ownCap && !(owns[0] % 100) && !amount) return m; const own = new Set(owns).size > 1 ? 0 : owns[0], cap = accountCapOf(p, user); const name = t(w.name); - const b = spanBtn(el("span", m.className + " aq-set" + (own ? " own" : ""))); + // a window counted in a unit, with its total, can be capped at an amount + // of it in place of a share + const unit = w.limit > 0 && w.unit ? t(w.unit) : ""; + const amountText = (v) => (countFormat.format(v) + " " + unit).trim(); + const b = spanBtn(el("span", m.className + " aq-set" + (own || amount ? " own" : ""))); b.append(...m.childNodes); - if (own) b.append(el("span", "aq-own", own >= 100 ? t("No cap") : t("Cap {n}%", { n: own }))); + if (amount) b.append(el("span", "aq-own", t("Cap {n}", { n: amountText(amount) }))); + else if (own) b.append(el("span", "aq-own", own >= 100 ? t("No cap") : t("Cap {n}%", { n: own }))); const reset = m.title || (w.resetsAt ? resetText(new Date(w.resetsAt), new Date(w.resetsAt).toLocaleString(intlLang())) : ""); - b.title = [reset, own >= 100 ? t("No cap on {window}: it is used to 100%, whatever this account's cap. Click to change", { window: name }) + b.title = [reset, amount ? t("{window} has a cap of its own: magpie counts this account as used up once it has used {n} of {window}, until it renews. Click to change", { window: name, n: amountText(amount) }) + : own >= 100 ? t("No cap on {window}: it is used to 100%, whatever this account's cap. Click to change", { window: name }) : own ? t("{window} has a cap of its own: magpie counts this account as used up once {window} is at {n}%, until it renews. Click to change", { window: name, n: own }) : t("Click to give {window} a cap of its own, apart from this account's", { window: name })].filter(Boolean).join("\n"); b.setAttribute("aria-haspopup", "menu"); @@ -14240,6 +14257,10 @@ function windowCapMeter(m, p, user, w) { : v >= 100 ? t("{window} of {who} has no cap", { window: name, who: user }) : t("{who} stops at {n}% of {window}", { who: user, n: v, window: name })); const other = () => pillNumber(b, own && own < 100 ? String(own) : "", "1–99", "acap-in", t("Cap for {window}, in percent", { window: name }), capOf, t("A cap is a share from 1% to 99%"), own, set); + const setAmount = (v) => accountAction("provider/windowcap", { id: p.id, account: user, window: w.capId, ...w.tiers && { windows: ids }, amount: v }, + t("{who} stops at {n} of {window}", { who: user, n: amountText(v), window: name })); + const amountOf = (v) => { v = Number(v.replace(/[\s,]/g, "")); return v > 0 && Number.isFinite(v) ? v : null; }; + const otherAmount = () => pillNumber(b, amount ? String(amount) : "", unit, "acap-in", t("Cap for {window}, in {unit}", { window: name, unit }), amountOf, t("An amount above 0"), amount, setAmount); b.onclick = (e) => { e.stopPropagation(); if (b.classList.contains("open")) return closeProtoMenu(); @@ -14251,9 +14272,11 @@ function windowCapMeter(m, p, user, w) { ]; for (const n of shares) opts.push({ v: n, name: n + "%", note: "", literalName: true }); opts.push({ v: -1, name: "Other…", note: "A share of your own, 1–99%" }); - openProtoMenu(b, opts, own, (v) => { + if (unit) opts.push({ v: -2, name: t("Amount…"), note: amount ? amountText(amount) : t("At most this much {unit}", { unit }), literalName: true }); + openProtoMenu(b, opts, amount ? -2 : own, (v) => { if (v === -1) return other(); - if (v !== own) set(v); + if (v === -2) return otherAmount(); + if (v !== own || amount) set(v); }, t("Cap for {window}", { window: name }), "sess-menu"); }; return b; diff --git a/internal/gui/assets/i18n.js b/internal/gui/assets/i18n.js index 758d1bec0..9044f951c 100644 --- a/internal/gui/assets/i18n.js +++ b/internal/gui/assets/i18n.js @@ -4042,6 +4042,13 @@ const I18N = { "{window} of {who} has no cap": "{who} 的{window}不设上限", "{who} stops at {n}% of {window}": "{who} 的{window}用到 {n}% 即停", "Cap for {window}, in percent": "{window}的上限,百分比", + "Cap {n}": "上限 {n}", + "{window} has a cap of its own: magpie counts this account as used up once it has used {n} of {window}, until it renews. Click to change": "{window}有自己的上限:这个账号的{window}用到 {n} 后,magpie 就当它已用完,直到{window}重置。点击更改", + "{who} stops at {n} of {window}": "{who} 的{window}用到 {n} 即停", + "Cap for {window}, in {unit}": "{window}的上限,单位:{unit}", + "An amount above 0": "上限是大于 0 的数量", + "Amount…": "固定数量…", + "At most this much {unit}": "最多用这么多{unit}", "Account's cap · {n}%": "账号上限 · {n}%", "Account's cap · none": "账号上限 · 无", "As the account's other windows": "与账号的其他窗口相同", @@ -8775,6 +8782,13 @@ const I18N = { "{window} of {who} has no cap": "{who} 的{window}不設上限", "{who} stops at {n}% of {window}": "{who} 的{window}用到 {n}% 即停", "Cap for {window}, in percent": "{window}的上限,百分比", + "Cap {n}": "上限 {n}", + "{window} has a cap of its own: magpie counts this account as used up once it has used {n} of {window}, until it renews. Click to change": "{window}有自己的上限:這個帳號的{window}用到 {n} 後,magpie 就當它已用完,直到{window}重置。點擊變更", + "{who} stops at {n} of {window}": "{who} 的{window}用到 {n} 即停", + "Cap for {window}, in {unit}": "{window}的上限,單位:{unit}", + "An amount above 0": "上限是大於 0 的數量", + "Amount…": "固定數量…", + "At most this much {unit}": "最多用這麼多{unit}", "Account's cap · {n}%": "帳號上限 · {n}%", "Account's cap · none": "帳號上限 · 無", "As the account's other windows": "與帳號的其他時段相同", @@ -13522,6 +13536,13 @@ const I18N = { "{window} of {who} has no cap": "{who} の{window}は上限なし", "{who} stops at {n}% of {window}": "{who} は{window}の {n}% で停止", "Cap for {window}, in percent": "{window}の上限(%)", + "Cap {n}": "上限 {n}", + "{window} has a cap of its own: magpie counts this account as used up once it has used {n} of {window}, until it renews. Click to change": "{window}には独自の上限があります:このアカウントが{window}を {n} 使うと、magpie はリセットまで使い切ったものとみなします。クリックで変更", + "{who} stops at {n} of {window}": "{who} は{window}を {n} 使うと停止", + "Cap for {window}, in {unit}": "{window}の上限({unit})", + "An amount above 0": "上限は 0 より大きい量です", + "Amount…": "固定量…", + "At most this much {unit}": "{unit}をこの量まで", "Account's cap · {n}%": "アカウントの上限 · {n}%", "Account's cap · none": "アカウントの上限 · なし", "As the account's other windows": "アカウントの他のウィンドウと同じ", @@ -18284,6 +18305,13 @@ const I18N = { "{window} of {who} has no cap": "{window} von {who} hat kein Limit", "{who} stops at {n}% of {window}": "{who} stoppt bei {n} % von {window}", "Cap for {window}, in percent": "Limit für {window}, in Prozent", + "Cap {n}": "Limit {n}", + "{window} has a cap of its own: magpie counts this account as used up once it has used {n} of {window}, until it renews. Click to change": "{window} hat ein eigenes Limit: Sobald dieses Konto {n} von {window} verbraucht hat, gilt es für magpie als aufgebraucht, bis {window} sich erneuert. Klicke zum Ändern", + "{who} stops at {n} of {window}": "{who} stoppt bei {n} von {window}", + "Cap for {window}, in {unit}": "Limit für {window}, in {unit}", + "An amount above 0": "Eine Menge über 0", + "Amount…": "Menge…", + "At most this much {unit}": "Höchstens so viele {unit}", "Account's cap · {n}%": "Limit des Kontos · {n} %", "Account's cap · none": "Limit des Kontos · keins", "As the account's other windows": "Wie die anderen Zeitfenster des Kontos", diff --git a/internal/gui/providers.go b/internal/gui/providers.go index 47ffa0d04..8be27ca0f 100644 --- a/internal/gui/providers.go +++ b/internal/gui/providers.go @@ -181,6 +181,9 @@ type providerJSON struct { // one for that window apart, by the account and then the window's // capId (provider.AccountWindowCaps); 100 is none on that window AccountWindowCaps map[string]map[string]int `json:"accountWindowCaps,omitempty"` + // AccountWindowAmounts: a window capped at a fixed amount of its own + // unit in place of a share (provider.AccountWindowAmounts) + AccountWindowAmounts map[string]map[string]float64 `json:"accountWindowAmounts,omitempty"` // the names the user gave its accounts, by the account in lower // case (provider.AccountNames, #1515), and the name of the key plan // each account was found to stand in for (provider.SeatNameOf): the @@ -768,7 +771,7 @@ func providerInfoWith(p provider.Provider, ls provider.Listing, agents []agentUs ID: p.ID, Name: p.Name, Icon: p.Icon, IconFrom: p.IconFrom, Preset: p.Preset, Host: p.Host(), Chat: p.Chat, Responses: p.Responses, Anthropic: p.Anthropic, Gemini: p.Gemini, Decide: p.Decide, BaseAPI: p.BaseAPI, ModelTest: p.ModelTest(), TestsAs: p.TestClients(), DecideTest: p.AsksDecideModels(), MarksKinds: p.MarksKinds(), Catalog: p.Catalog, Website: p.Website, KeysURL: p.KeysURL, - 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, PassHeaders: p.PassHeaders, Searches: p.Searches, Cline: p.ClinePinnable(), PinUpstream: p.PinUpstream, Unredacted: p.Unredacted, CountFree: p.CountFree, InsecureTLS: p.InsecureTLS, TakesInsecureTLS: p.TakesInsecureTLS(), HTTP1: p.HTTP1, LimitRestOff: p.LimitRestOff, ImageFilesOff: p.ImageFilesOff, TakesImageFiles: p.TakesImageFiles(), NativeCompaction: p.NativeCompaction, CarriesCompaction: p.CarriesCompaction(), PassUserAgent: !p.MagpieUserAgent, OwnClient: p.OwnClient(), PassErrors: p.PassErrors, TakesPassErrors: p.TakesPassErrors(), AuthHeader: p.AuthHeader, BothAuth: p.BothAuth(), BalanceURL: p.BalanceURL, BalancePath: p.BalancePath, BalanceMethod: p.BalanceMethod, ModelsURL: p.ModelsURL, ListOff: p.ListsOff(), TakesListOff: p.Account == nil && !p.IsPlugin() && !p.DecideOnly(), TakesModelHeaders: p.Account == nil, DecideAPIKind: p.DecideAPIKind(), + Proxy: p.Proxy, AccountProxies: p.AccountProxies, AccountModels: p.AccountModels, AccountCaps: p.AccountCaps, AccountWindowCaps: p.AccountWindowCaps, AccountWindowAmounts: p.AccountWindowAmounts, AccountNames: p.AccountNames, Headers: p.Headers, ExtraBody: p.ExtraBody, ReplyHeaders: p.ReplyHeaders, PassHeaders: p.PassHeaders, Searches: p.Searches, Cline: p.ClinePinnable(), PinUpstream: p.PinUpstream, Unredacted: p.Unredacted, CountFree: p.CountFree, InsecureTLS: p.InsecureTLS, TakesInsecureTLS: p.TakesInsecureTLS(), HTTP1: p.HTTP1, LimitRestOff: p.LimitRestOff, ImageFilesOff: p.ImageFilesOff, TakesImageFiles: p.TakesImageFiles(), NativeCompaction: p.NativeCompaction, CarriesCompaction: p.CarriesCompaction(), PassUserAgent: !p.MagpieUserAgent, OwnClient: p.OwnClient(), PassErrors: p.PassErrors, TakesPassErrors: p.TakesPassErrors(), AuthHeader: p.AuthHeader, BothAuth: p.BothAuth(), BalanceURL: p.BalanceURL, BalancePath: p.BalancePath, BalanceMethod: p.BalanceMethod, ModelsURL: p.ModelsURL, ListOff: p.ListsOff(), TakesListOff: p.Account == nil && !p.IsPlugin() && !p.DecideOnly(), TakesModelHeaders: p.Account == nil, DecideAPIKind: p.DecideAPIKind(), Ready: p.Ready(), Chosen: p.PicksOf(avail), Agents: make([]providerAgent, 0, len(agents)), Fallback: p.Fallback, Routing: p.Routing, Sink: p.Sink, UseFirst: p.UseFirst, Affinity: p.Affinity, KeepLogin: p.KeepLogin, KeepLoginAs: p.KeepLoginAs, SwitchOnly: p.SwitchOnly, RestartApp: p.RestartApp, Self: p.SelfAnswered(), KeepSelf: p.KeepSelf, 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(), MaxAccounts: p.MaxAccounts, PluginAccounts: p.PluginAtOnce(), PriceRate: p.PriceRate, @@ -1665,6 +1668,10 @@ func providerRoutes(mux *http.ServeMux, w Windows) { // Windows, for windowcap, in place of Window: a family's // windows, which the GUI shows as one meter Windows []string `json:"windows"` + // Amount, for windowcap in place of Cap: a fixed amount of the + // window's own unit the account is used to at most, 0 to lift it + // (provider.AccountWindowAmounts) + Amount *float64 `json:"amount"` // Weight, for accountweight: the account's share under By // weight routing, 1 to provider.MaxKeyWeight (0 or 1: none) Weight int `json:"weight"` @@ -2094,7 +2101,7 @@ func providerRoutes(mux *http.ServeMux, w Windows) { // limits on requests at once, with accountconcurrency, and // their weights, with accountweight if old != nil { - in.AccountCaps, in.AccountWindowCaps = old.AccountCaps, old.AccountWindowCaps + in.AccountCaps, in.AccountWindowCaps, in.AccountWindowAmounts = old.AccountCaps, old.AccountWindowCaps, old.AccountWindowAmounts in.AccountConcurrency = old.AccountConcurrency in.AccountWeights = old.AccountWeights in.AccountNames = old.AccountNames // with accountname @@ -2372,7 +2379,12 @@ func providerRoutes(mux *http.ServeMux, w Windows) { if len(req.Windows) == 0 { req.Windows = []string{req.Window} } - if err := provider.SetWindowCaps(in.ID, req.Account, req.Windows, req.Cap); err != nil { + set := func() error { return provider.SetWindowCaps(in.ID, req.Account, req.Windows, req.Cap) } + if req.Amount != nil { + // a fixed amount of the window's unit, 0 to lift it + set = func() error { return provider.SetWindowAmount(in.ID, req.Account, req.Windows, *req.Amount) } + } + if err := set(); err != nil { fail(rw, err) return } diff --git a/internal/gui/tests/window-cap.test.cjs b/internal/gui/tests/window-cap.test.cjs index 50187c384..e33a7a8ea 100644 --- a/internal/gui/tests/window-cap.test.cjs +++ b/internal/gui/tests/window-cap.test.cjs @@ -51,6 +51,13 @@ const past = () => ({ const aside = (name, used) => ({ ...win(name, used, 600), ownCap: true }); const credits = (plan) => ({ provider: "codex", windows: [aside("Credits", plan), aside("Extra credits", 0), win("Total credits", plan / 4, 600)] }); const split = () => ({ "me@example.com": credits(60), "Friend@Example.com": credits(60) }); +// a window counted in a unit with its total (9won_25273 on Discord: a +// day's credits) can be capped at an amount of it instead: me has used 120 +// of the day's 1000 credits +const daily = () => ({ + "me@example.com": { provider: "codex", windows: [win("5 hours", 10, 4), { ...win("Daily credits", 12, 20), amount: 120, limit: 1000, unit: "credits" }] }, + "Friend@Example.com": under()["Friend@Example.com"], +}); function serve(lang, posts, use) { const ps = fresh(); @@ -71,11 +78,17 @@ function serve(lang, posts, use) { posts.push(body); const p = providers.providers.find((x) => x.id === body.id); const all = structuredClone(p.accountWindowCaps || {}), k = body.account.toLowerCase(); - const caps = all[k] || {}; - if (body.cap) caps[body.window] = body.cap; - else delete caps[body.window]; + const amts = structuredClone(p.accountWindowAmounts || {}); + const caps = all[k] || {}, amt = amts[k] || {}; + // an amount and a share on one window replace each other + delete caps[body.window]; + delete amt[body.window]; + if (body.amount) amt[body.window] = body.amount; + else if (body.cap) caps[body.window] = body.cap; if (Object.keys(caps).length) all[k] = caps; else delete all[k]; + if (Object.keys(amt).length) amts[k] = amt; else delete amts[k]; p.accountWindowCaps = all; + p.accountWindowAmounts = amts; return json(providers); } if (url.pathname.startsWith("/api/")) return json({}); @@ -86,11 +99,11 @@ function serve(lang, posts, use) { } const words = { - en: { cap: (n) => `Cap ${n}%`, none: "No cap", byWindow: "Caps by window", held: "At its cap · back in 3h", head: "Cap for 5 hours", account: "Account's cap · none", off: "No cap on this window", other: "Other…" }, - zh: { cap: (n) => `上限 ${n}%`, none: "不设上限", byWindow: "按窗口设上限", held: "已达上限 · 3 小时后恢复", head: "5 小时的上限", account: "账号上限 · 无", off: "此窗口不设上限", other: "其他…" }, - "zh-TW": { cap: (n) => `上限 ${n}%`, none: null, byWindow: "按時段設上限", held: null, head: "5 小時的上限", account: "帳號上限 · 無", off: "此時段不設上限", other: null }, - ja: { cap: null, none: null, byWindow: "ウィンドウごとの上限", held: null, head: "5 時間の上限", account: "アカウントの上限 · なし", off: "このウィンドウは上限なし", other: null }, - de: { cap: null, none: null, byWindow: "Limits je Zeitfenster", held: null, head: "Limit für 5 Stunden", account: "Limit des Kontos · keins", off: "Kein Limit für dieses Zeitfenster", other: null }, + en: { cap: (n) => `Cap ${n}%`, none: "No cap", byWindow: "Caps by window", held: "At its cap · back in 3h", head: "Cap for 5 hours", account: "Account's cap · none", off: "No cap on this window", other: "Other…" , amount: "Amount…", own: "Cap 300 credits" }, + zh: { cap: (n) => `上限 ${n}%`, none: "不设上限", byWindow: "按窗口设上限", held: "已达上限 · 3 小时后恢复", head: "5 小时的上限", account: "账号上限 · 无", off: "此窗口不设上限", other: "其他…" , amount: "固定数量…", own: "上限 300 积分" }, + "zh-TW": { cap: (n) => `上限 ${n}%`, none: null, byWindow: "按時段設上限", held: null, head: "5 小時的上限", account: "帳號上限 · 無", off: "此時段不設上限", other: null , amount: "固定數量…", own: "上限 300 積分" }, + ja: { cap: null, none: null, byWindow: "ウィンドウごとの上限", held: null, head: "5 時間の上限", account: "アカウントの上限 · なし", off: "このウィンドウは上限なし", other: null , amount: "固定量…", own: "上限 300 クレジット" }, + de: { cap: null, none: null, byWindow: "Limits je Zeitfenster", held: null, head: "Limit für 5 Stunden", account: "Limit des Kontos · keins", off: "Kein Limit für dieses Zeitfenster", other: null , amount: "Menge…", own: "Limit 300 Credits" }, }; const NEW = [ "No cap on {window}: it is used to 100%, whatever this account's cap. Click to change", @@ -100,6 +113,8 @@ const NEW = [ "Cap for {window}, in percent", "Account's cap · {n}%", "Account's cap · none", "As the account's other windows", "No cap on this window", "Use this window to 100%", "Cap for {window}", "Caps by window", "A window can have a cap of its own: click its meter below", + "Cap {n}", "{window} has a cap of its own: magpie counts this account as used up once it has used {n} of {window}, until it renews. Click to change", + "{who} stops at {n} of {window}", "Cap for {window}, in {unit}", "An amount above 0", "Amount…", "At most this much {unit}", ]; for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) { @@ -198,6 +213,46 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", assert.deepEqual(errors, []); }); + test(`${label}: a window counted in a unit is capped at an amount of it, typed, and lifted`, async (t) => { + const { page, errors, posts } = await open(t, "amount", daily); + // the day's credits: Amount… last, after Other… + await still(page, "me@example.com", meter(page, "me@example.com", 1)); + await menu(page).waitFor(); + const names = await menu(page).locator(".pm-name").allTextContents(); + assert.equal(names.length, 9); + assert.equal(names[8], w.amount); + let n = posts.length; + await item(page, w.amount).click(); + const typed = row(page, "me@example.com").locator("input.acap-in"); + await typed.waitFor(); + await typed.fill("0"); + await typed.press("Enter"); + await page.waitForTimeout(150); + assert.equal(posts.length, n, "0 posted as an amount"); + await still(page, "me@example.com", meter(page, "me@example.com", 1)); + await item(page, w.amount).click(); + await typed.waitFor(); + await typed.fill("300"); + await typed.press("Enter"); + assert.deepEqual(await posted(posts, n), { id: "codex", account: "me@example.com", window: "daily credits", amount: 300 }); + await row(page, "me@example.com").locator(".aq-own").first().waitFor(); + assert.equal(await row(page, "me@example.com").locator(".aq-own").first().textContent(), w.own); + // the mark stands at 300 of 1000; 120 used is under it + assert.deepEqual(await row(page, "me@example.com").locator(".aq-cap").evaluateAll((ms) => ms.map((m) => m.style.left)), ["30%"]); + assert.equal(await row(page, "me@example.com").locator(".acap-held").count(), 0); + // the amount is current in the menu; the five hours, with no unit, has no Amount… + await still(page, "me@example.com", meter(page, "me@example.com", 1)); + assert.equal(await menu(page).locator(".pm-item.on .pm-name").textContent(), w.amount); + // back to the account's: 0, the amount goes + n = posts.length; + await item(page, w.account).click(); + assert.deepEqual(await posted(posts, n), { id: "codex", account: "me@example.com", window: "daily credits", cap: 0 }); + await page.waitForFunction(() => !document.querySelector('.editor .acc[data-account-id="me@example.com"] .aq-own')); + await still(page, "me@example.com", meter(page, "me@example.com", 0)); + assert.equal(await menu(page).locator(".pm-name").count(), 8); + assert.deepEqual(errors, []); + }); + test(`${label}: a window's cap is set from its meter in the app's menu, typed, and lifted`, async (t) => { const { page, errors, posts } = await open(t, "set", under); // me's five hours: the menu, headed by the window, no native select diff --git a/internal/provider/account_caps.go b/internal/provider/account_caps.go index 1895f558f..464066b78 100644 --- a/internal/provider/account_caps.go +++ b/internal/provider/account_caps.go @@ -22,6 +22,20 @@ package provider // while any window is at or past its own share. The on-demand windows // (Aside) are not the allowance and never count. // +// A window whose reading counts it in a unit, with its total (WorkBuddy's +// credits, a plan's requests or tokens), can instead be capped at a fixed +// amount of that unit (9won_25273 on Discord: at most N credits a day of a +// daily-credits window, then the next account), kept per account and +// window (AccountWindowAmounts). The account is held once the window's +// count is at or past the amount, as at a share; a window read without a +// total leaves the amount aside and takes the account's share. A window +// has a share of its own or an amount, never both: setting one clears the +// other. +// +// The cap reads the vendor's own count of the window, so what the account +// spent outside magpie (the vendor's app, another machine) counts toward +// it as the vendor reports it; magpie can only hold back its own requests. +// // The cap is the user's, not the vendor's: what it holds back never spends // a Codex reset. The resets are spent on the vendor's own 100% (weekUsedUp, // usedUp, BackAt, heldUp), which the cap doesn't touch. @@ -29,6 +43,7 @@ package provider import ( "fmt" "maps" + "math" "slices" "strconv" "strings" @@ -71,6 +86,9 @@ func AccountCapOf(id, user string) int { type WindowCaps struct { All int Windows map[string]int + // Amounts are the windows capped at a fixed amount of their own unit + // instead, by WindowCapID (AccountWindowAmounts) + Amounts map[string]float64 Credits bool } @@ -94,6 +112,34 @@ func (c WindowCaps) Of(name string) (share int, credits bool) { return share, false } +// limitShare is the share at which a window holds the account, as Of +// (own when aside), with an amount cap on it read against the window's +// count: amount is then the cap in the window's unit, and share that +// amount as a share of the window's total of. A window read without a +// total (of 0) leaves its amount aside. +func (c WindowCaps) limitShare(name string, of float64, aside bool) (share float64, credits bool, amount float64) { + if a := c.Amounts[WindowCapID(name)]; a > 0 && of > 0 { + return a / of * 100, false, a + } + if aside { + return float64(c.own(name)), false, 0 + } + n, credits := c.Of(name) + return float64(n), credits, 0 +} + +// past says whether a window at used percent, count of its unit, is at or +// past the cap limitShare gave: by its count when the cap is an amount. +func past(share, amount, used, count float64) bool { + if share <= 0 { + return false + } + if amount > 0 { + return count >= amount + } + return used >= share +} + // own is the share at which a window set aside holds the account (Limit's // aside): only a cap the user set on that window itself, never the // account's or the credits', 0 for none. @@ -110,6 +156,11 @@ func (c WindowCaps) Holds() bool { if c.All > 0 || c.Credits { return true } + for _, v := range c.Amounts { + if v > 0 { + return true + } + } for _, v := range c.Windows { if v >= MinCap && v <= MaxCap { return true @@ -122,21 +173,21 @@ func (c WindowCaps) Holds() bool { // and its windows' own. As with AccountCap, an account made afresh beside // the agent's own reads them from providers.json. func (p Provider) CapsOf(user string) WindowCaps { - caps, wins := p.AccountCaps, p.AccountWindowCaps - if caps == nil && wins == nil { + caps, wins, amts := p.AccountCaps, p.AccountWindowCaps, p.AccountWindowAmounts + if caps == nil && wins == nil && amts == nil { if s, ok := storedPicks(p.ID); ok { - caps, wins = s.AccountCaps, s.AccountWindowCaps + caps, wins, amts = s.AccountCaps, s.AccountWindowCaps, s.AccountWindowAmounts } } k := accountKey(user) - return WindowCaps{All: caps[k], Windows: wins[k]} + return WindowCaps{All: caps[k], Windows: wins[k], Amounts: amts[k]} } // AccountCapsOf is CapsOf of the provider id. func AccountCapsOf(id, user string) WindowCaps { if s, ok := storedPicks(id); ok { k := accountKey(user) - return WindowCaps{All: s.AccountCaps[k], Windows: s.AccountWindowCaps[k]} + return WindowCaps{All: s.AccountCaps[k], Windows: s.AccountWindowCaps[k], Amounts: s.AccountWindowAmounts[k]} } return WindowCaps{} } @@ -177,9 +228,10 @@ func SetWindowCaps(id, ref string, windows []string, cap int) error { return fmt.Errorf("%s has no account %q", p.Name, ref) } k := accountKey(r) - if !slices.ContainsFunc(ws, func(w string) bool { return p.AccountWindowCaps[k][w] != cap }) { + if !slices.ContainsFunc(ws, func(w string) bool { return p.AccountWindowCaps[k][w] != cap || p.AccountWindowAmounts[k][w] > 0 }) { return nil } + p.AccountWindowAmounts = withoutAmounts(p.AccountWindowAmounts, k, ws) all := map[string]map[string]int{} for u, m := range p.AccountWindowCaps { all[u] = maps.Clone(m) @@ -201,6 +253,96 @@ func SetWindowCaps(id, ref string, windows []string, cap int) error { return Save(*p) } +// SetWindowAmount caps the windows named windows of the account ref of the +// subscription id at amount of their own unit (credits, requests, tokens), +// in place of a share of their own; 0 lifts it, and the windows follow the +// account's cap again. +func SetWindowAmount(id, ref string, windows []string, amount float64) error { + if amount < 0 || math.IsNaN(amount) || math.IsInf(amount, 0) { + return fmt.Errorf("a window's cap is an amount above 0, not %v", amount) + } + var ws []string + for _, w := range windows { + if w = WindowCapID(w); w == "" { + return fmt.Errorf("name the usage window to cap") + } + ws = append(ws, w) + } + if len(ws) == 0 { + return fmt.Errorf("name the usage window to cap") + } + p, err := Find(id) + if err != nil { + return err + } + if p.Account == nil { + return fmt.Errorf("%s has keys, not subscription accounts with usage windows to cap", p.Name) + } + r, ok := p.accountRef(ref) + if !ok { + return fmt.Errorf("%s has no account %q", p.Name, ref) + } + k := accountKey(r) + if !slices.ContainsFunc(ws, func(w string) bool { + _, own := p.AccountWindowCaps[k][w] + return p.AccountWindowAmounts[k][w] != amount || own + }) { + return nil + } + amts := withoutAmounts(p.AccountWindowAmounts, k, nil) + if amount > 0 { + if amts == nil { + amts = map[string]map[string]float64{} + } + if amts[k] == nil { + amts[k] = map[string]float64{} + } + for _, w := range ws { + amts[k][w] = amount + } + } else { + amts = withoutAmounts(amts, k, ws) + } + p.AccountWindowAmounts = amts + // an amount stands in for the window's own share + if own := p.AccountWindowCaps[k]; own != nil { + all := map[string]map[string]int{} + for u, m := range p.AccountWindowCaps { + all[u] = maps.Clone(m) + } + for _, w := range ws { + delete(all[k], w) + } + if len(all[k]) == 0 { + delete(all, k) + } + p.AccountWindowCaps = all + } + return Save(*p) +} + +// withoutAmounts is a copy of m with account k's amounts on windows ws +// left out (none for a nil ws); nil for none left. +func withoutAmounts(m map[string]map[string]float64, k string, ws []string) map[string]map[string]float64 { + var out map[string]map[string]float64 + for u, as := range m { + c := maps.Clone(as) + if u == k { + for _, w := range ws { + delete(c, w) + } + } + if len(c) == 0 { + continue + } + if out == nil { + out = map[string]map[string]float64{} + } + out[u] = c + } + return out +} + // SetAccountCap caps the account ref of the subscription id at cap percent // of its windows; 0 lifts the cap. func SetAccountCap(id, ref string, cap int) error { @@ -289,6 +431,29 @@ func normalWindowCaps(m map[string]map[string]int) map[string]map[string]int { return out } +// normalWindowAmounts is m as it is kept: accounts and windows in lower +// case, amounts above 0, empty ones left out; nil for none. +func normalWindowAmounts(m map[string]map[string]float64) map[string]map[string]float64 { + var out map[string]map[string]float64 + for u, ws := range m { + u = accountKey(u) + for w, a := range ws { + w = WindowCapID(w) + if u == "" || w == "" || !(a > 0) || math.IsInf(a, 0) { + continue + } + if out == nil { + out = map[string]map[string]float64{} + } + if out[u] == nil { + out[u] = map[string]float64{} + } + out[u][w] = a + } + } + return out +} + // CapHold is how an account is held by its caps for a model: the share // used of the fullest window holding it, that window's cap, when the last // of those windows renews (zero when one doesn't say), and Credits when @@ -298,6 +463,11 @@ type CapHold struct { Cap int Back time.Time Credits bool + // Amount is the cap when the fullest window holding it is capped at a + // fixed amount (AccountWindowAmounts): Count of it used, in Unit. Cap + // is then that amount as a share, rounded up. + Amount, Count float64 + Unit string } // CapHeld says how an allowance, as last known, holds the account for @@ -312,11 +482,8 @@ func (a Allowance) CapHeld(model string, caps WindowCaps, now time.Time) *CapHol var h *CapHold unknown, byCap := false, false for _, l := range a.capLimits(model) { - share, credits := caps.Of(l.Name) - if l.aside { - share, credits = caps.own(l.Name), false - } - if share <= 0 || l.Used < float64(share) { + share, credits, amount := caps.limitShare(l.Name, l.Of, l.aside) + if !past(share, amount, l.Used, l.Amount) { continue } if !l.Resets.IsZero() && !l.Resets.After(now) { @@ -326,7 +493,11 @@ func (a Allowance) CapHeld(model string, caps WindowCaps, now time.Time) *CapHol h = &CapHold{} } if l.Used > h.Used || h.Cap == 0 { - h.Used, h.Cap = l.Used, share + h.Used, h.Cap = l.Used, min(int(math.Ceil(share)), 100) + h.Amount, h.Count, h.Unit = 0, 0, "" + if amount > 0 { + h.Amount, h.Count, h.Unit = amount, l.Amount, l.Unit + } } byCap = byCap || !credits if l.Resets.IsZero() { @@ -356,11 +527,8 @@ func (a Allowance) NearCap(model string, caps WindowCaps, points float64, now ti } model = strings.ToLower(model) for _, l := range a.capLimits(model) { - share, _ := caps.Of(l.Name) - if l.aside { - share = caps.own(l.Name) - } - if share <= 0 || l.Used < float64(share)-points { + share, _, amount := caps.limitShare(l.Name, l.Of, l.aside) + if share <= 0 || l.Used < share-points && (amount <= 0 || l.Amount < amount) { continue } if !l.Resets.IsZero() && !l.Resets.After(now) { @@ -377,8 +545,8 @@ func (a Allowance) NearCap(model string, caps WindowCaps, points float64, now ti // caps reach nothing. func capReached(q SubscriptionQuota, caps WindowCaps, now time.Time) bool { for _, w := range q.Windows { - share, _ := caps.Of(w.Name) - if share <= 0 || w.Aside || w.Model != "" || w.Used < float64(share) { + share, _, amount := caps.limitShare(w.Name, w.Limit, false) + if w.Aside || w.Model != "" || !past(share, amount, w.Used, w.Amount) { continue } if w.ResetsAt != nil && !w.ResetsAt.After(now) { diff --git a/internal/provider/account_caps_amount_test.go b/internal/provider/account_caps_amount_test.go new file mode 100644 index 000000000..2070f68ff --- /dev/null +++ b/internal/provider/account_caps_amount_test.go @@ -0,0 +1,115 @@ +package provider + +import ( + "math" + "testing" + "time" +) + +// 9won_25273 on Discord: an account capped at a fixed amount of a window +// counted in a unit (at most 300 of a day's 1000 credits) is held once +// the vendor's count reaches it, and its share is the amount's share of +// the total; a window read without a total leaves the amount aside. +func TestWindowAmountCapHeld(t *testing.T) { + now := time.Now() + day := now.Add(5 * time.Hour) + read := func(count float64) Allowance { + return allowanceOf([]QuotaWindow{ + {Name: "Daily credits", Used: count / 10, Amount: count, Limit: 1000, Unit: "credits", ResetsAt: &day, Span: 24 * time.Hour}, + }, now) + } + caps := WindowCaps{Amounts: map[string]float64{"daily credits": 300}} + if !caps.Holds() { + t.Fatal("an amount cap holds nothing") + } + if h := read(299).CapHeld("gpt-6", caps, now); h != nil { + t.Fatalf("299 of 300 credits, held: %+v", h) + } + h := read(300).CapHeld("gpt-6", caps, now) + if h == nil || h.Amount != 300 || h.Count != 300 || h.Unit != "credits" || h.Cap != 30 || !h.Back.Equal(day) || h.Credits { + t.Fatalf("300 of 300 credits: %+v", h) + } + // the amount's share rounds up: 250.5 of 1000 holds at 26%, not 25% + odd := WindowCaps{Amounts: map[string]float64{"daily credits": 250.5}} + if h := read(260).CapHeld("gpt-6", odd, now); h == nil || h.Cap != 26 { + t.Fatalf("250.5 of 1000: %+v", h) + } + // the amount stands in for the account's own share on that window + both := WindowCaps{All: 10, Amounts: map[string]float64{"daily credits": 300}} + if h := read(200).CapHeld("gpt-6", both, now); h != nil { + t.Fatalf("200 credits, at 20%% past the account's 10%%, held: %+v", h) + } + // near the cap by a few points of its share + if !read(290).NearCap("gpt-6", caps, 2, now) || read(200).NearCap("gpt-6", caps, 2, now) { + t.Fatal("NearCap by the amount's share") + } + // renewed since it was read + if h := read(400).CapHeld("gpt-6", caps, day.Add(time.Minute)); h != nil { + t.Fatalf("held by a renewed window: %+v", h) + } + // a reading with no total: the amount can't be told, the account's + // share goes on + noTotal := allowanceOf([]QuotaWindow{{Name: "Daily credits", Used: 50, Amount: 900, ResetsAt: &day}}, now) + if h := noTotal.CapHeld("gpt-6", caps, now); h != nil { + t.Fatalf("an amount read against no total held: %+v", h) + } + if h := noTotal.CapHeld("gpt-6", both, now); h == nil || h.Cap != 10 || h.Amount != 0 { + t.Fatalf("no total, the account's 10%%: %+v", h) + } + // capReached, for the agent signed in, goes by the count too + ws := []QuotaWindow{{Name: "Daily credits", Used: 31, Amount: 310, Limit: 1000, Unit: "credits", ResetsAt: &day}} + if !capReached(SubscriptionQuota{Windows: ws}, caps, now) { + t.Fatal("310 of 300 credits not reached") + } + ws[0].Amount, ws[0].Used = 100, 10 + if capReached(SubscriptionQuota{Windows: ws}, caps, now) { + t.Fatal("100 of 300 credits reached") + } +} + +// An amount and a share on one window replace each other; 0 lifts the +// amount; a bad amount is refused; settings keep it in lower case. +func TestSetWindowAmount(t *testing.T) { + signIn(t) // me@example.com on codex + if err := SetWindowCap("codex", "me@example.com", "Weekly", 40); err != nil { + t.Fatal(err) + } + if err := SetWindowAmount("codex", "ME@example.com", []string{"Weekly"}, 300); err != nil { + t.Fatal(err) + } + c := AccountCapsOf("codex", "me@example.com") + if c.Amounts["weekly"] != 300 || c.Windows != nil { + t.Fatalf("the amount beside the week's own share: %+v", c) + } + if err := SetWindowCap("codex", "me@example.com", "weekly", 50); err != nil { + t.Fatal(err) + } + c = AccountCapsOf("codex", "me@example.com") + if c.Amounts != nil || c.Windows["weekly"] != 50 { + t.Fatalf("a share set over the amount: %+v", c) + } + if err := SetWindowAmount("codex", "me@example.com", []string{"weekly"}, 12.5); err != nil { + t.Fatal(err) + } + for _, bad := range []float64{-1, math.NaN(), math.Inf(1)} { + if err := SetWindowAmount("codex", "me@example.com", []string{"weekly"}, bad); err == nil { + t.Errorf("%v taken", bad) + } + } + if err := SetWindowAmount("codex", "me@example.com", []string{" "}, 10); err == nil { + t.Error("a window with no name taken") + } + if p, _ := Find("codex"); p.AccountWindowAmounts["me@example.com"]["weekly"] != 12.5 { + t.Fatalf("saved as %+v", p.AccountWindowAmounts) + } + if err := SetWindowAmount("codex", "me@example.com", []string{"weekly"}, 0); err != nil { + t.Fatal(err) + } + if p, _ := Find("codex"); p.AccountWindowAmounts != nil || p.AccountWindowCaps != nil { + t.Fatalf("lifted, still %+v %+v", p.AccountWindowAmounts, p.AccountWindowCaps) + } + got := normalWindowAmounts(map[string]map[string]float64{"ME@Example.com": {" Weekly ": 5, "five": 0, "inf": math.Inf(1), "nan": math.NaN()}, "": {"x": 1}}) + if len(got) != 1 || len(got["me@example.com"]) != 1 || got["me@example.com"]["weekly"] != 5 { + t.Fatalf("normal: %+v", got) + } +} diff --git a/internal/provider/codex_switch.go b/internal/provider/codex_switch.go index f42392388..92ec332b2 100644 --- a/internal/provider/codex_switch.go +++ b/internal/provider/codex_switch.go @@ -394,8 +394,8 @@ func roomLeft(q SubscriptionQuota, share float64, caps WindowCaps, now time.Time continue } line := share - if c, _ := caps.Of(w.Name); c > 0 && float64(c) < line { - line = float64(c) + if c, _, _ := caps.limitShare(w.Name, w.Limit, false); c > 0 && c < line { + line = c } room = min(room, line-w.Used) } diff --git a/internal/provider/copilot_accounts.go b/internal/provider/copilot_accounts.go index 10914a182..35027b07c 100644 --- a/internal/provider/copilot_accounts.go +++ b/internal/provider/copilot_accounts.go @@ -166,6 +166,7 @@ func moveAccountSettings(id string, moves map[string]string) error { moved = moveKey(p.AccountModels, from, to) || moved moved = moveKey(p.AccountCaps, from, to) || moved moved = moveKey(p.AccountWindowCaps, from, to) || moved + moved = moveKey(p.AccountWindowAmounts, from, to) || moved moved = moveKey(p.AccountConcurrency, from, to) || moved moved = moveKey(p.AccountWeights, from, to) || moved moved = moveKey(p.AccountNames, from, to) || moved diff --git a/internal/provider/provider.go b/internal/provider/provider.go index adeebe68d..01dbc38b2 100644 --- a/internal/provider/provider.go +++ b/internal/provider/provider.go @@ -484,6 +484,12 @@ type Provider struct { // and then the window's WindowCapID: 1–99, or 100 for none on it. A // window not in it takes the account's AccountCaps. AccountWindowCaps map[string]map[string]int `json:"accountWindowCaps,omitempty"` + // AccountWindowAmounts is, for a subscription, the fixed amount of a + // window's own unit (credits, requests, tokens) an account is used to + // at most where the user set one in place of a share (9won_25273 on + // Discord), by account and window as AccountWindowCaps. A window has + // one or the other. + AccountWindowAmounts map[string]map[string]float64 `json:"accountWindowAmounts,omitempty"` // CapStop, for a subscription whose accounts are capped, ends there // (plugins#349): while every account is held at its cap, a request is // answered 429, as the vendor would, rather than sent on to Fallback. @@ -905,6 +911,13 @@ func (p Provider) clone() Provider { } p.AccountWindowCaps = m } + if p.AccountWindowAmounts != nil { + m := make(map[string]map[string]float64, len(p.AccountWindowAmounts)) + for k, v := range p.AccountWindowAmounts { + m[k] = maps.Clone(v) + } + p.AccountWindowAmounts = m + } p.AccountConcurrency = maps.Clone(p.AccountConcurrency) p.AccountWeights = maps.Clone(p.AccountWeights) p.Contexts = maps.Clone(p.Contexts) @@ -1011,7 +1024,7 @@ func accountSettings(a, pk Provider) Provider { // plugin's provider too (isee1_1 on Discord) a.Unredacted = pk.Unredacted a.Proxy, a.AccountProxies, a.AccountModels, a.AccountModelsAll = pk.Proxy, pk.AccountProxies, pk.AccountModels, pk.AccountModelsAll - a.AccountCaps, a.AccountWindowCaps = pk.AccountCaps, pk.AccountWindowCaps + a.AccountCaps, a.AccountWindowCaps, a.AccountWindowAmounts = pk.AccountCaps, pk.AccountWindowCaps, pk.AccountWindowAmounts a.CapStop, a.CapCareful = pk.CapStop, pk.CapCareful a.UseFirst = pk.UseFirst a.AccountNames = pk.AccountNames @@ -1677,6 +1690,7 @@ func normalize(p Provider) Provider { p.AccountModelsAll = normalModelsAll(p.AccountModelsAll, p.AccountModels) p.AccountCaps = normalAccountCaps(p.AccountCaps) p.AccountWindowCaps = normalWindowCaps(p.AccountWindowCaps) + p.AccountWindowAmounts = normalWindowAmounts(p.AccountWindowAmounts) p.AccountNames = normalAccountNames(p.AccountNames) p.KeySpendCaps = normalKeySpendCaps(p.KeySpendCaps) p.KeyOwnBalances = normalKeyOwnBalances(p.KeyOwnBalances)