diff --git a/docs/subsystems/gateway-routing.md b/docs/subsystems/gateway-routing.md index dc3b7dd23..1f2b5ebb8 100644 --- a/docs/subsystems/gateway-routing.md +++ b/docs/subsystems/gateway-routing.md @@ -176,7 +176,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 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. 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`). 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) 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. 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`). 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. 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 is `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. 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 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 5a5b29aba..2857e83e2 100644 --- a/docs/subsystems/providers-accounts.md +++ b/docs/subsystems/providers-accounts.md @@ -342,7 +342,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; `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 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 window whose reset time has passed has started again, whatever share it was read at (`resetPassed`). That holds for a reading kept from before (`AsOf`) and for a fresh one: Claude Code's `/usage` gives a reset to the minute and can lag it, so a run just after a reset can still say 100% with that reset. `claudeWindows` hands such a window back empty on every path, and `usedPast`, `usedUp`, `BackAt` and `capReached` leave it out when they judge an account spent, for Codex, Claude Code and `magpie quota wait` alike. A card can still show a kept reading as it was read (`reported`, for a Claude card while `/usage` is unavailable); that changes what it shows, never which account is used. A reset `/usage` gives as a time alone ("resets 3pm") can be read as its next one, a day on (`claudeResetTime`), and is then not seen as passed here. - A restart to update can run two magpies for up to the old one's drain diff --git a/internal/gateway/cap_near.go b/internal/gateway/cap_near.go new file mode 100644 index 000000000..3342a9733 --- /dev/null +++ b/internal/gateway/cap_near.go @@ -0,0 +1,127 @@ +package gateway + +// Near its cap, one turn at a time (dyzdyz010 on Discord: capped at 90%, +// used to 100%). Routing holds a capped account by its last reading, and +// turns sent together were each planned on the same one: an account a +// point under its cap took every one of them, and went as far past it as +// they used between them. Within nearCapPoints of a usage cap set on it, +// an account takes one turn at a time. A turn that finds it busy goes to +// the next account or member when there is one, the account kept behind +// them; else it waits for the turn before it. Once its turn comes it is +// held by what is known then: the reading the reply before it left +// (Codex's codex.rate_limits, Claude's rate_limit_event), or, when that +// reply told nothing, the usage read again now (at most carefulWait). The +// cap is then passed by one turn at most, not by every turn at once. + +import ( + "context" + "sync" + "time" + + "github.com/yetone/magpie/internal/provider" +) + +// nearCapPoints is how many points under a cap an account takes one turn at a +// time: as careful caps read again (carefulNear), a turn of a big model +// on a small plan spending a few points. +const nearCapPoints = carefulNear + +// nearCaps is each account's one turn near its cap, by candidate.who(). +type nearCaps struct { + mu sync.Mutex + slots map[string]chan struct{} + wait int // turns waiting for a slot, for tests +} + +func (n *nearCaps) slot(who string) chan struct{} { + n.mu.Lock() + defer n.mu.Unlock() + if n.slots == nil { + n.slots = map[string]chan struct{}{} + } + s, ok := n.slots[who] + if !ok { + s = make(chan struct{}, 1) + n.slots[who] = s + } + return s +} + +// waiting is how many turns wait for an account's turn near its cap. +func (n *nearCaps) waiting() int { + n.mu.Lock() + defer n.mu.Unlock() + return n.wait +} + +// tryTake takes who's turn when it is free, and gives back its release. +func (n *nearCaps) tryTake(who string) (func(), bool) { + s := n.slot(who) + select { + case s <- struct{}{}: + return releaseOnce(s), true + default: + return nil, false + } +} + +// take waits for who's turn till ctx ends. +func (n *nearCaps) take(ctx context.Context, who string) (func(), error) { + s := n.slot(who) + n.mu.Lock() + n.wait++ + n.mu.Unlock() + defer func() { + n.mu.Lock() + n.wait-- + n.mu.Unlock() + }() + select { + case s <- struct{}{}: + return releaseOnce(s), nil + case <-ctx.Done(): + return nil, ctx.Err() + } +} + +func releaseOnce(s chan struct{}) func() { + var once sync.Once + return func() { once.Do(func() { <-s }) } +} + +// nearCapOf says whether c's account is within nearCapPoints of a usage +// cap set on it, by what is known of its usage at now, and the share it +// is at for the model. +func nearCapOf(c candidate, now time.Time) (float64, bool) { + a := c.p.Account + if a == nil { + return 0, false + } + caps := provider.HoldCaps(c.p, a.Agent, a.User) + if a.Agent == "codex" && freeOnChatGPT(c.model, a.Plan) { + return 0, false // spends nothing a cap keeps (capHeld) + } + if !caps.Holds() { + return 0, false + } + al, ok := allowances(a.UsageAgent())[a.User] + if !ok || !al.NearCap(c.model, caps, nearCapPoints, now) { + return 0, false + } + used, _ := al.For(c.model, now) + return used, true +} + +// nearCapAgain, once a turn has waited for the one before it on an +// account near its cap that was at used then, reads the account's usage +// again when nothing has told it since (the reply before it said nothing +// of it), waiting at most carefulWait. +func nearCapAgain(ctx context.Context, c candidate, used float64) { + if now, ok := nearCapOf(c, time.Now()); !ok || now != used { + return // heard from the reply before it, or renewed + } + a := c.p.Account + ctx, cancel := context.WithTimeout(ctx, carefulWait) + defer cancel() + readUsageNow(ctx, a.UsageAgent(), a.User) +} diff --git a/internal/gateway/cap_near_test.go b/internal/gateway/cap_near_test.go new file mode 100644 index 000000000..352b8e4e3 --- /dev/null +++ b/internal/gateway/cap_near_test.go @@ -0,0 +1,329 @@ +package gateway + +import ( + "encoding/json" + "io" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "slices" + "strconv" + "strings" + "sync" + "testing" + "time" + + "github.com/yetone/magpie/internal/provider" +) + +// nearCapBackend is a ChatGPT backend for the near-cap tests: each +// account's five hours read at used[acct] by /wham/usage, every turn held +// until open is closed. A turn's reply says the account is at heard[acct] +// (its codex.rate_limits event), or nothing of it when heard has none; once +// a turn has ended, /wham/usage says after[acct] when it has one. +type nearCapBackend struct { + mu sync.Mutex + used, after map[string]float64 + heard map[string]float64 + tried []string + ended int + open chan struct{} + five, week int64 +} + +func newNearCapBackend(t *testing.T, used, heard, after map[string]float64) *nearCapBackend { + t.Helper() + now := time.Now() + b := &nearCapBackend{used: used, heard: heard, after: after, open: make(chan struct{}), + five: now.Add(2 * time.Hour).Unix(), week: now.Add(4 * 24 * time.Hour).Unix()} + up := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + acct := r.Header.Get("chatgpt-account-id") + switch r.URL.Path { + case "/backend-api/codex/responses": + io.ReadAll(r.Body) + b.mu.Lock() + b.tried = append(b.tried, acct) + b.mu.Unlock() + select { + case <-b.open: + case <-r.Context().Done(): + return + } + var lines []string + if n, ok := b.heard[acct]; ok { + lines = append(lines, `event: codex.rate_limits`+"\n"+`data: {"type":"codex.rate_limits","plan_type":"plus","rate_limits":{"allowed":true,"limit_reached":false,"primary":{"used_percent":`+jsonFloat(n)+`,"window_minutes":300,"reset_at":`+jsonInt(b.five)+`},"secondary":{"used_percent":10,"window_minutes":10080,"reset_at":`+jsonInt(b.week)+`}},"credits":null,"metered_limit_name":null,"limit_name":null}`) + } + lines = append(lines, + `data: {"type":"response.created","response":{"id":"r1","model":"gpt-5.5"}}`, + `data: {"type":"response.output_text.delta","delta":"pong"}`, + `data: {"type":"response.completed","response":{"id":"r1","usage":{"input_tokens":7,"output_tokens":1}}}`) + io.WriteString(w, sse(lines...)) + b.mu.Lock() + b.ended++ + b.mu.Unlock() + case "/backend-api/wham/usage": + b.mu.Lock() + used := b.used[acct] + if n, ok := b.after[acct]; ok && b.ended > 0 { + used = n + } + b.mu.Unlock() + json.NewEncoder(w).Encode(map[string]any{"plan_type": "plus", + "rate_limit": map[string]any{"allowed": true, + "primary_window": map[string]any{"used_percent": used, "limit_window_seconds": 18000, "reset_at": b.five}, + "secondary_window": map[string]any{"used_percent": 10, "limit_window_seconds": 604800, "reset_at": b.week}}}) + default: + w.WriteHeader(404) + } + })) + t.Cleanup(up.Close) + t.Cleanup(func() { + select { + case <-b.open: + default: + close(b.open) + } + }) + was := provider.CodexBase + provider.CodexBase = up.URL + "/backend-api/codex" + t.Cleanup(func() { provider.CodexBase = was }) + return b +} + +func jsonFloat(n float64) string { + bs, _ := json.Marshal(n) + return string(bs) +} + +func (b *nearCapBackend) sent() []string { + b.mu.Lock() + defer b.mu.Unlock() + return append([]string(nil), b.tried...) +} + +// nearCapAccounts, Codex's accounts signed in (me@example.com, and the +// spares) and the fake backend up, routes them in order, caps me at capAt +// and reads every one from the backend, waiting for me's reading to be +// want. +func nearCapAccounts(t *testing.T, capAt int, want float64, spares ...string) { + t.Helper() + old := allowances + allowances = provider.Allowances + t.Cleanup(func() { allowances = old }) + if err := provider.SetRouting("codex", provider.Ordered); err != nil { + t.Fatal(err) + } + if err := provider.SetAccountCap("codex", "me@example.com", capAt); err != nil { + t.Fatal(err) + } + users := append([]string{"me@example.com"}, spares...) + for _, u := range users { + provider.StaleAllowance("codex", u) + } + t.Cleanup(func() { + for _, u := range users { + provider.StaleAllowance("codex", u) + } + }) + for deadline := time.Now().Add(5 * time.Second); ; time.Sleep(10 * time.Millisecond) { + n, _ := provider.Allowances("codex")["me@example.com"].For("gpt-5.5", time.Now()) + if n == want { + break + } + if time.Now().After(deadline) { + t.Fatalf("never read: %v%%", n) + } + } +} + +type nearReply struct { + code int + body string +} + +// postAtOnce sends n turns at once, each in its own goroutine. +func postAtOnce(t *testing.T, srv *Server, n int) chan nearReply { + out := make(chan nearReply, n) + for range n { + go func() { + code, body := resetPost(t, srv) + out <- nearReply{code, body} + }() + } + return out +} + +func waitFor(t *testing.T, what string, ok func() bool) { + t.Helper() + for deadline := time.Now().Add(10 * time.Second); !ok(); time.Sleep(5 * time.Millisecond) { + if time.Now().After(deadline) { + t.Fatalf("never: %s", what) + } + } +} + +// dyzdyz010 on Discord: an account capped at 90% was used to 100%. Every +// turn sent at once to an account a point under its cap was planned on the +// same reading, so each went to it, and the account went as far past its +// cap as they took between them. Within nearCapPoints of a cap an +// account takes one turn at a time: the others go to the next account. +func TestNearCapTakesOneTurnAtATime(t *testing.T) { + codexSignedIn(t, "spare@example.com") + b := newNearCapBackend(t, map[string]float64{"acct-1": 89, "acct-2": 20}, + map[string]float64{"acct-1": 92, "acct-2": 21}, nil) + nearCapAccounts(t, 90, 89, "spare@example.com") + srv := New() + const n = 4 + replies := postAtOnce(t, srv, n) + // every turn is at the vendor, before any is answered: each was + // routed on the reading of 89% + waitFor(t, "every turn sent", func() bool { return len(b.sent()) == n }) + close(b.open) + for range n { + if r := <-replies; r.code != 200 || !strings.Contains(r.body, "pong") { + t.Fatalf("%d %s", r.code, r.body) + } + } + got := map[string]int{} + for _, a := range b.sent() { + got[a]++ + } + if got["acct-1"] != 1 || got["acct-2"] != n-1 { + t.Fatalf("sent %v; want one turn to the account near its cap, the rest to the other", got) + } +} + +// The account near its cap the only one: a turn waits for the one before +// it, and is then held by what that one's reply said (92%), not sent past +// the cap on the old reading. +func TestNearCapWaitsThenHolds(t *testing.T) { + codexSignedIn(t) + b := newNearCapBackend(t, map[string]float64{"acct-1": 89}, map[string]float64{"acct-1": 92}, nil) + nearCapAccounts(t, 90, 89) + srv := New() + replies := postAtOnce(t, srv, 2) + waitFor(t, "one turn sent, one waiting", func() bool { return len(b.sent()) == 1 && srv.nearCap.waiting() == 1 }) + close(b.open) + codes := map[int]int{} + var held string + for range 2 { + r := <-replies + codes[r.code]++ + if r.code == 429 { + held = r.body + } + } + if codes[200] != 1 || codes[429] != 1 || len(b.sent()) != 1 { + t.Fatalf("codes %v, sent %v; want one answered, one held at the cap", codes, b.sent()) + } + if !strings.Contains(held, "usage cap") { + t.Fatalf("held as %s", held) + } +} + +// A reply that tells nothing of the account's usage: the turn that waited +// for it reads the usage again before it goes, and is held at the cap the +// reading says it has reached. +func TestNearCapReadsAgainAfterASilentReply(t *testing.T) { + codexSignedIn(t) + b := newNearCapBackend(t, map[string]float64{"acct-1": 89}, nil, map[string]float64{"acct-1": 93}) + nearCapAccounts(t, 90, 89) + srv := New() + replies := postAtOnce(t, srv, 2) + waitFor(t, "one turn sent, one waiting", func() bool { return len(b.sent()) == 1 && srv.nearCap.waiting() == 1 }) + close(b.open) + codes := map[int]int{} + for range 2 { + codes[(<-replies).code]++ + } + if codes[200] != 1 || codes[429] != 1 || len(b.sent()) != 1 { + t.Fatalf("codes %v, sent %v; want the second read again and held", codes, b.sent()) + } +} + +// Under its cap by more than nearCapPoints, turns go at once, together. +func TestFarFromCapTurnsGoTogether(t *testing.T) { + codexSignedIn(t) + b := newNearCapBackend(t, map[string]float64{"acct-1": 50}, map[string]float64{"acct-1": 51}, nil) + nearCapAccounts(t, 90, 50) + srv := New() + replies := postAtOnce(t, srv, 3) + waitFor(t, "every turn sent", func() bool { return len(b.sent()) == 3 }) + close(b.open) + for range 3 { + if r := <-replies; r.code != 200 { + t.Fatalf("%d %s", r.code, r.body) + } + } +} + +// dyzdyz010's own case: Claude Code accounts, each capped at 90% of its +// five hours, Stop at the caps on. Turns sent together while the first +// account is a point under its cap: one goes to it, the other to the +// second account, not both past the first's cap on one reading. +func TestNearCapClaudeAccountsTakeOneTurnEach(t *testing.T) { + gate := filepath.Join(t.TempDir(), "gate") + log := claudeSubscriptionFirstSays(t, ` while [ ! -f `+gate+` ]; do sleep 0.05; done + echo '{"type":"stream_event","event":{"type":"message_start","message":{"id":"m","model":"claude-sonnet-5","usage":{"input_tokens":1}}}}' + echo '{"type":"stream_event","event":{"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"pong"}}}' + echo '{"type":"stream_event","event":{"type":"message_delta","delta":{"stop_reason":"end_turn"},"usage":{"output_tokens":1}}}' + echo '{"type":"stream_event","event":{"type":"message_stop"}}' + echo '{"type":"result","subtype":"success","is_error":false,"result":"pong"}' +`) + t.Cleanup(func() { os.WriteFile(gate, nil, 0o600) }) + old := allowances + allowances = provider.Allowances + t.Cleanup(func() { allowances = old }) + if err := provider.SetRouting("claude", provider.Ordered); err != nil { + t.Fatal(err) + } + for _, u := range []string{"me@example.com", "spare@example.com"} { + if err := provider.SetAccountCap("claude", u, 90); err != nil { + t.Fatal(err) + } + } + five, week := time.Now().Add(2*time.Hour).Unix(), time.Now().Add(4*24*time.Hour).Unix() + provider.NoteClaudeLimits("me@example.com", []provider.ClaudeLimit{{Kind: "five_hour", Used: 0.89, ResetsAt: five}, {Kind: "seven_day", Used: 0.1, ResetsAt: week}}) + provider.NoteClaudeLimits("spare@example.com", []provider.ClaudeLimit{{Kind: "five_hour", Used: 0.2, ResetsAt: five}, {Kind: "seven_day", Used: 0.1, ResetsAt: week}}) + t.Cleanup(func() { + provider.StaleAllowance("claude", "me@example.com") + provider.StaleAllowance("claude", "spare@example.com") + }) + if n, _ := provider.Allowances("claude")["me@example.com"].For("claude-sonnet-5", time.Now()); n != 89 { + t.Fatalf("read at %v%%", n) + } + s := New() + t.Cleanup(s.subscription.abortAll) + out := make(chan nearReply, 2) + for i := range 2 { + go func() { + code, body := sendTo(s, "/v1/messages", `{"model":"claude/claude-sonnet-5","max_tokens":50,"stream":true,"messages":[{"role":"user","content":"ping `+strconv.Itoa(i)+`"}]}`) + out <- nearReply{code, body} + }() + } + // a Claude Code run on each account the turns went to: the account + // near its cap may have a run started ahead for its next turn too + waitFor(t, "a run on each account", func() bool { + b, _ := os.ReadFile(log) + return strings.Contains(string(b), "own") && strings.Contains(string(b), "tok-spare") + }) + os.WriteFile(gate, nil, 0o600) + for range 2 { + if r := <-out; r.code != 200 || !strings.Contains(r.body, "pong") { + t.Fatalf("%d %s", r.code, r.body) + } + } + var got []string + s.trace.mu.Lock() + for _, r := range s.trace.routes { + for _, try := range r.Tries { + got = append(got, try.ID) + } + } + s.trace.mu.Unlock() + slices.Sort(got) + if strings.Join(got, ",") != "claude,claude@spare@example.com" { + t.Fatalf("tried %v; want one turn on the account near its cap, one on the spare", got) + } +} diff --git a/internal/gateway/gateway.go b/internal/gateway/gateway.go index 74350e3e4..446d78bd6 100644 --- a/internal/gateway/gateway.go +++ b/internal/gateway/gateway.go @@ -550,6 +550,8 @@ type Server struct { // the requests out at each key or account with a MaxConcurrency, and // those waiting their turn (concurrency.go) lanes lanes + // each account's one turn at a time near its usage cap (cap_near.go) + nearCap nearCaps // the requests each key or account with a MaxRPM sent in the last // minute, and those about to go (rpm.go) rpms rpms @@ -3162,11 +3164,24 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro // handed the request on, written once the next try begins var failedRow func() walkBegan := time.Now() // the serial walk's start, for groupBudget (#5113) + // the turn near its cap the try before took, given back as the next + // begins or the request ends (cap_near.go) + var nearDone func() + defer func() { + if nearDone != nil { + nearDone() + } + }() + nearBehind := map[string]bool{} // accounts near their cap moved behind the rest once for i := 0; i < len(cands); i++ { if failedRow != nil { failedRow() failedRow = nil } + if nearDone != nil { + nearDone() + nearDone = nil + } c := cands[i] if handed.release != nil && handed.who != c.who() { handed.release() @@ -3216,6 +3231,58 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro failTo(w, kept, from, call.Status, cmp.Or(msg, call.Error)) break } + if used, near := nearCapOf(c, time.Now()); near && aff.Why != "strict" && capHeld(c.p, c.p, c.model, time.Now()) == nil { + // within nearCapPoints of its usage cap, the account takes one + // turn at a time (dyzdyz010 on Discord): busy, the turn goes to + // the next one first, this one kept behind them, else waits for + // the turn before it and is held by what that one left. A + // conversation kept strictly on it goes on past its cap, as + // strictKeep keeps it, and an account already held when its try + // begins was let in past its cap on purpose (a reset spent for + // it, its credits), so is not held again here. + done, ok := s.nearCap.tryTake(c.who()) + if !ok && i < len(cands)-1 && !nearBehind[c.who()] { + nearBehind[c.who()] = true + cands = append(slices.Delete(slices.Clone(cands), i, i+1), c) + i-- + continue + } + if !ok { + var err error + if done, err = s.nearCap.take(r.Context(), c.who()); err != nil { + // the agent went away while it waited: nothing was sent + call.Status, call.Error = canceled(r.Context()) + break + } + nearCapAgain(r.Context(), c, used) + } + nearDone = done + if h := capHeld(c.p, c.p, c.model, time.Now()); h != nil { + nearDone() + nearDone = nil + c.capped = h + ws := barredOf([]candidate{c}, c.p, false, from, nil) + msg, back := cappedError(call.Model, ws, time.Now()) + skipped = append(skipped, c.label()+": "+msg) + if i < len(cands)-1 { + continue + } + // held at its cap by the turn before it: the agent is told + // the failure of one asked before, else the cap + if other != nil { + call.Status, call.Error, call.Usage.ErrType = other.Status, other.Error, other.errType + s.trace.update(tr, func(t *Route) { t.Fail = toldFail(other) }) + failTo(w, kept, from, call.Status, call.Error) + break + } + if d := time.Until(back); d > 0 && !kept.sent { + w.Header().Set("Retry-After", strconv.Itoa(int(d.Seconds())+1)) + } + call.Status, call.Error = 429, cappedRecord(ws) + failTo(w, kept, from, 429, msg) + break + } + } if !autoReset && c.onCredits() { // going to the account on its credits, its week used up: a // reset it spends by itself when the week runs out goes