diff --git a/docs/subsystems/gateway-routing.md b/docs/subsystems/gateway-routing.md index c00cbb0d9..d3d08572c 100644 --- a/docs/subsystems/gateway-routing.md +++ b/docs/subsystems/gateway-routing.md @@ -316,6 +316,7 @@ the key's leaves the call as asked, with a log line (`compactRefused`). - 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 goes on for as long as a translated stream's do, `translatedQuietLongest` (30 minutes) with nothing from the vendor, and then the try is ended: the client gets a 504 " sent nothing for …", as its stream's error event when the reply has passed, and nothing is tried again after so long a wait (`holdWriter.endStuck`). Before, the comments stopped at `keepaliveLongest` (5 minutes) and the client met only its own idle timeout: pi's "stream idle timeout after 300000ms" on a relayed Claude (Wing8Aqua on X; `TestQuietClaudeStreamKeptAlivePastFiveMinutes`, `TestQuietClaudeStreamStuckEndsWithAnError`). 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 group member's reply that ends having said nothing at all — no text, no reasoning, no call, in an event that says nothing itself: a Chat `finish_reason` other than `length`, `error` or a filter, Messages' `end_turn`, `stop_sequence` or `tool_use`, a `completed` Responses reply, Gemini's `STOP` — is held as no answer while a member is left (`eventEmptyEnd`, `holdWriter.emptyFails`, 502 `emptyEnded`), so the next member answers and nobody rests; a reply held whole is judged in the one parse `settle` already makes (`readWhole`), and the last member's empty reply, or a model asked alone, goes as it came (#6712: an AI Studio plugin's 200 with a role chunk and `stop`; `TestEmptyStopFailsOverToTheNextMember`, `TestEmptyStopEndsAtTheLastMember`); a 200 that is no reply of the protocol's fails as a translated reply that didn't stream does (502, "… did not stream"), for the next candidate to answer, and the last one's reaches the agent as the stream's error. A held stream that has sent nothing but the frames before a reply (`response.created`, `response.in_progress`, `codex.rate_limits`, pings, an empty part begun, and any event `streamEvent` doesn't know to carry text, reasoning, a call or a reply's end (`replyEvent`), or an item not known that isn't a call or a tool's (`streamPart.said`): `eventLead`; Aliceonly on #1418: an unknown event was taken for content and let a frames-only 200 through, and its `server_is_overloaded` reached Codex with five candidates left) stays held as long as its agent is kept alive, up to `holdLead` (4 minutes, under the 300s Codex waits for an event; `keptQuiet`), so a `server_is_overloaded` that comes after it is a failure the next candidate answers (#1418: let through at 15s, the ChatGPT backend's failure 36s in ended Codex's turn with sub2api, next in the group, never asked). A stream whose agent can't be kept alive (Gemini's) is let through after `holdLongest` (15s), as before. Codex counts only events toward that 300s, not comments, so the bound is the request's, not each try's: once Codex on Responses has heard no event for `agentQuietMost` (4 minutes) since the request began or its last event (`keptAlive.tooQuiet`), the try in hand is let through (`scan`, `keepQuiet`), and no group replan or same-one retry is taken whose pause would end past it (fadenoob on Discord: held tries and replan pauses added up past 300s and Codex reconnected on "idle timeout waiting for SSE"). A translated reply whose upstream stream stops before it said its reply had — an Anthropic one with no stop_reason and no message_stop, a Responses one with no `response.completed`, the same two a relayed one is told by (`sniff.whole`; a Chat stream may end without `[DONE]` and be whole), a Gemini or Code Assist one whose last chunk has no candidate's `finishReason` (`geminiEnds`, #1643: `usageMetadata` is no end, Vertex AI sends it on every chunk; a chunk with no candidate at all is the empty reply's to answer, #667), and a relayed Gemini one told the same way (#1644; it ends in Gemini's own `{"error":{"code":502,…,"status":"UNAVAILABLE"}}` data line from `streamFailure`, `TestGeminiRelayEndedShort`; whatever a relayed stream gets appended, that error or a filled-in `finish_reason`, begins after a blank line, two newlines when the upstream's last write stopped inside a line, so it is an event of its own rather than more of the half-written one, and the half event itself is dropped: a relayed stream holds the line the upstream never ended back, puts it out when the reply ends whole or is gathered (`TestGrokPluginNonStreamLastLineUnended`), and throws it away when a failure is appended in its place, for no client can parse it — pi read "malformed server-sent event JSON" off a stream Z.ai reset mid-line, and died before the error after it; a line whose data parses (its JSON whole, or `[DONE]`) is no half event and goes out before the failure (#2446, #2580, `TestPassthroughStreamCutMidLine`, `TestChatStreamCutMidLineLeavesNoHalfEvent`, `TestChatStreamCutAfterWholeEventKeepsIt`, `TestGeminiCompatFinishAfterPartialLine`), and a Chat one from Gemini's OpenAI-compatible API (`geminiCompat`) with no `finish_reason`, relayed or translated (`saysItsEnd`; Linka on Discord: the upstream hung up between a whole function call and its `finish_reason`, and Pi threw the call away as "Stream ended without finish_reason"; that API counts the usage only once the generation is done, so when the last chunk carried it only the `finish_reason` was lost and it is filled in, `tool_calls` after a call and `stop` otherwise, as a relayed chunk before `[DONE]` or a translated reply's end, and the reply counts as whole (`chatTail`); only one with no usage at its end is a cut, `TestGeminiCompatRelayEndedShort`, `TestGeminiCompatTranslatedEndedShort`) — ends the turn with "the reply ended before it was complete" (`errEndedShort`, `TestResponsesUpstreamEndedShort`, `TestGeminiUpstreamEndedShort`), asked again in place where the upstream goes on from a prefill (`continuation.go`). only one with no usage at its end is a cut, `TestGeminiCompatRelayEndedShort`, `TestGeminiCompatTranslatedEndedShort`), and a Chat one from Command Code's API (`commandCodeHost`), whose slow starts a killed worker ends with no closing chunk at all, relayed (esp32gallery on #2471: 20 of 665 requests in a day, every ledger row a 200 with no stop and no error while the client read "Stream ended without finish_reason"; `TestCommandCodeRelayEndedShort`, `TestCommandCodeTaillessFailsOver`) — ends the turn with "the reply ended before it was complete" (`errEndedShort`, `TestResponsesUpstreamEndedShort`, `TestGeminiUpstreamEndedShort`), asked again in place where the upstream goes on from a prefill (`continuation.go`). A client that asked for no stream is told the same 502 of such a cut (`translate`, `TestNonStreamEndedShort`, `TestGeminiNonStreamEndedShort`), rather than handed what came as its whole reply. One such ending is not a cut: a request capped at a short probe's worth (`cutVoidTokens`, 1024) whose reply spent some of it (thought, said or called something) and then ended cleanly with no end said ended at its length (`endsAtProbeCap`), and goes as a `length` stop, translated whole or streamed, and as a `response.incomplete` at `max_output_tokens` when a Responses plugin's stream is asked whole (`gathered`). Open Design's glm-5.3-flash always thinks, spent a model test's 16 tokens on it and ended after `content_block_stop`, so every plain test of it was this 502, waited out through the patience (plugins#827; `TestProbeCapEndsAtLength`, `TestGatheredProbeCapIncomplete`). A reply asked for more, one that spent nothing, or a Gemini or Code Assist one (Gemini ends every reply with its finishReason, `MAX_TOKENS` included, so one without it was cut: `TestGeminiUpstreamEndedShort` asks for 256) is still the cut. A relayed stream (passthrough to an agent of the same protocol) is still relayed as it came, with no end added (#5736). A translated reply from an Anthropic or Responses upstream that ended but said nothing (no text, call, search or image) and counted no token at all is no reply either, whatever its end says (`repliesCounted`, #2086: an Anthropic-compatible proxy's 200 ended a Codex turn as `response.completed` with no output, no usage and no served model, and Codex didn't ask again). It is the empty reply's to answer (#667): asked again in place, then failed with "an empty reply", streamed or not, for every client (`TestUncountedEmptyReplyFails`, `TestUncountedEmptyReplyFailsEveryClient`). Claude's own empty `end_turn` counts its prompt and stays a whole reply (`TestWellFormedStreamsStillComplete`). A relayed one is read the same way once: a Responses stream whose `response.completed` carries no output and counted no token is no reply either, failed before it is let through, held for the group's next candidate, and nobody rests (#2471, MurmuredVelpro: WorkBuddy AI's account ended Codex's turn completed with `output: []` and all-zero usage three times running, the healthy members never asked; `TestEmptyCompletedFailsOver`). A reply passed through in its own protocol isn't read this way, but for that completed. - A vendor whose API is the client's own (a relayed request, or a translated one whose upstream error shape is the client's: Chat and Responses share OpenAI's) has its JSON error body go to the client as it came (`writeVendorErrorFrom`, ne9ko9 on Discord): its status, its own `type`, a numeric `code`, `param`, `request_id` and every field magpie knows nothing of. Only `error.message` is magpie's: the provider's name before the vendor's words (a describer asking for another model, the Claude sign-in rewording in `claude_signin.go` and the agent read it there), with a note where magpie has one (an account's `Explain`, a region note, the wrong-endpoint note, `saysBusy`, a 413's byte-limit hint). And a prompt too long for the model (`tooLong`) sets only the fields that make the client's agent compact: status 400, and `type`/`code` (OpenAI's `context_length_exceeded`), `type` and the "prompt is too long: " lead (Anthropic's), `code`/`status` (Gemini's), each spliced in place (`setErrorField`) so every other byte stays. A body that isn't JSON, or not in the client's shape, and another API's error are rebuilt in the client's shape (`writeVendorError`) as before. An error status the hold reads as the safety filter's refusal (`policyRefusal`) is still told in magpie's words once no one else answers ([`kept_error_test.go`](../../internal/gateway/kept_error_test.go)). +- What the agent reads of a vendor's error puts the vendor first, so a user can copy it to the vendor as it was said (@gptchan404 on X, [`upstream_said.go`](../../internal/gateway/upstream_said.go)). The first line is the provider's name, then the vendor's own words (`provider.VendorWords`: `APIError`'s reading with none of magpie's hints), then what the vendor named it by, `(HTTP , , request id )`, leaving out any part its words already hold. A plugin's message is its vendor's words, then the plugin's advice after " — " (as `provider.Explain` joins them). Only the part before the dash is the vendor's (`pluginWords`), and the advice goes on magpie's line. magpie's own notes follow on a line of their own, `magpie: …`. This applies to every client protocol, whole and streamed (`upstreamTold` in `writeVendorErrorFrom`), and to a safety-filter refusal no one else answered, whose magpie line is ` refused this request (safety filter: ) via ` (`refusalTold`). Only the agent sees it this way. A try's held reply keeps magpie's reading (`holdWriter.retold`, applied by `retell` as the bytes leave for the agent), because the rest, the rate hold, the retired model, the verify hold and the failover all read the held bytes and `call.Error`, which are unchanged. A held verify answer (`verifyHeld`) is magpie's own, with no vendor asked, and keeps its one-line form ([`upstream_said_test.go`](../../internal/gateway/upstream_said_test.go)). - A reply that said nothing (`emptyReply`, #667) on `emptyAccounts` (2) accounts of one provider's model running is about the request, not the account: the candidates of that model that remain aren't asked (`emptied` in the candidate loop; other providers and the group's other members still are), and nobody rests (vhjjkkhg on X: Alma's Responses turns to Antigravity's Gemini 3.8 Flash went round 8 to 9 accounts over 10+ minutes). `TestEmptyReplyOnTwoAccountsEndsTheRequest` in `internal/gateway/antigravity_empty_bound_test.go`. - A provider of a key whose errors the user leaves to the client (`errors=pass`, `Provider.PassErrors`, set in its editor's Advanced "Errors" menu or with `magpie provider set errors=pass`; `TakesPassErrors` keeps it to a provider of a key, never a signed-in account or a plugin's; ne9ko9 on Discord) is asked once. The candidate loop's `holdWriter` holds nothing for it (`pass := c.p.PassesErrors()` at the hold choke point; only a stream already begun is held), so no retry, wait, re-plan, refusal handover or next member answers for it; `forward` asks once after `dsRetryGone` (magpie's own file ids), `passthrough` and `forwardTranslated` return the first failure without a re-ask in another shape, `streamTranslated` neither continues nor asks again after an empty reply, and `restAfterMarked` rests none of its keys. Its error goes through `passError` (`pass_errors.go`): on the client's own API the vendor's status, Content-Type and body as sent; on another, the client's shape with the vendor's status, type, code (a number too), param and words, nothing inferred (no too-long, busy or 413 words). Retry-After and the rate-limit headers go with it. `TestPassErrorsAskedOnce`, `TestPassErrorsNotInferred`, `TestPassErrorsOtherAPI` in `internal/gateway/pass_errors_test.go`. - A vendor's error keeps its `code` and `param` on its way to an OpenAI-shaped client (`writeVendorError`), where `writeError` used to set both to null: a status error relayed or translated, and a request refused inside a Responses stream. A Responses stream's `error` event or failed response whose error is of type `invalid_request_error` is the request at fault (`requestRefused`, read by its type, not its words): its `Event` carries status 400 and the vendor's error (`Event.Said`), so a client answered whole gets the vendor's 400 with its code and param (the whole-translated path wrote 502 `api_error`), a reply cut by it isn't resumed (`continuation.again`), and a translated stream's error says the vendor's type, code and param (`saidError`), so `holdWriter` reads it as the 400 it is. Before, the hold read magpie's `api_error` as a 502: the same request was sent three times, then to the other accounts, and every one rested (magpie-releases#18: the ChatGPT backend answers `access_programs` naming a program the workspace hasn't got with a 200 stream whose error is `access_program_not_enabled`). Asked once, nobody rests ([`codex_access_programs_test.go`](../../internal/gateway/codex_access_programs_test.go)). diff --git a/internal/gateway/codex_backend.go b/internal/gateway/codex_backend.go index 04347cdae..df1bc03ee 100644 --- a/internal/gateway/codex_backend.go +++ b/internal/gateway/codex_backend.go @@ -4123,9 +4123,15 @@ func lacksEndpoint(status int) bool { // summaryEndedShort is a summary ask answered 502 because the reply // stopped before its end: a translated one serve held whole and found -// cut (errEndedShort, #3526, Edward4226's third shape). +// cut (errEndedShort, #3526, Edward4226's third shape). The words end +// the vendor's line of the error, before what upstreamTold names it by. func summaryEndedShort(rec *recorder) bool { - return rec.status == http.StatusBadGateway && strings.HasSuffix(provider.APIError(rec.body.Bytes(), ""), errEndedShort.Error()) + if rec.status != http.StatusBadGateway { + return false + } + line, _, _ := strings.Cut(provider.APIError(rec.body.Bytes(), ""), magpieSays) + line = strings.TrimSuffix(line, " (HTTP 502)") + return strings.HasSuffix(line, errEndedShort.Error()) } // upstreamFailed is a relay's own word that the provider behind it turned diff --git a/internal/gateway/fallback.go b/internal/gateway/fallback.go index 91380f52c..9c33a4ac2 100644 --- a/internal/gateway/fallback.go +++ b/internal/gateway/fallback.go @@ -2789,6 +2789,11 @@ type holdWriter struct { // one in the same stream (refusalHandover); handedOver says it was over *refusalHandover handedOver bool + + // retold is how the vendor's error the try wrote is told to the + // agent (retell): the held bytes keep magpie's reading of it, which + // the rest, the rate hold and the retired model are read from + retold []retelling } // onLoop sets what is told of a loop before it ends the reply (reask), @@ -2936,7 +2941,10 @@ func (h *holdWriter) Write(b []byte) (int, error) { } if h.passing { h.sent(b) - return h.w.Write(b) + if n, err := h.w.Write(retell(h.retold, b)); err != nil { + return n, err + } + return len(b), nil } n, err := h.held.Write(b) if h.stream && h.failure == 0 { @@ -3734,7 +3742,7 @@ func (h *holdWriter) release() { streamError(h.w, h.alive.proto, h.alive.model, h.failure, who+" "+h.failMsg) case h.status >= 400: // an error status, once the agent has a stream: told as its error - streamError(h.w, h.alive.proto, h.alive.model, h.status, provider.APIError(h.held.Bytes(), http.StatusText(h.status))) + streamError(h.w, h.alive.proto, h.alive.model, h.status, retellText(h.retold, provider.APIError(h.held.Bytes(), http.StatusText(h.status)))) default: // a reply given whole by a vendor that ignored stream:true, // after the agent was kept alive: sent as the stream it asked @@ -3744,7 +3752,7 @@ func (h *holdWriter) release() { return } h.pass() - h.w.Write(h.held.Bytes()) + h.w.Write(retell(h.retold, h.held.Bytes())) h.flush() } diff --git a/internal/gateway/gateway.go b/internal/gateway/gateway.go index 87a85e54c..f1d49a76f 100644 --- a/internal/gateway/gateway.go +++ b/internal/gateway/gateway.go @@ -5737,7 +5737,8 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro // nobody is left: the agent is told it was refused, as a // request it shouldn't send again as it is, not handed an empty // reply it would ask again for, paying for each - failTo(w, kept, from, refusedStatus, call.Error) + // told with the vendor's own words first (refusalTold) + failTo(w, kept, from, refusedStatus, refusalTold(c.p, c.model, hw.status, call.Usage.RequestID, hw.failMsg, c.p.IsPlugin())) } else if hw.turnedAway && hw.failed() { // nobody is left to answer what Antigravity turned away: the // agent is told why, at a status it doesn't retry, not the 429 diff --git a/internal/gateway/kept_error.go b/internal/gateway/kept_error.go index b9be8acfd..527804882 100644 --- a/internal/gateway/kept_error.go +++ b/internal/gateway/kept_error.go @@ -2,6 +2,7 @@ package gateway import ( "bytes" + "cmp" "encoding/json" "net/http" "strings" @@ -39,6 +40,17 @@ func errorShape(proto provider.Protocol) int { // 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 { + // the agent is told the vendor's words first, as it said them, and + // magpie's after (upstreamTold); a try's held reply keeps magpie's + // reading, which what follows the try reads, and is told so only on + // its way to the agent (retell) + msg = cmp.Or(msg, p.Name+": "+provider.APIError(body, res.Status)) + told := upstreamTold(p.Name, res.StatusCode, res.Header, body, msg, p.IsPlugin()) + if h := holdOf(w); h != nil { + h.retellAs(msg, told) + } else { + msg = told + } if status, ok := writeKeptError(w, proto, upstream, p, res, msg, body); ok { return status } diff --git a/internal/gateway/kept_error_test.go b/internal/gateway/kept_error_test.go index 1a2d9c58e..5fa1cb26d 100644 --- a/internal/gateway/kept_error_test.go +++ b/internal/gateway/kept_error_test.go @@ -12,7 +12,8 @@ import ( // 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 +// which names the provider, and its status, code and request id after the +// vendor's words (upstreamTold). It was rebuilt from the status, with only a // string code kept. func TestSameAPIErrorKeptAsSent(t *testing.T) { for _, c := range []struct { @@ -23,13 +24,13 @@ func TestSameAPIErrorKeptAsSent(t *testing.T) { }{ {"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"}`}, + `{"error":{"message":"A: Request rejected by gateway rule (FX-1214) (HTTP 400, request id req-77)","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"}`}, + `{"type":"error","error":{"type":"upstream_rule","message":"A: Request rejected by gateway rule (HTTP 403, 20031, request id req_01)","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}}`}, + `{"error":{"message":"A: Request rejected by gateway rule (HTTP 400, 1214)","type":"upstream_rule","code":1214,"param":"input","extra":true}}`}, } { t.Run(c.name, func(t *testing.T) { fresh(t) @@ -57,7 +58,7 @@ func TestSameAPIOverflowKeepsTheRest(t *testing.T) { 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" { + 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 (HTTP 400, 1261, request id r1)" { t.Fatalf("the vendor's other fields were lost: %s", b) } } diff --git a/internal/gateway/remote_magpie_restricted_test.go b/internal/gateway/remote_magpie_restricted_test.go index 7dfe1312d..766757644 100644 --- a/internal/gateway/remote_magpie_restricted_test.go +++ b/internal/gateway/remote_magpie_restricted_test.go @@ -128,7 +128,7 @@ func TestRemoteMagpieVerifyHeldOnTheModel(t *testing.T) { t.Fatalf("%d %s", code, body) } for range 2 { - if code, again := postAs(t, s, "", req); code != 403 || provider.APIError([]byte(again), "") != msg { + if code, again := postAs(t, s, "", req); code != 403 || !sameVerify(provider.APIError([]byte(again), ""), msg) { t.Fatalf("held: %d %s", code, again) } } diff --git a/internal/gateway/upstream_said.go b/internal/gateway/upstream_said.go new file mode 100644 index 000000000..52eef210e --- /dev/null +++ b/internal/gateway/upstream_said.go @@ -0,0 +1,224 @@ +package gateway + +import ( + "bytes" + "encoding/json" + "fmt" + "net/http" + "strings" + + "github.com/tidwall/gjson" + + "github.com/yetone/magpie/internal/provider" +) + +// magpieSays begins the line of an error told to the agent that is +// magpie's own, after the vendor's: what magpie read of the error and +// what to do, kept apart from the vendor's words so a user can copy +// those as they were said, to the vendor (@gptchan404 on X). +const magpieSays = "\nmagpie: " + +// upstreamTold is a vendor's error as the agent is told it: on its first +// line the provider's name, the vendor's own words as it said them and +// what it named the error by — its HTTP status, its code and its request +// id, each left out when its words already say it — and after it, on a +// line of its own, whatever magpie said beyond those words (msg, the +// error as explained, less the provider's name and the vendor's words it +// begins with). An agent that shows only an error's first line shows the +// vendor's. A plugin's error (plugin) is its vendor's words with the +// plugin's advice after a " — ", as provider.Explain joins them: only the +// words before it are the vendor's, and the advice is told on magpie's +// line (pluginWords). +func upstreamTold(name string, status int, header http.Header, b []byte, msg string, plugin bool) string { + words := provider.VendorWords(b) + if plugin { + words = pluginWords(words) + } + head := name + ": " + rest := strings.TrimPrefix(msg, head) + // APIError's status line ("403 Forbidden: …"), which the first + // line says as HTTP 403 + rest = strings.TrimPrefix(rest, fmt.Sprintf("%d %s: ", status, http.StatusText(status))) + if words != "" && strings.HasPrefix(rest, words) { + rest = rest[len(words):] + } + rest = strings.TrimLeft(rest, " —-:") + named := upstreamNamed(status, vendorCode(b), vendorRequestID(header, b), words) + line := head + words + switch { + case words == "" && named != "": + line = head + named + case named != "": + line += " (" + named + ")" + } + if rest == "" || rest == words { + return line + } + return line + magpieSays + rest +} + +// upstreamNamed is what a vendor named its error by, as the first line +// of upstreamTold says it: "HTTP 403, content_policy_rejected, request id +// …", each part the vendor's words don't already hold, and no code that +// is only the status again (Google's "code": 403). +func upstreamNamed(status int, code, reqID, words string) string { + var parts []string + if status >= 400 { + parts = append(parts, fmt.Sprintf("HTTP %d", status)) + } + if code != "" && code != fmt.Sprint(status) && !strings.Contains(words, code) { + parts = append(parts, code) + } + if reqID != "" && !strings.Contains(words, reqID) { + parts = append(parts, "request id "+reqID) + } + return strings.Join(parts, ", ") +} + +// vendorCode is the code a vendor's error body names its error by: the +// error's code (a string or a number), else its type, else its status +// (Gemini's RESOURCE_EXHAUSTED…), at the top level for a body with no +// error object. "" for none, and for the bare type "error". +func vendorCode(b []byte) string { + e := gjson.GetBytes(b, "error") + if !e.IsObject() { + e = gjson.ParseBytes(b) + if !e.IsObject() { + return "" + } + } + for _, k := range []string{"code", "type", "status"} { + v := e.Get(k) + if v.Type != gjson.String && v.Type != gjson.Number { + continue + } + if s := strings.TrimSpace(v.String()); s != "" && s != "error" && s != "0" { + return s + } + } + return "" +} + +// vendorRequestID is the id a vendor gave the failed request, for the +// user to quote to it: the reply's Request-Id or X-Request-Id, else the +// body's request_id (Anthropic's). +func vendorRequestID(h http.Header, b []byte) string { + if id := requestID(h); id != "" { + return id + } + for _, k := range []string{"request_id", "error.request_id", "requestId"} { + if v := gjson.GetBytes(b, k); v.Type == gjson.String && strings.TrimSpace(v.String()) != "" { + return strings.TrimSpace(v.String()) + } + } + return "" +} + +// refusalTold is what the agent is told of a request the vendor's safety +// filter refused and nobody else answered: the vendor's own words first, +// as upstreamTold puts them (status the vendor's, when it answered with +// an error status), and magpie's line after them, which names the model +// and the filter's reason (refusedError). why is the refusal's note, +// "safety filter: — " (refusedNote) or the +// reason with what Anthropic's stop_details said (refusedDetail). +func refusalTold(p provider.Provider, model string, status int, reqID, why string, plugin bool) string { + reason, words, said := strings.Cut(why, " — ") + reason = strings.TrimPrefix(reason, "safety filter: ") + if !said { + // a stop reason, with nothing said beside it but what + // stop_details may give, in the reason's parentheses + words = reason + } + advice := "" + if plugin && said { + // the plugin's advice goes on magpie's line (pluginWords) + if w := pluginWords(words); w != words { + words, advice = w, " — "+strings.TrimSpace(words[len(w)+len(" — "):]) + } + } + code := reason + if i := strings.IndexByte(code, ' '); i > 0 { + code = code[:i] + } + line := p.Name + ": " + words + if named := upstreamNamed(status, code, reqID, words); named != "" { + line += " (" + named + ")" + } + return line + magpieSays + refusedError(p, model, "safety filter: "+code) + advice +} + +// pluginWords is the vendor's part of a plugin's error message: what comes +// before the first " — ", after which a plugin puts its own advice +// (Factory's "… (upstream request id …, code …) — Factory's usage policy +// check reads the whole conversation, …"). +func pluginWords(said string) string { + w, _, _ := strings.Cut(said, " — ") + return w +} + +// retelling is one error's text as magpie read it (from) and as the agent +// is told it (to). +type retelling struct{ from, to string } + +// holdOf is the try's holdWriter under w and the writers wrapped around +// it, nil for none. +func holdOf(w http.ResponseWriter) *holdWriter { + for w != nil { + if h, ok := w.(*holdWriter); ok { + return h + } + u, ok := w.(interface{ Unwrap() http.ResponseWriter }) + if !ok { + return nil + } + w = u.Unwrap() + } + return nil +} + +// retellAs has the try's reply tell the agent to where it says from. +func (h *holdWriter) retellAs(from, to string) { + if from == "" || from == to { + return + } + h.mu.Lock() + h.retold = append(h.retold, retelling{from, to}) + h.mu.Unlock() +} + +// retell is b with each error magpie wrote in it told as rs say, in each +// way a JSON string of it can be written (with and without HTML's +// characters escaped); b itself, never written to, when none is in it. +func retell(rs []retelling, b []byte) []byte { + for _, r := range rs { + from, to := jsonStringBody(r.from, true), jsonStringBody(r.to, true) + if bytes.Contains(b, from) { + b = bytes.ReplaceAll(b, from, to) + continue + } + // once only: to holds from, so a second pass of the same bytes + // would tell it twice + if from, to = jsonStringBody(r.from, false), jsonStringBody(r.to, false); bytes.Contains(b, from) { + b = bytes.ReplaceAll(b, from, to) + } + } + return b +} + +// retellText is s told as rs say. +func retellText(rs []retelling, s string) string { + for _, r := range rs { + s = strings.ReplaceAll(s, r.from, r.to) + } + return s +} + +// jsonStringBody is s as a JSON string's contents, its HTML characters escaped +// as encoding/json does by default or not. +func jsonStringBody(s string, escapeHTML bool) []byte { + var buf bytes.Buffer + e := json.NewEncoder(&buf) + e.SetEscapeHTML(escapeHTML) + e.Encode(s) + return bytes.TrimSuffix(bytes.TrimSuffix(bytes.TrimPrefix(buf.Bytes(), []byte(`"`)), []byte("\n")), []byte(`"`)) +} diff --git a/internal/gateway/upstream_said_test.go b/internal/gateway/upstream_said_test.go new file mode 100644 index 000000000..727981e28 --- /dev/null +++ b/internal/gateway/upstream_said_test.go @@ -0,0 +1,144 @@ +package gateway + +import ( + "encoding/json" + "io" + "net/http" + "net/http/httptest" + "strconv" + "strings" + "testing" + + "github.com/yetone/magpie/internal/provider" +) + +// toldAsks are an error's ask in each protocol the gateway answers, whole +// and streamed. +var toldAsks = []struct{ name, path, body string }{ + {"messages", "/v1/messages", `{"model":"f/m","max_tokens":64,"messages":[{"role":"user","content":"hi"}]}`}, + {"messages stream", "/v1/messages", `{"model":"f/m","max_tokens":64,"stream":true,"messages":[{"role":"user","content":"hi"}]}`}, + {"chat", "/v1/chat/completions", `{"model":"f/m","messages":[{"role":"user","content":"hi"}]}`}, + {"chat stream", "/v1/chat/completions", `{"model":"f/m","stream":true,"messages":[{"role":"user","content":"hi"}]}`}, + {"responses", "/v1/responses", `{"model":"f/m","input":"hi"}`}, + {"responses stream", "/v1/responses", `{"model":"f/m","stream":true,"input":"hi"}`}, + {"gemini", "/v1beta/models/f/m:generateContent", `{"contents":[{"role":"user","parts":[{"text":"hi"}]}]}`}, + {"gemini stream", "/v1beta/models/f/m:streamGenerateContent?alt=sse", `{"contents":[{"role":"user","parts":[{"text":"hi"}]}]}`}, +} + +// inJSON is s as it reads inside a JSON string. +func inJSON(s string) string { + b, _ := json.Marshal(s) + return strings.ReplaceAll(strings.Trim(string(b), `"`), `\u0026`, "&") +} + +// @gptchan404 on X: a vendor's refusal reached the agent wrapped in +// magpie's words ("claude-opus-5-5 refused this request (safety filter: +// content_policy_rejected — ) via Factory"), so the user +// had no error of the vendor's own to take back to it. Every protocol, +// whole and streamed, is now told the vendor's words first, with its +// status, on a line of their own, and magpie's after them. +func TestRefusalToldWithTheVendorsWordsFirst(t *testing.T) { + for _, up := range []provider.Protocol{provider.Anthropic, provider.Chat} { + for _, ask := range toldAsks { + t.Run(string(up)+"/"+ask.name, func(t *testing.T) { + fresh(t) + f := &scripted{replies: []reply{{403, "application/json", factoryPolicy403(up == provider.Anthropic)}}} + scriptedOn(t, "f", up, f) + _, out := sendTo(New(), ask.path, ask.body) + first := "F: " + factoryPolicyMsg + " (HTTP 403)" + if !strings.Contains(out, inJSON(first+"\nmagpie: m refused this request (safety filter: content_policy_rejected) via F")) { + t.Errorf("not the vendor's words first, then magpie's:\n%s", out) + } + }) + } + } +} + +// Any other error of a vendor's is told the same way: its words, status, +// code and request id first, as it said them; and a client of OpenAI's +// shape keeps the vendor's code on the error. +func TestVendorErrorToldWithItsOwnWordsFirst(t *testing.T) { + for _, up := range []provider.Protocol{provider.Anthropic, provider.Chat} { + for _, ask := range toldAsks { + t.Run(string(up)+"/"+ask.name, func(t *testing.T) { + fresh(t) + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + io.ReadAll(r.Body) + w.Header().Set("Content-Type", "application/json") + w.Header().Set("Request-Id", "req_7Hq2") + w.WriteHeader(http.StatusBadRequest) + if up == provider.Anthropic { + io.WriteString(w, `{"type":"error","error":{"type":"invalid_request_error","message":"messages.0.content: Input should be a valid list"}}`) + return + } + io.WriteString(w, `{"error":{"message":"messages.0.content: Input should be a valid list","type":"invalid_request_error","code":"invalid_value"}}`) + })) + t.Cleanup(srv.Close) + p := provider.Provider{ID: "f", Name: "F", Key: "k", Models: []string{"m"}} + if up == provider.Anthropic { + p.Anthropic = srv.URL + } else { + p.Chat = srv.URL + "/v1" + } + if err := provider.Save(p); err != nil { + t.Fatal(err) + } + _, out := sendTo(New(), ask.path, ask.body) + code := "invalid_value" + if up == provider.Anthropic { + code = "invalid_request_error" + } + first := "F: messages.0.content: Input should be a valid list (HTTP 400, " + code + ", request id req_7Hq2)" + if !strings.Contains(out, inJSON(first)) { + t.Errorf("not the vendor's words, status, code and request id first:\n%s", out) + } + oai := strings.HasPrefix(ask.path, "/v1/chat") || strings.HasPrefix(ask.path, "/v1/responses") + if oai && up == provider.Chat && !strings.Contains(out, `"invalid_value"`) { + t.Errorf("the vendor's code left out of the error: %s", out) + } + }) + } + } +} + +func TestUpstreamTold(t *testing.T) { + b := []byte(`{"error":{"message":"Your credit balance is too low","type":"invalid_request_error"}}`) + h := http.Header{"X-Request-Id": {"r1"}} + for _, c := range []struct{ msg, want string }{ + {"P: Your credit balance is too low", "P: Your credit balance is too low (HTTP 400, invalid_request_error, request id r1)"}, + {"P: Your credit balance is too low — top up at example.com", "P: Your credit balance is too low (HTTP 400, invalid_request_error, request id r1)\nmagpie: top up at example.com"}, + {"", "P: Your credit balance is too low (HTTP 400, invalid_request_error, request id r1)"}, + } { + if got := upstreamTold("P", 400, h, b, c.msg, false); got != c.want { + t.Errorf("%q:\n got %q\nwant %q", c.msg, got, c.want) + } + } + // an empty body: who, and its status, first; magpie's reading after + if got := upstreamTold("P", 403, http.Header{}, nil, "P: 403 Forbidden: "+provider.NoDetails, false); got != "P: HTTP 403\nmagpie: "+provider.NoDetails { + t.Errorf("empty body: %q", got) + } +} + +// The Factory plugin's refusal (packages/factory, @gptchan404's case): +// Factory's words and its request id and code on the first line, the +// plugin's advice on magpie's, after the refusal. +func TestPluginAdviceToldOnMagpiesLine(t *testing.T) { + advice := factoryPolicyMsg[strings.Index(factoryPolicyMsg, " — ")+len(" — "):] + factory := "This request was blocked by Factory's usage policy check. (upstream request id 8d1f0c2a3b4e5f60::LAX, code content_policy_rejected)" + p := provider.Provider{ID: "factory", Name: "Factory"} + got := refusalTold(p, "claude-opus-5-5", 400, "", "safety filter: content_policy_rejected — "+factoryPolicyMsg, true) + want := "Factory: " + factory + " (HTTP 400)\nmagpie: claude-opus-5-5 refused this request (safety filter: content_policy_rejected) via Factory — " + advice + if got != want { + t.Errorf("refusal:\n got %q\nwant %q", got, want) + } + b := []byte(`{"error":{"type":"permission_error","message":` + strconv.Quote(factoryPolicyMsg) + `}}`) + got = upstreamTold("Factory", 403, http.Header{}, b, "Factory: "+factoryPolicyMsg, true) + if want := "Factory: " + factory + " (HTTP 403, permission_error)\nmagpie: " + advice; got != want { + t.Errorf("error:\n got %q\nwant %q", got, want) + } + // a vendor's own words keep their dash when no plugin wrote them + got = upstreamTold("Factory", 403, http.Header{}, b, "Factory: "+factoryPolicyMsg, false) + if want := "Factory: " + factoryPolicyMsg + " (HTTP 403, permission_error)"; got != want { + t.Errorf("not a plugin's:\n got %q\nwant %q", got, want) + } +} diff --git a/internal/gateway/verify_test.go b/internal/gateway/verify_test.go index cc272a8ae..d4a729f43 100644 --- a/internal/gateway/verify_test.go +++ b/internal/gateway/verify_test.go @@ -31,9 +31,11 @@ func TestVerifyRefusalRestsTheLastOne(t *testing.T) { t.Fatalf("try %+v rest %+v", try, try.Rest) } - // the agent reconnects at once: held, not sent on + // the agent reconnects at once: held, not sent on, and told the same: + // the vendor's words and where to verify (the first reply puts the + // vendor's words first, upstreamTold; a held one is magpie's own) for range 3 { - if code, again := postAs(t, s, "", req); code != 403 || provider.APIError([]byte(again), "") != msg { + if code, again := postAs(t, s, "", req); code != 403 || !sameVerify(provider.APIError([]byte(again), ""), msg) { t.Fatalf("%d %s", code, again) } } @@ -122,7 +124,7 @@ func TestAgyCLIVerifyWords(t *testing.T) { s := New() code, got := postAs(t, s, "", `{"model":"a/m","messages":[{"role":"user","content":"hi"}]}`) msg := provider.APIError([]byte(got), "") - if code != 403 || strings.Count(msg, "needs to be verified") != 1 || !strings.HasSuffix(msg, c.tail) { + if code != 403 || strings.Count(msg, "needs to be verified") != 1 || !strings.Contains(msg, c.tail) { t.Fatalf("%d: %s", code, msg) } r := s.trace.routes[len(s.trace.routes)-1] @@ -132,3 +134,14 @@ func TestAgyCLIVerifyWords(t *testing.T) { } } } + +// sameVerify says whether two answers to an account Google wants verified +// tell the same: Google's words, and the link to verify it at. +func sameVerify(a, b string) bool { + for _, w := range []string{"Verify your account to continue.", "open https://accounts.google.com/signin/continue?sarp=1&x=2 in a browser"} { + if !strings.Contains(a, w) || !strings.Contains(b, w) { + return false + } + } + return true +} diff --git a/internal/gateway/zcode_blocked_test.go b/internal/gateway/zcode_blocked_test.go index e96899963..552e7900f 100644 --- a/internal/gateway/zcode_blocked_test.go +++ b/internal/gateway/zcode_blocked_test.go @@ -147,9 +147,9 @@ func TestRelayRefusalSaysWhatItWas(t *testing.T) { name, ct, body string want []string }{ - {"cloudflare", "text/html; charset=UTF-8", cf, []string{"403 Forbidden: a web page, not an API reply: “Attention Required! | Cloudflare”", provider.BlockedHint}}, - {"page", "text/html", "403 Forbidden

403 Forbidden


nginx
", []string{"403 Forbidden: a web page, not an API reply: “403 Forbidden”"}}, - {"empty", "", "", []string{"403 Forbidden: " + provider.NoDetails}}, + {"cloudflare", "text/html; charset=UTF-8", cf, []string{"Relay: a web page, not an API reply: “Attention Required! | Cloudflare” (HTTP 403)", provider.BlockedHint}}, + {"page", "text/html", "403 Forbidden

403 Forbidden


nginx
", []string{"Relay: a web page, not an API reply: “403 Forbidden” (HTTP 403)"}}, + {"empty", "", "", []string{"Relay: HTTP 403\nmagpie: " + provider.NoDetails}}, {"json", "application/json", `{"error":{"message":"this key may not use gpt-5.5","type":"forbidden"}}`, []string{"this key may not use gpt-5.5"}}, } { t.Run(c.name, func(t *testing.T) { @@ -194,18 +194,19 @@ func TestRelayRefusalSaysWhatItWas(t *testing.T) { // (maralica on Discord, "magpie-grok"): it is asked for its own model id, // never one magpie named, with WorkBuddy's User-Agent as sent, and // whatever reason its 403 gives reaches the agent: plain text, JSON, a -// page with no title, a page's fragment, an XML error. +// page with no title, a page's fragment, an XML error. The relay's words +// come first, with its status, as upstreamTold says them. func TestChatRelayRefusalSaysWhy(t *testing.T) { const ua = "WorkBuddy/5.9.2 WorkBuddy/5.9.2 CLI/2.165.0" for _, c := range []struct { name, ct, body, want string }{ - {"text", "text/plain", "only Claude Code and Codex CLI are allowed", "magpie-grok: 403 Forbidden: only Claude Code and Codex CLI are allowed"}, - {"json", "application/json", `{"error":{"message":"client WorkBuddy is not allowed","type":"forbidden"}}`, "magpie-grok: client WorkBuddy is not allowed"}, - {"untitled page", "text/html", "

403

only Claude Code & Codex CLI are allowed

", "magpie-grok: 403 Forbidden: a web page, not an API reply: “403 only Claude Code & Codex CLI are allowed”"}, - {"fragment", "text/html", "

Forbidden

\n

client not allowed

", "magpie-grok: 403 Forbidden: Forbidden client not allowed"}, - {"xml", "application/xml", `ClientNotAllowedclient not allowed`, "magpie-grok: 403 Forbidden: ClientNotAllowed client not allowed"}, - {"empty", "", "", "magpie-grok: 403 Forbidden: " + provider.NoDetails}, + {"text", "text/plain", "only Claude Code and Codex CLI are allowed", "magpie-grok: only Claude Code and Codex CLI are allowed (HTTP 403)"}, + {"json", "application/json", `{"error":{"message":"client WorkBuddy is not allowed","type":"forbidden"}}`, "magpie-grok: client WorkBuddy is not allowed (HTTP 403, forbidden)"}, + {"untitled page", "text/html", "

403

only Claude Code & Codex CLI are allowed

", "magpie-grok: a web page, not an API reply: “403 only Claude Code & Codex CLI are allowed” (HTTP 403)"}, + {"fragment", "text/html", "

Forbidden

\n

client not allowed

", "magpie-grok: Forbidden client not allowed (HTTP 403)"}, + {"xml", "application/xml", `ClientNotAllowedclient not allowed`, "magpie-grok: ClientNotAllowed client not allowed (HTTP 403)"}, + {"empty", "", "", "magpie-grok: HTTP 403\nmagpie: " + provider.NoDetails}, } { for _, model := range []string{"magpie-grok/grok-4.7", "group/g"} { t.Run(c.name+" "+model, func(t *testing.T) { diff --git a/internal/provider/test.go b/internal/provider/test.go index a25b4bd3d..23731c382 100644 --- a/internal/provider/test.go +++ b/internal/provider/test.go @@ -1174,6 +1174,15 @@ func APIError(b []byte, fallback string) string { return apiError(b, fallback) } +// VendorWords is what a vendor's error body says in its own words, as +// APIError reads them but with none of magpie's hints after them: the +// error's message (with its type and code when the message is only a +// status line), or the body itself cut short. "" for a body that says +// nothing (empty), for the caller to say so. +func VendorWords(b []byte) string { + return strings.TrimPrefix(apiError(b, ""), ": ") +} + // cmdGoNoAPI is Command Code's Provider API refusing a Go plan's key: // "Your Go plan doesn't include API access. Upgrade to Provider or higher // …" (#969). Go's key is only taken where Command Code's CLI asks, which