diff --git a/docs/reference.md b/docs/reference.md index a192fba2a..76abec9b0 100644 --- a/docs/reference.md +++ b/docs/reference.md @@ -1441,7 +1441,13 @@ minutes. Out of credit rests half an hour. Any other failure rests a minute, lon again, up to 10 minutes; a subscription that fails with a window used up rests until that window renews. `magpie provider rest-cap 4h` moves both of those caps, 30 and 10 minutes, for one provider's keys and -accounts, up to 8 days; `default` gives them back. +accounts, from 1 minute (every rest a minute) up to 8 days; `default` gives +them back. `magpie provider rest-cap off` is for a relay or an account +pool whose unknown errors come now and then: a key or account of it that +fails without saying why (a 5xx, a dropped connection) doesn't rest at all, +and the next request asks it again. A refused key (401, 403), a model it +doesn't serve, being out of quota or credit, or a rate limit still rests +it as above. **When the safety filter refuses.** A reply the vendor's safety filter refuses before any of it is said rests nobody: it is about what was asked, diff --git a/docs/subsystems/gateway-routing.md b/docs/subsystems/gateway-routing.md index caa9583f4..383d97d76 100644 --- a/docs/subsystems/gateway-routing.md +++ b/docs/subsystems/gateway-routing.md @@ -79,7 +79,7 @@ recorded as a prediction failure (`noPrediction`). - A rule by folder (`Rule.Folders`, `folders=~/work/acme,~/oss`; Cario0x on X: routing by the project being worked on) matches when the folder the agent works in is one of them or inside one (`provider.FolderUnder`, [`rulefolder.go`](../../internal/provider/rulefolder.go)): at a path's boundary, so `/a/b` is not under `/a/bc`; `~` is the home folder; a Windows drive is one with its WSL mount (`C:\work` is `/mnt/c/work`) and a `\\wsl$\` or `\\wsl.localhost\` share is the distro's own path; case doesn't count on macOS and Windows, nor ever for a drive. A rule outside folders (`Rule.ExceptFolders`, `except-folders=~/big-task`; #1606, Ti800) matches when the folder is in none of them, and an agent that says none isn't known to be in one, so it matches; a rule may have both (`Rule.ByFolder`, `inFolders`). The folder is read from the request only when a rule of the group has folders or except-folders (`workDir` in [`workdir.go`](../../internal/gateway/workdir.go)), in each agent's own words, taken from captured requests: Claude Code's ` - Primary working directory: ` (its `<`/`>` as entities; ` (was )` after a change dropped), Codex's `` ``, Pi's `` in the system prompt, and OpenCode's `Working directory:` inside its `` block. Only the system prompt and the user's and system messages' text count, never the model's words or a tool's result, and the last said wins. An agent that says none has no folder, and no `folders=` rule matches it (unknown, never empty). The same reading tells a plugin's fetch where its agent works ([provider-plugins](provider-plugins.md#where-the-agent-works-for-a-plugins-fetch)). A pause rule may hold by folder too (below). The trace's `RuleHit.Folder` is the folder read, and the Routing page tells it beside the rule's `folder …` condition. `TestFolderUnder`, `TestRuleMatchesByFolder`, `TestParseRuleFolders`, `TestWorkDirOfEachAgent`, `TestRuleByFolder`, `TestRuleMatchesExceptFolders`, `routing-folder.test.cjs`. Rules by folder are never in a shared group (`ShareGroup` drops every `ByFolder` rule). - 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`. 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`). 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`); otherwise a capped or barred set returns `cappedError` or `barredError`. 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. -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, 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`). 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 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`). 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`). 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) 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 subscription account that fails any other way with a window full, by magpie's latest reading of its windows, rests until that window renews. 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. 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. 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 only: the backoff count stays, and a refusal after it rests the key again the usual way. 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`). 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). 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. siwc, API-key requests to openai.com and the legacy `/responses/compact` are left as they were. +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, 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`). The failure count is kept per key or account (`restKey`), not per model, except for a model refusal below, and an answer clears it (`served`). `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`). 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 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`). 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`). 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) 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 subscription account that fails any other way with a window full, by magpie's latest reading of its windows, rests until that window renews. 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. 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. 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 only: the backoff count stays, and a refusal after it rests the key again the usual way. 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`). 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). 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. siwc, API-key requests to openai.com and the legacy `/responses/compact` are left as they were. 5. The last candidate's error reaches the agent, with one exception for a group (#1418, `patience.go`). When every member has failed in a way that passes (`busy`: 408, 500, 502, 503, 504 or 529 that isn't a proxy, a quota or response protection, or a 429 that is a short rate limit, not a plan or credit), 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. `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. 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 keeps only the same-one retries `passing` gives the last one left. 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. ## Constraints and failure behavior diff --git a/internal/cli/providers_cli.go b/internal/cli/providers_cli.go index fee2e634c..27b9ba51c 100644 --- a/internal/cli/providers_cli.go +++ b/internal/cli/providers_cli.go @@ -74,10 +74,13 @@ const providerUsage = `usage: without saying when it is back (default: 15 minutes; at most 8 days), or until the time of day a daily allowance comes back, on this computer's clock or at the vendor's offset from UTC - magpie provider rest-cap [30m|6h|1d|default] + magpie provider rest-cap [1m|30m|6h|1d|off|default] the most a key or account sits out while it keeps failing or being rate limited, its rest doubling each time from a minute (default: - 10 minutes for a failure, 30 for a rate limit; at most 8 days) + 10 minutes for a failure, 30 for a rate limit; at most 8 days); + off: one that fails without saying why (a relay's 5xx) doesn't + rest at all, while out of quota, its key refused or rate limited + still rests it magpie provider listed yes|no no: its models serve only through routing groups, not in the list magpie provider off|on switch it off (kept, but no agent or request uses it), or on again magpie provider test [--as codex|claude-code] [model…] @@ -1655,14 +1658,14 @@ func quotaRestCmd(rest []string) error { // while they keep failing or being rate limited (#2008). func restCapCmd(rest []string) error { if len(rest) < 1 || len(rest) > 2 { - return fmt.Errorf("magpie provider rest-cap [30m|6h|1d|default]") + return fmt.Errorf("magpie provider rest-cap [1m|30m|6h|1d|off|default]") } p, err := provider.Find(rest[0]) if err != nil { return err } if len(rest) > 1 { - minutes, err := restMinutes(rest[1]) + minutes, err := restCapMinutes(rest[1]) if err != nil { return err } @@ -1673,7 +1676,9 @@ func restCapCmd(rest []string) error { return err } } - if p.RestCap > 0 { + if p.NoFailRest() { + fmt.Printf("%s · a key or account that fails without saying why doesn't rest: the next request asks it again. Out of quota or credit, its key refused or its model not served still rests it; rate limited, at most 30 minutes (magpie's own)\n", p.Name) + } else if p.RestCap > 0 { fmt.Printf("%s · a key or account that keeps failing sits out at most %s\n", p.Name, restWords(time.Duration(p.RestCap)*time.Minute)) } else { fmt.Printf("%s · a key or account that keeps failing sits out at most 10 minutes, 30 when rate limited (magpie's own)\n", p.Name) @@ -1681,6 +1686,21 @@ func restCapCmd(rest []string) error { return nil } +// restCapMinutes reads a rest cap as restCapCmd takes it: as restMinutes +// does, but off (or never) is provider.RestCapOff, no rest after an +// unknown failure, and a cap under a minute is turned away with what to +// set instead, as the first rest is a minute already. +func restCapMinutes(s string) (int, error) { + switch strings.ToLower(strings.TrimSpace(s)) { + case "off", "never", "no": + return provider.RestCapOff, nil + } + if d, err := time.ParseDuration(strings.TrimSpace(s)); err == nil && d > 0 && d < time.Minute { + return 0, fmt.Errorf("the shortest rest cap is 1m, which rests a minute every time, not longer; off doesn't rest after an unknown failure at all") + } + return restMinutes(s) +} + // restMinutes reads a rest as quotaRestCmd takes it: default (0), a // number of minutes, a Go duration (90m, 6h) or a number of days (7d). func restMinutes(s string) (int, error) { diff --git a/internal/cli/quota_reset_cli_test.go b/internal/cli/quota_reset_cli_test.go index 4ff166fa3..5d7e6d9e9 100644 --- a/internal/cli/quota_reset_cli_test.go +++ b/internal/cli/quota_reset_cli_test.go @@ -76,4 +76,19 @@ func TestRestCapCmd(t *testing.T) { if err := restCapCmd([]string{"xk", "default"}); err != nil || cap() != 0 { t.Fatalf("default: %v %d", err, cap()) } + // Kismet Alan on Discord: a relay whose unknown errors pass is set + // never to rest after one, saved and read back so; a minute is the + // shortest cap, and under it is turned away, not read as default + if err := restCapCmd([]string{"xk", "off"}); err != nil || cap() != provider.RestCapOff { + t.Fatalf("off: %v %d", err, cap()) + } + if p, _ := provider.Find("xk"); !p.NoFailRest() { + t.Fatal("off not read back as no rest") + } + if err := restCapCmd([]string{"xk", "1m"}); err != nil || cap() != 1 { + t.Fatalf("1m: %v %d", err, cap()) + } + if err := restCapCmd([]string{"xk", "30s"}); err == nil || cap() != 1 { + t.Fatalf("30s taken: %v %d", err, cap()) + } } diff --git a/internal/gateway/rest_cap_test.go b/internal/gateway/rest_cap_test.go index e5fdfee63..cc74ab81b 100644 --- a/internal/gateway/rest_cap_test.go +++ b/internal/gateway/rest_cap_test.go @@ -50,3 +50,62 @@ func TestRestCapOr(t *testing.T) { t.Error(d) } } + +// Kismet Alan on Discord: a relay or account pool whose unknown errors +// come now and then, the next request often going through, is set never +// to rest after one (`magpie provider rest-cap off`). Its 5xx and its +// dropped connection rest it no more, nor count toward a backoff; what +// says why still rests it as before: a rate limit (magpie's own 30 +// minutes cap), out of quota, its key refused, its model not served. +func TestRestCapOff(t *testing.T) { + s := &Server{} + c := candidate{p: provider.Provider{ID: "nofail", Key: "k", RestCap: provider.RestCapOff}, model: "m", rest: "nofail#k"} + id := c.restKey() + t.Cleanup(func() { + clearRest(id) + clearRest(c.restID()) + routed.Lock() + delete(routed.failures, id) + delete(routed.failures, c.restID()) + routed.Unlock() + }) + fail := `{"error":{"message":"upstream connect error","type":"api_error"}}` + for i, status := range []int{500, 502, 503, 504, 520} { + r := s.restAfter(c, status, http.Header{}, []byte(fail)) + if r.Why != failOther || r.By != "off" || r.Until.After(time.Now()) { + t.Fatalf("#%d %d: rests %v by %s (%s), want no rest", i+1, status, time.Until(r.Until), r.By, r.Why) + } + if resting(c) { + t.Fatalf("#%d %d: set aside", i+1, status) + } + } + routed.Lock() + n := routed.failures[id] + routed.Unlock() + if n != 0 { + t.Fatalf("%d failures counted", n) + } + // what says why rests it still + for _, k := range []struct { + status int + body string + why string + }{ + {401, `{"error":{"message":"invalid api key","type":"api_error"}}`, failOther}, + {403, `{"error":{"message":"forbidden","type":"api_error"}}`, failOther}, + {429, `{"error":{"message":"Too many requests","type":"rate_limit_error"}}`, failRate}, + {429, `{"error":{"message":"You exceeded your current quota, please check your plan","type":"insufficient_quota"}}`, failCredit}, + {404, `{"error":{"message":"The model m does not exist or you do not have access to it","type":"invalid_request_error"}}`, failOther}, + } { + clearRest(id) + clearRest(c.restID()) + r := s.restAfter(c, k.status, http.Header{}, []byte(k.body)) + if r.Why != k.why || r.By == "off" || !r.Until.After(time.Now()) || !resting(c) { + t.Fatalf("%d %s: rests %v by %s (%s), want a rest as %s", k.status, k.body, time.Until(r.Until), r.By, r.Why, k.why) + } + } + // a rate limit's cap is magpie's own 30 minutes, not none + if d := c.p.RestCapOr(longestRateRest); d != longestRateRest { + t.Fatalf("rate cap %v", d) + } +} diff --git a/internal/gateway/routing.go b/internal/gateway/routing.go index c7342bafb..38c8fab43 100644 --- a/internal/gateway/routing.go +++ b/internal/gateway/routing.go @@ -380,7 +380,9 @@ type Rest struct { // (the allowance window it filled renews), "quota" (no word of when), // "cooldown" (a minute), "backoff" (longer each time it fails again, // or is rate limited again as soon as it is back), "restricted" (the - // vendor restricted the account: two hours, or until lifted by hand). + // vendor restricted the account: two hours, or until lifted by hand), + // "off" (no rest: its provider is set not to rest after an unknown + // failure, provider.RestCapOff). By string `json:"by"` Failures int `json:"failures,omitempty"` // in a row, for a backoff // Key is what it rests by, for the app to lift the rest (Unrest) @@ -699,6 +701,16 @@ func (s *Server) restAfterMarked(c candidate, status int, header http.Header, bo } r.Link, _ = provider.Verification([]byte(r.said)) default: + // the provider set never to rest after a failure that says nothing + // of why (provider.RestCapOff; Kismet Alan on Discord: a relay's + // or an account pool's unknown errors come now and then, and the + // next request often goes through): it isn't set aside, nor its + // failure counted. A key refused, a model not served, or a window + // full still rests it, as they say why + if c.p.NoFailRest() && why == failOther && !unserved && status != http.StatusUnauthorized && status != http.StatusForbidden && (c.p.Account == nil || c.full(now).IsZero()) { + r.By, r.Until = "off", now + return r + } counted := c.restKey() if unserved { counted = c.restID() diff --git a/internal/gui/assets/i18n.js b/internal/gui/assets/i18n.js index 60d5ed201..93a0c64c3 100644 --- a/internal/gui/assets/i18n.js +++ b/internal/gui/assets/i18n.js @@ -3609,6 +3609,7 @@ const I18N = { "It rests 15 minutes: out of quota, with no word of when it resets": "它休息 15 分钟:额度用尽,但没说何时重置", "It has failed {n} times in a row: it rests {d}, longer each time": "它已连续失败 {n} 次:休息 {d},每次更久", "It rests {d}, longer if it fails again": "它休息 {d},再失败就更久", + "It doesn't rest: its provider is set to ask it again after an error like this": "它不休息:它的提供方设为遇到这类错误后照常再问它", "It rests {d}": "它休息 {d}", "It cools down {d}: the vendor didn't say for how long": "它冷却 {d}:厂商没说要多久", "It was rate limited again as soon as it was back ({n} times in a row): it rests {d}, longer each time until it answers": "恢复后立即再次被限流(连续 {n} 次):休息 {d},逐次延长,直到正常应答", @@ -7790,6 +7791,7 @@ const I18N = { "It rests 15 minutes: out of quota, with no word of when it resets": "它休息 15 分鐘:額度用盡,但沒說何時重置", "It has failed {n} times in a row: it rests {d}, longer each time": "它已連續失敗 {n} 次:休息 {d},每次更久", "It rests {d}, longer if it fails again": "它休息 {d},再失敗就更久", + "It doesn't rest: its provider is set to ask it again after an error like this": "它不休息:它的提供方設為遇到這類錯誤後照常再問它", "It rests {d}": "它休息 {d}", "It cools down {d}: the vendor didn't say for how long": "它冷卻 {d}:廠商沒說要多久", "It was rate limited again as soon as it was back ({n} times in a row): it rests {d}, longer each time until it answers": "恢復後立即再次被限流(連續 {n} 次):休息 {d},逐次延長,直到正常應答", @@ -11987,6 +11989,7 @@ const I18N = { "It rests 15 minutes: out of quota, with no word of when it resets": "15 分休止します:クォータ切れで、リセット時刻の知らせがありません", "It has failed {n} times in a row: it rests {d}, longer each time": "{n} 回連続で失敗しました:{d} 休止し、毎回長くなります", "It rests {d}, longer if it fails again": "{d} 休止します。再び失敗するとさらに長くなります", + "It doesn't rest: its provider is set to ask it again after an error like this": "休止しません:このプロバイダーは、この種のエラーの後も次にそのまま尋ねる設定です", "It rests {d}": "{d} 休止します", "It cools down {d}: the vendor didn't say for how long": "{d} クールダウンします:ベンダーが期間を示しませんでした", "It was rate limited again as soon as it was back ({n} times in a row): it rests {d}, longer each time until it answers": "復帰直後に再びレート制限されました({n} 回連続):{d} 休止し、応答するまで毎回長くなります", @@ -16191,6 +16194,7 @@ const I18N = { "It rests 15 minutes: out of quota, with no word of when it resets": "Es pausiert 15 Minuten: Kontingent aufgebraucht, ohne Angabe zum Zurücksetzen", "It has failed {n} times in a row: it rests {d}, longer each time": "Es ist {n}-mal in Folge fehlgeschlagen: Es pausiert {d}, jedes Mal länger", "It rests {d}, longer if it fails again": "Es pausiert {d}, länger bei erneutem Fehler", + "It doesn't rest: its provider is set to ask it again after an error like this": "Es pausiert nicht: Sein Anbieter ist so eingestellt, dass es nach einem solchen Fehler wieder gefragt wird", "It rests {d}": "Es pausiert {d}", "It cools down {d}: the vendor didn't say for how long": "Es kühlt {d} ab: Der Anbieter hat keine Dauer genannt", "It was rate limited again as soon as it was back ({n} times in a row): it rests {d}, longer each time until it answers": "Es erhielt gleich nach der Rückkehr erneut ein Rate-Limit ({n}-mal in Folge): Es pausiert {d}, jedes Mal länger, bis es antwortet", diff --git a/internal/gui/assets/routing.js b/internal/gui/assets/routing.js index 7efde5434..8d935f7fe 100644 --- a/internal/gui/assets/routing.js +++ b/internal/gui/assets/routing.js @@ -466,6 +466,9 @@ case "resets": return t("It rests until {time}, when the vendor says the limit resets", { time }); case "quota": return t("It rests 15 minutes: out of quota, with no word of when it resets"); case "verify": return t("The vendor wants the account verified first: it rests half an hour, or until you say it's verified"); + // its provider set never to rest after an unknown failure + // (`magpie provider rest-cap off`): asked again next time + case "off": return t("It doesn't rest: its provider is set to ask it again after an error like this"); // the vendor restricted the account itself (#1849): only its lifting, // which the vendor's appeal asks for, brings it back case "restricted": return t("The vendor restricted the account: it rests {d}, as only the vendor lifting the restriction brings it back. Appeal with the vendor; once it's lifted, try it again here", { d }); diff --git a/internal/gui/tests/routing-rest-off.test.cjs b/internal/gui/tests/routing-rest-off.test.cjs new file mode 100644 index 000000000..0c9bd25e4 --- /dev/null +++ b/internal/gui/tests/routing-rest-off.test.cjs @@ -0,0 +1,102 @@ +// Run with Node's test runner and Playwright on the module path; see README.md. +// A provider set never to rest after an unknown failure (`magpie provider +// rest-cap off`; Kismet Alan on Discord: a relay's 5xx comes now and +// then and the next request goes through): the Routing page tells its 502 +// as not resting, the request gone on to the next, and its row isn't shown +// resting — in every language the page speaks. +const assert = require("node:assert/strict"); +const fs = require("node:fs/promises"); +const path = require("node:path"); +const { test } = require("node:test"); +const { chromium, webkit } = require("playwright"); + +const assets = path.resolve(__dirname, "../assets"); +const now = new Date(); +const day = [now.getFullYear(), now.getMonth() + 1, now.getDate()].map((n) => String(n).padStart(2, "0")).join("-"); +const start = new Date(now.getTime() - 60e3).toISOString(); +const a = { id: "relay#a", provider: "relay", name: "Relay", kind: "key", who: "key a", model: "glm-5" }; +const b = { id: "relay#b", provider: "relay", name: "Relay", kind: "key", who: "key b", model: "glm-5" }; +const rest = { why: "other", by: "off", status: 502, until: new Date(now.getTime() - 59e3).toISOString() }; +const routes = [{ + id: 100, seq: 100, time: start, agent: "codex", model: "relay/glm-5", provider: "relay", + order: [a, b], + tries: [ + { id: a.id, model: a.model, start, done: true, status: 502, ms: 900, fail: "other", rest, error: "Relay: upstream connect error" }, + { id: b.id, model: b.model, start, done: true, status: 200, ms: 1200 }, + ], + done: true, status: 200, ms: 2100, +}]; + +function serve(lang, lifted) { + const state = { agents: [{ id: "codex", name: "Codex", path: "/test/config.toml", fields: [] }], profiles: [], settings: { lang, theme: "light" } }; + return async (route) => { + const url = new URL(route.request().url()); + const json = (data) => route.fulfill({ json: data }); + if (url.pathname === "/boot.js") return route.fulfill({ contentType: "text/javascript", body: `window.bootPrefs = {lang:"${lang}",theme:"light",web:true};` }); + if (url.pathname === "/wails/runtime.js") return route.fulfill({ contentType: "text/javascript", body: "export const Window = {};" }); + if (url.pathname === "/api/state") return json(state); + if (url.pathname === "/api/plugins") return json({ plugins: [] }); + if (url.pathname === "/api/gateway/trace") { + if (url.searchParams.get("wait")) await new Promise((r) => setTimeout(r, 20e3)); + return json({ mine: true, now: now.toISOString(), seq: 1, totals: { requests: 0, rerouted: 0, errors: 0 }, routes: [] }); + } + if (url.pathname === "/api/gateway/history") { + const d = url.searchParams.get("day"); + return json({ cut: false, days: [{ day, requests: routes.length }], routes: d ? routes : [] }); + } + if (url.pathname === "/api/gateway/unrest") { + lifted.push(JSON.parse(route.request().postData() || "{}")); + return json({ lifted: true }); + } + if (url.pathname === "/api/groups") return json({ groups: [] }); + if (url.pathname === "/api/providers") return json({ providers: [], excluded: [], gateway: { running: true, window: true } }); + if (url.pathname.startsWith("/api/")) return json({}); + const file = path.join(assets, url.pathname === "/" ? "index.html" : url.pathname); + const contentType = { ".html": "text/html", ".js": "text/javascript", ".css": "text/css", ".svg": "image/svg+xml", ".png": "image/png" }[path.extname(file)]; + await route.fulfill({ body: await fs.readFile(file), contentType }); + }; +} + +const want = { + en: "It doesn't rest: its provider is set to ask it again after an error like this", + zh: "它不休息:它的提供方设为遇到这类错误后照常再问它", + "zh-TW": "它不休息:它的提供方設為遇到這類錯誤後照常再問它", + ja: "休止しません:このプロバイダーは、この種のエラーの後も次にそのまま尋ねる設定です", + de: "Es pausiert nicht: Sein Anbieter ist so eingestellt, dass es nach einem solchen Fehler wieder gefragt wird", +}; + +for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) { + for (const lang of Object.keys(want)) { + for (const width of [1100, 420]) { + test(`${engine} ${lang} ${width}px: a key set never to rest after an unknown failure is told as not resting`, async (t) => { + const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" })); + const context = await browser.newContext({ viewport: { width, height: 900 }, reducedMotion: "reduce" }); + const page = await context.newPage(); + page.setDefaultTimeout(5000); + const errors = []; + page.on("pageerror", (e) => errors.push(e.message)); + await page.route("**/*", serve(lang, [])); + t.after(async () => { + if (process.env.ARTIFACT_DIR) { + await fs.mkdir(process.env.ARTIFACT_DIR, { recursive: true }); + await page.screenshot({ path: path.join(process.env.ARTIFACT_DIR, `${engine}-${lang}-${width}-rest-off.png`), fullPage: true }); + } + await browser.close(); + }); + await page.goto("http://magpie.test/?view=routing"); + await page.locator(".rt-days .rt-day").nth(1).click(); + await page.locator(".rt-req").first().waitFor(); + await page.locator(".rt-req").first().click(); + await page.locator(".rt-steps li").first().waitFor(); + await page.waitForTimeout(300); + const steps = await page.locator(".rt-steps li").evaluateAll((ls) => ls.map((l) => l.textContent)); + assert.equal(steps.filter((s) => s.includes(want[lang])).length, 1, JSON.stringify(steps)); + if (lang !== "en") assert(!steps.some((s) => s.includes("doesn't rest")), JSON.stringify(steps)); + // nobody's row is shown resting + assert.equal(await page.locator(".rt-act .st.rest").count(), 0); + assert(await page.evaluate(() => document.documentElement.scrollWidth <= window.innerWidth + 1), "the page scrolls sideways"); + assert.deepEqual(errors, []); + }); + } + } +} diff --git a/internal/provider/concurrency.go b/internal/provider/concurrency.go index b3de1d1e2..b801ef3dc 100644 --- a/internal/provider/concurrency.go +++ b/internal/provider/concurrency.go @@ -322,8 +322,23 @@ func SetQuotaResetAt(id, at string) error { return Save(*p) } +// RestCapOff is RestCap set to off (`magpie provider rest-cap off`): +// a key or account of the provider that fails without saying why — a +// relay's or an account pool's 5xx, a dropped connection — doesn't rest at +// all, and is asked again by the next request as if it hadn't failed +// (Kismet Alan on Discord: an aggregator's unknown errors fail now and +// then, and the next request often goes through). What the vendor said +// plainly still rests it as ever: out of quota or credit, rate limited, +// its key refused (401, 403), its model not served, its window full. +const RestCapOff = -1 + +// NoFailRest says p's keys and accounts don't rest after an unknown +// failure (RestCapOff). +func (p Provider) NoFailRest() bool { return p.RestCap == RestCapOff } + // RestCapOr is the most one of p's keys or accounts sits out while it keeps -// failing: the user's RestCap, else the gateway's own def. +// failing: the user's RestCap, else the gateway's own def (RestCapOff +// included: it says nothing of a rate limit's rest). func (p Provider) RestCapOr(def time.Duration) time.Duration { if c := min(max(p.RestCap, 0), MaxQuotaRest); c > 0 { return time.Duration(c) * time.Minute @@ -333,10 +348,10 @@ func (p Provider) RestCapOr(def time.Duration) time.Duration { // SetRestCap sets the most, in minutes, the provider's keys and accounts // sit out while they keep failing or being rate limited, 0 for the -// gateway's own. +// gateway's own, RestCapOff for no rest after an unknown failure. func SetRestCap(id string, minutes int) error { - if minutes < 0 || minutes > MaxQuotaRest { - return fmt.Errorf("the longest rest is from 0 (magpie's own) to %d minutes (8 days), not %d", MaxQuotaRest, minutes) + if minutes != RestCapOff && (minutes < 0 || minutes > MaxQuotaRest) { + return fmt.Errorf("the longest rest is from 0 (magpie's own) to %d minutes (8 days), or off, not %d", MaxQuotaRest, minutes) } p, err := Find(id) if err != nil { diff --git a/internal/provider/provider.go b/internal/provider/provider.go index 0c02bd2c5..a2fe46d35 100644 --- a/internal/provider/provider.go +++ b/internal/provider/provider.go @@ -186,7 +186,8 @@ type Provider struct { // out while it keeps failing or keeps being rate limited as soon as // its rest is over (#2008); 0 is the gateway's own, 10 minutes for a // failure and 30 for a rate limit. The vendor's own "try again in" - // still stands over it. + // still stands over it. RestCapOff (-1): no rest at all after a + // failure that says nothing of why, a rate limit's as the gateway's own. RestCap int `json:"restCap,omitempty"` // PriceRate is what the provider charges against the official price @@ -1172,7 +1173,9 @@ func normalize(p Provider) Provider { p.QueueLimit, p.QueueWait = min(max(p.QueueLimit, 0), MaxQueueLimit), min(max(p.QueueWait, 0), MaxQueueWait) p.MaxRPM = min(max(p.MaxRPM, 0), MaxRPMLimit) p.QuotaRest = min(max(p.QuotaRest, 0), MaxQuotaRest) - p.RestCap = min(max(p.RestCap, 0), MaxQuotaRest) + if p.RestCap != RestCapOff { + p.RestCap = min(max(p.RestCap, 0), MaxQuotaRest) + } if _, err := ParseResetAt(p.QuotaResetAt); err != nil { p.QuotaResetAt = "" }