diff --git a/docs/subsystems/gateway-routing.md b/docs/subsystems/gateway-routing.md index b7332b2c1..93a66d739 100644 --- a/docs/subsystems/gateway-routing.md +++ b/docs/subsystems/gateway-routing.md @@ -198,7 +198,7 @@ recorded as a prediction failure (`noPrediction`). - A rule's hours and days (`Rule.Time`, `provider.TimeWindow`) are read on `ruleClock` in the zone they were set in (`TimeWindow.Zone`, an IANA name; gaubeebangeel on X: magpie on a cloud server in UTC, its user in Beijing, the hours 8 off). The GUI saves the browser's zone when the hours or days are changed in the editor and leaves a rule's zone alone otherwise; the CLI (`magpie group rule add … time=09:00-18:00@Asia/Shanghai` or `tz=`) and the TUI save the one typed, or this computer's (`provider.LocalZone`: `$TZ`, `time.Local`, the `/etc/localtime` link) when it has an IANA name. A window with no zone, every one saved before zones were kept, stays on magpie's own clock. A zone magpie doesn't know is refused on save (`TimeWindow.clean`), and one in a file edited by hand makes the window never hold (`zoneOf`): the rule is as if absent, never always on and never hours off. Zones come from Go's embedded tzdata, so Windows knows them too. `/api/groups` gives magpie's clock (`clock`: its zone and offset in seconds), and when it differs from the hours' zone the Routing groups page tells the zone beside them, on the group's rules and in the editor (`zoneNote` in [`plugins/routing/client.js`](../../internal/gui/assets/plugins/routing/client.js)): the zone's name, or the server's offset for hours with none. `TestRuleTimeWindowInItsZone`, `TestRuleTimeWindowInItsZoneAtTurnStart`, `TestRuleTimeWindowUnknownZone`, `TestParseRuleTimeZone`, `TestGroupRuleTimeZoneCmd`, `routing-time-zone.test.cjs`. 3. Candidates come from `planGroup` for a group or `plan` for a provider. They are filtered by `sealedReaders` and `allowedCandidates`. An account past its share is held out of the candidates (`capHeld`): a usage cap's share, each window at its own where the account gives it one (`AccountWindowCaps`, willz on Discord: 50% of the five hours, 40% of the week) and at the account's cap otherwise, or 100% of a window for a Codex account set not to spend its credits (`provider.HoldCaps`, `WindowCaps.Of`, `CodexNoCredits`). A ChatGPT account's call on `codex-auto-review`, which OpenAI counts in no window, is held by no usage cap, only by credits it may not spend (`freeOnChatGPT`, #1593, `TestAccountCapLetsAutoReviewThrough`); a Free plan's call is capped as any other (`TestAccountCapHoldsAutoReviewOnAFreePlan`). The account is held while any window is past its own share, and `cappedError` and the trace name the fullest such window's share and cap. When every candidate is held and one held for its credits spends its resets by itself, `autoReset` spends a reset on it and it is tried (`planned.held`). A Codex account let spend its credits is never held or refused for its week, so before a try goes to one whose week its last reading says is used up and that spends a reset when its week runs out, `resetBeforeCredits` spends one first, one a week at most, in routing and in the relay (`resetBeforeCreditsOn`); a reset is free and credits cost money (tongzhenbao on X, `TestCodexResetBeforeCredits`). Otherwise a capped or barred set returns `cappedError` or `barredError`. A provider with Stop at the caps on (`CapStop`, plugins#349) answers that 429 instead of going on to its fallbacks when every primary account is held (`plan`, `TestCapStopSkipsTheFallbacks`); off, the default, the fallbacks take it as before. With every account held and no fallback left to take it, a request for a model the user put in routing groups of their own goes on to those groups, in the user's order, each as its own routing orders it (`provider.GroupsAfter`, `groupsAfter`, planned again in serve with them after the fallbacks; a group magpie found, hidden or switched off, or one with no other member, is none). The Codex app signed in to ChatGPT asks Codex's own model, never the group built around it, so its capped account answered 429 though a group had two APIs after it (adorable_piglet on Discord, v0.1.3354; `TestCappedCodexOwnModelGoesToItsGroup`). `CapStop` still answers the 429, and a request for the group itself was routed so before (`TestCappedSubscriptionGivesWayInGroup`). A careful provider (`CapCareful`, plugins#349, off by default, `cap_careful.go`) has `readCareful` read a capped account's usage again before planning when its reading is over 15s old within 5 points of a cap, or over 5m old at all, waiting at most 10s and asking a failed account again at most every 15s; `capHold` then holds an account whose usage was never read, whose last read failed or whose reading is still that old (`carefulDoubt`, `Weighed.Unread` in the trace), as one at its cap is: unknown is not spent (`TestCarefulHoldsWhatItCantTell`, `TestCarefulReadsAgainNearTheCap`, `TestCarefulEveryAccountUnread`, `TestCarefulOffByDefault`). Planning goes by the last reading, so turns sent together were each planned on the same one: an account a point under its cap took all of them and went past it by what they used between them (dyzdyz010 on Discord: capped at 90%, used to 100%). In serve's walk an account within 5 points of a usage cap (`nearCapOf`, `nearCapPoints`, `cap_near.go`) takes one turn at a time (`Server.nearCap`, its turn held until the try ends): a turn that finds it busy goes to the next candidate first, the account moved behind them once (`nearBehind`); the last candidate waits. Once its turn comes `capHeld` judges it again, by what the reply before it left (Codex's `codex.rate_limits`, Claude's `rate_limit_event`), or, when that reply said nothing of the account's usage, by a reading taken again then (`nearCapAgain`, at most `carefulWait`); held, it is passed over, and when it was the last the agent gets `cappedError`'s 429. The cap is passed by one turn at most, as a gateway key's limit is, Claude Code accounts as Codex's (`TestNearCapTakesOneTurnAtATime`, `TestNearCapWaitsThenHolds`, `TestNearCapReadsAgainAfterASilentReply`, `TestFarFromCapTurnsGoTogether`, `TestNearCapClaudeAccountsTakeOneTurnEach`). A conversation kept on its account by Stays: Strict goes on past the cap as `strictKeep` keeps it, and takes no turn there (`TestStrictAffinityGoesPastTheCap`). Then `affine` moves the conversation's last answerer first, unless it is resting or nearly used up. An `X-Magpie-Account` header (`AccountHeader`) pins the request to one account: only that account is tried, and when it can't answer the caller is told why. A header value is ASCII on the wire and fetch refuses one that isn't, so an account whose user isn't ASCII (北冥, plugins#615) is named percent-encoded; `pinnedName` decodes it, the value as written matches too, and the trace and the call's record name it decoded (`TestAccountPinnedPercentEncoded`). 4. The candidate loop calls `attempt` on each candidate in turn, through a `holdWriter`. The writer holds the reply until it is clearly passing. A candidate that fails before anything is sent rests (`failure`): out of credit for 30 minutes (a key longer each time it is refused so again once its rest has ended: 30 minutes, 2 hours, 8 hours, a day, 3 days, then a week (`creditLadder`, `creditBackoff`), the same rung while a rest still runs, a new run after "Try now" (`Unrest`) or an answer; each such rest, its rung and when it ends, is kept in `rests.json` beside `providers.json` (written through a renamed temp file whenever one is set or dropped, `saveRests`) and read once as the gateway starts to listen (`loadRests`), so a restart rests out what is left and climbs on from the rung: an ended rest keeps its rung there as in memory, unless it ended over `restsKeep` (35 days) ago, a key no longer in `providers.json` is let go, and a file or `providers.json` that can't be read or parsed adds no rest (PaulT on Discord, `TestKeyCreditRestOutlivesRestart`, `TestKeyCreditRestFileCorrupt`); a refusal that names its reset rests till then, and one that says it can pass soon (a `Retry-After`, OpenRouter's in-flight budget or "can only afford", a "try again in 30 seconds", `creditSoon`) rests 30 minutes or less and doesn't climb; a remote magpie's model rests 30 minutes as before: PaulT on Discord, `TestKeyOutOfCreditRestsLongerEachTime`; a ChatGPT account until the reset its refusal names, else until its full window renews, else 5 hours, `chatgptCreditRest`, and a reading finding its window renewed has it back: PaulT on Discord, `TestChatGPTOutOfCreditsRestsLong`), out of quota until reset, rate limited until retry-after, otherwise a minute and longer on repeats: doubled each time, up to `longestRetry` (10 minutes) for a failure and `longestRateRest` (30 minutes) for a rate limit back as soon as its rest is over, or up to the provider's own `restCap` in minutes (`Provider.RestCapOr`, at most `MaxQuotaRest`; `magpie provider rest-cap 4h`, #2008: a free key down for hours was asked every 10 minutes). A time the vendor names stands over it as before (`TestOwnRestCap`). An error `failure` reads as out of credit is `retryable` at any 4xx, so the next account or member is asked and this one rests as credit; before, a 400 or 422 counted only by `quotaWords`, and SuperMagic's 400 「您的可用积分已不足…通过「充值」通道补充积分」 went to the agent with another account of 6,467 points unasked, the empty one never rested (#4095, mycf_711; `TestCredit400MovesToTheNextAccount`). A shape refusal that also says so (`creditWords` in `shapeRefused`) is the credit it says. The failure count is kept per key or account (`restKey`), and any of its models' answers clears it (`served`). Each model's own count (`restID`) is kept beside it and cleared only by that model's answer (`servedCandidate`): once it is past the account's, a sibling model answered since it last did, so the failure is the model's and it climbs its own ladder and rests alone, its siblings still served (#2241, weizsw: an Antigravity seat's gemini-3.5-flash-lite rested a minute 41 times of 43 while gemini-3.8-flash kept answering; `TestModelLadderClimbsPastSiblingAnswers`). Every model failing with no answer between still climbs the account's ladder and rests the account, and a candidate naming no model has the account's count alone. `rest-cap off` (`provider.RestCapOff`, `restCap: -1`) is for a relay or account pool whose unknown errors come now and then and pass by the next request (Kismet Alan on Discord): a failure that says nothing of why (`failOther`: a 5xx, a dropped connection) then rests nobody and isn't counted, its trace rest `by: "off"` with no time left. A 401 or 403, a model not served, an account's window full, a rate limit (magpie's own 30-minute cap), quota, credit and a restriction still rest it as before (`TestRestCapOff`). A provider the user added can be set never to rest for a limit instead (`provider.LimitRestOff`, `limitRestOff` in providers.json; the editor's Advanced fold, "Set it aside when out of quota or rate limited", ticked by default): a refusal `restAfterMarked` reads as out of quota, out of credit or rate limited, and any 429, then rests nothing, isn't counted or sunk, and is `by: "off"`; `restDrawer` rests no image model of it. The next request is sent to it as usual. It is for a relay whose limits pass in a moment (zoecats on Discord: a local aggregator said "quota exhausted" while it switched upstreams, and magpie answered itself for 30 minutes; `TestLimitRestOffKeepsAsking`, `TestLimitRestOffRestsNothingForALimit`). A 401, a model not served and a plain failure still rest it. The shortest cap otherwise is a minute, the first rest; `rest-cap 30s` is turned away and names `off`. A 400, 403, 404 or 422 that says the model isn't served (`unservedWords`) and says nothing of quota, credit or a rate limit rests only that key's or account's model (`modelRefused`, keyed by `restID`, its backoff counted apart): its other models are still served first in order (#1235, SenseNova's 403 "model is not available in the current token plan"). A Google account's Code Assist (the Antigravity and Gemini CLI built-ins) answering 404 `NOT_FOUND` ("Requested entity was not found.") rests its model the same way, as its endpoint is the same for every model (`codeAssistModelMissing`; Packing1 on Discord: Argon, listed for a Google AI Pro account, answered 404 and rested the whole account; `TestCodeAssistMissingModelRestsTheModel`). A refusal for want of quota, credit or rate, for an account its vendor restricted, or for a verify it asks of its account there, from another computer's magpie (a Remote magpie provider, LAN share) rests only the model it was about (`remoteModelRest`, keyed by `restID`, in `restAfterMarked` and `rateRest`): that magpie serves each of its models from its own providers and rests them itself, so one out of quota there says nothing of the others (bigsteven on Discord: a 429 for one model rested every model on the remote for the 3 hours it named, so a group never moved on to the remote's other models; `TestRemoteMagpieQuotaRestsTheModel`, `TestRemoteMagpieRestrictedRestsTheModel`). Such a rest out of quota or credit (`Rest.there`) still puts the model behind the others, but is never given again without asking (`quotaHeld` passes it by): that magpie holds its own rests and answers from them at once, and what it serves under a name may have changed there since (zaidu259434 on X: a routing group there moved off a spent Open Design, and this magpie gave Open Design's 402 again until the time it named, never asking; `TestRemoteMagpieQuotaIsAskedNotReplayed`, `TestHandAddedMagpieQuotaIsAskedNotReplayed`). Another magpie added by hand, as an OpenAI-compatible provider of the user's own name rather than the preset, is read as one by its reply: a magpie names the provider that answered or held it (`X-Magpie-Provider`, `providerHeader`; `noteMember`, also on a `quotaHeld` or `verifyHeld` answer), as no vendor does, and `keepRetry` notes it as `answeredThereHeader`, since this magpie writes its own provider into the same header of its reply and the note is kept from the client (lagrangepoint1813 on Discord: "Remote Magpie: Claude Code: You've hit your session limit" answered every model of it, from `quotaHeld`, for the five hours it named; `TestAnotherMagpieAddedByHandRestsTheModel`, asked there and held there). Its key refused, the computer unreachable, or the key's own limit there (`keyLimited`'s 429, which carries `X-Magpie-Limit-Reset`, `remoteKeyLimitHeader`), still rests it whole: #2077's reporter had a Claude Code session limit on the other magpie refuse its Qoder models here (`TestRemoteMagpieRestsTheModel`, two gateways over HTTP; `TestRemoteMagpieKeyLimitRestsTheKey`). The held try keeps that marker only as a note of magpie's own (`keepRetry` sets `keyLimitThereHeader`, which `holdWriter` never passes on), so the rest is whole however the 429 came, and the marker never reaches the agent or a magpie this one answers, which would read it as this magpie's own key limit (#2791, ggbdpq; `TestRemoteMagpieKeyLimitRestsTheRemote`, `TestRemoteMagpieKeyLimitMarkerStaysHere`). A 400, 404, 410 or 422 that says the model is retired (`retiredWords`: OpenCode Zen's 410 `ModelDeprecated` "Model exo-free has been deprecated.", whose own model list still names it; MOMO on Discord) rests only that model the same way, is retryable so a group's next member or another provider of it is asked, and is remembered (`provider.Retire`, `retired.json` beside `providers.json`): the model leaves that provider's entries in the catalog (`buildEntries`), so /v1/models, every agent's model list and the found groups go without it, until a request on it is answered again (`Unretire` in `servedCandidate`) or a week has passed. A refresh of the vendor's list doesn't bring it back early, since that list is where it still is. A `provider/model` request for it is still sent. A 400 or 422 that says this upstream's API can't take the request's shape (`shapeWords`: xAI's 422 "unknown item type" (#350), OpenAI's "Unknown parameter", and a limit of a model's own on tool schemas, OpenCode Go's 400 "JSON schema exceeds the maximum nesting depth of 10 levels" on muse-spark-1.3-contributor, #1870), or that it is served on another API than the one asked (`wrongEndpoint`, once the member has tried every API it has a URL for: #2670, a relay with a Chat URL alone refusing tools with reasoning and `none` too), rests nobody: the next candidate is asked once (`shapeRefused`, `failShape`), and the last one's error reaches the agent. A request missing what every API requires ("field required") isn't one, nor is a 200 that mentions it. A model asking for an earlier reply's reasoning the history doesn't have (`reasoningBackRefused` in `thinking_back.go`: Command Code's Beam answering "Missing required parameter: 'messages[1].reasoning_content'" to a second turn, DeepSeek's and Kimi's words for their tool turns) is one too, after any refill `refuseThinkingBack` makes: the request is whole, and another member's model may not ask for it (EDwinpzy on Discord, `TestGroupFailsOverAMissingReasoning`); a missing `messages` or `model` still stops (`TestMissingReasoningIsNotABadRequest`). Command Code's Provider API turning a request away with nothing but a trace id (`unsaidWords`: `{"message":"invalid request error trace_id: ","type":"invalid_request_error"}`, a 400, or a 422 before) is handled the same way: it turns away a request whose history and asked-for output together are over a limit below the model's listed context (the reporter's A/B: one ~748K-token agent conversation answered 200 with `max_completion_tokens` 64000 and this 400 with 384000, the model's listed max output), which another member's model may take, and the key is fine (#2313, `TestGroupFailsOverCommandCodesBare400`). Its overflow, which names the model's context length before the trace id, and an error that names a `param`, aren't one. A relay's own cap on one request's input that says so (`tooLongRe`: B.ai's 400 "Input token exceed the limit", on a 380K request under the model's 1M window; #2445, worksyang) is taken as an overflow (`overflowed`), which no word list of `retryable` matched: a group's next member that may hold the request is asked (`withRoom`, `failOverflow`), nobody rests, another account of the same model isn't asked, and with no member left the agent is told the conversation is too long, so it compacts. The conversation remembers the refusal (`noteOverflow` in [`affinity.go`](../../internal/gateway/affinity.go), by its stick key and the member's provider and model, with the request's size): its next request at least as large asks that member after the others (`behindOverflow`, after `roomy`, so after a rule that named it), behind and not out, until the member answers one (`forgetOverflow`) or the conversation shrinks below the refused size. Another conversation, and a 413 byte cap, are not affected (#3453, `TestOverflowRefusedOnceIsAskedLast`). A rate limit worded with input tokens (`paceWords`) isn't one, and a plain bad request is still asked of nobody else (`TestRelayInputCapGoesToTheNextMember`). Chinese that names the input rather than the context is one too (`tooLongRe`'s third line: a group member's 400 「内容太长了,请精简输入或开启新对话」, z.ai's 「Prompt 超长」, iFlytek Spark's 「…字数太多,需要精简输入」, 「输入长度超过限制」); before, it was a plain failure that rested the member and asked no other (#4420, MYCF711; `TestChineseInputTooLongGoesToTheNextMember`). Each names what was sent beside its length, so a field's or the reply's length isn't one, and Chinese pace words (速率, 频繁, 并发, 每分钟…, in `paceWords`) beside them make it a rate limit, not a size (`TestChineseNotTooLong`). A 400 or 422 whose message speaks only of length, without naming what is long (`lengthWords` in `fallback.go`: 太长, 过长, 精简, 开启新对话, "too long", "too large", "shorten"), with no pace word and no part of the request named (`partWords`: a picture, a file, the reply, a field), is the request too long for that member once the request is past half its window (`saysLength`, `lengthMargin` 0.5 in `tooLongUnsaid`), not the 1.2 margin a refusal that says nothing needs: a vendor whose own ceiling is under the window it declares answered 「内容太长了…」 at ~730K of a declared 1M (#4420, MYCF711). It then goes as an unsaid overflow goes: to a member with room, nobody resting, else to the agent as "prompt is too long" (`TestLengthWordsPastHalfTheWindowGoToTheNextMember`). A refusal that says nothing of length is read as an overflow only from the vendors seen to answer one so, by the plugin that serves them (`unsaidStatus` in `fallback.go`: Devin's 5xx, Qoder's, Qoder CN's, WorkBuddy's and WorkBuddy AI's 400/413/422, Factory's 413), once the request is 1.2 times past the window (`unsaidMargin`), the window no less than the most the model has answered here or its list's `max_context_window`; any other provider's failure, a custom relay's, OpenAI's or Anthropic's, reaches the agent with its own status and words, as does a transport failure from any vendor (#5486, NEKO-CwC; `TestRelayFailureKeepsItsOwnWords`, `TestUnsaidVendorsStillOverflow`, `TestTransportFailureIsNotTooLong`). Under half the window the same words are left as the vendor's error. A subscription account that fails any other way with a window full, by magpie's latest reading of its windows, rests until that window renews; when every full window that counts the model counts some models only (`Allowance.Pooled`), only that model rests (`restID`), and its siblings in their own windows still answer (plugins#817: ZCode's GLM-5.3 gift bucket spent left GLM-5.3-Flash's; `TestScopedWindowFullRestsTheModelOnly`). A 401 or 403 is the exception: one that names a quota is out of quota already (`usedUpWords`), and one that doesn't is about the key or the request, so it rests on the backoff ladder whatever the reading says (plugins#243, zygs1083-dotcom: a Factory account read at 98% sat out its week over one plain 403; `TestPlain403DoesNotRestUntilTheWindow`). A plain 403 (`plainForbidden`: no quota, credit, rate, verification, restriction or model not served) from a second key or account of the same provider, model and reasoning in one request is the request refused, not each account: neither rests, the first one's rest and counted failure are taken back (`forbiddenAlike`, `unforbid`), and the provider's other mates are asked last (`matesLast`). Before, that one request walked every account of the provider into backoff (`TestPlain403OnTwoMatesRestsNeither`). One account's plain 403 alone still rests it. A 500, 502 or 503 that says nothing of why (`plainUnavailable`: no quota, credit, rate, overload, proxy down, ChatGPT reset or protection refusal, and some words) is read the same way when a second account of the same provider, model and reasoning gives it in the same words and status, ids left out (`refusalWords`), and the provider answered another request within `answeringLately` (5 minutes, `answeredLately`, noted in `servedCandidate`): neither rests, and the last one left isn't asked again after a moment (`sameRefusal`). Before, one agent's request an upstream always refused (mycf_711 on Discord: 127 of a provider's 128 503s were "AIError AI服务异常", for an empty tool schema) walked every account into backoff and the other agents found them all resting. One account's 503 alone, 503s in other words, and alike 503s from a provider that answered nothing lately (an outage) still rest as before, so an outage is backed off once 5 minutes have passed since its last answer (`TestPlain5xxOnTwoMatesRestsNeither`). Both quota rests and window rests are held to `longestQuota` (8 days), so a reset time read wrong (a year off) doesn't bench the account for that long. The next candidate is then tried. A failed provider waits `fallbackCooldown` (1 minute) at the back. An overload is no failure of the account's (`vendorOverloaded`: a 529, the ChatGPT backend's `server_is_overloaded` and Anthropic's `overloaded_error` among them, or a 5xx whose words say overloaded, as Gemini's 503 does): its model rests on that account `overloadRest` (30 seconds), or as long as a Retry-After asks up to `overloadRestMost` (a minute), every time alike, and no failure is counted on the backoff ladder (celestial_eagle_99230 on Discord: eight Codex accounts each rested up to the 10-minute cap for ChatGPT's overload, "failed 5 times in a row", leaving nothing to answer). A WorkBuddy account the vendor restricted (#1849: 403 `{"code":11140,"msg":"request illegal","displayMsg":{"en":"Your account has been restricted due to unusual activity",…}}`) rests `restrictedRest` (2 hours) as `restricted` (`failRestricted`), not the minutes of an unknown failure: only WorkBuddy lifting the restriction, after the user's appeal, brings it back. Both shapes are known: the built-in's `wbExplain` and the plugin's `explained()` (0.1.17, the mover's `min`) end the error with `provider.WBRestrictedHint` (`restrictedSaid`), and the vendor's own body, its code 11140 or its words (`provider.WBRestricted`), counts only from a WorkBuddy candidate (`restrictedRefused`, `isWorkBuddy`), as another vendor's 11140 is its own. Bare "request illegal" isn't matched. A vendor's risk control reads the request as well as the account, so a restricted account (`failRestricted`, ZCode's 3012 too) walls its provider off for the rest of the request (`riskRefused`, `elsewhere`; `busyNow` and `roomy`'s left-out list too): none of the provider's other accounts is sent it, a group's other provider is asked, and with none left the agent is told and the account rests, the last one left too. Before, one request was sent on from account to account and each was restricted in turn (_teamtaylor_ on Discord; `TestRiskRefusalNotSentToTheProvidersOtherAccounts`, `TestRiskRefusalAloneIsToldAndRests`). The next request still goes to the provider's next account. A remote magpie's restriction walls off nothing (`remoteModelRest`). WorkBuddy's 11128 channel refusal stays `promptRefused` and rests nobody. The Routing page names it "account restricted by the vendor", says the appeal is the way back, and gives the account's row a button that lifts the rest (`/api/gateway/unrest`) once the vendor has. Every other rest a key or account takes (quota, rate limit, retry-after, a failure's backoff) can be lifted by hand the same way (#1869): "Try now" on its row on the Routing page and beside its rest note in the provider's key list. It ends the rest, and with Sink on puts the key back from the back of the order; the backoff count stays, and a refusal after it rests the key again the usual way. Every lift before its time (Try now, `UnrestAll` for a replaced key, `renewed` for windows that renewed) is noted by its rest key (`restingUntil.lifted`) and handed to the Routing page in the trace (`TraceState.Lifted`, `lifted` in `/api/gateway/trace`), and a lift wakes a page waiting on the trace though no route changed (`trace.lifted`). The page stops showing a rest or a sink found before its lift, wherever the lift was asked for (zoecats on Discord: Try now in the provider's editor left Routing at 429 until a restart; `TestTryNowToldToTheRoutingPage`, `routing-lifted-elsewhere.test.cjs`). With another magpie serving the gateway, Try now lifts nothing (#3555). The vendor's safety filter refusing a reply rests nobody, whether it refuses the turn before any of the reply is said or once some of it has been said (`refused`, `refusedAfter`). So does one said in a stream a client is answered whole from (a Codex account is streamed upstream for a `stream:false` Responses, Chat or Messages request): each decoder gives the refusal's error event status 400 and its code (`filterRefused`), a whole reply it cut is answered the refusal rather than its words so far, and Anthropic's error shape, which has no code, carries it in `refusedHeader`; before, it was answered 502 `api_error`, asked again, and each account rested (#3274). `restAfterMarked` itself rests nobody, and counts no failure, for a 400 whose error object `policyRefusal` reads as a refusal, by its code, never by words a body may echo of the request. A refusal after the reasoning went through as it came (a vendor whose reasoning is never held, a trusted DeepSeek member, a hold that timed out) but before a word of the answer or a call is handed over (`refusalHandover`, `refusal_handover.go`): when the agent streams Anthropic Messages, Chat Completions or Responses, another candidate is left and `refusalAsksAgain` allows one more (`handsOver`), what passes is read event by event (`passOver`); the refusal's event and everything after it are not sent, an Anthropic block still open gets its `content_block_stop`, the try fails as a refusal with nothing said (`failRefused`, nobody rests, `matesFirst`), and the next try writes through `spliceAfter`, so its stream is the same reply: Anthropic's `message_start` is dropped and its block indexes go after those sent; Responses' `response.created`/`in_progress`/`queued` are dropped, `output_index` goes after the items sent and `sequence_number` goes on from the last one sent; Chat chunks go as they come. Once text or a call has gone, a refusal is the agent's as before (`refusalAfter`). Without another candidate nothing changes. A Gemini stream is not handed over, the reasoning item of a Responses stream handed over gets no `output_item.done`, and the next reply's `response.completed` lists only its own output (#4604). Zhipu's `finish_reason` `"sensitive"` and error 1301 (敏感), DashScope's `data_inspection_failed` and Volcengine Ark's `*SensitiveContentDetected` are refusals (`filterReasons`, `sensitiveCode`). Its note on the try (and in the error the agent gets when nobody is left) is the vendor's reason, with Anthropic's `stop_details` category and explanation when it gave them (`refusedDetail`, #1768: "safety filter: refusal (category cyber)"); none is made up when it gave none. `stop_details` is carried through the IR (`Event.StopDetails`), so a Claude subscription run through the claude CLI and a translated Anthropic route keep it for an Anthropic client too. How many more candidates a refusal before any of the reply is asked of is Settings' `RefusalRetries` (`refusalAsksAgain`, counted per request in the candidate loop; a group's other members count too): unset, every one left (#248); 0, none (#1925, DD on Discord). A Claude subscription account's refusal of a conversation of `retellMost` (100K) tokens or more leaves the subscription's other accounts out (`tooBigToRetell`, `otherThanClaudeAccounts`): each would be a new Claude Code told the whole conversation, all of it written to that account's cache again, for a refusal about the content it most likely gives too (Aisiverto on X: a 900K conversation refused and told again cost a Pro account most of its 5 hours). The size is the larger of what the account counted and `estimate`; other members are still asked, and a smaller conversation still goes to the next account (`TestClaudeSubscriptionBigRefusalNotToldAgain`, `TestClaudeSubscriptionRefusalMovesToNextAccount`). When nobody is left, an agent on Anthropic's Messages API gets the held refusal itself, the vendor's 200 with `stop_reason` `refusal` and its `stop_details`, streamed or whole (`holdWriter.handBack`), since that is what Claude Code switches to its fallback model on; a 400 is only an API error to it. Codex and Chat clients still get `failTo`'s 400 (`refusedStatus`), which they don't ask again for. `TestRefusalRetries*` in [`refusal_retries_test.go`](../../internal/gateway/refusal_retries_test.go) cover keys, a group and the Claude subscription. The ChatGPT backend's 502 "response protection is unavailable" is about the request's content, not the account: the same history fails the same on each of its accounts and models. It rests nobody, isn't tried again after a moment, and isn't asked of the provider's other accounts or models; another provider left in a group is asked once (`protectionRefused`, `elsewhere`). One cause is known (#1270): a history that replays the backend's own `web_search_call` in a request that doesn't declare the `web_search` tool is refused so, whatever the account, model or turn (a plain turn, a thread's description, a compaction, Codex's own text compaction for a custom provider with `tools: []`). Every request to the ChatGPT backend with such a history therefore declares cached-only search (`{"type":"web_search","external_web_access":false}`, `provider.DeclareSearch`): an account's in `codexBody`, Codex's own sign-in relayed in `codexUpstreamOn`. It goes in the tools, or for Responses Lite (its header, `reasoning.context` `all_turns`, or an `additional_tools` item already there), which refuses a top-level `web_search`, in the `additional_tools` item. A request that offered no tools gets `tool_choice` `none` so the model can't search; one with a forced choice keeps it. A history without a search, or a request that declares search already, is relayed unchanged; Codex's own `web.run` (a function in the `web` namespace, which Codex offers in place of the hosted tool on a Responses Lite model or with its standalone web search on, and runs through `/alpha/search`) counts as declaring it, since the backend refuses a request carrying both `web.run` and the hosted `web_search` (Savin on Discord, Codex 0.163.0-alpha; `TestSearchedConversationUnderWebRun`). siwc, API-key requests to openai.com and the legacy `/responses/compact` are left as they were. The ChatGPT backend also turns a whole request away when one tool name in it, a call's in the input or a tool's in `tools`, is outside `^[a-zA-Z0-9_.-]+\z` (400 "Invalid 'input[83].name': string does not match pattern"; wing3556 on Discord, on a compaction): a call another provider's model wrote with a space, a colon or non-ASCII in its name, kept in the history beside its "no such tool", failed every later turn on Codex. Every request to it sends each such name as `provider.CodexToolName` makes it (each refused byte `_`, cut to 55, `_` and 8 hex of its sha256, the same on every request), a valid one unchanged and a body with none byte for byte (`CodexToolNames`): an account's in `codexBody`, Codex's own sign-in's in `codexUpstreamOn` (`/responses/compact` too). A tool the agent declared under such a name is called back by its own: a translated reply through `decoderFor` (`codexNamesBack`), a relayed Responses reply through `nsTidy.back` (`codexRenamedIn`; `TestCodexToolNamesTheBackendTakes`). Namespaces, the OpenAI API, Azure and Copilot are not covered (#4875). Command Code turning a model away for its Zero Data Retention setting (its plugin's switch, 0.1.14, which sends `x-cmd-zdr: 1`; magpie-community/plugins#246) is a refusal of that request's setting, not of the model or the account: the Provider API's 422 with `"code":"cmd_zdr_no_providers"` and the 400 the plugin makes of Go's error line with `"type":"cmd_zdr_no_providers"` (`zdrCoded`, matched as the error's code or type, never by its words, whose "…a different model.","type":"invalid_request_error" read as a model unserved and rested the model on the account). `keepRetry` notes it beside the error (`zdrHeader`), since the error the agent gets may keep no code (Anthropic's shape, or the 400's numeric code). It rests nobody, anywhere (`restAfterMarked` returns `by: "off"`), so the model answers as soon as the switch is off; it isn't asked of the provider's other accounts at that model, which carry the same header (`notMates`), nor again after a moment; another member, the provider's other models among them, is asked once, and with none left the agent gets Command Code's words (`TestCommandCodeZDRRefusalRestsNothing`, `TestZDRRefusalNeverRests`). Another vendor's refusal in the same words, without the code, still rests the model (`TestZDRRefusalIsCommandCodesCodeOnly`). -5. The last candidate's error reaches the agent, with one exception for a group (#1418, `patience.go`), which a plain provider shares once its same-one retries are spent (below). When every member has failed in a way that passes (`busy`, its statuses `busyStatus`: 408, 500, 502, 503, 504, 529, or Cloudflare's 520 to 524, which a relay behind it answers with now and then (`TestCloudflareErrorIsTriedAgain`; the same-one retries of `passing` read the same list), that isn't a proxy, a quota, response protection, or an upstream that answered a stream request with a whole reply, which fails the same however often it is asked (`didNotStream`; the same-one retries of `passing` leave it alone too, `TestStreamlessMemberIsAskedOnce`), or a 429 that is a short rate limit, not a plan or credit, nor an account's token wall: a vendor code in `wallCodes`, Raccoon's `user_model_rate_limited`, which rests as a rate limit but is asked again neither here nor by the same-one retries, as each ask draws on the bucket it waits for; plugins#512, `TestTokenWallFailsFast`), and nothing of the reply has been sent, the members that failed so are asked again in turn after a pause (`replan`). The pause is `retryPause` doubled each round up to `replanLongest()` (30 times `retryPause`, 30s), and never shorter than the soonest Retry-After; a member whose Retry-After ends past the pause is asked after the others. This goes on while the group's `Patience` lasts. A member of a group in the group uses the innermost that sets `Patience` (`innerPatience`, #2410), as FirstToken (#2246) and Sink (#2255) do; unset falls back to the group asked for, and an inner `PatienceOff` skips replan for that member (`TestNestedGroupPatienceThroughOuter`, `TestNestedGroupPatienceInnerOff`, `TestNestedGroupPatienceFallsBackToOuter`). `replanRounds` (12) is only a backstop that never comes first: the pauses alone add up to `PatienceLongest` in 11 rounds (with 6, a group set to 240s gave up after 90s of pauses, real-jacket on #1418; `TestPatienceIsUsedUp`). The budget is the group's `Patience`, counted from the first time every member had failed, when the agent would have had the error (`waitFrom`; `Group.Waits`: 0 follows the default for every group, `groupPatience`, itself 0 for `PatienceDefault`, 60s; -1, `PatienceOff`, turns it off; at most `PatienceLongest`, 240s). A pause that would end past the budget isn't taken, and the agent gets the error; a member the vendor said is back within a second past its budget (read in whole seconds) is asked as the budget ends (`TestReporterResetFitsTheDefaultPatience`). The last member out of its quota or credit (not `busy`), after an earlier member failed in a way that passes, has those earlier ones asked again the same way, and rests as they did (`lastSpent`): before, the agent had the relay's moment of 503 while the relay would answer a moment on (`TestGroupRelayBlipDoesNotEndOnSpentLast`). While another member is busy too, the last one isn't first tried again alone (`passing`): the members take turns, and once the budget has begun, the same-one retries aren't taken either. While the budget lasts, the last candidate's failure is held (`newHoldWriter`), and a streaming agent is kept alive through the pause with SSE comments (`pauseAlive`). The try is traced with `Again` (the pause), `Replan` (how many are asked again) and `Patience` (the budget in seconds). The group editor's "Every member busy" row sets it. A plain provider (a `provider/model` request, its accounts and fallbacks the candidates) first takes the same-one retries `passing` gives the last one left: `lastRetries` for a busy vendor, `rateRetries` for a rate limit, each pause `retryPause< patience=2m|off|default`; the provider editor shows no row for it and its save keeps it, `TestProviderSaveKeepsPatience`), unset `singlePatience` (`PatienceDefault`, 60s), counted from when the agent would have had the error, so it works with no setting and the user's value wins either way (`TestSingleProviderOwnPatienceWins`; ChatGPT's reset of a large request, `codexReset`, is left out: Codex is told it at its 503 with what may help, as `codexBusy` leaves it). A provider's own Patience is for a request to it alone: a group it is in, set or unset, keeps the group's (zoecats on Discord: a local relay's short 429 went straight to Claude Code once the few retries were spent). So a 429 whose Retry-After is 20s is waited out, the stream kept alive past `keepHeldAfter`; one of an hour, a quota, credit or plan limit, a 401 or 403, a refusal, response protection's 502 and `didNotStream` are not `busy` or don't fit the budget, and reach the agent at once as the vendor said them. Its tries are traced with `Again` alone, no `Replan` or `Patience`, so the Routing page tells it as the last one left asked again rather than as a group's members (`TestSingleProviderWaitsOutAShortRateLimit`, `TestSingleProviderPassesALongLimitThrough`, `TestSingleProviderAgentGoneInTheWait` in [`single_busy_test.go`](../../internal/gateway/single_busy_test.go)). Codex's own one-account relay (`codexUpstreamOn`, below) doesn't join it: its request is relayed unchanged outside the candidate loop, and the backend's 429 is always the plan's usage limit (`codexBusy` never retries one), so the short rate limit this waits out doesn't arise there; its overloads keep their `lastRetries` and then the subscription's fallbacks. An agent that goes away in either pause (the same-one retry's or a group's replan) ends the request there with 499: nobody is asked again, and the try whose pause it was is marked `Gone` (#1894, heng91: a relay down while its proxy was off, the agent's window closed). The Routing page says the agent canceled the request before the retry and lists it as canceled, rather than ending its story on "tried again in 2s", a retry that never came (`TestAgentGoneInTheRetryPause`, `routing-agent-gone.test.cjs`). A request its agent cancels, in such a pause or while a try is out (a person stopped the reply, or sent the next message while it came and the agent asked again), is logged 499 "the agent canceled the request" (`usage.CanceledBy`), with the error type `agent_canceled` (`usage.CanceledErrType`), which a middleware's usage rows carry too, so a module tells it from magpie's own limit below without the message. It is no failure: the agent saw no error (#2398). The Requests card and the totals line over the Requests list count it apart (`Totals.Canceled`); its success share, the Failed filter, the CSV's `error` column, the Routing page's errors and the Context page's error rate leave it out; the Requests list, the Routing page and Recent calls show it muted, in neither the failed nor the answered colour, from `canceled` on the row, route and call; and the OTLP export sends its span and its try's with status code 499, no error and no error type (`TestAgentCanceledIsNoError`, `TestAgentCanceledIsNoFailure`, `TestLedgerTellsCanceledRows`, `TestContextLeavesCanceledOutOfErrors`, `TestOTelWaterfallFailureAndCancellation`). Codex signed in to ChatGPT, its turn relayed to the backend as it came, gone mid-reply is logged the same 499 (#4866) and counted the same way (`TestCodexGoneMidReplyIsNoFailure`). magpie's own limit running out on a request it asked of itself is logged 499 too, and stays a failure (#2318, `TestCanceledTellsTheAgentFromMagpiesLimit`). A record logged before the error type, and a day's history kept before routes said `canceled`, are read the same way, by status and message (`TestHistoryTellsCanceledRoutes`). A try that answered is recorded (`served`, `answered`) for routing, affinity and usage. A try is added to the route's `Tries` only as it is asked, so a later try is the record that the gateway went on from this one, and the Routing page tells what came of a try from that, never from where it stood in the order (#2281, xishuchkui-code: an Antigravity 502 empty reply that went on to the next account was told as "an error another account wouldn't fix, so Claude Code gets it"). The one case the record can't show is the last try left out of its allowance after an earlier failure that wasn't one, where the agent is told the earlier error: that try is marked `Earlier` (`routing-went-on.test.cjs`). +5. The last candidate's error reaches the agent, with one exception for a group (#1418, `patience.go`), which a plain provider shares once its same-one retries are spent (below). When every member has failed in a way that passes (`busy`, its statuses `busyStatus`: 408, 500, 502, 503, 504, 529, or Cloudflare's 520 to 524, which a relay behind it answers with now and then (`TestCloudflareErrorIsTriedAgain`; the same-one retries of `passing` read the same list), that isn't a proxy, a quota, response protection, or an upstream that answered a stream request with a whole reply, which fails the same however often it is asked (`didNotStream`; the same-one retries of `passing` leave it alone too, `TestStreamlessMemberIsAskedOnce`), or a 429 that is a short rate limit, not a plan or credit, nor an account's token wall: a vendor code in `wallCodes`, Raccoon's `user_model_rate_limited`, which rests as a rate limit but is asked again neither here nor by the same-one retries, as each ask draws on the bucket it waits for; plugins#512, `TestTokenWallFailsFast`), and nothing of the reply has been sent, the members that failed so are asked again in turn after a pause (`replan`). The pause is `retryPause` doubled each round up to `replanLongest()` (30 times `retryPause`, 30s), and never shorter than the soonest Retry-After; a member whose Retry-After ends past the pause is asked after the others. This goes on while the group's `Patience` lasts. A member of a group in the group uses the innermost that sets `Patience` (`innerPatience`, #2410), as FirstToken (#2246) and Sink (#2255) do; unset falls back to the group asked for, and an inner `PatienceOff` skips replan for that member (`TestNestedGroupPatienceThroughOuter`, `TestNestedGroupPatienceInnerOff`, `TestNestedGroupPatienceFallsBackToOuter`). `replanRounds` (12) is only a backstop that never comes first: the pauses alone add up to `PatienceLongest` in 11 rounds (with 6, a group set to 240s gave up after 90s of pauses, real-jacket on #1418; `TestPatienceIsUsedUp`). The budget is the group's `Patience`, counted from the first time every member had failed, when the agent would have had the error (`waitFrom`; `Group.Waits`: 0 follows the default for every group, `groupPatience`, itself 0 for `PatienceDefault`, 60s; -1, `PatienceOff`, turns it off; at most `PatienceLongest`, 240s). A pause that would end past the budget isn't taken, and the agent gets the error; a member the vendor said is back within a second past its budget (read in whole seconds) is asked as the budget ends (`TestReporterResetFitsTheDefaultPatience`). The last member out of its quota or credit (not `busy`), after an earlier member failed in a way that passes, has those earlier ones asked again the same way, and rests as they did (`lastSpent`): before, the agent had the relay's moment of 503 while the relay would answer a moment on (`TestGroupRelayBlipDoesNotEndOnSpentLast`). While another member is busy too, the last one isn't first tried again alone (`passing`): the members take turns, and once the budget has begun, the same-one retries aren't taken either. While the budget lasts, the last candidate's failure is held (`newHoldWriter`), and a streaming agent is kept alive through the pause with SSE comments (`pauseAlive`). The try is traced with `Again` (the pause), `Replan` (how many are asked again) and `Patience` (the budget in seconds). The group editor's "Every member busy" row sets it. A plain provider (a `provider/model` request, its accounts and fallbacks the candidates) first takes the same-one retries `passing` gives the last one left: `lastRetries` for a busy vendor, `rateRetries` for a rate limit, each pause `retryPause< patience=2m|off|default`; the provider editor shows no row for it and its save keeps it, `TestProviderSaveKeepsPatience`), unset `singlePatience` (`PatienceDefault`, 60s), counted from when the agent would have had the error, so it works with no setting and the user's value wins either way (`TestSingleProviderOwnPatienceWins`; ChatGPT's reset of a large request, `codexReset`, is left out: Codex is told it at its 503 with what may help, as `codexBusy` leaves it). A provider's own Patience is for a request to it alone: a group it is in, set or unset, keeps the group's (zoecats on Discord: a local relay's short 429 went straight to Claude Code once the few retries were spent). So a 429 whose Retry-After is 20s is waited out, the stream kept alive past `keepHeldAfter`; one of an hour, a quota, credit or plan limit, a 401 or 403, a refusal, response protection's 502 and `didNotStream` are not `busy` or don't fit the budget, and reach the agent at once as the vendor said them. Its tries are traced with `Again` alone, no `Replan` or `Patience`, so the Routing page tells it as the last one left asked again rather than as a group's members (`TestSingleProviderWaitsOutAShortRateLimit`, `TestSingleProviderPassesALongLimitThrough`, `TestSingleProviderAgentGoneInTheWait` in [`single_busy_test.go`](../../internal/gateway/single_busy_test.go)). Codex's own one-account relay (`codexUpstreamOn`, below) doesn't join it: its request is relayed unchanged outside the candidate loop, and the backend's 429 is always the plan's usage limit (`codexBusy` never retries one), so the short rate limit this waits out doesn't arise there; its overloads keep their `lastRetries` and then the subscription's fallbacks. A client that says how long it waits, in seconds (`provider.WaitHeader`, `X-Magpie-Wait`: a model test asking a remote magpie sends its own wait, `pluginTestWait`, 60s, since the remote serves plugins' models), takes neither pause when it would end within `clientRoom` (10s) of that wait (`keptAlive.outlives`), and has the error while it still waits; before, the test gave up at 20s on a 502 the remote held through its 60s patience (plugins#827, `TestClientWaitBoundsPatience`, `TestRemoteMagpieProbeWait`). Like every `X-Magpie-` header it goes no further upstream. An agent that goes away in either pause (the same-one retry's or a group's replan) ends the request there with 499: nobody is asked again, and the try whose pause it was is marked `Gone` (#1894, heng91: a relay down while its proxy was off, the agent's window closed). The Routing page says the agent canceled the request before the retry and lists it as canceled, rather than ending its story on "tried again in 2s", a retry that never came (`TestAgentGoneInTheRetryPause`, `routing-agent-gone.test.cjs`). A request its agent cancels, in such a pause or while a try is out (a person stopped the reply, or sent the next message while it came and the agent asked again), is logged 499 "the agent canceled the request" (`usage.CanceledBy`), with the error type `agent_canceled` (`usage.CanceledErrType`), which a middleware's usage rows carry too, so a module tells it from magpie's own limit below without the message. It is no failure: the agent saw no error (#2398). The Requests card and the totals line over the Requests list count it apart (`Totals.Canceled`); its success share, the Failed filter, the CSV's `error` column, the Routing page's errors and the Context page's error rate leave it out; the Requests list, the Routing page and Recent calls show it muted, in neither the failed nor the answered colour, from `canceled` on the row, route and call; and the OTLP export sends its span and its try's with status code 499, no error and no error type (`TestAgentCanceledIsNoError`, `TestAgentCanceledIsNoFailure`, `TestLedgerTellsCanceledRows`, `TestContextLeavesCanceledOutOfErrors`, `TestOTelWaterfallFailureAndCancellation`). Codex signed in to ChatGPT, its turn relayed to the backend as it came, gone mid-reply is logged the same 499 (#4866) and counted the same way (`TestCodexGoneMidReplyIsNoFailure`). magpie's own limit running out on a request it asked of itself is logged 499 too, and stays a failure (#2318, `TestCanceledTellsTheAgentFromMagpiesLimit`). A record logged before the error type, and a day's history kept before routes said `canceled`, are read the same way, by status and message (`TestHistoryTellsCanceledRoutes`). A try that answered is recorded (`served`, `answered`) for routing, affinity and usage. A try is added to the route's `Tries` only as it is asked, so a later try is the record that the gateway went on from this one, and the Routing page tells what came of a try from that, never from where it stood in the order (#2281, xishuchkui-code: an Antigravity 502 empty reply that went on to the next account was told as "an error another account wouldn't fix, so Claude Code gets it"). The one case the record can't show is the last try left out of its allowance after an earlier failure that wasn't one, where the agent is told the earlier error: that try is marked `Earlier` (`routing-went-on.test.cjs`). ## Constraints and failure behavior @@ -220,7 +220,7 @@ recorded as a prediction failure (`noPrediction`). - A request refused for its bytes (`byteCapRefusal` in [`body_cap.go`](../../internal/gateway/body_cap.go): a 413, or words such as Command Code's 400 "Request body is 40.1 MB, over the 32 MB limit for one request (33554432 bytes)", EDwinpzy on Discord; never a 401, 403, 429 or a context overflow) is asked again in `forward` with its oldest history images left out (`refitOverCap`), up to three times. The cap is the smallest size the refusal names below what was sent, else three quarters of what was sent, and it is kept per provider id for as long as magpie runs (`bodyCaps`), so the next request near it is fitted in `forwardOnce` before it goes (`withinCap`). A request is fitted to three quarters of the cap. Each left-out image becomes a text part, "[An earlier image was left out here to keep this request under its size limit.]", which names neither magpie nor the vendor. The latest user message's images (`latestUser`: not a tool result, not Codex's compaction prompt) and every text, tool output included, stay; the rest of the body keeps its bytes. When leaving out every earlier image can't bring it under, or it is refused at every size, the agent gets a 413 `request_too_large` naming the size, the cap and what was kept (`overCap`), so Codex is told `context_length_exceeded` and its compaction goes on to the text-only ask (`summaryTooLarge`, `plainCompact`) instead of sending the same body into the compaction guard's hold. Every route reaches it, magpie's own (compaction, titles, the classifier, search, vision) included, since they all go through `forward`. - The vendor's reply headers a provider passes on (`ReplyHeaders` and the default request ids, see [providers and accounts](providers-accounts.md), #4145) reach the agent from the reply it is given alone. Every request that can become the agent's reply goes out through `forward` (relayed, translated, a plugin's fetch, a signed-in account) or `retrieveAs`/`retrieveOpen` (embeddings, audio), and each tells its reply's passed headers to the try that asked through the try's context (`withReplySink`, `heardReply` in [`reply_headers.go`](../../internal/gateway/reply_headers.go)). The sink is the try's `holdWriter` (`heardUpstream`), so a try that fails and is let go takes its vendor's headers with it, a fallback's reply carries the provider that answered's, and a failure `release`d to the agent carries its own vendor's. A reply to another provider (a side model, a searcher) is not heard: the sink takes its own provider's alone. Within a try the last reply replaces the earlier ones (an ask again without a refused beta, a Mantle reroute), and once the try has its status nothing more is heard (a cut reply's continuation). count_tokens writes them straight (`passReplyHeaders`), and embeddings through `heardHeaders`. A stream whose headers `keepAlive` sent before the vendor answered (past `keepHeldAfter`) has none: they can't follow a status already sent. Not carried: images, video and the Codex backend relay, which copies its reply's headers whole already. `TestReplyHeadersPassedOn`, `TestReplyHeadersOfTheReplyGiven`, `TestReplyHeadersOnCountTokens`, `TestReplyHeadersOnEmbeddings`. - The agent's request headers a provider passes on (`PassHeaders`, see [providers and accounts](providers-accounts.md); 3jRzfF52Qx on X) go with every try `forwardOnce` makes, so chat, responses, messages, count_tokens, a group's members, fallbacks, signed-in accounts and a plugin's fetch all take them: `forwardOnce` puts the agent's headers in the try's context under the try's provider id (`provider.WithClientHeaders`), and `Provider.Sign` passes the ones that provider lists and no other's. Not carried: embeddings, images, video and the Codex backend relay, which don't go through `forwardOnce`. `TestPassHeadersReachTheProvider`, `TestPassHeadersOnlyToTheirProvider`. -- A streamed request is never left silent while its vendor says nothing. `holdWriter.watch` runs beside each try: past `keepHeldAfter` (3s) it sends a held try's agent the stream's 200 and SSE comments (`keepAlive`), one every `keepHeldEvery` (5s), none of the try, so another candidate may still answer in the same stream. It was 15s, and a proxy between the agent and magpie that hangs up on a request with nothing back for about 10s ended every turn slower to its first event: Codex on Windows sends 127.0.0.1 through a Clash-style app's system proxy, `127.*` in its bypass list or not, and its turns ended 499 (mrten_95615 on Discord; `TestHeldStreamHeardBeforeAProxyCuts`). A failure before it is still a status; once the reply passes, it puts a comment between two of its lines after `keepaliveEvery` of quiet. It stops after `keepaliveLongest` (5 minutes) with nothing from the vendor. A translated stream (`streamTranslated`) whose upstream has begun its reply and then says nothing at all, not even a comment (a relay that sends the rest of a long reply in one burst at its end), is kept alive in the client's own protocol by a ticker beside its reader (`keepThroughSilence`): every `keepaliveEvery` it sends the client's keepalive (`enc.keepalive`: a ping for Anthropic, `response.in_progress` for Responses, a comment for Chat, nothing for Gemini), which also counts as the try heard from, so the held stream's comments go on too; it stops once the upstream has been silent for `translatedQuietLongest` (30 minutes), past the 10 minutes `upstreamHeaderWait` gives a vendor to begin and long enough for a long reasoning turn sent whole at its end, after which the client's own timeout ends the wait (youyo.p on Discord: before, Claude Code heard only comments, which its event watchdog doesn't count, and gave up 300s on; `TestTranslatedSilenceKeptAliveForABound`). An upstream that has answered its headers but sent no byte yet is still waited for under the held stream's comments alone (`notAnAPIReply` reads its first bytes before the reply is translated). An Anthropic client is sent a ping at most once each `pingEvery` (1 minute), comments between, and none before `message_start`: Claude Code's watchdog counts only 30 pings in a row as life, and a ping on every upstream keepalive spent them in the first minute; the SDKs' `MessageStream` fails on any event before `message_start` (`anthropicEncoder.keepalive`, `TestTranslatedStreamKeepsClientAlive`). A try waiting for its key's or account's slot or for room in its minute (`lanes.take`, `rpms.wait`) is kept alive the same way (`keepQueued`), for as long as it waits; once the 200 is out, the try is held, and its failure or its queue turning it away reaches the agent as the stream's error (`failTo`), not a status (coeo91 on Discord). A wait shorter than `keepHeldAfter` sends nothing, so its 429 keeps its `Retry-After`. A proxy in front such as Cloudflare (125s) otherwise ends the request (#947). Gemini streams get no comments (#934). A vendor that then ignores `stream:true` and answers 200 with its reply whole has it sent as the agent's stream (`wholeAsStream`: Chat, Responses, Anthropic), not as the stream's error, while a reply under a type that says neither JSON nor a stream is held as a stream when its first bytes are one (`sseStart`), read event by event like one that says so, so an error among its frames still goes to the next candidate (#1418: it went through at once); a Chat stream a vendor ends with `finish_reason:"error"` — WorkBuddy's and a DeepSeek harness's word for a turn it failed, not finished (#2471) — is the failure the word says, held for the group's next candidate, and nobody rests, as an empty reply's (`TestFinishReasonErrorFailsOver`); a 200 that is no reply of the protocol's fails as a translated reply that didn't stream does (502, "… did not stream"), for the next candidate to answer, and the last one's reaches the agent as the stream's error. A held stream that has sent nothing but the frames before a reply (`response.created`, `response.in_progress`, `codex.rate_limits`, pings, an empty part begun, and any event `streamEvent` doesn't know to carry text, reasoning, a call or a reply's end (`replyEvent`), or an item not known that isn't a call or a tool's (`streamPart.said`): `eventLead`; Aliceonly on #1418: an unknown event was taken for content and let a frames-only 200 through, and its `server_is_overloaded` reached Codex with five candidates left) stays held as long as its agent is kept alive, up to `holdLead` (4 minutes, under the 300s Codex waits for an event; `keptQuiet`), so a `server_is_overloaded` that comes after it is a failure the next candidate answers (#1418: let through at 15s, the ChatGPT backend's failure 36s in ended Codex's turn with sub2api, next in the group, never asked). A stream whose agent can't be kept alive (Gemini's) is let through after `holdLongest` (15s), as before. Codex counts only events toward that 300s, not comments, so the bound is the request's, not each try's: once Codex on Responses has heard no event for `agentQuietMost` (4 minutes) since the request began or its last event (`keptAlive.tooQuiet`), the try in hand is let through (`scan`, `keepQuiet`), and no group replan or same-one retry is taken whose pause would end past it (fadenoob on Discord: held tries and replan pauses added up past 300s and Codex reconnected on "idle timeout waiting for SSE"). A translated reply whose upstream stream stops before it said its reply had — an Anthropic one with no stop_reason and no message_stop, a Responses one with no `response.completed`, the same two a relayed one is told by (`sniff.whole`; a Chat stream may end without `[DONE]` and be whole), a Gemini or Code Assist one whose last chunk has no candidate's `finishReason` (`geminiEnds`, #1643: `usageMetadata` is no end, Vertex AI sends it on every chunk; a chunk with no candidate at all is the empty reply's to answer, #667), and a relayed Gemini one told the same way (#1644; it ends in Gemini's own `{"error":{"code":502,…,"status":"UNAVAILABLE"}}` data line from `streamFailure`, `TestGeminiRelayEndedShort`; whatever a relayed stream gets appended, that error or a filled-in `finish_reason`, begins after a blank line, two newlines when the upstream's last write stopped inside a line, so it is an event of its own rather than more of the half-written one, and the half event itself is dropped: a relayed stream holds the line the upstream never ended back, puts it out when the reply ends whole or is gathered (`TestGrokPluginNonStreamLastLineUnended`), and throws it away when a failure is appended in its place, for no client can parse it — pi read "malformed server-sent event JSON" off a stream Z.ai reset mid-line, and died before the error after it; a line whose data parses (its JSON whole, or `[DONE]`) is no half event and goes out before the failure (#2446, #2580, `TestPassthroughStreamCutMidLine`, `TestChatStreamCutMidLineLeavesNoHalfEvent`, `TestChatStreamCutAfterWholeEventKeepsIt`, `TestGeminiCompatFinishAfterPartialLine`), and a Chat one from Gemini's OpenAI-compatible API (`geminiCompat`) with no `finish_reason`, relayed or translated (`saysItsEnd`; Linka on Discord: the upstream hung up between a whole function call and its `finish_reason`, and Pi threw the call away as "Stream ended without finish_reason"; that API counts the usage only once the generation is done, so when the last chunk carried it only the `finish_reason` was lost and it is filled in, `tool_calls` after a call and `stop` otherwise, as a relayed chunk before `[DONE]` or a translated reply's end, and the reply counts as whole (`chatTail`); only one with no usage at its end is a cut, `TestGeminiCompatRelayEndedShort`, `TestGeminiCompatTranslatedEndedShort`) — ends the turn with "the reply ended before it was complete" (`errEndedShort`, `TestResponsesUpstreamEndedShort`, `TestGeminiUpstreamEndedShort`), asked again in place where the upstream goes on from a prefill (`continuation.go`). only one with no usage at its end is a cut, `TestGeminiCompatRelayEndedShort`, `TestGeminiCompatTranslatedEndedShort`), and a Chat one from Command Code's API (`commandCodeHost`), whose slow starts a killed worker ends with no closing chunk at all, relayed (esp32gallery on #2471: 20 of 665 requests in a day, every ledger row a 200 with no stop and no error while the client read "Stream ended without finish_reason"; `TestCommandCodeRelayEndedShort`, `TestCommandCodeTaillessFailsOver`) — ends the turn with "the reply ended before it was complete" (`errEndedShort`, `TestResponsesUpstreamEndedShort`, `TestGeminiUpstreamEndedShort`), asked again in place where the upstream goes on from a prefill (`continuation.go`). A client that asked for no stream is told the same 502 of such a cut (`translate`, `TestNonStreamEndedShort`, `TestGeminiNonStreamEndedShort`), rather than handed what came as its whole reply. A translated reply from an Anthropic or Responses upstream that ended but said nothing (no text, call, search or image) and counted no token at all is no reply either, whatever its end says (`repliesCounted`, #2086: an Anthropic-compatible proxy's 200 ended a Codex turn as `response.completed` with no output, no usage and no served model, and Codex didn't ask again). It is the empty reply's to answer (#667): asked again in place, then failed with "an empty reply", streamed or not, for every client (`TestUncountedEmptyReplyFails`, `TestUncountedEmptyReplyFailsEveryClient`). Claude's own empty `end_turn` counts its prompt and stays a whole reply (`TestWellFormedStreamsStillComplete`). A relayed one is read the same way once: a Responses stream whose `response.completed` carries no output and counted no token is no reply either, failed before it is let through, held for the group's next candidate, and nobody rests (#2471, MurmuredVelpro: WorkBuddy AI's account ended Codex's turn completed with `output: []` and all-zero usage three times running, the healthy members never asked; `TestEmptyCompletedFailsOver`). A reply passed through in its own protocol isn't read this way, but for that completed. +- A streamed request is never left silent while its vendor says nothing. `holdWriter.watch` runs beside each try: past `keepHeldAfter` (3s) it sends a held try's agent the stream's 200 and SSE comments (`keepAlive`), one every `keepHeldEvery` (5s), none of the try, so another candidate may still answer in the same stream. It was 15s, and a proxy between the agent and magpie that hangs up on a request with nothing back for about 10s ended every turn slower to its first event: Codex on Windows sends 127.0.0.1 through a Clash-style app's system proxy, `127.*` in its bypass list or not, and its turns ended 499 (mrten_95615 on Discord; `TestHeldStreamHeardBeforeAProxyCuts`). A failure before it is still a status; once the reply passes, it puts a comment between two of its lines after `keepaliveEvery` of quiet. It stops after `keepaliveLongest` (5 minutes) with nothing from the vendor. A translated stream (`streamTranslated`) whose upstream has begun its reply and then says nothing at all, not even a comment (a relay that sends the rest of a long reply in one burst at its end), is kept alive in the client's own protocol by a ticker beside its reader (`keepThroughSilence`): every `keepaliveEvery` it sends the client's keepalive (`enc.keepalive`: a ping for Anthropic, `response.in_progress` for Responses, a comment for Chat, nothing for Gemini), which also counts as the try heard from, so the held stream's comments go on too; it stops once the upstream has been silent for `translatedQuietLongest` (30 minutes), past the 10 minutes `upstreamHeaderWait` gives a vendor to begin and long enough for a long reasoning turn sent whole at its end, after which the client's own timeout ends the wait (youyo.p on Discord: before, Claude Code heard only comments, which its event watchdog doesn't count, and gave up 300s on; `TestTranslatedSilenceKeptAliveForABound`). An upstream that has answered its headers but sent no byte yet is still waited for under the held stream's comments alone (`notAnAPIReply` reads its first bytes before the reply is translated). An Anthropic client is sent a ping at most once each `pingEvery` (1 minute), comments between, and none before `message_start`: Claude Code's watchdog counts only 30 pings in a row as life, and a ping on every upstream keepalive spent them in the first minute; the SDKs' `MessageStream` fails on any event before `message_start` (`anthropicEncoder.keepalive`, `TestTranslatedStreamKeepsClientAlive`). A try waiting for its key's or account's slot or for room in its minute (`lanes.take`, `rpms.wait`) is kept alive the same way (`keepQueued`), for as long as it waits; once the 200 is out, the try is held, and its failure or its queue turning it away reaches the agent as the stream's error (`failTo`), not a status (coeo91 on Discord). A wait shorter than `keepHeldAfter` sends nothing, so its 429 keeps its `Retry-After`. A proxy in front such as Cloudflare (125s) otherwise ends the request (#947). Gemini streams get no comments (#934). A vendor that then ignores `stream:true` and answers 200 with its reply whole has it sent as the agent's stream (`wholeAsStream`: Chat, Responses, Anthropic), not as the stream's error, while a reply under a type that says neither JSON nor a stream is held as a stream when its first bytes are one (`sseStart`), read event by event like one that says so, so an error among its frames still goes to the next candidate (#1418: it went through at once); a Chat stream a vendor ends with `finish_reason:"error"` — WorkBuddy's and a DeepSeek harness's word for a turn it failed, not finished (#2471) — is the failure the word says, held for the group's next candidate, and nobody rests, as an empty reply's (`TestFinishReasonErrorFailsOver`); a 200 that is no reply of the protocol's fails as a translated reply that didn't stream does (502, "… did not stream"), for the next candidate to answer, and the last one's reaches the agent as the stream's error. A held stream that has sent nothing but the frames before a reply (`response.created`, `response.in_progress`, `codex.rate_limits`, pings, an empty part begun, and any event `streamEvent` doesn't know to carry text, reasoning, a call or a reply's end (`replyEvent`), or an item not known that isn't a call or a tool's (`streamPart.said`): `eventLead`; Aliceonly on #1418: an unknown event was taken for content and let a frames-only 200 through, and its `server_is_overloaded` reached Codex with five candidates left) stays held as long as its agent is kept alive, up to `holdLead` (4 minutes, under the 300s Codex waits for an event; `keptQuiet`), so a `server_is_overloaded` that comes after it is a failure the next candidate answers (#1418: let through at 15s, the ChatGPT backend's failure 36s in ended Codex's turn with sub2api, next in the group, never asked). A stream whose agent can't be kept alive (Gemini's) is let through after `holdLongest` (15s), as before. Codex counts only events toward that 300s, not comments, so the bound is the request's, not each try's: once Codex on Responses has heard no event for `agentQuietMost` (4 minutes) since the request began or its last event (`keptAlive.tooQuiet`), the try in hand is let through (`scan`, `keepQuiet`), and no group replan or same-one retry is taken whose pause would end past it (fadenoob on Discord: held tries and replan pauses added up past 300s and Codex reconnected on "idle timeout waiting for SSE"). A translated reply whose upstream stream stops before it said its reply had — an Anthropic one with no stop_reason and no message_stop, a Responses one with no `response.completed`, the same two a relayed one is told by (`sniff.whole`; a Chat stream may end without `[DONE]` and be whole), a Gemini or Code Assist one whose last chunk has no candidate's `finishReason` (`geminiEnds`, #1643: `usageMetadata` is no end, Vertex AI sends it on every chunk; a chunk with no candidate at all is the empty reply's to answer, #667), and a relayed Gemini one told the same way (#1644; it ends in Gemini's own `{"error":{"code":502,…,"status":"UNAVAILABLE"}}` data line from `streamFailure`, `TestGeminiRelayEndedShort`; whatever a relayed stream gets appended, that error or a filled-in `finish_reason`, begins after a blank line, two newlines when the upstream's last write stopped inside a line, so it is an event of its own rather than more of the half-written one, and the half event itself is dropped: a relayed stream holds the line the upstream never ended back, puts it out when the reply ends whole or is gathered (`TestGrokPluginNonStreamLastLineUnended`), and throws it away when a failure is appended in its place, for no client can parse it — pi read "malformed server-sent event JSON" off a stream Z.ai reset mid-line, and died before the error after it; a line whose data parses (its JSON whole, or `[DONE]`) is no half event and goes out before the failure (#2446, #2580, `TestPassthroughStreamCutMidLine`, `TestChatStreamCutMidLineLeavesNoHalfEvent`, `TestChatStreamCutAfterWholeEventKeepsIt`, `TestGeminiCompatFinishAfterPartialLine`), and a Chat one from Gemini's OpenAI-compatible API (`geminiCompat`) with no `finish_reason`, relayed or translated (`saysItsEnd`; Linka on Discord: the upstream hung up between a whole function call and its `finish_reason`, and Pi threw the call away as "Stream ended without finish_reason"; that API counts the usage only once the generation is done, so when the last chunk carried it only the `finish_reason` was lost and it is filled in, `tool_calls` after a call and `stop` otherwise, as a relayed chunk before `[DONE]` or a translated reply's end, and the reply counts as whole (`chatTail`); only one with no usage at its end is a cut, `TestGeminiCompatRelayEndedShort`, `TestGeminiCompatTranslatedEndedShort`) — ends the turn with "the reply ended before it was complete" (`errEndedShort`, `TestResponsesUpstreamEndedShort`, `TestGeminiUpstreamEndedShort`), asked again in place where the upstream goes on from a prefill (`continuation.go`). only one with no usage at its end is a cut, `TestGeminiCompatRelayEndedShort`, `TestGeminiCompatTranslatedEndedShort`), and a Chat one from Command Code's API (`commandCodeHost`), whose slow starts a killed worker ends with no closing chunk at all, relayed (esp32gallery on #2471: 20 of 665 requests in a day, every ledger row a 200 with no stop and no error while the client read "Stream ended without finish_reason"; `TestCommandCodeRelayEndedShort`, `TestCommandCodeTaillessFailsOver`) — ends the turn with "the reply ended before it was complete" (`errEndedShort`, `TestResponsesUpstreamEndedShort`, `TestGeminiUpstreamEndedShort`), asked again in place where the upstream goes on from a prefill (`continuation.go`). A client that asked for no stream is told the same 502 of such a cut (`translate`, `TestNonStreamEndedShort`, `TestGeminiNonStreamEndedShort`), rather than handed what came as its whole reply. One such ending is not a cut: a request capped at a short probe's worth (`cutVoidTokens`, 1024) whose reply spent some of it (thought, said or called something) and then ended cleanly with no end said ended at its length (`endsAtProbeCap`), and goes as a `length` stop, translated whole or streamed, and as a `response.incomplete` at `max_output_tokens` when a Responses plugin's stream is asked whole (`gathered`). Open Design's glm-5.3-flash always thinks, spent a model test's 16 tokens on it and ended after `content_block_stop`, so every plain test of it was this 502, waited out through the patience (plugins#827; `TestProbeCapEndsAtLength`, `TestGatheredProbeCapIncomplete`). A reply asked for more, one that spent nothing, or a Gemini or Code Assist one (Gemini ends every reply with its finishReason, `MAX_TOKENS` included, so one without it was cut: `TestGeminiUpstreamEndedShort` asks for 256) is still the cut. A relayed stream (passthrough to an agent of the same protocol) is still relayed as it came, with no end added (#5736). A translated reply from an Anthropic or Responses upstream that ended but said nothing (no text, call, search or image) and counted no token at all is no reply either, whatever its end says (`repliesCounted`, #2086: an Anthropic-compatible proxy's 200 ended a Codex turn as `response.completed` with no output, no usage and no served model, and Codex didn't ask again). It is the empty reply's to answer (#667): asked again in place, then failed with "an empty reply", streamed or not, for every client (`TestUncountedEmptyReplyFails`, `TestUncountedEmptyReplyFailsEveryClient`). Claude's own empty `end_turn` counts its prompt and stays a whole reply (`TestWellFormedStreamsStillComplete`). A relayed one is read the same way once: a Responses stream whose `response.completed` carries no output and counted no token is no reply either, failed before it is let through, held for the group's next candidate, and nobody rests (#2471, MurmuredVelpro: WorkBuddy AI's account ended Codex's turn completed with `output: []` and all-zero usage three times running, the healthy members never asked; `TestEmptyCompletedFailsOver`). A reply passed through in its own protocol isn't read this way, but for that completed. - A vendor whose API is the client's own (a relayed request, or a translated one whose upstream error shape is the client's: Chat and Responses share OpenAI's) has its JSON error body go to the client as it came (`writeVendorErrorFrom`, ne9ko9 on Discord): its status, its own `type`, a numeric `code`, `param`, `request_id` and every field magpie knows nothing of. Only `error.message` is magpie's: the provider's name before the vendor's words (a describer asking for another model, the Claude sign-in rewording in `claude_signin.go` and the agent read it there), with a note where magpie has one (an account's `Explain`, a region note, the wrong-endpoint note, `saysBusy`, a 413's byte-limit hint). And a prompt too long for the model (`tooLong`) sets only the fields that make the client's agent compact: status 400, and `type`/`code` (OpenAI's `context_length_exceeded`), `type` and the "prompt is too long: " lead (Anthropic's), `code`/`status` (Gemini's), each spliced in place (`setErrorField`) so every other byte stays. A body that isn't JSON, or not in the client's shape, and another API's error are rebuilt in the client's shape (`writeVendorError`) as before. An error status the hold reads as the safety filter's refusal (`policyRefusal`) is still told in magpie's words once no one else answers ([`kept_error_test.go`](../../internal/gateway/kept_error_test.go)). - A provider of a key whose errors the user leaves to the client (`errors=pass`, `Provider.PassErrors`, set in its editor's Advanced "Errors" menu or with `magpie provider set errors=pass`; `TakesPassErrors` keeps it to a provider of a key, never a signed-in account or a plugin's; ne9ko9 on Discord) is asked once. The candidate loop's `holdWriter` holds nothing for it (`pass := c.p.PassesErrors()` at the hold choke point; only a stream already begun is held), so no retry, wait, re-plan, refusal handover or next member answers for it; `forward` asks once after `dsRetryGone` (magpie's own file ids), `passthrough` and `forwardTranslated` return the first failure without a re-ask in another shape, `streamTranslated` neither continues nor asks again after an empty reply, and `restAfterMarked` rests none of its keys. Its error goes through `passError` (`pass_errors.go`): on the client's own API the vendor's status, Content-Type and body as sent; on another, the client's shape with the vendor's status, type, code (a number too), param and words, nothing inferred (no too-long, busy or 413 words). Retry-After and the rate-limit headers go with it. `TestPassErrorsAskedOnce`, `TestPassErrorsNotInferred`, `TestPassErrorsOtherAPI` in `internal/gateway/pass_errors_test.go`. - A vendor's error keeps its `code` and `param` on its way to an OpenAI-shaped client (`writeVendorError`), where `writeError` used to set both to null: a status error relayed or translated, and a request refused inside a Responses stream. A Responses stream's `error` event or failed response whose error is of type `invalid_request_error` is the request at fault (`requestRefused`, read by its type, not its words): its `Event` carries status 400 and the vendor's error (`Event.Said`), so a client answered whole gets the vendor's 400 with its code and param (the whole-translated path wrote 502 `api_error`), a reply cut by it isn't resumed (`continuation.again`), and a translated stream's error says the vendor's type, code and param (`saidError`), so `holdWriter` reads it as the 400 it is. Before, the hold read magpie's `api_error` as a 502: the same request was sent three times, then to the other accounts, and every one rested (magpie-releases#18: the ChatGPT backend answers `access_programs` naming a program the workspace hasn't got with a 200 stream whose error is `access_program_not_enabled`). Asked once, nobody rests ([`codex_access_programs_test.go`](../../internal/gateway/codex_access_programs_test.go)). diff --git a/internal/gateway/continuation.go b/internal/gateway/continuation.go index ffc12d1be..446bd640f 100644 --- a/internal/gateway/continuation.go +++ b/internal/gateway/continuation.go @@ -78,6 +78,35 @@ var errStreamCut = errors.New("stream cut mid-reply") // and be whole, so Chat is not one. var errEndedShort = errors.New("the reply ended before it was complete") +// endsAtProbeCap says whether a reply that stopped short of its end, its +// connection closed cleanly, is taken as one that ended at its length: +// the request capped it at a short probe's worth (cutVoidTokens) and the +// reply spent some of it, thinking or saying something. A vendor that +// ends a reply at max_tokens with no closing event looks the same as one +// that cut it, and a reply asked for 16 tokens that thought them all is +// what such an ending most likely is: Open Design's glm-5.3-flash always +// thinks, spent a model test's 16 tokens on it and ended after +// content_block_stop, with no message_delta or message_stop, so every +// plain test of it through a remote magpie was a 502 waited out through +// the patience (plugins#827). A larger reply that ends so is still a cut, +// and so is a Gemini or Code Assist one of any size: Gemini ends every +// reply with its finishReason, MAX_TOKENS included, so one without it was +// cut (vertexCut, asked for 256, TestGeminiUpstreamEndedShort). +func endsAtProbeCap(proto provider.Protocol, capped int, spent bool) bool { + return (proto == provider.Anthropic || proto == provider.Responses) && + spent && capped > 0 && capped <= cutVoidTokens +} + +// spends says whether an event spent some of a reply's tokens: text, +// a call, reasoning, a search or an image. +func spends(ev Event) bool { + switch ev.Kind { + case KThink, KSealed: + return true + } + return saysSomething(ev) +} + // geminiEnds says whether a Gemini chunk ends the reply, as replyEnds // does for events that name their type. Gemini's and Code Assist's chunks // name none and there is no [DONE]: the last one is the one whose @@ -439,6 +468,8 @@ func (s *Server) streamTranslated(w http.ResponseWriter, r *http.Request, p prov // try's reasoning was found stuck in a loop before it had, and it is // let go to ask again (loopReasks) var spoke, relooped bool + // spent: this try spent some of the reply's tokens (endsAtProbeCap) + var spent bool var summaryUpstream bool reasks := 0 if h, ok := w.(*holdWriter); ok { @@ -460,6 +491,7 @@ func (s *Server) streamTranslated(w http.ResponseWriter, r *http.Request, p prov return // the rest of a try let go for its loop } spoke = spoke || saysSomething(ev) + spent = spent || spends(ev) switch ev.Kind { case KThink, KSealed: if ev.Kind == KThink && !summaryUpstream { @@ -526,7 +558,7 @@ func (s *Server) streamTranslated(w http.ResponseWriter, r *http.Request, p prov // continuation's prefill away cutBy, cutCode, cutErr := failed, failedCode, serr failed, failedCode, failedStatus, cut, serr = "", "", 0, false, nil - errNamed = 0 + errNamed, spent = 0, false var held func() // what a textCallSee of this try holds back req := request if cont.resume { @@ -657,6 +689,14 @@ func (s *Server) streamTranslated(w http.ResponseWriter, r *http.Request, p prov // finish_reason after its generation was done u.add(Usage{Stop: fin}) serr = dec(string(finishChunk(fin)), attemptSee) + } else if endsAtProbeCap(actual, req.MaxTokens, spent) { + // a short probe's reply that stopped at its own + // small limit with no end said (plugins#827): + // ended at its length, as the vendor should have + // said + u.add(Usage{Stop: "length"}) + serr = nil + attemptSee(Event{Kind: KStop, Stop: "length"}) } } } diff --git a/internal/gateway/fallback.go b/internal/gateway/fallback.go index 1b89d2643..732f9a83b 100644 --- a/internal/gateway/fallback.go +++ b/internal/gateway/fallback.go @@ -3089,6 +3089,9 @@ type keptAlive struct { // 40 MB upload asked four times) failed 502 instead of being made // without a model (#4862) whole bool + // clientEnd is when the client said it stops waiting (clientEnd), + // zero when it said nothing + clientEnd time.Time // Only opted-in Claude cache reporting can defer initial keepalives. // Selection releases it before process startup; expiry keeps the stream alive. cacheReportUntil time.Time @@ -3125,6 +3128,32 @@ func (a *keptAlive) tooQuiet(d time.Duration) bool { return a != nil && a.streams && a.proto == provider.Responses && !a.told.IsZero() && time.Since(a.told)+d >= agentQuietMost } +// clientRoom is how long a client that said how long it waits is left, +// after a pause, for the try the pause is for to answer and the reply or +// its error to reach it. +const clientRoom = 10 * time.Second + +// clientEnd is when a request's client stops waiting, from the seconds +// it named in provider.WaitHeader (a model test asking a remote magpie), +// counted from start; zero when it named none, or nothing readable. +func clientEnd(h http.Header, start time.Time) time.Time { + n, err := strconv.Atoi(strings.TrimSpace(h.Get(provider.WaitHeader))) + if err != nil || n <= 0 { + return time.Time{} + } + return start.Add(time.Duration(min(n, 3600)) * time.Second) +} + +// outlives says whether a pause of d, with clientRoom after it, would end +// past the time the client said it waits: its pause isn't taken, and the +// client has the error while it still waits for one (plugins#827: a +// remote magpie's model test waited 20s while the server kept its 502 +// through the provider's patience, 45s and more, and the test said only +// that no answer came). +func (a *keptAlive) outlives(d time.Duration) bool { + return a != nil && !a.clientEnd.IsZero() && time.Now().Add(d+clientRoom).After(a.clientEnd) +} + // keepAlive tells the agent of a stream held past keepHeldAfter for its // reasoning that it goes on, every keepHeldEvery: held for up to // holdThinking (4 minutes), the agent heard nothing at all, and Alma's diff --git a/internal/gateway/gateway.go b/internal/gateway/gateway.go index ff916f961..3e09bc2f9 100644 --- a/internal/gateway/gateway.go +++ b/internal/gateway/gateway.go @@ -3210,7 +3210,7 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro unlisted, unlistedW = nil, nil } // what the tries' held streams sent the agent ahead of a reply (#751) - kept := &keptAlive{proto: from, model: askedFor, told: start, whole: wantsWhole(r.Context())} + kept := &keptAlive{proto: from, model: askedFor, told: start, whole: wantsWhole(r.Context()), clientEnd: clientEnd(r.Header, start)} if k := handedOnOf(r); k != nil && !kept.whole { // Codex's own sign-in waited for first, with Codex kept alive kept = k @@ -4868,7 +4868,7 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro if memberWait == 0 { memberWait = patience } - if next, wait, ok := replan(busyNow, rounds, waitFrom, patienceFallback); ok && !kept.tooQuiet(wait) { + if next, wait, ok := replan(busyNow, rounds, waitFrom, patienceFallback); ok && !kept.tooQuiet(wait) && !kept.outlives(wait) { try.Fail, try.Again = failureOf(c, hw.code(), hw.errBody()), wait.Milliseconds() if lastSpent { rest := s.restAfterMarked(c, hw.code(), hw.header, hw.errBody(), hw.sharedPool) @@ -4892,7 +4892,7 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro break } } - if wait, ok := passing(hw.code(), hw.header, hw.errBody(), again); ok && !protected && !sameRefusal && !hw.turnedAway && hw.failed() && waitFrom.IsZero() && !kept.tooQuiet(wait) { + if wait, ok := passing(hw.code(), hw.header, hw.errBody(), again); ok && !protected && !sameRefusal && !hw.turnedAway && hw.failed() && waitFrom.IsZero() && !kept.tooQuiet(wait) && !kept.outlives(wait) { // nobody else is left: the same one again, after a moment (not // what Antigravity turned away: it turns it away again; nor // once the group's patience is spent) @@ -6143,7 +6143,7 @@ func (s *Server) passthrough(w http.ResponseWriter, r *http.Request, p provider. // asked streamed, the stream read here (gathered) var gather *gathered if gathers(p, proto, body) { - gather = &gathered{h: http.Header{}, status: http.StatusOK} + gather = &gathered{h: http.Header{}, status: http.StatusOK, capped: int(gjson.GetBytes(body, "max_output_tokens").Int())} body = withFields(body, map[string]any{"stream": true}) } searchFn := false // Codex's tool search sent as a function @@ -8702,9 +8702,13 @@ func (s *Server) translate(w http.ResponseWriter, r *http.Request, p provider.Pr } var col collector ended := false // the upstream said its reply ended + spent := false // the reply spent some of its tokens (endsAtProbeCap) var tail chatTail var found searchTally // the searches it ran by itself - see, held := written(zenSee(zen, col.add)) + see, held := written(zenSee(zen, func(ev Event) { + spent = spent || spends(ev) + col.add(ev) + })) err = readSSE(rd, func(_, data string) error { tail.see([]byte(data)) found.see(actual, []byte(data)) @@ -8757,6 +8761,13 @@ func (s *Server) translate(w http.ResponseWriter, r *http.Request, p provider.Pr // with: a minute limit in a 200 stream is a 429, not a 502 return writeVendorError(w, from, cmp.Or(col.errStatus, streamStatus(said)), p.Name+": "+said, col.errSaid), said } + if col.err == "" && !ended && saysItsEnd(p, actual, model) && r.Context().Err() == nil && endsAtProbeCap(actual, request.MaxTokens, spent) { + // a short probe's reply that stopped at its own small limit with + // no end said (endsAtProbeCap, plugins#827): ended at its length, + // as the vendor should have said + col.add(Event{Kind: KStop, Stop: "length"}) + ended = true + } if col.err == "" && !ended && saysItsEnd(p, actual, model) && r.Context().Err() == nil { // an Anthropic stream that just stopped — no stop_reason, no // message_stop — or a Responses one with no response.completed is diff --git a/internal/gateway/gathered.go b/internal/gateway/gathered.go index ccec56d9a..ed2452d10 100644 --- a/internal/gateway/gathered.go +++ b/internal/gateway/gathered.go @@ -29,6 +29,9 @@ type gathered struct { h http.Header status int buf bytes.Buffer + // capped: the max_output_tokens the client asked, for a reply that + // stopped at it with no end said (endsAtProbeCap) + capped int } func (g *gathered) Header() http.Header { return g.h } @@ -40,7 +43,9 @@ func (g *gathered) Write(b []byte) (int, error) { return g.buf.Write(b) } // stream's items, or else its text, when the event left it empty. // A reply that came whole goes as it came. A stream that failed, or ended // before saying its reply had, is a 502, as a translated one is -// (TestNonStreamEndedShort), never an empty 200. +// (TestNonStreamEndedShort), never an empty 200 — unless a short probe's +// reply stopped at its own small limit (endsAtProbeCap): its response as +// the stream began it, incomplete at max_output_tokens. func (g *gathered) finish(w http.ResponseWriter, p provider.Provider, sse bool, cut string, failed string) (int, string) { if !sse { for k, vs := range g.h { @@ -50,7 +55,8 @@ func (g *gathered) finish(w http.ResponseWriter, p provider.Provider, sse bool, w.Write(g.buf.Bytes()) return g.status, failed } - var resp json.RawMessage + var resp, begun json.RawMessage // begun: the response as the stream began it + spent := false // a delta of the reply's came (endsAtProbeCap) items := map[int]json.RawMessage{} var text strings.Builder // the reply's text, for a stream with no items streamErr := "" @@ -68,7 +74,12 @@ func (g *gathered) finish(w http.ResponseWriter, p provider.Provider, sse bool, if e.Type == "" { e.Type = event } + if strings.HasSuffix(e.Type, ".delta") { + spent = true + } switch e.Type { + case "response.created", "response.in_progress": + begun = e.Response case "response.output_text.delta": text.WriteString(e.Delta) case "response.output_item.done": @@ -82,6 +93,10 @@ func (g *gathered) finish(w http.ResponseWriter, p provider.Provider, sse bool, } return nil }) + if (len(resp) == 0 || resp[0] != '{') && streamErr == "" && cut == "" && failed == "" && + len(begun) > 0 && begun[0] == '{' && endsAtProbeCap(provider.Responses, g.capped, spent) { + resp = incompleteAtLength(begun) + } if len(resp) == 0 || resp[0] != '{' { msg := failed switch { @@ -111,6 +126,22 @@ func (g *gathered) finish(w http.ResponseWriter, p provider.Provider, sse bool, return http.StatusOK, "" } +// incompleteAtLength is a response as its stream began it, made the +// response.incomplete a reply stopped at its max_output_tokens ends with. +func incompleteAtLength(begun json.RawMessage) json.RawMessage { + var m map[string]json.RawMessage + if json.Unmarshal(begun, &m) != nil { + return nil + } + m["status"] = json.RawMessage(`"incomplete"`) + m["incomplete_details"] = json.RawMessage(`{"reason":"max_output_tokens"}`) + b, err := json.Marshal(m) + if err != nil { + return nil + } + return b +} + // withStreamedOutput is resp with the stream's items as its output when // its own output is missing or empty. func withStreamedOutput(resp json.RawMessage, items map[int]json.RawMessage) json.RawMessage { diff --git a/internal/gateway/probe_cap_test.go b/internal/gateway/probe_cap_test.go new file mode 100644 index 000000000..7a48510c3 --- /dev/null +++ b/internal/gateway/probe_cap_test.go @@ -0,0 +1,148 @@ +package gateway + +import ( + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" + + "github.com/yetone/magpie/internal/provider" +) + +// Open Design's glm-5.3-flash, as plugins#827's log has it: a reply that +// thinks, closes its block and ends, with no message_delta or +// message_stop, when the model test's 16 tokens are spent. +func probeCapStream(model string) []string { + return []string{ + anthStart(model, 5), + `{"type":"content_block_start","index":0,"content_block":{"type":"thinking","thinking":""}}`, + anthThink("The user says hi. I should"), + `{"type":"content_block_stop","index":0}`, + } +} + +func probeCapAsk(maxTokens string, stream bool) string { + s := "false" + if stream { + s = "true" + } + return `{"model":"up/glm-5.3-flash","max_tokens":` + maxTokens + `,"stream":` + s + `,"messages":[{"role":"user","content":"hi"}]}` +} + +// A short probe's reply that thought its whole small budget and ended +// with no end said ended at its length, whole or streamed (plugins#827: +// every plain test of such a model was a 502 "ended before it was +// complete", waited out through the patience). A reply asked for more +// that ends so is still a cut, and so is one that spent nothing. +func TestProbeCapEndsAtLength(t *testing.T) { + for _, stream := range []bool{false, true} { + name := map[bool]string{false: "whole", true: "stream"}[stream] + t.Run(name, func(t *testing.T) { + up := func(events ...string) { + fresh(t) + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "text/event-stream") + for _, ev := range events { + w.Write([]byte("data: " + ev + "\n\n")) + } + })) + t.Cleanup(srv.Close) + if err := provider.Save(provider.Provider{ID: "up", Name: "UP", Key: "k", Models: []string{"glm-5.3-flash"}, Anthropic: srv.URL}); err != nil { + t.Fatal(err) + } + } + up(probeCapStream("glm-5.3-flash")...) + code, body := post(t, "/v1/chat/completions", probeCapAsk("16", stream)) + if code != 200 || strings.Contains(body, "ended before") || !strings.Contains(body, `"finish_reason":"length"`) { + t.Errorf("probe's reply at its cap: status %d: %s", code, body) + } + // asked for more than a probe's worth: a cut + code, body = post(t, "/v1/chat/completions", probeCapAsk("4096", stream)) + if !strings.Contains(body, "ended before it was complete") || (!stream && code != 502) { + t.Errorf("a long reply cut short served as ended (status %d): %s", code, body) + } + // nothing spent: a cut, whatever its cap + up(anthStart("glm-5.3-flash", 5)) + code, body = post(t, "/v1/chat/completions", probeCapAsk("16", stream)) + if !strings.Contains(body, "ended before it was complete") || (!stream && code != 502) { + t.Errorf("a reply that spent nothing served as ended (status %d): %s", code, body) + } + }) + } +} + +// A Responses plugin's stream asked whole, capped at a probe's worth and +// ended with no response.completed after spending some of it, is the +// response incomplete at max_output_tokens, not a 502; one capped past a +// probe's worth is still the 502. +func TestGatheredProbeCapIncomplete(t *testing.T) { + stream := sse( + `data: {"type":"response.created","response":{"id":"r1","object":"response","model":"m","status":"in_progress"}}`, + `data: {"type":"response.reasoning_summary_text.delta","delta":"The user"}`) + for _, c := range []struct { + capped int + code int + }{{16, 200}, {4096, 502}, {0, 502}} { + g := &gathered{h: http.Header{}, status: 200, capped: c.capped} + g.h.Set("Content-Type", "text/event-stream") + g.Write([]byte(stream)) + rec := httptest.NewRecorder() + code, _ := g.finish(rec, provider.Provider{Name: "p"}, true, "", "") + if code != c.code { + t.Errorf("capped %d: status %d, want %d: %s", c.capped, code, c.code, rec.Body) + continue + } + if code == 200 && (!strings.Contains(rec.Body.String(), `"status":"incomplete"`) || !strings.Contains(rec.Body.String(), `"reason":"max_output_tokens"`)) { + t.Errorf("capped %d: %s", c.capped, rec.Body) + } + } + // a stream that spent nothing is still the 502 + g := &gathered{h: http.Header{}, status: 200, capped: 16} + g.h.Set("Content-Type", "text/event-stream") + g.Write([]byte(sse(`data: {"type":"response.created","response":{"id":"r1","object":"response","status":"in_progress"}}`))) + rec := httptest.NewRecorder() + if code, _ := g.finish(rec, provider.Provider{Name: "p"}, true, "", ""); code != 502 { + t.Errorf("nothing spent: status %d: %s", code, rec.Body) + } +} + +// A client that says how long it waits (provider.WaitHeader: a model test +// asking a remote magpie) is told a busy failure while it still waits: +// no retry pause or patience round is taken that would end past it +// (plugins#827: the test waited 20s, the server held its 502 through the +// provider's patience, and the test said only that nothing answered). +// A client that said nothing, or a wait long enough, is retried as +// before. +func TestClientWaitBoundsPatience(t *testing.T) { + const busy = `{"type":"error","error":{"type":"api_error","message":"upstream went away"}}` + for _, c := range []struct { + name string + wait string + retry bool + }{{"short wait", "1", false}, {"no wait said", "", true}, {"unreadable", "soon", true}, {"long wait", "3600", true}} { + t.Run(c.name, func(t *testing.T) { + u := &busyUpstream{replies: []busyReply{{code: 502, body: busy}}} + s := busyProvider(t, u) + scaled(t, 300*time.Millisecond) + gw := httptest.NewServer(s.Handler()) + t.Cleanup(gw.Close) + req, _ := http.NewRequest("POST", gw.URL+"/v1/messages", strings.NewReader(singleAsk(false))) + req.Header.Set("Content-Type", "application/json") + if c.wait != "" { + req.Header.Set(provider.WaitHeader, c.wait) + } + res, err := http.DefaultClient.Do(req) + if err != nil { + t.Fatal(err) + } + res.Body.Close() + if res.StatusCode != 502 { + t.Errorf("status %d, want the 502", res.StatusCode) + } + if n := u.asked(); (n > 1) != c.retry { + t.Errorf("upstream asked %d times, retried want %v", n, c.retry) + } + }) + } +} diff --git a/internal/provider/plugins.go b/internal/provider/plugins.go index f96a0159c..530a4037a 100644 --- a/internal/provider/plugins.go +++ b/internal/provider/plugins.go @@ -55,6 +55,13 @@ const ( // (host.js), as it does the two above. const FallbackHeader = "X-Magpie-Fallback" +// WaitHeader tells a magpie's gateway how many seconds its client waits +// for the answer: a model test asking a remote magpie sends its own wait, +// and the gateway takes no retry pause or patience round that would end +// past it, so the test is told the error rather than running out of time +// (plugins#827). Like every X-Magpie- header it goes no further. +const WaitHeader = "X-Magpie-Wait" + // SessionToPluginHeader and SubagentToPluginHeader tell a plugin's fetch // the session the agent named (sessionOf: Claude Code's // x-claude-code-session-id and the rest) and the Claude Code subagent the diff --git a/internal/provider/remote_probe_wait_test.go b/internal/provider/remote_probe_wait_test.go new file mode 100644 index 000000000..b1ec8bf2d --- /dev/null +++ b/internal/provider/remote_probe_wait_test.go @@ -0,0 +1,51 @@ +package provider + +import ( + "context" + "fmt" + "net/http" + "net/http/httptest" + "sync" + "testing" + "time" +) + +// A model test through a remote magpie waits as long as a plugin's test +// does here (pluginTestWait), since the remote serves plugins' models and +// retries for them, and tells the remote how long it waits (WaitHeader) +// so the remote answers with its error inside it (plugins#827: the test +// gave the remote 20s, the remote held its 502 for 45s and more). +func TestRemoteMagpieProbeWait(t *testing.T) { + defer func(w, pw time.Duration) { testWait, pluginTestWait = w, pw }(testWait, pluginTestWait) + testWait, pluginTestWait = 1*time.Second, 4*time.Second + var mu sync.Mutex + var said []string + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + mu.Lock() + said = append(said, r.Header.Get(WaitHeader)) + mu.Unlock() + time.Sleep(1500 * time.Millisecond) // past testWait, within pluginTestWait + w.Header().Set("Content-Type", "text/event-stream") + fmt.Fprint(w, "data: {\"choices\":[{\"index\":0,\"delta\":{\"content\":\"hi\"}}]}\n\ndata: [DONE]\n\n") + })) + defer srv.Close() + p := Provider{ID: "office", Preset: RemoteMagpiePreset, Key: "sk-magpie-k", Chat: srv.URL + "/v1"} + r := probe(context.Background(), p, Chat, srv.URL+"/v1/chat/completions", []byte(`{"model":"m","stream":true}`), "m", testWait) + if !r.OK { + t.Errorf("remote magpie's test given testWait only: %+v", r) + } + mu.Lock() + defer mu.Unlock() + if len(said) == 0 || said[0] != "4" { + t.Errorf("%s said %q, want the probe's own wait, 4", WaitHeader, said) + } + // a provider that isn't a remote magpie is told nothing + said = nil + mu.Unlock() + q := Provider{ID: "relay", Key: "k", Chat: srv.URL + "/v1"} + probe(context.Background(), q, Chat, srv.URL+"/v1/chat/completions", []byte(`{"model":"m","stream":true}`), "m", 3*time.Second) + mu.Lock() + if len(said) != 1 || said[0] != "" { + t.Errorf("a relay was told %s %q", WaitHeader, said) + } +} diff --git a/internal/provider/test.go b/internal/provider/test.go index 9bee0b62d..bc3f4d6ef 100644 --- a/internal/provider/test.go +++ b/internal/provider/test.go @@ -17,6 +17,7 @@ import ( "net/url" "regexp" "slices" + "strconv" "strings" "sync" "time" @@ -265,7 +266,9 @@ func tinyBody(q Provider, proto Protocol, model string) (url, body string) { // sign-in or ask its vendor more than once before it answers, as it does // for the gateway, which gives it no such bound (mingxia_16024 on // Discord: every Qoder and WorkBuddy model's test ended at 20s while -// agents were answered). +// agents were answered), and for a remote magpie, whose gateway serves +// such plugins' models in turn and asks again where its own retries do +// (plugins#827: a plugin model tested in 60s here had 20s through it). // connectWait is how long a probe waits for its connection (a TLS // handshake done, through any proxy) before it gives up on the host: an // address nothing answers at is said in that time, not the whole wait's @@ -806,6 +809,11 @@ func probeOnce(ctx context.Context, p Provider, proto Protocol, url string, body p.warmPlugin(ctx) wait = max(wait, pluginTestWait) } + if p.IsRemoteMagpie() { + // it serves plugins' models too, and retries for them + // (pluginTestWait) + wait = max(wait, pluginTestWait) + } ctx, cancel := context.WithTimeout(probelog.WithModel(ctx, model), wait) defer cancel() rctx := ctx @@ -854,6 +862,11 @@ func probeOnce(ctx context.Context, p Provider, proto Protocol, url string, body // out for minutes as an agent's turn is (Qoder's free models) req.Header.Set(FallbackHeader, "1") } + if p.IsRemoteMagpie() { + // its gateway takes no pause that ends past the test's wait, and + // the test is told the error (WaitHeader, plugins#827) + req.Header.Set(WaitHeader, strconv.Itoa(int(wait/time.Second))) + } if err := p.Sign(ctx, req, proto, body); err != nil { r.Error = err.Error() return r