diff --git a/docs/subsystems/gateway-routing.md b/docs/subsystems/gateway-routing.md index eb9620969..7c5b41d94 100644 --- a/docs/subsystems/gateway-routing.md +++ b/docs/subsystems/gateway-routing.md @@ -186,6 +186,7 @@ recorded as a prediction failure (`noPrediction`). - A request whose key is a Claude sign-in (`claudeSignIn`: `Authorization: Bearer sk-ant-oat…`, Claude Code signed in to claude.ai with magpie as its base URL) is never told a 401, nor a 403 saying "OAuth token has been revoked". magpie never passes that sign-in on, so such an answer is a provider refusing magpie's credential, or one of magpie's own Claude accounts lapsing; told it, Claude Code renews its own sign-in before each of its retries (ten for one request) and then asks to `/login`. Any error whose message mentions x-api-key, whatever its status, Claude Code tells as "Not logged in · Please run /login" too. It is told as a 502 in magpie's words, an `api_error` saying " refused magpie's credential (HTTP 401): …" with x-api-key said as "API key", and any other error such a request is told keeps its status with x-api-key said as "API key", as does a stream's error after its 200 (`keepsSignIn`, `claude_signin.go`). Recent calls and the usage log keep the provider's status and message. Any other 403, and a request with magpie's key or an API key, is answered as before. The sign-in's beta (`oauth-…` in `anthropic-beta`) isn't passed on either (`askedBetas`), so a provider gets the request as Claude Code with magpie's key sends it; a provider's own `header.anthropic-beta` still goes. - A 2xx that can't be an API's answer is the 502 it stands for (`notAnAPIReply`, #1012): a web page (`text/html`, or a body that begins as one: a sign-in page, Cloudflare's challenge), a body with nothing in it, or one sent as JSON that doesn't begin as JSON. Every upstream request goes through it (`forwardOnce`, and the built-in clients' own: the ChatGPT backend's `/responses`), so it fails over, rests and is logged as a 502 does, its reason naming the page's title. - 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`. - 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`). 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 reply passed through in its own protocol isn't read this way. diff --git a/internal/gateway/gateway.go b/internal/gateway/gateway.go index 10f953228..c60bf8010 100644 --- a/internal/gateway/gateway.go +++ b/internal/gateway/gateway.go @@ -4707,10 +4707,13 @@ func (s *Server) forwardOnce(ctx context.Context, p provider.Provider, to provid } // Cline's whole replies come in {success, data}; a web page or // nothing at all, served 200, is the 502 it stands for (#1012) + // OpenCode's gateway refusing a request before the model was asked, + // a 400 whose body is no error at all (#3740), is the 502 such a + // fault of a moment stands for // Zhipu's and Z.ai's Responses API refuses a key 200 in the platform's // envelope: the 401 (or 429 …) it stands for, so the next key or // member is asked and the agent told why (@xanahopper on X) - res = notAnAPIReply(clineUnwrapped(p, provider.ZhipuEnveloped(req, res)), "") + res = notAnAPIReply(clineUnwrapped(p, provider.ZhipuEnveloped(req, openCodeBareRefusal(req, res))), "") if p.Account != nil && p.Account.Agent == "codex" { // a large request ChatGPT closed the connection on: asked again, // nobody resting for it, and said what may help (#1628) diff --git a/internal/gateway/opencode_bare400_test.go b/internal/gateway/opencode_bare400_test.go new file mode 100644 index 000000000..8456ff55b --- /dev/null +++ b/internal/gateway/opencode_bare400_test.go @@ -0,0 +1,181 @@ +package gateway + +import ( + "io" + "net/http" + "net/http/httptest" + "strings" + "sync" + "testing" + "time" + + "github.com/yetone/magpie/internal/provider" +) + +// openCodeBareBody is what OpenCode's gateway answered s-leeq's turn-start +// requests (yetone/magpie#3740): a 400 whose body names the model and +// nothing else — no error in it, no reason, no request id. +const openCodeBareBody = `{"model":"deepseek-v4.1-flash"}` + +// openCodeServed is a turn the gateway answers. +const openCodeServed = `{"id":"gw-1","object":"chat.completion","model":"deepseek-v4.1-flash","choices":[{"index":0,"message":{"role":"assistant","content":"ok"},"finish_reason":"stop"}],"usage":{"prompt_tokens":5,"completion_tokens":1,"total_tokens":6}}` + +// bareOpenCode answers the first refusals requests with the bare 400, +// then the rest with served; beyond that, replies[i], the last one after +// that. It counts what it was asked. +type bareOpenCode struct { + mu sync.Mutex + refusals int + replies []bareReply + asked int +} + +// bareReply is an answer of the gateway's, with the status it came as. +type bareReply struct { + code int + body string +} + +func (b *bareOpenCode) RoundTrip(r *http.Request) (*http.Response, error) { + if r.Body != nil { + io.Copy(io.Discard, r.Body) + r.Body.Close() + } + b.mu.Lock() + i := b.asked + b.asked++ + b.mu.Unlock() + var x bareReply + switch { + case i < b.refusals: + x = bareReply{400, openCodeBareBody} + case i-b.refusals < len(b.replies): + x = b.replies[i-b.refusals] + default: + x = b.replies[len(b.replies)-1] + } + return &http.Response{StatusCode: x.code, Status: statusText(x.code), + Header: http.Header{"Content-Type": {"application/json"}}, + Body: io.NopCloser(strings.NewReader(x.body)), Request: r}, nil +} + +func statusText(code int) string { + if code == 200 { + return "200 OK" + } + return "400 Bad Request" +} + +func (b *bareOpenCode) went() int { + b.mu.Lock() + defer b.mu.Unlock() + return b.asked +} + +func openCodeGoOf(t *testing.T, b http.RoundTripper) *Server { + t.Helper() + t.Setenv("XDG_CONFIG_HOME", t.TempDir()) + t.Setenv("XDG_CACHE_HOME", t.TempDir()) + if err := provider.Save(provider.Provider{ID: "ocgo", Name: "OpenCode Go", Key: "k", + Chat: "https://opencode.ai/zen/go/v1", Models: []string{"deepseek-v4.1-flash"}}); err != nil { + t.Fatal(err) + } + pause := retryPause + retryPause = time.Millisecond + t.Cleanup(func() { retryPause = pause }) + s := New() + s.client = &http.Client{Transport: b} + return s +} + +// postChat asks the gateway as s-leeq's client did, on /v1/chat/completions. +func postChat(t *testing.T, s *Server) (int, string) { + t.Helper() + req := httptest.NewRequest("POST", "/v1/chat/completions", + strings.NewReader(`{"model":"ocgo/deepseek-v4.1-flash","messages":[{"role":"user","content":"hello"}]}`)) + rec := httptest.NewRecorder() + s.Handler().ServeHTTP(rec, req) + return rec.Code, rec.Body.String() +} + +// The gateway refusing a turn's first request while the backend it names +// has nothing cached for it yet, then serving the same request (s-leeq's +// timeline: four 400s over 13s, a 200 of the same prompt 28s in) is the +// gateway's fault of a moment, not the request's: it is asked again, and +// the answer reaches the client. Read as the 400 it came as, nothing +// retries it: the caller's turn ended on it (#3740). +func TestOpenCodeGoBare400AskedAgain(t *testing.T) { + b := &bareOpenCode{refusals: 1, replies: []bareReply{{200, openCodeServed}}} + code, out := postChat(t, openCodeGoOf(t, b)) + if code != 200 || !strings.Contains(out, `"ok"`) || b.went() != 2 { + t.Fatalf("%d %q, asked %d times", code, out, b.went()) + } +} + +// A bare 400 the retries don't outlive is the gateway's refusal before +// the model was asked, not the request's own fault — said as the 502 it +// stands for, which a caller retries, not as a 400 that says the request +// was at fault, which nothing retries (#3740). +func TestOpenCodeGoBare400ToldAs502(t *testing.T) { + b := &bareOpenCode{refusals: 99, replies: []bareReply{{200, openCodeServed}}} + code, out := postChat(t, openCodeGoOf(t, b)) + if code != http.StatusBadGateway || !strings.Contains(out, "not an API reply") || strings.Contains(out, `"ok"`) { + t.Fatalf("%d %q", code, out) + } + if b.went() < 3 { // asked again: the passing retries, then patience + t.Fatalf("asked %d times", b.went()) + } +} + +// The bare 400 is about the request (s-leeq: 30 of 214 requests with +// ~246K tokens of tools, none of 420 with under 1K): in a group the next +// member serves it, and the OpenCode key is set aside for nobody, so the +// next request goes to it as before (#3740). +func TestOpenCodeGoBare400RestsNobody(t *testing.T) { + b := &bareOpenCode{refusals: 1, replies: []bareReply{{200, openCodeServed}}} + s := openCodeGoOf(t, b) + other := 0 + s.client = &http.Client{Transport: roundTripFunc(func(r *http.Request) (*http.Response, error) { + if provider.OpenCodeURL(r.URL.String()) { + return b.RoundTrip(r) + } + io.Copy(io.Discard, r.Body) + other++ + return &http.Response{StatusCode: 200, Status: "200 OK", Header: http.Header{"Content-Type": {"application/json"}}, + Body: io.NopCloser(strings.NewReader(openCodeServed)), Request: r}, nil + })} + if err := provider.Save(provider.Provider{ID: "oth", Name: "Other", Key: "k", + Chat: "https://other.example/v1", Models: []string{"deepseek-v4.1-flash"}}); err != nil { + t.Fatal(err) + } + if err := provider.SaveGroup(provider.Group{ID: "ds", Name: "DS", Routing: provider.Ordered, + Members: []string{"ocgo/deepseek-v4.1-flash", "oth/deepseek-v4.1-flash"}}); err != nil { + t.Fatal(err) + } + ask := func(say string) int { + req := httptest.NewRequest("POST", "/v1/chat/completions", + strings.NewReader(`{"model":"ds","messages":[{"role":"user","content":"`+say+`"}]}`)) + rec := httptest.NewRecorder() + s.Handler().ServeHTTP(rec, req) + return rec.Code + } + if code := ask("the big one"); code != 200 || b.went() != 1 || other != 1 { + t.Fatalf("first: %d, OpenCode asked %d, the other %d", code, b.went(), other) + } + if code := ask("a small one"); code != 200 || b.went() != 2 || other != 1 { + t.Fatalf("second: %d, OpenCode asked %d, the other %d: the key rested for a bare 400", code, b.went(), other) + } +} + +// A 400 that names anything — here the session OpenCode answers a request +// without — is an error, and goes to the caller as it came. +func TestOpenCodeGoError400Untouched(t *testing.T) { + b := &bareOpenCode{replies: []bareReply{{400, openCodeMissing}}} + code, out := postChat(t, openCodeGoOf(t, b)) + if code != http.StatusBadRequest || !strings.Contains(out, "x-opencode-session") { + t.Fatalf("%d %q", code, out) + } + if b.went() != 1 { + t.Fatalf("asked %d times", b.went()) + } +} diff --git a/internal/gateway/opencode_session.go b/internal/gateway/opencode_session.go index 465415e62..882622f4b 100644 --- a/internal/gateway/opencode_session.go +++ b/internal/gateway/opencode_session.go @@ -1,6 +1,9 @@ package gateway import ( + "bytes" + "encoding/json" + "io" "log" "net/http" "slices" @@ -61,3 +64,46 @@ func logOpenCodeRefusal(p provider.Provider, req *http.Request, status int) { log.Printf("opencode: %s answered %d to %s %s%s; x-opencode-session %s; headers sent: %s", p.ID, status, req.Method, req.URL.Host, req.URL.Path, session, strings.Join(names, ", ")) } + +// errorKeys are the fields any error an API answers carries, in its own +// body or in an error object of it: a body none of them name says nothing +// of why. +var errorKeys = []string{"error", "message", "msg", "code", "type", "param", "detail", "reason", "description"} + +// openCodeBare is said in the 502 openCodeBareRefusal makes of a bare 400, +// for restAfterMarked to rest nobody for it. +const openCodeBare = "which is no error, not an API reply" + +// openCodeBareRefusal is res as the 502 it stands for, when OpenCode's +// gateway answers a request with a 400 whose body is no error at all: +// {"model":"deepseek-v4.1-flash"}, the model's name and nothing else +// (#3740, s-leeq), with nothing in or out and no reply id. The same +// request is answered some seconds later (s-leeq's timelines: four to six +// 400s over 13s to 25s, then a 200 of the same prompt), so it is read as +// the 502 such a failure is: 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. It is tied to the request +// (in s-leeq's day, 30 of 214 requests carrying ~246K tokens of tools +// failed so and none of 420 carrying under 1K), so nobody rests for it +// (restAfterMarked): the key goes on serving the requests it serves. A +// 400 that names anything, as the missing x-opencode-session refusal +// does, goes on as it came, as does a body that isn't a JSON object. +func openCodeBareRefusal(req *http.Request, res *http.Response) *http.Response { + if res == nil || res.StatusCode != http.StatusBadRequest || res.Body == nil || + req == nil || !provider.OpenCodeURL(req.URL.String()) { + return res + } + b, _ := io.ReadAll(io.LimitReader(res.Body, 64<<10)) + // what wasn't read is read after what was: a body is never cut + res.Body = readCloser{io.MultiReader(bytes.NewReader(b), res.Body), res.Body} + var v map[string]any + if len(b) == 64<<10 || json.Unmarshal(bytes.TrimSpace(b), &v) != nil { + return res + } + for _, k := range errorKeys { + if _, ok := v[k]; ok { + return res + } + } + return asBadGateway(res, "", "answered "+res.Status+" with "+clipRunes(strings.TrimSpace(string(b)), 200)+", "+openCodeBare) +} diff --git a/internal/gateway/routing.go b/internal/gateway/routing.go index 322411d3f..38339563c 100644 --- a/internal/gateway/routing.go +++ b/internal/gateway/routing.go @@ -1128,6 +1128,12 @@ func (s *Server) restAfterMarked(c candidate, status int, header http.Header, bo // as soon as the switch is off return Rest{Why: why, Status: status, By: "off", Until: now} } + if status == http.StatusBadGateway && bytes.Contains(body, []byte(openCodeBare)) { + // OpenCode's bare 400 (openCodeBareRefusal, #3740) is about the + // request, not the key: the key's other requests go through, so + // none is set aside and the failure counts nowhere + return Rest{Why: why, Status: status, By: "off", Until: now} + } if status == http.StatusBadRequest || status == http.StatusForbidden { // a 403 too: Factory's usage policy check refuses at 403 // (content_policy_rejected), which failureOf alone reads as the