Every agent's model. One place. Codex on DeepSeek, Claude Code on Kimi, from the menu bar.
gateway: a safety refusal said in a stream is a refusal for a client answered whole too, and rests nobody (#3274, CartethyiaQwQ)
yetoneefb7cb11d4e9
diff --git a/docs/subsystems/gateway-routing.md b/docs/subsystems/gateway-routing.mdindex 77c891d0a..8773a1485 100644--- a/docs/subsystems/gateway-routing.md+++ b/docs/subsystems/gateway-routing.md@@ -99,7 +99,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-<name>` 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=<model>`; 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=<model> 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 <id> 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`), 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 <id> 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 <id> 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`). 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), 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. Command Code's Provider API turning a request away with nothing but a trace id (`unsaidWords`: `{"message":"invalid request error trace_id: <hex>","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. A rate limit worded with input tokens (`paceWords`) isn't one, and a plain bad request is still asked of nobody else (`TestRelayInputCapGoesToTheNextMember`). 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. 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; 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. 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`).+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 <id> 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`), 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 <id> 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 <id> 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`). 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), 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. Command Code's Provider API turning a request away with nothing but a trace id (`unsaidWords`: `{"message":"invalid request error trace_id: <hex>","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. A rate limit worded with input tokens (`paceWords`) isn't one, and a plain bad request is still asked of nobody else (`TestRelayInputCapGoesToTheNextMember`). 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. 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`). 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. 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; 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. 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`). 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, 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), 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. 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. 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`).## Constraints and failure behaviordiff --git a/internal/gateway/anthropic.go b/internal/gateway/anthropic.goindex 53a281c35..ff39514f1 100644--- a/internal/gateway/anthropic.go+++ b/internal/gateway/anthropic.go@@ -1259,7 +1259,8 @@ func decodeAnthropic(data string, emit func(Event)) error {}emit(Event{Kind: KUsage, Usage: ev.Usage.usage(), SafeguardResults: review, StopDetails: stopDetails(ev.Delta.StopDetails)})case "error":- emit(Event{Kind: KError, Text: cmp.Or(ev.Error.Message, ev.Error.Type, streamErrorText(data)), Code: refusedCode(data)})+ code, status, said := filterRefused(data)+ emit(Event{Kind: KError, Text: cmp.Or(ev.Error.Message, ev.Error.Type, streamErrorText(data)), Code: code, Status: status, Said: said})}return nil}diff --git a/internal/gateway/chat.go b/internal/gateway/chat.goindex b6b38ddb6..bdd4faf49 100644--- a/internal/gateway/chat.go+++ b/internal/gateway/chat.go@@ -1223,7 +1223,8 @@ func (d *chatDecoder) decode(data string, emit func(Event)) error {return nil}if ch.Error != nil {- emit(Event{Kind: KError, Text: cmp.Or(ch.Error.Message, streamErrorText(data)), Code: refusedCode(data)})+ code, status, said := filterRefused(data)+ emit(Event{Kind: KError, Text: cmp.Or(ch.Error.Message, streamErrorText(data)), Code: code, Status: status, Said: said})return nil}if !d.started {diff --git a/internal/gateway/fallback.go b/internal/gateway/fallback.goindex e127f3945..87bd727e8 100644--- a/internal/gateway/fallback.go+++ b/internal/gateway/fallback.go@@ -3112,6 +3112,30 @@ func policyRefusal(raw []byte) (string, bool) {// an answer.const highRiskRefusal = "The request was rejected because it was considered high risk"+// filterRefused is a stream's error event (its data) as an Event carries+// it when it is the vendor's safety filter refusing the request: its code+// (refusedCode), status refusedStatus, and an error of the request's own+// (Said) with that code. A client answered whole is then told it as a 400+// refusal, which the hold reads as one (policyRefusal) and asks the next+// account, resting nobody; without the status it was answered 502+// api_error, asked again on every account, and each one rested (#3274: a+// Codex account's response.failed cyber_policy, its error with no type).+// A code policyRefusal doesn't know as a refusal goes as content_filter,+// for the hold to know it still. Not a refusal, it is "", 0 and nil.+func filterRefused(data string) (string, int, json.RawMessage) {+ code := refusedCode(data)+ if code == "" {+ return "", 0, nil+ }+ said := code+ c, _ := json.Marshal(map[string]string{"code": code})+ if _, ok := policyRefusal(c); !ok {+ said = "content_filter"+ }+ b, _ := json.Marshal(map[string]any{"error": map[string]string{"type": "invalid_request_error", "code": said}})+ return code, refusedStatus, b+}+// refusedCode is the code of a stream's error event (its data) when it is// the vendor's safety filter refusing, for a translation of it to keep:// said in another protocol as only its message, ChatGPT's bio_policy readdiff --git a/internal/gateway/gateway.go b/internal/gateway/gateway.goindex ae256889d..f47632a91 100644--- a/internal/gateway/gateway.go+++ b/internal/gateway/gateway.go@@ -5930,12 +5930,27 @@ func (s *Server) translate(w http.ResponseWriter, r *http.Request, p provider.Prmsg := p.Name + ": " + err.Error()return writeError(w, from, 502, msg), msg}- if col.err != "" && !saidAnything(col.res.Parts) {+ // a reply the vendor refused part way is no answer either: handed+ // whole, its words so far went as a finished turn and the refusal as+ // a failure after it, which rested the account (#3274). Nothing has+ // reached the client yet, so it is told the refusal, as it would be+ // with nothing said+ if col.err != "" && (!saidAnything(col.res.Parts) || col.errSaid != nil) {said := col.errif markAntigravityRefused(w, p, request.System, said) {said += " — " + antigravityTurnedAwayHintu.ErrType = turnedAwayErrType}+ if code := gjson.GetBytes(col.errSaid, "error.code").String(); code != "" {+ e, _ := json.Marshal(map[string]string{"code": code, "message": col.err})+ if note, ok := policyRefusal(e); ok {+ // the safety filter's: said beside the error, which loses+ // its code in Anthropic's shape, for settle to ask the next+ // account and rest nobody (#3274), as keepRetry notes a+ // status refusal+ w.Header().Set(refusedHeader, note)+ }+ }// a request the vendor refused in its stream is answered as// refused, with its code (magpie-releases#18); anything else is// the vendor failingdiff --git a/internal/gateway/refusal_whole_test.go b/internal/gateway/refusal_whole_test.gonew file mode 100644index 000000000..9ef3e8530--- /dev/null+++ b/internal/gateway/refusal_whole_test.go@@ -0,0 +1,161 @@+package gateway++import (+ "io"+ "net/http"+ "net/http/httptest"+ "strings"+ "testing"+ "time"++ "github.com/yetone/magpie/internal/provider"+)++// cyberPolicyMsg is what the ChatGPT backend said refusing CartethyiaQwQ's+// Codex turn (#3274), as the reporter quoted it from magpie, without+// magpie's cut at 300 characters ("bef…").+const cyberPolicyMsg = `This content was flagged for possible cybersecurity risk. If this seems wrong, try rephrasing your request. If you're doing authorized security work that requires more cyber permissive safeguards, apply for Daybreak access via https://platform.openai.com/settings/organization/status-and-access`++// liveRests is every candidate resting now, by its rest key.+func liveRests() []string {+ restingUntil.Lock()+ defer restingUntil.Unlock()+ var out []string+ for k, u := range restingUntil.m {+ if time.Now().Before(u) {+ out = append(out, k+" by "+restingUntil.note[k].By)+ }+ }+ return out+}++// A Codex account's refusal said inside its stream — response.failed or+// the error event, with a code (cyber_policy) and no type, or after some+// of the reply — is told to a client answered whole (stream:false+// Responses, Chat and Messages, each streamed upstream) as a refusal: the+// next account is asked and nobody rests (#3274). Before, the whole path+// answered it 502 api_error: the same account was asked again, and every+// account but the last rested, so two such turns benched a pool.+func TestStreamRefusalAnsweredWholeRestsNobody(t *testing.T) {+ refusals := []struct {+ name string+ events []string+ }{+ {"response.failed", []string{+ `data: {"type":"response.created","response":{"id":"r0"}}`,+ `data: {"type":"response.failed","response":{"id":"r0","status":"failed","error":{"code":"cyber_policy","message":"` + cyberPolicyMsg + `"}}}`}},+ {"error event", []string{+ `data: {"type":"response.created","response":{"id":"r0"}}`,+ `data: {"type":"error","code":"cyber_policy","message":"` + cyberPolicyMsg + `","param":null}`}},+ {"after some text", []string{+ `data: {"type":"response.created","response":{"id":"r0"}}`,+ `data: {"type":"response.output_text.delta","delta":"Sure, "}`,+ `data: {"type":"response.failed","response":{"id":"r0","status":"failed","error":{"code":"cyber_policy","message":"` + cyberPolicyMsg + `"}}}`}},+ }+ routes := []struct{ name, path, body string }{+ {"responses", "/v1/responses", `{"model":"codex/gpt-5.5","stream":false,"input":"ping"}`},+ {"chat", "/v1/chat/completions", `{"model":"codex/gpt-5.5","messages":[{"role":"user","content":"ping"}]}`},+ {"messages", "/v1/messages", `{"model":"codex/gpt-5.5","max_tokens":64,"messages":[{"role":"user","content":"ping"}]}`},+ }+ for _, x := range refusals {+ refuse := func(w http.ResponseWriter) {+ w.Header().Set("Content-Type", "text/event-stream")+ io.WriteString(w, sse(x.events...))+ }+ for _, rt := range routes {+ ask := func(s *Server) (int, string) {+ rec := httptest.NewRecorder()+ s.Handler().ServeHTTP(rec, httptest.NewRequest("POST", rt.path, strings.NewReader(rt.body)))+ return rec.Code, rec.Body.String()+ }+ t.Run(x.name+"/"+rt.name+"/next answers", func(t *testing.T) {+ codexSignedIn(t, "[email protected]")+ var tried []string+ chatgptRefusing(t, &tried, refuse)+ s := New()+ code, body := ask(s)+ if code != 200 || !strings.Contains(body, "pong") || strings.Join(tried, ",") != "acct-1,acct-2" {+ t.Fatalf("status %d (tried %v): %s", code, tried, body)+ }+ if r := lastRoute(s); len(r.Tries) != 2 || r.Tries[0].Fail != failRefused || r.Tries[0].Rest != nil {+ t.Fatalf("tries: %+v", r.Tries)+ }+ if rs := liveRests(); len(rs) > 0 {+ t.Fatalf("set aside by a refusal: %v", rs)+ }+ })+ t.Run(x.name+"/"+rt.name+"/nobody left", func(t *testing.T) {+ codexSignedIn(t, "[email protected]", "[email protected]")+ var tried []string+ chatgptRefusing(t, &tried, refuse, "acct-2", "acct-3")+ s := New()+ code, body := ask(s)+ if code != 400 || !strings.Contains(body, "refused this request") || !strings.Contains(body, "cyber_policy") ||+ strings.Join(tried, ",") != "acct-1,acct-2,acct-3" {+ t.Fatalf("status %d (tried %v): %s", code, tried, body)+ }+ for _, try := range lastRoute(s).Tries {+ if try.Fail != failRefused || try.Rest != nil {+ t.Fatalf("tries: %+v", lastRoute(s).Tries)+ }+ }+ if rs := liveRests(); len(rs) > 0 {+ t.Fatalf("set aside by a refusal: %v", rs)+ }+ })+ }+ }+}++// restAfter, wherever it is reached, rests nobody for a 400 whose error+// object is the safety filter's (#3274's cyber_policy), counting no+// failure; read from the error's code, a 400 that only echoes the same+// words of the request in its message still rests, as a plain 400 does.+func TestRestAfterPolicyRefusal(t *testing.T) {+ for _, x := range []struct {+ name string+ body string+ rest bool+ }{+ {"cyber_policy", `{"error":{"type":"invalid_request_error","code":"cyber_policy","message":"` + cyberPolicyMsg + `","param":null}}`, false},+ {"plain", `{"error":{"message":"bad request","type":"invalid_request_error"}}`, true},+ // the user's own prompt quoted back in an unrelated 400+ {"words echoed", `{"error":{"type":"invalid_request_error","code":"string_above_max_length","message":"Invalid 'input[0].content': string too long. Got 'safety filter: cyber_policy — apply for Daybreak access …'","param":"input[0].content"}}`, true},+ {"words, no code", `{"error":{"type":"invalid_request_error","code":null,"message":"Unsupported value in 'instructions': safety filter: cyber_policy, Daybreak access"}}`, true},+ } {+ t.Run(x.name, func(t *testing.T) {+ s := &Server{}+ c := candidate{p: provider.Provider{ID: "codex", Account: &provider.Account{Agent: "codex", User: "refusal-" + strings.ReplaceAll(x.name, " ", "-") + "@x.com"}}, model: "gpt-5.5", rest: "codex#" + x.name}+ t.Cleanup(func() {+ clearRest(c.restKey())+ clearRest(c.restID())+ routed.Lock()+ delete(routed.failures, c.restKey())+ delete(routed.failures, c.restID())+ routed.Unlock()+ })+ for i := 0; i < 3; i++ {+ r := s.restAfter(c, 400, http.Header{}, []byte(x.body))+ if !x.rest {+ if r.By != "off" || r.Why != failRefused || r.Until.After(time.Now()) || resting(c) {+ t.Fatalf("refusal #%d rests by %s (%s) until %v", i+1, r.By, r.Why, r.Until)+ }+ continue+ }+ if r.By != "backoff" || time.Until(r.Until) <= 0 {+ t.Fatalf("400 #%d rests by %s until %v; want backoff", i+1, r.By, r.Until)+ }+ break+ }+ if x.rest {+ return+ }+ routed.Lock()+ n, m := routed.failures[c.restKey()], routed.failures[c.restID()]+ routed.Unlock()+ if n != 0 || m != 0 {+ t.Fatalf("refusal counted %d account and %d model failures", n, m)+ }+ })+ }+}diff --git a/internal/gateway/responses.go b/internal/gateway/responses.goindex 1dab20b84..64f586701 100644--- a/internal/gateway/responses.go+++ b/internal/gateway/responses.go@@ -1580,7 +1580,11 @@ func (d *responsesDecoder) decode(data string, emit func(Event)) error {msg = ev.Response.Error.Message}status, said := requestRefused(data)- emit(Event{Kind: KError, Text: cmp.Or(msg, streamErrorText(data)), Code: refusedCode(data), Status: status, Said: said})+ code, fs, fsaid := filterRefused(data)+ if status == 0 {+ status, said = fs, fsaid+ }+ emit(Event{Kind: KError, Text: cmp.Or(msg, streamErrorText(data)), Code: code, Status: status, Said: said})return nil}stop := "stop"@@ -1608,7 +1612,11 @@ func (d *responsesDecoder) decode(data string, emit func(Event)) error {msg = cmp.Or(ev.Error.Message, msg)}status, said := requestRefused(data)- emit(Event{Kind: KError, Text: cmp.Or(msg, streamErrorText(data)), Code: refusedCode(data), Status: status, Said: said})+ code, fs, fsaid := filterRefused(data)+ if status == 0 {+ status, said = fs, fsaid+ }+ emit(Event{Kind: KError, Text: cmp.Or(msg, streamErrorText(data)), Code: code, Status: status, Said: said})}return nil}diff --git a/internal/gateway/routing.go b/internal/gateway/routing.goindex 23cc0ce34..a1be2b41f 100644--- a/internal/gateway/routing.go+++ b/internal/gateway/routing.go@@ -820,6 +820,18 @@ func (s *Server) restAfterMarked(c candidate, status int, header http.Header, bo// as soon as the switch is offreturn Rest{Why: why, Status: status, By: "off", Until: now}}+ if status == http.StatusBadRequest {+ if _, ok := policyRefusal(body); ok {+ // the safety filter refused the request's content (#3274:+ // Codex's 400 cyber_policy), read from the vendor's error+ // object, never from words a body may echo of the request:+ // any account is refused it alike, so none is set aside and+ // the failure counts nowhere. The serve loop doesn't rest a+ // refusal it reads (failRefused); this holds for every other+ // route that rests one+ return Rest{Why: failRefused, Status: status, By: "off", Until: now}+ }+ }// read before the allowance is asked again below: out of a pool that// counts some models only, the account's others are still in theirs// (Cursor's Auto with Other Models used up)diff --git a/internal/gateway/upstream.go b/internal/gateway/upstream.goindex 90b5c25cc..29c7f9465 100644--- a/internal/gateway/upstream.go+++ b/internal/gateway/upstream.go@@ -170,7 +170,8 @@ func carriedError(data string) (ev Event, ok bool) {if t != "error" && t != "response.failed" && !carries(v.Error) && !carries(r.Error) {return Event{}, false}- return Event{Kind: KError, Text: streamErrorText(data, r.Error, v.Error), Code: refusedCode(data)}, true+ code, status, said := filterRefused(data)+ return Event{Kind: KError, Text: streamErrorText(data, r.Error, v.Error), Code: code, Status: status, Said: said}, true}// streamErrorText is what an upstream's error event says: the message of