diff --git a/docs/subsystems/gateway-routing.md b/docs/subsystems/gateway-routing.md index a4363e3ac..355a2c5fe 100644 --- a/docs/subsystems/gateway-routing.md +++ b/docs/subsystems/gateway-routing.md @@ -202,6 +202,7 @@ recorded as a prediction failure (`noPrediction`). - 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 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 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)). - An error that reaches the agent in a stream already begun can't carry its status, so `streamError` says it in the words (`saysPassing`, #2372, zminds): for a status that may pass (408, 429, 5xx) whose text names none of the words a text-judging agent retries on (Pi decides by its `errorMessage` alone), it appends `(: you can retry your request)`; a request's own fault (400, 401, 404 …) and a text that already says so are left as they were. `TestStreamErrorSaysItPasses` holds Pi's own lists; `TestGroupLastFailureInStreamSaysItPasses` runs a group whose last member fails after the keepalive. A 413 byte cap in that stream says `request_too_large` in the error text, and Chat and Anthropic name that type, so Pi compacts; Gemini keeps its own status shape (`TestStreamedByteCapSaysRequestTooLargeToPi`, `TestStreamErrorByteCapInEveryShape`). Responses' `response.failed` code for it is `context_length_exceeded`, the one code Codex compacts on: with `server_error` it sent the same body five more times ("reconnecting 5/5"), each refused, and never compacted (celestial_eagle_99230 on Discord, an nginx 413 page in front of a DeepSeek model; `TestCodexByteCapInStreamCompacts`). An overload told so (a 529, or a 5xx whose words say overloaded, `saidOverloaded`) is `server_is_overloaded` there, as the ChatGPT backend says one in a stream: Codex shows the model at capacity and stops, where `server_error` had it reconnect five times, each turn asked again by magpie, and end on the last error alone (wjh66 on Discord; `TestCodexKeptAliveOverloadSaysServerIsOverloaded`). Codex reads a 413, or a 400 `context_length_exceeded`, told by HTTP status as an unexpected status or an invalid request and compacts on neither, so when Codex (`fromCodex`) asked for a stream, a byte cap or an overflow is told in a stream even before one began (`keptAlive.compactsInStream`, `failTo`; `TestCodexByteCapBeforeStreamCompacts`). Another client keeps its status (`TestByteCapBeforeStreamStaysStatusForOthers`), and so does magpie's own summary ask for a compaction (`keptAlive.whole`, set for `wantsWhole`), which is never sent a 200 or a keepalive either: `codexCompact` reads a 413 as its cue to ask the conversation as text and then compact without a model, and told in a stream it failed 502 instead (#4862, `TestCompactionOverByteCapEveryTime`, `TestCompactionOverByteCapSlowFitting`). Nobody rests for either. Wherever the protocol says a model with the error (Chat's first chunk, Anthropic's `message_start`, Responses' `response.created` and the events after it), it is the model the agent asked for, as `serve` has it, an effort on it kept (`keptAlive.model`; on Codex's own sign-in, the one Codex wrote) (#3728, jilen: with `"model":""` fx took Chat's first chunk for a broken one and stopped there; `TestStreamErrorNamesTheModel`, `TestKeptAliveChatErrorNamesTheModel`, `TestKeptAliveChatOnCodexErrorNamesTheModel`, `TestKeptAliveCodexErrorNamesTheModel`). An error after a reply that already went, a loop cut's, still starts a message of its own after the vendor's, under a new id and no model (#3792). - Claude's, GPT's, Gemini's and DeepSeek's reasoning is held (`refusesAfterThinking`, up to `holdThinking`, 4 minutes) so that a refusal after it goes to the next candidate unseen (#248). It is held only while one could: on the last candidate a refusal isn't asked again, so their reasoning streams as it comes there, and a refusal after it reaches the agent as the vendor's own. Held there, a lone relay's Claude or GPT showed Claude Code its thinking all at once with the text, and Codex none until then (iTianbao on X). Gemini's streams there too: a reply that only reasoned is asked again in place by `streamTranslated`, the reasoning the agent has kept and the next try's after it (#667), so holding it only kept Codex on a Gemini model with nothing at all, not even `response.created`, for the whole of its thinking (LuckymanJC on Discord; `TestThinkingStreamsWithNoOneElse`'s gemini cases). DeepSeek's is held since plugins #540: deepseek-v4.1-flash on WorkBuddy reasoned, then ended `content_filter` with nothing said (the WorkBuddy plugin takes the filter's canned "Sorry, I can't respond to this question." out of such a reply), and with its reasoning already through, the group's next member was never asked (`TestDeepSeekRefusalAfterThinkingFailsOver`). Where a refusal after the reasoning can still go to the next candidate in the same stream (`handsOver`: the agent asked for a Chat, Anthropic or Responses stream and another candidate is left; [`refusal_handover.go`](../../internal/gateway/refusal_handover.go)), a member whose thinking has gone on to an answer `thoughtCleanMost` (3) times running has its reasoning as it comes (`holdsThinking`), and a refusal after it, nothing yet said, is handed over, the next candidate's stream following as the same reply: DeepSeek's whether or not it can be handed over (#4512), Claude's, GPT's and Gemini's only where it can, so their refusal never reaches the agent while another could answer. Held whatever the member answered, a group of one model's accounts showed Claude Code its Claude's thinking only with its text, all at once, and never its `thinking with effort` (#4166). A retryable error after the reasoning, nothing yet said (Anthropic's `overloaded_error` mid-stream), is handed over the same way (`passOver`), its status and words failing the try as a held one's would, so trusting a member doesn't cost the group its failover; one the next candidate wouldn't be asked for (a request at fault) is the agent's (`TestTrustedThinkingFailsOverOnEveryPath`: Claude, GPT and Gemini members, refused, overloaded or invalid, to Claude Code, a Chat client and Codex; `TestClaudeTrustedThinkingErrorFailsOver`). A refusal takes the trust back (`thoughtRefused`), and the member's next reasoning is held again. `TestDeepSeekThinkingStreamsOnceTrusted`, `TestDeepSeekRefusalHoldsATrustedMemberAgain`, `TestClaudeThinkingStreamsOnceTrusted` and `TestClaudeTrustedThinkingStreamsThroughGroup` in [`thinking_streams_test.go`](../../internal/gateway/thinking_streams_test.go). Any other model's reasoning (GLM's, Kimi's…) is never held. diff --git a/internal/gateway/continuation.go b/internal/gateway/continuation.go index 80d2cf243..96f7fb705 100644 --- a/internal/gateway/continuation.go +++ b/internal/gateway/continuation.go @@ -571,7 +571,7 @@ func (s *Server) streamTranslated(w http.ResponseWriter, r *http.Request, p prov if turnedAway { u.ErrType = turnedAwayErrType } - return writeVendorError(w, from, res.StatusCode, failed, b), failed + return writeVendorErrorFrom(w, from, actual, p, res, failed, b), failed } } if err == nil && res.StatusCode < 400 { diff --git a/internal/gateway/gateway.go b/internal/gateway/gateway.go index 7bc7ed0b9..550fb26e7 100644 --- a/internal/gateway/gateway.go +++ b/internal/gateway/gateway.go @@ -6643,7 +6643,7 @@ func (s *Server) passthrough(w http.ResponseWriter, r *http.Request, p provider. if codexOutRefusal(p, proto, res.StatusCode, b) { return writeCodexOut(w, res.Header, res.StatusCode, msg, b), msg, true } - return writeVendorError(w, proto, res.StatusCode, msg, b), msg, true + return writeVendorErrorFrom(w, proto, proto, p, res, msg, b), msg, true } if remote != nil && res.Header.Get(KeptTurnHeader) != "" { // the other magpie kept the turn: what it answered is kept here @@ -8425,7 +8425,7 @@ func (s *Server) translate(w http.ResponseWriter, r *http.Request, p provider.Pr if turnedAway { u.ErrType = turnedAwayErrType } - return writeVendorError(w, from, res.StatusCode, msg, b), msg + return writeVendorErrorFrom(w, from, actual, p, res, msg, b), msg } dec := carryReasoning(decoderFor(p, actual, request.Tools), from, actual) rd, sse := eventStream(res) @@ -10033,6 +10033,9 @@ func writeVendorError(w http.ResponseWriter, proto provider.Protocol, status int return writeErrorSaid(w, proto, status, msg, code, param) } +// requestBytesHint is what a 413 is told: a cap on the request's bytes. +const requestBytesHint = "This is a request-body byte limit, not the model's context: compact the conversation (/compact in Codex or Claude Code), or start a new one with a short summary; fewer images or smaller tool results also help." + // writeErrorSaid is writeError with the code and param an OpenAI-shaped // answer names, nil for none. func writeErrorSaid(w http.ResponseWriter, proto provider.Protocol, status int, msg string, code, param any) int { @@ -10067,9 +10070,8 @@ func writeErrorSaid(w http.ResponseWriter, proto provider.Protocol, status int, } } if h, held := w.(*holdWriter); status == http.StatusRequestEntityTooLarge && (!held || !h.hold) { - const hint = "This is a request-body byte limit, not the model's context: compact the conversation (/compact in Codex or Claude Code), or start a new one with a short summary; fewer images or smaller tool results also help." - if !strings.Contains(msg, hint) { - msg += " — " + hint + if !strings.Contains(msg, requestBytesHint) { + msg += " — " + requestBytesHint } } var v any diff --git a/internal/gateway/kept_error.go b/internal/gateway/kept_error.go new file mode 100644 index 000000000..b9be8acfd --- /dev/null +++ b/internal/gateway/kept_error.go @@ -0,0 +1,138 @@ +package gateway + +import ( + "bytes" + "encoding/json" + "net/http" + "strings" + + "github.com/tidwall/gjson" + + "github.com/yetone/magpie/internal/provider" +) + +// errorShape is the family of error bodies an API answers with: Chat's and +// Responses' are OpenAI's {"error":{"message","type","code","param"}}, +// Anthropic's {"type":"error","error":{"type","message"}}, Gemini's +// {"error":{"code","message","status"}}. 0 for one with none of its own. +func errorShape(proto provider.Protocol) int { + switch proto { + case provider.Chat, provider.Responses: + return 1 + case provider.Anthropic: + return 2 + case provider.Gemini: + return 3 + } + return 0 +} + +// writeVendorErrorFrom answers a vendor's error as writeVendorError does, +// but for a vendor that speaks the client's own API (upstream's error +// shape is the client's): the vendor's body goes to the client as it came, +// its status, type, a numeric code and every field magpie doesn't know +// (ne9ko9 on Discord). Only the message is magpie's: the provider's name +// and the vendor's words, with a note of why where magpie has one (an +// account's Explain, a region, the wrong endpoint), a busy relay said so +// (saysBusy) and a 413's hint. A prompt too long for the model is said as +// the client's API says it (tooLong: the status, type and code that make +// the agent compact). Every other byte is the vendor's. A body not in the client's +// shape is rebuilt in it, as before. +func writeVendorErrorFrom(w http.ResponseWriter, proto, upstream provider.Protocol, p provider.Provider, res *http.Response, msg string, body []byte) int { + if status, ok := writeKeptError(w, proto, upstream, p, res, msg, body); ok { + return status + } + return writeVendorError(w, proto, res.StatusCode, msg, body) +} + +// writeKeptError writes the vendor's error body b as writeVendorErrorFrom +// says, false with nothing written when b isn't an error in proto's shape. +func writeKeptError(w http.ResponseWriter, proto, upstream provider.Protocol, p provider.Provider, res *http.Response, msg string, b []byte) (int, bool) { + shape := errorShape(proto) + if shape == 0 || errorShape(upstream) != shape || !json.Valid(b) { + return 0, false + } + said := gjson.GetBytes(b, "error.message") + if said.Type != gjson.String || !gjson.GetBytes(b, "error").IsObject() { + return 0, false + } + status := res.StatusCode + // the message is magpie's: the provider's name, the vendor's words as + // APIError reads them, then any notes (explained, wrongAPINote…), so + // the agent, a describer asking for another model and a sign-in's + // rewording all know which provider said it. + text := msg + if text == "" { + text = provider.APIError(b, res.Status) + } + text = saysBusy(status, text) + out := b + if tooLong(status, text) { + status = http.StatusBadRequest + switch shape { + case 1: + out = setErrorField(out, "type", "invalid_request_error") + out = setErrorField(out, "code", "context_length_exceeded") + case 2: + out = setErrorField(out, "type", "invalid_request_error") + if !strings.Contains(strings.ToLower(text), "prompt is too long") { + text = "prompt is too long: " + text + } + case 3: + out = setErrorField(out, "code", http.StatusBadRequest) + out = setErrorField(out, "status", "INVALID_ARGUMENT") + } + } + if h, held := w.(*holdWriter); status == http.StatusRequestEntityTooLarge && (!held || !h.hold) { + if !strings.Contains(text, requestBytesHint) { + text += " — " + requestBytesHint + } + } + if text != said.String() { + out = setErrorField(out, "message", text) + } + ct := res.Header.Get("Content-Type") + if !strings.Contains(strings.ToLower(ct), "json") { + ct = "application/json" + } + w.Header().Set("Content-Type", ct) + w.WriteHeader(status) + w.Write(out) + return status, true +} + +// setErrorField sets name in b's error object to v, splicing it where the +// field is (or first in the object when it isn't) so every other byte of b +// stays as it was. +func setErrorField(b []byte, name string, v any) []byte { + var enc bytes.Buffer + e := json.NewEncoder(&enc) + e.SetEscapeHTML(false) // a vendor's <, > and & as it wrote them (#260) + if e.Encode(v) != nil { + return b + } + val := bytes.TrimRight(enc.Bytes(), "\n") + if f := gjson.GetBytes(b, "error."+gjson.Escape(name)); f.Exists() && f.Index > 0 { + if f.Raw == string(val) { + return b + } + out := make([]byte, 0, len(b)+len(val)) + out = append(out, b[:f.Index]...) + out = append(out, val...) + return append(out, b[f.Index+len(f.Raw):]...) + } + obj := gjson.GetBytes(b, "error") + if !obj.IsObject() || obj.Index <= 0 { + return b + } + at := obj.Index + strings.IndexByte(obj.Raw, '{') + 1 + key, _ := json.Marshal(name) + field := append(append(append([]byte{}, key...), ':'), val...) + if strings.TrimSpace(obj.Raw[strings.IndexByte(obj.Raw, '{')+1:]) != "}" { + field = append(field, ',') + } + out := make([]byte, 0, len(b)+len(field)) + out = append(out, b[:at]...) + out = append(out, field...) + return append(out, b[at:]...) +} diff --git a/internal/gateway/kept_error_test.go b/internal/gateway/kept_error_test.go new file mode 100644 index 000000000..1a2d9c58e --- /dev/null +++ b/internal/gateway/kept_error_test.go @@ -0,0 +1,93 @@ +package gateway + +import ( + "net/http/httptest" + "strings" + "testing" + + "github.com/tidwall/gjson" + "github.com/yetone/magpie/internal/provider" +) + +// ne9ko9 on Discord: a vendor that speaks the client's own API has its +// error reach the client as it came: its status, its own type, a numeric +// code and the fields magpie knows nothing of, every byte but the message, +// which names the provider. It was rebuilt from the status, with only a +// string code kept. +func TestSameAPIErrorKeptAsSent(t *testing.T) { + for _, c := range []struct { + name, path, req string + proto provider.Protocol + status int + body, want string + }{ + {"chat", "/v1/chat/completions", `{"model":"a/m","messages":[{"role":"user","content":"hi"}]}`, provider.Chat, 400, + `{"error":{"message":"Request rejected by gateway rule (FX-1214)","type":"upstream_rule","code":1214,"param":null,"extra":{"trace":"t-9"}},"request_id":"req-77"}`, + `{"error":{"message":"A: Request rejected by gateway rule (FX-1214)","type":"upstream_rule","code":1214,"param":null,"extra":{"trace":"t-9"}},"request_id":"req-77"}`}, + {"anthropic", "/v1/messages", `{"model":"a/m","max_tokens":10,"messages":[{"role":"user","content":"hi"}]}`, provider.Anthropic, 403, + `{"type":"error","error":{"type":"upstream_rule","message":"Request rejected by gateway rule","code":20031,"details":["region"]},"request_id":"req_01"}`, + `{"type":"error","error":{"type":"upstream_rule","message":"A: Request rejected by gateway rule","code":20031,"details":["region"]},"request_id":"req_01"}`}, + {"responses", "/v1/responses", `{"model":"a/m","input":"hi"}`, provider.Responses, 400, + `{"error":{"message":"Request rejected by gateway rule","type":"upstream_rule","code":1214,"param":"input","extra":true}}`, + `{"error":{"message":"A: Request rejected by gateway rule","type":"upstream_rule","code":1214,"param":"input","extra":true}}`}, + } { + t.Run(c.name, func(t *testing.T) { + fresh(t) + a := &scripted{replies: []reply{{c.status, "", c.body}}} + scriptedOn(t, "a", c.proto, a) + w := httptest.NewRecorder() + New().Handler().ServeHTTP(w, httptest.NewRequest("POST", c.path, strings.NewReader(c.req))) + if w.Code != c.status || w.Body.String() != c.want { + t.Fatalf("the vendor's error was rewritten:\n got %d %s\nwant %d %s", w.Code, w.Body.String(), c.status, c.want) + } + }) + } +} + +// A prompt too long for the model is still said the way the client's API +// says it, so the agent compacts: on the vendor's own body, with only the +// fields that say so changed and every other one kept. +func TestSameAPIOverflowKeepsTheRest(t *testing.T) { + fresh(t) + a := &scripted{replies: []reply{{400, "", `{"error":{"message":"Prompt exceeds max length","code":1261,"type":"zhipu_error","extra":"x"},"request_id":"r1"}`}}} + scriptedOn(t, "a", provider.Chat, a) + w := httptest.NewRecorder() + New().Handler().ServeHTTP(w, httptest.NewRequest("POST", "/v1/chat/completions", strings.NewReader(`{"model":"a/m","messages":[{"role":"user","content":"hi"}]}`))) + b := w.Body.String() + if w.Code != 400 || gjson.Get(b, "error.code").String() != "context_length_exceeded" || gjson.Get(b, "error.type").String() != "invalid_request_error" { + t.Fatalf("overflow not said as Chat says it: %d %s", w.Code, b) + } + if gjson.Get(b, "error.extra").String() != "x" || gjson.Get(b, "request_id").String() != "r1" || gjson.Get(b, "error.message").String() != "A: Prompt exceeds max length" { + t.Fatalf("the vendor's other fields were lost: %s", b) + } +} + +// Another API's error is rebuilt in the client's shape, as before. +func TestOtherAPIErrorRebuilt(t *testing.T) { + fresh(t) + a := &scripted{replies: []reply{{400, "", `{"error":{"message":"Request rejected by gateway rule","type":"upstream_rule","code":1214,"extra":true}}`}}} + scriptedOn(t, "a", provider.Chat, a) + w := httptest.NewRecorder() + New().Handler().ServeHTTP(w, httptest.NewRequest("POST", "/v1/messages", strings.NewReader(`{"model":"a/m","max_tokens":10,"messages":[{"role":"user","content":"hi"}]}`))) + b := w.Body.String() + if w.Code != 400 || gjson.Get(b, "type").String() != "error" || gjson.Get(b, "error.type").String() != "invalid_request_error" || !strings.Contains(gjson.Get(b, "error.message").String(), "Request rejected by gateway rule") { + t.Fatalf("not rebuilt in Anthropic's shape: %d %s", w.Code, b) + } +} + +func TestSetErrorField(t *testing.T) { + for _, c := range []struct { + in, name string + v any + want string + }{ + {`{"error":{"message":"a","code":7}}`, "code", "x", `{"error":{"message":"a","code":"x"}}`}, + {`{"error":{"message":"a"}}`, "type", "t", `{"error":{"type":"t","message":"a"}}`}, + {`{"error":{}}`, "type", "t", `{"error":{"type":"t"}}`}, + {`{"error": { "message":"a