diff --git a/docs/subsystems/gateway-request-hooks.md b/docs/subsystems/gateway-request-hooks.md index 2a58389cb..d1d62843d 100644 --- a/docs/subsystems/gateway-request-hooks.md +++ b/docs/subsystems/gateway-request-hooks.md @@ -114,7 +114,11 @@ bounded hook timeout. Request-owned state is released after notification. - `internal/gateway/middleware.go`: `gatewayHooks`, before routing and around the middleware, so `onResponse` sees what the agent got. `serveAgent` runs it for every agent request; Codex's own ChatGPT sign-in passthrough - (`codex_backend.go`) runs it without the synchronous middleware. + (`codex_backend.go`) runs it without the synchronous middleware. The + requests magpie makes on its own call `serve` directly and run no hooks: + Codex's compaction and its fallback turn, titles, System One's + classifier, search and vision (#4847). A request over a provider's byte + cap is fitted in the gateway itself, not by a hook (`body_cap.go`). - `internal/gateway/gateway_hooks.go`: bounded response observation and `gatewayReply`, a stream made one reply. - `internal/plugin/gateway_test.go` and `internal/gateway/gateway_hook_test.go`: diff --git a/docs/subsystems/gateway-routing.md b/docs/subsystems/gateway-routing.md index f1ca61f50..9e72ac79b 100644 --- a/docs/subsystems/gateway-routing.md +++ b/docs/subsystems/gateway-routing.md @@ -194,6 +194,7 @@ recorded as a prediction failure (`noPrediction`). - An error status whose body holds no message of its own says what it was (`provider.Unsaid`, through `APIError` and the plan-quota and drawing readers): a web page by its title as plain words, a firewall's block page (`EdgeBlocked`: Alibaba Cloud's, Cloudflare's "you have been blocked", "used Cloudflare to restrict access" and `error code: 1005`–`1020`) with `BlockedHint` after it, and an empty body under an HTTP status as refused with no details, often a firewall or proxy in front of the API (`NoDetails`; an empty `response.failed` event, whose fallback is no status, still reads "upstream stream failed"). A bare "403 Forbidden" told a relay's user nothing (maralica on Discord). A JSON error still reads as its message. `TestAPIErrorUnsaid`, `TestRelayRefusalSaysWhatItWas`. Only the first bytes are peeked, which a stream waits for anyway, and a compressed body is left as it came. - A 400 that is no error at all, from OpenCode's gateway (`openCodeBareRefusal` in `forwardOnce`, #3740), is the 502 it stands for: OpenCode Go answered s-leeq's requests `400 {"model":"deepseek-v4.1-flash"}`, the model's name and nothing else, with nothing in or out, and the same request was answered some seconds later (13s to 25s in their timelines). A body any error field names goes on as it came (the missing `x-opencode-session` refusal among it), and so does a body that isn't a JSON object, or one over 64KB; a body is never cut. Read as the 502, a group's next member is asked, and a lone provider is asked again within its patience, which outlasts that window, where the 400 ended the turn at once. The failure is tied to the request (30 of 214 requests with ~246K tokens of tools, none of 420 with under 1K), so nobody rests for it (`restAfterMarked`, `openCodeBare`): the key goes on serving the requests it serves. Only OpenCode's hosts are read this way; every other vendor's bare 400 stays as it came. (`TestOpenCodeGoBare400AskedAgain`, `TestOpenCodeGoBare400ToldAs502`, `TestOpenCodeGoBare400RestsNobody`, `TestOpenCodeGoError400Untouched`) - A 2xx from Zhipu or Z.ai holding the platform's refusal envelope (`{"code":1000,"msg":…,"success":false}`, which their Responses API at `/api/v1` answers a refused key) is the refusal it stands for (`provider.ZhipuEnveloped` in `forwardOnce`): 401 for a key refused, 429 for a limit or no balance, as Zhipu's error codes give, so it fails over and rests as those do and the agent is told why. `TestZhipuResponsesRefusalIsRefusal`. +- 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`. - 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 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/body_cap.go b/internal/gateway/body_cap.go new file mode 100644 index 000000000..022d05bef --- /dev/null +++ b/internal/gateway/body_cap.go @@ -0,0 +1,391 @@ +package gateway + +import ( + "bytes" + "context" + "encoding/json" + "fmt" + "io" + "log" + "net/http" + "regexp" + "strconv" + "strings" + "sync" + + "github.com/tidwall/gjson" + + "github.com/yetone/magpie/internal/provider" +) + +// A provider's cap on the bytes of one request. +// +// Codex sends the whole conversation on every turn, its screenshots inline +// as base64, and its compaction's summary request is that conversation +// too. Past a vendor's byte cap — Command Code's "Request body is 40.1 MB, +// over the 32 MB limit for one request (33554432 bytes)" (EDwinpzy on +// Discord, a Codex session of many screenshots), Anthropic's 32 MB +// request_too_large, DeepSeek's 413 — every turn and every compaction was +// refused, the same body asked again until the compaction guard held it +// (compactFails), and the conversation could neither compact nor go on. +// +// A refusal that says the body is too large (byteCapRefusal) teaches the +// provider's cap: the one it states, or else three quarters of what was +// sent. The request is then sent again with the oldest images of its +// history left out, each replaced by a short text saying so, until it is +// under three quarters of the cap — room for the conversation to grow a +// few turns before more go, so its prompt cache isn't broken on every +// turn. The latest user message's images stay, and no text is touched: +// a tool's output keeps its words, only an image in it can go. Later +// requests to the provider are fitted the same way before they are sent +// (forwardOnce). Every route through serve goes through forward — the +// agent's turns, Codex's compaction, titles, the classifier, search and +// vision stand-ins — so each is fitted alike. +// +// When leaving every earlier image out still doesn't bring it under, the +// request isn't sent again: the refusal goes on as a 413 saying how large +// the request is, the cap, and that the latest images and the text were +// kept, which Codex takes as its cue to compact (streamError) and +// codexCompact as its cue to ask the summary as text (summaryTooLarge). + +// bodyCapWords are a vendor's words for a request body over its byte +// cap, not a conversation over the model's window (tooLong) nor a rate. +var bodyCapWords = regexp.MustCompile(`(?i)request[ _](body|entity|payload)( size)?( is| was)? (too large|too big|over|larger than|exceeds?|exceeded)|request body is [\d.]+ ?[kmg]i?b|payload too large|entity too large|request_too_large|(body|request|payload) (size )?(exceeds?|exceeded|is over|is larger than) (the )?(max|limit|\d)|length limit exceeded|maximum allowed number of bytes|limit for one request|(max(imum)?|request) (request |body )*size (limit )?(exceeded|of)`) + +// byteCapRefusal is a provider's refusal of a request for its bytes: a +// 413 that doesn't say the model's window is full, or any other refusal +// (Command Code's came as its own status) whose words say the body is +// over a limit. A sign-in's refusal or a rate limit is never one. +func byteCapRefusal(status int, errBody []byte) bool { + if status < 400 || status == http.StatusUnauthorized || status == http.StatusForbidden || status == http.StatusTooManyRequests { + return false + } + words := string(wordsOf(errBody)) + if tooLong(status, words) { + return false + } + return status == http.StatusRequestEntityTooLarge || bodyCapWords.MatchString(words) +} + +// capSizes are the sizes a refusal names: "33554432 bytes", "32 MB", +// "32MiB", "40.1 MB". +var capSizes = regexp.MustCompile(`(?i)(\d+(?:\.\d+)?)\s*(bytes|b|kb|kib|mb|mib|gb|gib)\b`) + +// statedCap is the cap a refusal names: the smallest size in its words +// under what was sent (the body's own size is often named beside it). A +// megabyte is 2^20 bytes, as "32 MB … (33554432 bytes)" counts it; the +// request is fitted well under the cap anyway (capRoom). 0 when it names +// none. +func statedCap(errBody []byte, sent int) int { + least := 0 + for _, m := range capSizes.FindAllStringSubmatch(string(wordsOf(errBody)), -1) { + f, err := strconv.ParseFloat(m[1], 64) + if err != nil || f <= 0 { + continue + } + unit := map[string]float64{"bytes": 1, "b": 1, "kb": 1 << 10, "kib": 1 << 10, "mb": 1 << 20, "mib": 1 << 20, "gb": 1 << 30, "gib": 1 << 30}[strings.ToLower(m[2])] + n := int(f * unit) + if n < 1<<10 || n >= sent { + continue // not a body's cap, or the body itself + } + if least == 0 || n < least { + least = n + } + } + return least +} + +// bodyCaps are the byte caps providers refused requests over, by +// provider id, for as long as magpie runs. +type bodyCaps struct { + mu sync.Mutex + m map[string]int +} + +func (c *bodyCaps) of(id string) int { + c.mu.Lock() + defer c.mu.Unlock() + return c.m[id] +} + +// learn keeps the smaller of n and the cap known before. +func (c *bodyCaps) learn(id string, n int) int { + c.mu.Lock() + defer c.mu.Unlock() + if c.m == nil { + c.m = map[string]int{} + } + if old := c.m[id]; old > 0 && old <= n { + return old + } + c.m[id] = n + return n +} + +// capRoom is what a request is fitted to under a cap: three quarters of +// it. capNear is how near the cap a request may come before it is fitted. +func capRoom(n int) int { return n / 4 * 3 } +func capNear(n int) int { return n / 10 * 9 } + +// withinCap is body as it goes to p: fitted under the cap p refused a +// larger request over, when one is known and body comes near it. +func (s *Server) withinCap(p provider.Provider, to provider.Protocol, path string, body []byte) []byte { + out, left := s.capFit(p, to, path, body) + if left > 0 { + log.Printf("%s: the request is %s, over the %s it takes in one request; the %d oldest images left out (%s)", p.Name, mb(len(body)), mb(s.bodyCaps.of(p.ID)), left, mb(len(out))) + } + return out +} + +// capFit is withinCap without its log line: body fitted under p's known +// cap, and how many images were left out for it. +func (s *Server) capFit(p provider.Provider, to provider.Protocol, path string, body []byte) ([]byte, int) { + n := s.bodyCaps.of(p.ID) + if n <= 0 || len(body) <= capNear(n) || countsTokens(path) { + return body, 0 + } + out, left, ok := withoutOldImages(to, body, capRoom(n)) + if !ok { + return body, 0 + } + return out, left +} + +// refitOverCap is forward's answer to res, a refusal of body for its +// bytes (byteCapRefusal): the cap learned, and the request sent again +// with its oldest images left out, as often as that brings it lower and +// is refused again. When nothing more can go, the refusal is said as a +// 413 that names the size, the cap and what was kept. +func (s *Server) refitOverCap(ctx context.Context, p provider.Provider, to provider.Protocol, path string, body []byte, in http.Header, res *http.Response) (*http.Response, error) { + var err error + for range 3 { + if res.StatusCode < 400 || countsTokens(path) { + return res, nil + } + b := peekError(res) + if !byteCapRefusal(res.StatusCode, b) { + return res, nil + } + // what forwardOnce sent: body as it fits it + was, _ := s.capFit(p, to, path, codexImagesFit(p, to, body)) + sent := len(was) + n := statedCap(b, sent) + if n == 0 { + n = capRoom(sent) // it said no number: less than was sent + } + n = s.bodyCaps.learn(p.ID, n) + fitted, left, ok := withoutOldImages(to, body, capRoom(n)) + if !ok || len(fitted) >= sent { + res.Body.Close() + return overCap(res, b, p, len(body), statedCap(b, len(body)), images(to, body)), nil + } + log.Printf("%s refused a request of %s (HTTP %d: %s); asking again with the %d oldest images left out (%s)", p.Name, mb(sent), res.StatusCode, provider.APIError(b, ""), left, mb(len(fitted))) + res.Body.Close() + // fitted is under capNear already, so forwardOnce sends it as it is + if res, err = s.forwardOnce(ctx, p, to, path, fitted, in); err != nil { + return res, err + } + } + if res.StatusCode >= 400 { + b := peekError(res) + if byteCapRefusal(res.StatusCode, b) { + // refused as often as it was asked smaller: said as a 413, so + // Codex's compaction asks as text (summaryTooLarge) + res.Body.Close() + return overCap(res, b, p, len(body), statedCap(b, len(body)), images(to, body)), nil + } + } + return res, nil +} + +// peekError is the first MiB of res's error body, res.Body left to read +// it all again. +func peekError(res *http.Response) []byte { + b, _ := io.ReadAll(io.LimitReader(res.Body, 1<<20)) + res.Body = readCloser{io.MultiReader(bytes.NewReader(b), res.Body), res.Body} + return b +} + +// overCap is a byte-cap refusal said as a 413 with what it is about: the +// request's size, the provider's cap when it named one, and that leaving +// out its earlier images didn't bring it under. +func overCap(res *http.Response, errBody []byte, p provider.Provider, size, n, imgs int) *http.Response { + said := provider.APIError(errBody, http.StatusText(res.StatusCode)) + limit := "what " + p.Name + " takes in one request" + if n > 0 { + limit = fmt.Sprintf("the %s %s takes in one request", mb(n), p.Name) + } + why := "it has no earlier image to leave out" + if imgs > 0 { + why = "even with its earlier images left out; the latest message's images and every text, tool output included, are kept" + } + msg := fmt.Sprintf("%s (HTTP %d: the request is %s, over %s, %s)", said, res.StatusCode, mb(size), limit, why) + out, _ := json.Marshal(map[string]any{"type": "error", "error": map[string]any{"type": "request_too_large", "message": msg}}) + h := res.Header.Clone() + h.Set("Content-Type", "application/json") + h.Del("Content-Length") + h.Del("Content-Encoding") + return &http.Response{ + Status: "413 Request Entity Too Large", StatusCode: http.StatusRequestEntityTooLarge, + Proto: res.Proto, ProtoMajor: res.ProtoMajor, ProtoMinor: res.ProtoMinor, + Header: h, Body: io.NopCloser(bytes.NewReader(out)), ContentLength: int64(len(out)), Request: res.Request, + } +} + +// imageLeftOut is what stands where an image was left out. It goes to the +// vendor, so it names neither magpie nor the vendor. +const imageLeftOut = "[An earlier image was left out here to keep this request under its size limit.]" + +// capImage is one image of a request's history: where its JSON object sits +// and what it is replaced with. +type capImage struct { + at, end int + with string +} + +// historyOf is where a protocol's conversation sits in its body. +func historyOf(to provider.Protocol) string { + switch to { + case provider.Responses: + return "input" + case provider.Gemini: + return "contents" + } + return "messages" +} + +// imageWith is the part an image of the protocol is replaced with, "" +// when part is no image. +func imageWith(to provider.Protocol, part gjson.Result) string { + text, _ := json.Marshal(imageLeftOut) + switch to { + case provider.Responses: + if part.Get("type").String() == "input_image" { + return `{"type":"input_text","text":` + string(text) + `}` + } + case provider.Chat: + if t := part.Get("type").String(); t == "image_url" || t == "input_image" { + return `{"type":"text","text":` + string(text) + `}` + } + case provider.Anthropic: + if part.Get("type").String() == "image" { + return `{"type":"text","text":` + string(text) + `}` + } + case provider.Gemini: + for _, k := range []string{"inlineData", "inline_data"} { + d := part.Get(k) + mt := d.Get("mimeType").String() + d.Get("mime_type").String() + if d.IsObject() && strings.HasPrefix(mt, "image/") { + return `{"text":` + string(text) + `}` + } + } + } + return "" +} + +// latestUser is the index of the history's latest user message: one the +// user wrote, not a tool's results (Anthropic's tool_result blocks, +// Gemini's functionResponse parts, Responses' function_call_output), nor +// Codex's compaction prompt that codexCompact puts last. -1 for none. +func latestUser(to provider.Protocol, items []gjson.Result) int { + for i := len(items) - 1; i >= 0; i-- { + it := items[i] + if it.Get("role").String() != "user" { + continue + } + if to == provider.Responses && it.Get("type").Exists() && it.Get("type").String() != "message" { + continue + } + content := it.Get("content") + if to == provider.Gemini { + content = it.Get("parts") + } + said, own := "", !content.IsArray() + if !content.IsArray() { + said = content.String() + } + content.ForEach(func(_, part gjson.Result) bool { + switch { + case part.Get("type").String() == "tool_result" || part.Get("functionResponse").Exists() || part.Get("function_response").Exists(): + default: + own = true + said += part.Get("text").String() + } + return true + }) + if own && strings.TrimSpace(said) != strings.TrimSpace(codexCompactPrompt) { + return i + } + } + return -1 +} + +// historyImages are the images of body's history, oldest first, that may +// be left out: inline ones (of 1 KB or more, which a link never is), not +// the latest user message's. +func historyImages(to provider.Protocol, body []byte) []capImage { + var items []gjson.Result + getIn(body, historyOf(to)).ForEach(func(_, it gjson.Result) bool { + items = append(items, it) + return true + }) + keep := latestUser(to, items) + var out []capImage + var walk func(v gjson.Result, depth int) + walk = func(v gjson.Result, depth int) { + if depth > 6 || !v.IsObject() && !v.IsArray() { + return + } + if v.IsObject() { + if with := imageWith(to, v); with != "" { + end := v.Index + len(v.Raw) + if len(v.Raw) >= 1<<10 && v.Index > 0 && end <= len(body) && string(body[v.Index:end]) == v.Raw { + out = append(out, capImage{at: v.Index, end: end, with: with}) + } + return + } + } + v.ForEach(func(_, c gjson.Result) bool { + walk(c, depth+1) + return true + }) + } + for i, it := range items { + if i != keep { + walk(it, 0) + } + } + return out +} + +// images counts what historyImages finds. +func images(to provider.Protocol, body []byte) int { return len(historyImages(to, body)) } + +// withoutOldImages is body under most bytes with the fewest of its oldest +// history images left out, each replaced by imageLeftOut; the rest of it +// byte for byte as it came. ok is false, and body as it came, when +// leaving every one out doesn't bring it under. +func withoutOldImages(to provider.Protocol, body []byte, most int) (out []byte, left int, ok bool) { + if len(body) <= most { + return body, 0, true + } + imgs := historyImages(to, body) + need, n := len(body)-most, 0 + for n < len(imgs) && need > 0 { + need -= imgs[n].end - imgs[n].at - len(imgs[n].with) + n++ + } + if need > 0 { + return body, 0, false + } + var b bytes.Buffer + b.Grow(len(body)) + last := 0 + for _, im := range imgs[:n] { + b.Write(body[last:im.at]) + b.WriteString(im.with) + last = im.end + } + b.Write(body[last:]) + return b.Bytes(), n, true +} diff --git a/internal/gateway/body_cap_test.go b/internal/gateway/body_cap_test.go new file mode 100644 index 000000000..eaac955f8 --- /dev/null +++ b/internal/gateway/body_cap_test.go @@ -0,0 +1,257 @@ +package gateway + +import ( + "fmt" + "io" + "net/http" + "net/http/httptest" + "strings" + "testing" + + "github.com/yetone/magpie/internal/provider" +) + +// commandCodeCap is Command Code's refusal of a Codex session's +// compaction (EDwinpzy on Discord, v0.1.2605, Codex Desktop on Windows, +// auto/deepseek-v4.1-flash): the history held many screenshots, and the +// summary request was over the vendor's byte cap. It came under a status +// of its own, not 413. +const commandCodeCap = `{"error":{"message":"Request body is 40.1 MB, over the 32 MB limit for one request (33554432 bytes)","type":"commandcode_error","code":400}}` + +const commandCodeMost = 32 << 20 + +// screenshot is a ~2 MB screenshot's data URL, its n in it so each is +// told apart. +func screenshot(n int) string { + return fmt.Sprintf("data:image/png;base64,SHOT%02d", n) + strings.Repeat("iVBORw0KGgo", 190_000) +} + +// screenshotSession is the reporter's shape: a Codex session of twenty +// screenshots, ~42 MB, each read by a tool (view_image's output) or +// pasted into a user message, then the latest user message with a +// screenshot of its own. compact ends it in Codex's compaction trigger. +func screenshotSession(compact bool) string { + var b strings.Builder + b.WriteString(`{"model":"fake/m1","stream":true,"store":false,"prompt_cache_key":"thread-shots","input":[`) + for i := range 19 { + if i%2 == 0 { + fmt.Fprintf(&b, `{"type":"message","role":"user","content":[{"type":"input_text","text":"look at screen %d"},{"type":"input_image","image_url":"%s"}]},`, i, screenshot(i)) + continue + } + fmt.Fprintf(&b, `{"type":"function_call","call_id":"call_%d","name":"view_image","arguments":"{\"path\":\"shot%d.png\"}"},`, i, i) + fmt.Fprintf(&b, `{"type":"function_call_output","call_id":"call_%d","output":[{"type":"input_text","text":"tool output %d kept"},{"type":"input_image","image_url":"%s"}]},`, i, i, screenshot(i)) + fmt.Fprintf(&b, `{"type":"message","role":"assistant","content":[{"type":"output_text","text":"seen %d"}]},`, i) + } + fmt.Fprintf(&b, `{"type":"message","role":"user","content":[{"type":"input_text","text":"the latest ask"},{"type":"input_image","image_url":"%s"}]}`, screenshot(19)) + if compact { + b.WriteString(`,{"type":"compaction_trigger"}`) + } + b.WriteString(`]}`) + return b.String() +} + +// postResponses posts body to the gateway's /v1/responses as Codex. +func postResponses(t *testing.T, s *Server, body string) (int, string) { + t.Helper() + gw := httptest.NewServer(s.Handler()) + t.Cleanup(gw.Close) + req, _ := http.NewRequest("POST", gw.URL+"/v1/responses", strings.NewReader(body)) + req.Header.Set("Content-Type", "application/json") + req.Header.Set("User-Agent", codexUA) + resp, err := http.DefaultClient.Do(req) + if err != nil { + t.Fatal(err) + } + defer resp.Body.Close() + b, _ := io.ReadAll(resp.Body) + return resp.StatusCode, string(b) +} + +// underCap checks a request sent after the cap was learned: under it, the +// oldest screenshots left out with the marker, the latest user message's +// screenshot and every text kept. +func underCap(t *testing.T, sent []byte) { + t.Helper() + s := string(sent) + if len(sent) > commandCodeMost*3/4 { + t.Errorf("sent %d bytes, over three quarters of the cap", len(sent)) + } + if strings.Contains(s, "SHOT00") || !strings.Contains(s, imageLeftOut) { + t.Error("the oldest screenshot wasn't left out with the marker") + } + if !strings.Contains(s, "SHOT19") { + t.Error("the latest user message's screenshot was left out") + } + for i := range 19 { + want := fmt.Sprintf("look at screen %d", i) + if i%2 == 1 { + want = fmt.Sprintf("tool output %d kept", i) + } + if !strings.Contains(s, want) { + t.Errorf("text %q is gone", want) + } + } + if strings.Contains(s, "This is the conversation so far") { + t.Error("asked as text, not as the conversation with its later images") + } +} + +// Codex's compaction of a session over the vendor's byte cap was refused +// every time, three times, and then held for five minutes by the guard; +// the same oversized request again after that. Now the request is asked +// again with its oldest screenshots left out, and Codex gets the model's +// summary. +func TestCompactionOverByteCapLeavesOutOldImages(t *testing.T) { + for _, proto := range []provider.Protocol{provider.Responses, provider.Chat} { + t.Run(string(proto), func(t *testing.T) { + up := &capped{proto: proto, most: commandCodeMost, status: 400, ctype: "application/json", body: commandCodeCap} + cappedOn(t, up) + code, body := codexPost(t, screenshotSession(true)) + if code != 200 { + t.Fatalf("Codex's compaction failed: %d %.400s", code, body) + } + if got := compactedText(t, body); got != "SUMMARY" { + t.Fatalf("summary %q", got) + } + calls := up.calls() + if len(calls) != 2 || len(calls[0]) <= commandCodeMost { + t.Fatalf("asked %d times (first %d bytes)", len(calls), len(calls[0])) + } + underCap(t, calls[1]) + }) + } +} + +// A turn of the same session is fitted as its compaction is, and the next +// turn to the same provider goes fitted at once: the cap is learned. +func TestTurnOverByteCapLeavesOutOldImages(t *testing.T) { + fresh(t) + up := &capped{proto: provider.Responses, most: commandCodeMost, status: 400, ctype: "application/json", body: commandCodeCap} + cappedOn(t, up) + s := New() + code, body := postResponses(t, s, screenshotSession(false)) + if code != 200 || !strings.Contains(body, "SUMMARY") { + t.Fatalf("the turn failed: %d %.400s", code, body) + } + calls := up.calls() + if len(calls) != 2 { + t.Fatalf("asked %d times", len(calls)) + } + underCap(t, calls[1]) + code, body = postResponses(t, s, screenshotSession(false)) + if code != 200 || !strings.Contains(body, "SUMMARY") { + t.Fatalf("the next turn failed: %d %.400s", code, body) + } + if calls = up.calls(); len(calls) != 3 { + t.Fatalf("the next turn was asked %d times, not once fitted", len(calls)-2) + } + underCap(t, calls[2]) +} + +// When the latest user message alone is over the cap there is nothing to +// leave out: the same body isn't sent again, and Codex is told it is a +// byte cap (context_length_exceeded, its cue to compact), with the size +// and the cap; another client gets a 413 saying so. +func TestOverByteCapNothingToLeaveOut(t *testing.T) { + var b strings.Builder + b.WriteString(`{"model":"fake/m1","stream":true,"input":[{"type":"message","role":"user","content":[{"type":"input_text","text":"all of these"}`) + for i := range 20 { + fmt.Fprintf(&b, `,{"type":"input_image","image_url":"%s"}`, screenshot(i)) + } + b.WriteString(`]}]}`) + fresh(t) + up := &capped{proto: provider.Responses, most: commandCodeMost, status: 400, ctype: "application/json", body: commandCodeCap} + cappedOn(t, up) + code, body := postResponses(t, New(), b.String()) + if code != 200 || failedCode(body) != "context_length_exceeded" { + t.Fatalf("Codex wasn't told to compact: %d %.600s", code, body) + } + for _, want := range []string{"over the 32 MB limit", "over the 32.0 MB 1017dp takes in one request", "no earlier image"} { + if !strings.Contains(body, want) { + t.Errorf("Codex's error lacks %q: %.600s", want, body) + } + } + if n := len(up.calls()); n != 1 { + t.Fatalf("the same body was sent %d times", n) + } +} + +// A plain refusal of a large request, a rate limit, or the model's window +// full is not a byte cap, and nothing is left out for it. +func TestByteCapRefusal(t *testing.T) { + for _, c := range []struct { + status int + body string + want bool + }{ + {400, commandCodeCap, true}, + {500, commandCodeCap, true}, + {413, nginx413, true}, + {413, deepseekBodyCap, true}, + {413, `{"type":"error","error":{"type":"request_too_large","message":"Request exceeds the maximum size"}}`, true}, + {400, deepseekOverflow, false}, + {429, `{"error":{"message":"Request too large for gpt-4o on tokens per min (TPM): Limit 30000"}}`, false}, + {400, `{"error":{"message":"Invalid tool schema"}}`, false}, + {401, commandCodeCap, false}, + } { + if got := byteCapRefusal(c.status, []byte(c.body)); got != c.want { + t.Errorf("%d %.60s: %v", c.status, c.body, got) + } + } + if n := statedCap([]byte(commandCodeCap), 42<<20); n != 32<<20 { + t.Errorf("stated cap %d", n) + } + if n := statedCap([]byte(deepseekBodyCap), 42<<20); n != 0 { + t.Errorf("stated cap %d of none", n) + } +} + +// Each protocol's images are left out where it keeps them, the latest +// user message's kept and the rest of the body as it came. +func TestWithoutOldImagesEachProtocol(t *testing.T) { + img := strings.Repeat("A", 4096) + for _, c := range []struct { + to provider.Protocol + body string + }{ + {provider.Chat, `{"messages":[{"role":"user","content":[{"type":"image_url","image_url":{"url":"data:image/png;base64,OLD` + img + `"}}]},{"role":"tool","tool_call_id":"c","content":[{"type":"text","text":"tool text"},{"type":"image_url","image_url":{"url":"data:image/png;base64,MID` + img + `"}}]},{"role":"user","content":[{"type":"text","text":"now"},{"type":"image_url","image_url":{"url":"data:image/png;base64,NEW` + img + `"}}]}]}`}, + {provider.Anthropic, `{"messages":[{"role":"user","content":[{"type":"image","source":{"type":"base64","media_type":"image/png","data":"OLD` + img + `"}}]},{"role":"user","content":[{"type":"tool_result","tool_use_id":"t","content":[{"type":"text","text":"tool text"},{"type":"image","source":{"type":"base64","media_type":"image/png","data":"MID` + img + `"}}]}]},{"role":"user","content":[{"type":"text","text":"now"},{"type":"image","source":{"type":"base64","media_type":"image/png","data":"NEW` + img + `"}}]}]}`}, + {provider.Gemini, `{"contents":[{"role":"user","parts":[{"inlineData":{"mimeType":"image/png","data":"OLD` + img + `"}}]},{"role":"user","parts":[{"functionResponse":{"name":"f","response":{"text":"tool text"}}},{"inlineData":{"mimeType":"image/png","data":"MID` + img + `"}}]},{"role":"user","parts":[{"text":"now"},{"inlineData":{"mimeType":"image/png","data":"NEW` + img + `"}}]}]}`}, + } { + t.Run(string(c.to), func(t *testing.T) { + out, left, ok := withoutOldImages(c.to, []byte(c.body), len(c.body)-6000) + s := string(out) + if !ok || left != 2 || strings.Contains(s, "OLD") || strings.Contains(s, "MID") || !strings.Contains(s, "NEW") || !strings.Contains(s, "tool text") || strings.Count(s, imageLeftOut) != 2 { + t.Fatalf("ok %v, %d left out: %.300s", ok, left, s) + } + if _, _, ok := withoutOldImages(c.to, []byte(c.body), 4000); ok { + t.Fatal("fitted under what the latest message alone holds") + } + }) + } +} + +// A provider that refuses the summary request however small its images +// make it: asked smaller three times, then said as a 413, so the +// compaction is asked as text and then made without a model, not sent +// again into the compaction guard's hold. +func TestCompactionOverByteCapEveryTime(t *testing.T) { + up := &capped{proto: provider.Responses, most: 0, status: 400, ctype: "application/json", body: commandCodeCap} + cappedOn(t, up) + code, body := codexPost(t, screenshotSession(true)) + if code != 200 { + t.Fatalf("Codex's compaction failed: %d %.400s", code, body) + } + if got := compactedText(t, body); !strings.Contains(got, "the latest ask") || strings.Contains(got, "iVBORw0KGgo") { + t.Fatalf("local summary: %.300s", got) + } + calls := up.calls() + if len(calls) > 6 { + t.Fatalf("asked %d times", len(calls)) + } + for i := 1; i < 4 && i < len(calls); i++ { + if len(calls[i]) >= len(calls[i-1]) { + t.Fatalf("ask %d (%d bytes) no smaller than the one before (%d)", i, len(calls[i]), len(calls[i-1])) + } + } +} diff --git a/internal/gateway/gateway.go b/internal/gateway/gateway.go index 188f357ed..89830e606 100644 --- a/internal/gateway/gateway.go +++ b/internal/gateway/gateway.go @@ -484,6 +484,9 @@ type Server struct { // get in a row, for a compaction that keeps failing to stop being // asked (codex_compact_guard.go, #2274) compactFails compactFails + // bodyCaps are the byte caps providers refused a request over + // (body_cap.go) + bodyCaps bodyCaps // codexTurns is the model each Codex last had a turn of its own // answered on, by caller (codexMemoryStandIn) codexTurns sync.Map @@ -4849,6 +4852,11 @@ func (s *Server) forward(ctx context.Context, p provider.Provider, to provider.P } }() res, err = s.forwardOnce(ctx, p, to, path, body, in) + if err == nil && res.StatusCode >= 400 { + // a body over the provider's byte cap: asked again with its + // oldest images left out, or said as a 413 (body_cap.go) + res, err = s.refitOverCap(ctx, p, to, path, body, in, res) + } if err == nil && mantleRoutes(p, to) { res, err = s.mantleReroute(ctx, p, to, path, body, in, res) } @@ -4915,6 +4923,9 @@ func (s *Server) forwardOnce(ctx context.Context, p provider.Provider, to provid body = kimiLockedSampling(p, to, body) body = clinePin(p, to, body) body = codexImagesFit(p, to, body) + // under the byte cap the provider refused a larger request over, + // its oldest images left out (body_cap.go) + body = s.withinCap(p, to, path, body) if to == provider.Responses { // whatever the route, Claude's blocks never reach a Responses API body = withoutClaudeSeals(body)