From 8cbaeecae976d2a8561293c1abc5daf6aa89d77f Mon Sep 17 00:00:00 2001 From: yetone Date: Fri, 6 Nov 2026 18:39:16 +0800 Subject: [PATCH] providers: errors=pass sends a vendor's error to the agent as it came, asked once MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ne9ko9 on Discord wants errors handled explicitly, not by inference, and a mode that passes them straight through. A custom or API-key provider (no account, an endpoint of its own, not a subscription) now takes `passErrors` in its config: "magpie handles" (the default, unchanged) or "Pass through". Nothing sets it but the user, and an edit that doesn't send it keeps the saved value. With it on, for that provider: - no rewriting: on the client's own API, upstream's status, Content-Type and bytes go out (passError); on another API, the client's shape is built with the vendor's own type, message and raw code and param (a numeric code stays a number). Retry-After and *ratelimit* headers go with it; - no too-long inference, no busy words, no 413 hint, no policy rewording (settle never runs: the try is passing); - no gateway retry: forward()'s Retries loop, refit, firstWait, the loop's re-asks, reloop, empties retry and streamTranslated's cont.again all stop; - no fallback and no rest: the candidate loop's one choke point, newHoldWriter(…, !pass && …), lets the try pass, so nothing after it is tried, and restAfterMarked answers By "off". magpie's own file-id re-ask (dsRetryGone) still runs, as it fixes magpie's own upload, not the vendor's answer. CLI: `magpie provider set errors=pass|magpie`; a bad value is refused and keeps the old one; an account is refused. `provider show` says "errors pass". GUI: Edit → Advanced → Errors, a quiet app-menu picker (openProtoMenu, no native select) with "magpie handles" and "Pass through", shown only where takesPassErrors; zh, zh-TW, ja, de. It is drawn by passerrors.js, imported when the editor draws the row (old-webkit's lazy list names it), and app.js pays for its few lines by two comments cut, so app.js is smaller than before and TestCoreScriptBudget's numbers are unchanged. Tests: - internal/gateway/pass_errors_test.go: TestPassErrorsAskedOnce (503, 429, 404 with numeric codes, alone and as a group's first member: exact bytes and status, asked once, the second member never asked, no rest), TestPassErrorsNotInferred (a too-long 400 byte-for-byte), TestPassErrorsOtherAPI (Anthropic 403 code 20031 to a Chat client, streamed and not). - internal/provider/pass_errors_test.go, internal/cli/errors_cli_test.go. - internal/gui/tests/provider-pass-errors.test.cjs: every language, 1100 and 420 wide, Chromium and WebKit. Run, through mote-run at this commit: - go test -count=1 -timeout 45m ./internal/gateway ./internal/provider ./internal/cli ./internal/gui (at the parent 19c45d5d4's tree): gateway, provider, cli ok; gui red only in TestMainWindowCorners/macOS_26_SDK, mote's macOS 27 (#3949). TestCoreScriptBudget ok. - Rebased on 2f660ca86: go vet of the four packages, the PassErrors, Budget, SameAPI and Errors tests and provider-pass-errors (60/60) again at this commit: ok. - GUI on mote: provider-pass-errors 60/60 (both engines), old-webkit and provider-pass-errors under BROWSER=webkit 36/36; i18n-keys red only in "a plugin's words are its own" (#5332, #5426, #5482). - The whole GUI suite on Linux (wsl-run, magpie-desktop, --test- concurrency=4): 21188 of 21666, 478 red. The 15 provider-editor files among the reds (vertex-editor, zero-priced-free, provider-fetch-again, provider-picks-stay, model-chip-steady and ten more) were run at this commit and at origin/main 2f660ca86 without it: 128 of 236 red on both, the same tests. The rest are in files this commit doesn't reach. - go vet ./..., GOOS=linux go vet -tags nogui ./..., GOOS=windows go vet ./...: ok. gofmt -l clean. - Full suite: run after the push under the suite lock. Broken by hand: every PassesErrors() gate set to false: AskedOnce, NotInferred and OtherAPI red (rewritten body, b asked, rested). The GUI test on the old code: 0/60. Not tried: a real vendor account or relay with errors=pass; Windows and Linux hardware (vet only). Reported-by: ne9ko9 (Discord) --- docs/subsystems/gateway-routing.md | 1 + internal/cli/errors_cli_test.go | 29 ++++ internal/cli/providers_cli.go | 23 +++ internal/gateway/continuation.go | 11 +- internal/gateway/gateway.go | 87 +++++++--- internal/gateway/pass_errors.go | 59 +++++++ internal/gateway/pass_errors_test.go | 112 ++++++++++++ internal/gateway/routing.go | 6 + internal/gui/assets/app.js | 20 ++- internal/gui/assets/i18n.js | 12 ++ internal/gui/assets/passerrors.js | 21 +++ internal/gui/providers.go | 19 ++- internal/gui/tests/old-webkit.test.cjs | 5 +- .../gui/tests/provider-pass-errors.test.cjs | 161 ++++++++++++++++++ internal/provider/pass_errors.go | 15 ++ internal/provider/pass_errors_test.go | 22 +++ internal/provider/provider.go | 12 ++ 17 files changed, 578 insertions(+), 37 deletions(-) create mode 100644 internal/cli/errors_cli_test.go create mode 100644 internal/gateway/pass_errors.go create mode 100644 internal/gateway/pass_errors_test.go create mode 100644 internal/gui/assets/passerrors.js create mode 100644 internal/gui/tests/provider-pass-errors.test.cjs create mode 100644 internal/provider/pass_errors.go create mode 100644 internal/provider/pass_errors_test.go diff --git a/docs/subsystems/gateway-routing.md b/docs/subsystems/gateway-routing.md index f6aa58d4a..ffda6641f 100644 --- a/docs/subsystems/gateway-routing.md +++ b/docs/subsystems/gateway-routing.md @@ -203,6 +203,7 @@ recorded as a prediction failure (`noPrediction`). - 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 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)). - 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/cli/errors_cli_test.go b/internal/cli/errors_cli_test.go new file mode 100644 index 000000000..59681250e --- /dev/null +++ b/internal/cli/errors_cli_test.go @@ -0,0 +1,29 @@ +package cli + +import ( + "testing" + + "github.com/yetone/magpie/internal/provider" +) + +// errors= sets whether a keyed provider's errors go to the agent as the +// vendor sent them (ne9ko9 on Discord); a signed-in account takes none. +func TestProviderSetErrors(t *testing.T) { + p := provider.Provider{ID: "relay", Name: "Relay", Key: "k", Chat: "https://x/v1"} + for _, c := range []struct { + v string + want bool + }{{"pass", true}, {"magpie", false}, {"pass-through", true}, {"default", false}} { + if err := applyPairs(&p, []string{"errors=" + c.v}); err != nil || p.PassErrors != c.want { + t.Fatalf("errors=%s: %v, got %v", c.v, err, p.PassErrors) + } + } + p.PassErrors = true + if err := applyPairs(&p, []string{"errors=loud"}); err == nil || !p.PassErrors { + t.Fatalf("errors=loud taken: %v", err) + } + a := provider.Provider{ID: "codex", Name: "Codex", Account: &provider.Account{}, Chat: "https://x/v1"} + if err := applyPairs(&a, []string{"errors=pass"}); err == nil || a.PassErrors { + t.Fatalf("an account took errors=pass: %v", err) + } +} diff --git a/internal/cli/providers_cli.go b/internal/cli/providers_cli.go index bcf4c364a..03a4248b7 100644 --- a/internal/cli/providers_cli.go +++ b/internal/cli/providers_cli.go @@ -62,6 +62,9 @@ const providerUsage = `usage: while it is busy or briefly rate limited, asking again after a pause (at most 4m); patience=off hands the agent the error at once; patience=default, 1m + errors=pass sends the agent its errors as the vendor sent them: + asked once, nothing read into them, no other provider tried; + errors=magpie, the default, has magpie handle them magpie provider key change the API key magpie provider icon give a custom provider a picture (PNG, JPEG, SVG…) or a built-in icon magpie provider fallback … where requests go when it's out of quota or down (none clears) @@ -863,6 +866,9 @@ func showProvider(p provider.Provider) error { if p.Searches { kv("search", "by itself"+muted.Render(" a client's web search goes to it as sent")) } + if p.PassesErrors() { + kv("errors", "pass"+muted.Render(" sent to the agent as the vendor sent them, asked once")) + } if p.PassUserAgent { why := " the User-Agent the agent gave, not magpie's" if !p.PassesUserAgent() { @@ -1194,6 +1200,23 @@ func applyPairs(p *provider.Provider, pairs []string) error { return err } p.Patience = n + case "errors": + // pass: its errors go to the agent as the vendor sent them, + // asked once, nothing inferred, no other provider tried and + // none rested for (ne9ko9 on Discord); magpie: handled by + // magpie, the default + var on bool + switch strings.ToLower(v) { + case "pass", "pass-through", "passthrough", "on", "yes": + on = true + case "magpie", "default", "off", "no": + default: + return fmt.Errorf("errors=pass|magpie, not %q", v) + } + if on && !p.TakesPassErrors() { + return fmt.Errorf("%s isn't a provider with an API key; errors= is for one", p.Name) + } + p.PassErrors = on case "user-agent", "ua": // agent: a request goes with the User-Agent the agent that // sent it gave, for a coding plan that serves only agents it diff --git a/internal/gateway/continuation.go b/internal/gateway/continuation.go index 96f7fb705..55161475d 100644 --- a/internal/gateway/continuation.go +++ b/internal/gateway/continuation.go @@ -445,7 +445,7 @@ func (s *Server) streamTranslated(w http.ResponseWriter, r *http.Request, p prov // only reasoning nobody acts on: a text or a call the agent // has would be said twice, and a continuation's prefill would // be asked to go on with the loop - if !t.reasoning || spoke || cont.resume || reasks >= loopReasks || r.Context().Err() != nil { + if !t.reasoning || spoke || cont.resume || reasks >= loopReasks || r.Context().Err() != nil || p.PassesErrors() { return false } reasks++ @@ -541,6 +541,11 @@ func (s *Server) streamTranslated(w http.ResponseWriter, r *http.Request, p prov empty, counts = emptyFails(actual), repliesCounted(actual) voids = cutVoidAt(actual) } + if err == nil && res.StatusCode >= 400 && !cont.resume && p.PassesErrors() { + // the user leaves its errors to the client (errors=pass) + defer res.Body.Close() + return passError(w, p, from, actual, res, u) + } if err == nil && res.StatusCode >= 400 { b, _ := io.ReadAll(io.LimitReader(res.Body, 1<<20)) res.Body.Close() @@ -674,7 +679,7 @@ func (s *Server) streamTranslated(w http.ResponseWriter, r *http.Request, p prov held() } if (empty || counts && uncounted(this)) && !said && answersNothing(stop) { - if empties < emptyRetries(w, r.Context()) && r.Context().Err() == nil { + if empties < emptyRetries(w, r.Context()) && r.Context().Err() == nil && !p.PassesErrors() { // asked again here first, for the agent to have the // answer rather than the error: Gemini on a long // conversation now and then ends with only its @@ -718,7 +723,7 @@ func (s *Server) streamTranslated(w http.ResponseWriter, r *http.Request, p prov // an error the client already has ends the reply: nothing of it // goes on after it (a group member's mid-reply error fails the // try at once, for the group's next member, #733) - if errSent || !cont.again(failedStatus, failedCode, again, r.Context()) { + if errSent || p.PassesErrors() || !cont.again(failedStatus, failedCode, again, r.Context()) { if held != nil { // what was held goes as the text it is, as it used to; // a reply that goes on reads it again instead diff --git a/internal/gateway/gateway.go b/internal/gateway/gateway.go index d2a1e8ecb..f1ddf7a3c 100644 --- a/internal/gateway/gateway.go +++ b/internal/gateway/gateway.go @@ -3367,11 +3367,17 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro // for its allowance running out to be told as that one's error // and once the agent has the stream's headers from an earlier try's // keepalives, for a failure to be told as the stream's error - hw := newHoldWriter(w, !last || again < max(lastRetries, rateRetries) || other != nil || kept.sent || autoPicks(c) && repicked < 2 || - patience > 0 && rounds < replanRounds && (waitFrom.IsZero() || time.Since(waitFrom) < patience) || wantWhole) + // a provider whose errors the user leaves to the client + // (errors=pass, ne9ko9 on Discord) is held for nothing: its reply, + // an error too, goes to the agent as it comes, and nothing is + // asked again, of it or of the next candidate. Only a stream the + // agent has the headers of already is held, to be told in it + pass := c.p.PassesErrors() + hw := newHoldWriter(w, kept.sent || !pass && (!last || again < max(lastRetries, rateRetries) || other != nil || autoPicks(c) && repicked < 2 || + patience > 0 && rounds < replanRounds && (waitFrom.IsZero() || time.Since(waitFrom) < patience) || wantWhole)) // a compaction's summary is held to its end, for a cut or an // error halfway to go to the next candidate (#2274) - hw.wantWhole = wantWhole + hw.wantWhole = wantWhole && !pass // Claude's and GPT's reasoning is held for a refusal after it only // while another candidate could answer instead: the last one's // refusal isn't asked again, so holding it only kept a lone relay's @@ -3400,7 +3406,7 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro if !last && c.claudeAccount() && slices.ContainsFunc(cands[i+1:], candidate.claudeAccount) { retell, noRetell = tooBigToRetell(from, body) } - if handsOver(streams, last || noRetell && len(otherThanClaudeAccounts(cands[i+1:])) == 0, wantWhole, from, refusals) { + if !pass && handsOver(streams, last || noRetell && len(otherThanClaudeAccounts(cands[i+1:])) == 0, wantWhole, from, refusals) { // reasoning that went through as it came, and a refusal after // it with nothing yet said: the next candidate answers in the // same stream (refusalHandover; yhwangl on X) @@ -3417,12 +3423,12 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro // a reply stuck in a loop is ended, not let run to its limit // (#1359) hw.loop = &loopGuard{} - hw.reloop = reloops < loopReasks + hw.reloop = reloops < loopReasks && !pass } // a member of a group in the group is timed by the innermost // group that sets a FirstToken (#2246), else by the group asked for firstToken := cmp.Or(c.firstToken, g.FirstToken) - if isGroup && firstToken > 0 && !last && streams { + if isGroup && firstToken > 0 && !last && streams && !pass { // slow to start, the next member is asked (Group.FirstToken) hw.firstWait = time.Duration(firstToken) * time.Second if left := groupBudget - time.Since(walkBegan); left < hw.firstWait { @@ -5440,9 +5446,16 @@ func (s *Server) forward(ctx context.Context, p provider.Provider, to provider.P } if err == nil && res.StatusCode >= 400 { // a file DeepSeek no longer holds: uploaded again, or the - // images sent inline (deepseek_files.go) + // images sent inline (deepseek_files.go). The file id was + // magpie's, so this one is asked again whatever the provider's + // errors setting res, err = s.dsRetryGone(ctx, p, to, path, body, in, res) } + if p.PassesErrors() { + // its errors are the client's to deal with (errors=pass): asked + // once, never again in another shape + return res, err + } if err == nil && res.StatusCode >= 400 { // a body over the provider's byte cap: asked again with its // oldest images left out, or said as a 413 (body_cap.go) @@ -6326,6 +6339,16 @@ func (s *Server) passthrough(w http.ResponseWriter, r *http.Request, p provider. if proto == provider.Responses && prevKeptBy(p) && !storeOff(body) { noteAnswered(r, prevRoute(p)) } + if res.StatusCode >= 400 && p.PassesErrors() { + // the user leaves its errors to the client (errors=pass): the + // vendor's error goes as it came, and nothing is asked again in + // another shape. Above, magpie only took back its own: a + // signature it gave, the previous response it named + defer res.Body.Close() + u.RequestID = requestID(res.Header) + status, msg := passError(w, p, proto, proto, res, u) + return status, msg, true + } // structured output turned away (Xiaomi MiMo's Token Plan takes no // json_schema, only text and json_object, #2126): a schema is asked // for as any JSON object with the schema in the system prompt, and if @@ -7635,6 +7658,10 @@ func (s *Server) forwardTranslated(ctx context.Context, p provider.Provider, to } return res, to, err } + if p.PassesErrors() { + // its errors are the client's (errors=pass): not asked again + return res, to, nil + } b, _ := io.ReadAll(io.LimitReader(res.Body, 1<<20)) res.Body.Close() res.Body = io.NopCloser(bytes.NewReader(b)) @@ -8442,6 +8469,9 @@ func (s *Server) translate(w http.ResponseWriter, r *http.Request, p provider.Pr } defer res.Body.Close() u.RequestID = requestID(res.Header) + if res.StatusCode >= 400 && p.PassesErrors() { + return passError(w, p, from, actual, res, u) + } if res.StatusCode >= 400 { b, _ := io.ReadAll(io.LimitReader(res.Body, 1<<20)) msg := explained(p, model, res, b) @@ -10075,6 +10105,28 @@ const requestBytesHint = "This is a request-body byte limit, not the model's con // 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 { + typ := errorTypeFor(status) + // a relay busy for a moment, said so Pi asks again (#2372) + msg = saysBusy(status, msg) + if tooLong(status, msg) { + // said the way the client's own API says it, so the agent + // compacts the conversation and tries again rather than stopping + status, typ, code = 400, "invalid_request_error", "context_length_exceeded" + if proto == provider.Anthropic && !strings.Contains(strings.ToLower(msg), "prompt is too long") { + msg = "prompt is too long: " + msg + } + } + if h, held := w.(*holdWriter); status == http.StatusRequestEntityTooLarge && (!held || !h.hold) { + if !strings.Contains(msg, requestBytesHint) { + msg += " — " + requestBytesHint + } + } + return writeErrorAs(w, proto, status, typ, msg, code, param) +} + +// errorTypeFor is the error type an OpenAI- or Anthropic-shaped answer +// names for status. +func errorTypeFor(status int) string { typ := "api_error" switch { case status == 400: @@ -10095,21 +10147,12 @@ func writeErrorSaid(w http.ResponseWriter, proto provider.Protocol, status int, case status == 529: typ = "overloaded_error" } - // a relay busy for a moment, said so Pi asks again (#2372) - msg = saysBusy(status, msg) - if tooLong(status, msg) { - // said the way the client's own API says it, so the agent - // compacts the conversation and tries again rather than stopping - status, typ, code = 400, "invalid_request_error", "context_length_exceeded" - if proto == provider.Anthropic && !strings.Contains(strings.ToLower(msg), "prompt is too long") { - msg = "prompt is too long: " + msg - } - } - if h, held := w.(*holdWriter); status == http.StatusRequestEntityTooLarge && (!held || !h.hold) { - if !strings.Contains(msg, requestBytesHint) { - msg += " — " + requestBytesHint - } - } + return typ +} + +// writeErrorAs writes an error in proto's shape, as said: nothing in it +// is read again or changed. +func writeErrorAs(w http.ResponseWriter, proto provider.Protocol, status int, typ, msg string, code, param any) int { var v any switch proto { case provider.Anthropic: diff --git a/internal/gateway/pass_errors.go b/internal/gateway/pass_errors.go new file mode 100644 index 000000000..3a19b537b --- /dev/null +++ b/internal/gateway/pass_errors.go @@ -0,0 +1,59 @@ +package gateway + +import ( + "encoding/json" + "io" + "net/http" + "strings" + + "github.com/tidwall/gjson" + + "github.com/yetone/magpie/internal/provider" +) + +// passError answers a vendor's error for a provider whose errors the user +// leaves to the client (errors=pass, ne9ko9 on Discord): nothing in it is +// inferred or said in magpie's words. A vendor on the client's own API has +// its status, headers' Content-Type and body go as they came; one on +// another API has its status, type, code (a number too), param and words +// written in the client's shape. Retry-After and the rate-limit headers go +// with it, as the vendor sent them. The message returned, for the log, is +// the provider's name and the vendor's words. +func passError(w http.ResponseWriter, p provider.Provider, proto, upstream provider.Protocol, res *http.Response, u *Usage) (int, string) { + b, _ := io.ReadAll(io.LimitReader(res.Body, 1<<20)) + status := res.StatusCode + words := provider.APIError(b, res.Status) + u.ErrType = provider.ErrorType(b) + for k, vs := range res.Header { + if l := strings.ToLower(k); l == "retry-after" || strings.Contains(l, "ratelimit") { + w.Header()[k] = vs + } + } + if shape := errorShape(proto); shape != 0 && errorShape(upstream) == shape { + if ct := res.Header.Get("Content-Type"); ct != "" { + w.Header().Set("Content-Type", ct) + } + w.WriteHeader(status) + w.Write(b) + return status, p.Name + ": " + words + } + typ, msg := errorTypeFor(status), words + var code, param any + if e := gjson.GetBytes(b, "error"); e.IsObject() { + if t := e.Get("type"); t.Type == gjson.String && t.String() != "" { + typ = t.String() + } else if t := e.Get("status"); t.Type == gjson.String && t.String() != "" { + typ = t.String() // Gemini's name for it + } + if m := e.Get("message"); m.Type == gjson.String { + msg = m.String() + } + if c := e.Get("code"); c.Exists() && c.Type != gjson.Null { + code = json.RawMessage(c.Raw) + } + if pr := e.Get("param"); pr.Exists() && pr.Type != gjson.Null { + param = json.RawMessage(pr.Raw) + } + } + return writeErrorAs(w, proto, status, typ, msg, code, param), p.Name + ": " + words +} diff --git a/internal/gateway/pass_errors_test.go b/internal/gateway/pass_errors_test.go new file mode 100644 index 000000000..7bfc30369 --- /dev/null +++ b/internal/gateway/pass_errors_test.go @@ -0,0 +1,112 @@ +package gateway + +import ( + "net/http/httptest" + "strings" + "testing" + + "github.com/tidwall/gjson" + "github.com/yetone/magpie/internal/provider" +) + +// passOn sets a saved provider's errors to the client's (errors=pass). +func passOn(t *testing.T, id string) { + t.Helper() + p, err := provider.Find(id) + if err != nil { + t.Fatal(err) + } + p.PassErrors = true + if !p.PassesErrors() { + t.Fatalf("%s takes no errors=pass", id) + } + if err := provider.Save(*p); err != nil { + t.Fatal(err) + } +} + +// restedAny is whether any rest is on id or one of its models. +func restedAny(id string) bool { + restingUntil.Lock() + defer restingUntil.Unlock() + for k := range restingUntil.m { + if k == id || strings.HasPrefix(k, id+"/") || strings.HasPrefix(k, id+"@") { + return true + } + } + return false +} + +// ne9ko9 on Discord: a provider whose errors the user leaves to the client +// is asked once. Its error reaches the agent as it came: not waited out, +// not handed to the group's next member, nothing rested for it. +func TestPassErrorsAskedOnce(t *testing.T) { + for _, c := range []struct { + name, body string + status int + }{ + {"busy", `{"error":{"message":"upstream overloaded","type":"server_error","code":50301}}`, 503}, + {"rate limit", `{"error":{"message":"Rate limit exceeded, please try again later","type":"rate_limit","code":1302}}`, 429}, + {"unserved model", `{"error":{"message":"The model m does not exist","code":"model_not_found"}}`, 404}, + } { + t.Run(c.name, func(t *testing.T) { + fresh(t) + a := &scripted{replies: []reply{{c.status, "", c.body}, {c.status, "", c.body}, {200, "", chatOK}}} + b := &scripted{replies: []reply{{200, "", chatOK}}} + scriptedOn(t, "a", provider.Chat, a) + scriptedOn(t, "b", provider.Chat, b) + passOn(t, "a") + if err := provider.SaveGroup(provider.Group{Name: "G", Members: []string{"a/m", "b/m"}, Routing: provider.Ordered}); err != nil { + t.Fatal(err) + } + // alone, and as a group's first member + for i, model := range []string{"a/m", "group/g"} { + code, body := postAs(t, New(), "", `{"model":"`+model+`","messages":[{"role":"user","content":"hi"}]}`) + if code != c.status || body != c.body || a.n != i+1 || b.n != 0 { + t.Fatalf("%s: got %d %s (a %d, b %d), want %d %s asked once", model, code, body, a.n, b.n, c.status, c.body) + } + if restedAny("a") { + t.Fatalf("%s: a provider passing its errors was rested", model) + } + } + }) + } +} + +// Nothing is inferred from a pass provider's error: a prompt too long is +// the vendor's own body, not said as context_length_exceeded. +func TestPassErrorsNotInferred(t *testing.T) { + fresh(t) + said := `{"error":{"message":"This model's maximum context length is 128000 tokens","code":1261,"type":"zhipu_error"},"request_id":"r1"}` + a := &scripted{replies: []reply{{400, "", said}}} + scriptedOn(t, "a", provider.Chat, a) + passOn(t, "a") + code, body := postAs(t, New(), "", `{"model":"a/m","messages":[{"role":"user","content":"hi"}]}`) + if code != 400 || body != said || a.n != 1 { + t.Fatalf("got %d %s after %d", code, body, a.n) + } +} + +// Another API's error is written in the client's shape with the vendor's +// type, numeric code and words, and nothing of magpie's in it, streamed or +// not. +func TestPassErrorsOtherAPI(t *testing.T) { + for _, stream := range []bool{false, true} { + fresh(t) + said := `{"type":"error","error":{"type":"upstream_rule","message":"Request rejected by gateway rule","code":20031}}` + a := &scripted{replies: []reply{{403, "", said}, {200, "", "{}"}}} + scriptedOn(t, "a", provider.Anthropic, a) + passOn(t, "a") + req := `{"model":"a/m","messages":[{"role":"user","content":"hi"}]}` + if stream { + req = `{"model":"a/m","stream":true,"messages":[{"role":"user","content":"hi"}]}` + } + w := httptest.NewRecorder() + New().Handler().ServeHTTP(w, httptest.NewRequest("POST", "/v1/chat/completions", strings.NewReader(req))) + b := w.Body.String() + if w.Code != 403 || a.n != 1 || gjson.Get(b, "error.type").String() != "upstream_rule" || + gjson.Get(b, "error.code").Raw != "20031" || gjson.Get(b, "error.message").String() != "Request rejected by gateway rule" { + t.Fatalf("stream %v: got %d %s after %d", stream, w.Code, b, a.n) + } + } +} diff --git a/internal/gateway/routing.go b/internal/gateway/routing.go index a79c14da2..91cbdc0a5 100644 --- a/internal/gateway/routing.go +++ b/internal/gateway/routing.go @@ -1355,6 +1355,12 @@ func (s *Server) restAfterMarked(c candidate, status int, header http.Header, bo // request is asked again, and no rest and no failure counted (#2873) return Rest{Why: why, Status: status, By: "off", Until: now} } + if c.p.PassesErrors() { + // the user leaves its errors to the client (errors=pass): none of + // its keys is set aside for one, and the next request is asked + // as this one was + return Rest{Why: why, Status: status, By: "off", Until: now} + } if header.Get(zdrHeader) != "" || zdrRefused(status, body) { // Command Code's Zero Data Retention setting refused the request: // the model and the account are as good as they were, and answer diff --git a/internal/gui/assets/app.js b/internal/gui/assets/app.js index 102665da2..4cd273685 100644 --- a/internal/gui/assets/app.js +++ b/internal/gui/assets/app.js @@ -7998,7 +7998,7 @@ function advancedSet(d, p) { !!d.proxyMode || Object.values(d.accountProxies || {}).some((x) => x?.mode) || [d.concurrency, d.maxAccounts, d.queueLimit, d.queueWait, d.maxRPM, d.priceRate, d.contexts, d.outputs, d.compacts].some((v) => String(v ?? "").trim()) || !!d.rateWindows?.length || - !!(d.searches || d.authHeader || d.passUserAgent || d.unredacted || d.countFree || d.pinUpstream || d.nativeCompaction || d.balanceToken || d.limitRestOff || d.http1 || d.imageFilesOff) || + !!(d.searches || d.authHeader || d.passUserAgent || d.unredacted || d.countFree || d.pinUpstream || d.nativeCompaction || d.balanceToken || d.limitRestOff || d.http1 || d.imageFilesOff || d.passErrors) || !!d.fallback?.length || !!p?.balanceToken?.set; } function priceRateError(ed) { @@ -9191,7 +9191,7 @@ function baseAPIOf(p) { // draftOf is a saved provider as its editor's form holds it. function draftOf(p) { - return { id: p.id, name: p.name, preset: p.preset, chat: p.chat, responses: p.responses, anthropic: p.anthropic, gemini: p.gemini || "", catalog: p.catalog, decide: p.decide || "", key: "", api: baseAPIOf(p), chosen: pickedOf(p), none: !!p.noModels, best: !!p.bestInFamily, extra: [], headers: headerRows(p.headers), extraBody: extraBodyText(p.extraBody), replyHeaders: (p.replyHeaders || []).join(", "), passHeaders: (p.passHeaders || []).join(", "), icon: p.icon || "", iconFrom: p.iconFrom || "", fallback: [...(p.fallback || [])], unlisted: !!p.unlisted, hiddenDrawers: [...(p.hiddenDrawers || [])], hiddenVideomakers: [...(p.hiddenVideomakers || [])], searches: !!p.searches, unredacted: !!p.unredacted, countFree: !!p.countFree, insecureTLS: !!p.insecureTLS, http1: !!p.http1, limitRestOff: !!p.limitRestOff, imageFilesOff: !!p.imageFilesOff, nativeCompaction: !!p.nativeCompaction, passUserAgent: !!p.passUserAgent, pinUpstream: !!p.pinUpstream, authHeader: p.authHeader || "", balanceURL: p.balanceURL || "", balancePath: p.balancePath || "", balanceMethod: p.balanceMethod || "", modelsURL: p.modelsURL || "", contexts: contextsText(p.contexts), outputs: contextsText(p.outputs), compacts: contextsText(p.compacts), keysUrl: p.keysUrl || "", ...proxyDraft(p), ...concurrencyDraft(p), rateWindows: (p.rateWindows || []).map((w) => ({ ...w })) }; + return { id: p.id, name: p.name, preset: p.preset, chat: p.chat, responses: p.responses, anthropic: p.anthropic, gemini: p.gemini || "", catalog: p.catalog, decide: p.decide || "", key: "", api: baseAPIOf(p), chosen: pickedOf(p), none: !!p.noModels, best: !!p.bestInFamily, extra: [], headers: headerRows(p.headers), extraBody: extraBodyText(p.extraBody), replyHeaders: (p.replyHeaders || []).join(", "), passHeaders: (p.passHeaders || []).join(", "), icon: p.icon || "", iconFrom: p.iconFrom || "", fallback: [...(p.fallback || [])], unlisted: !!p.unlisted, hiddenDrawers: [...(p.hiddenDrawers || [])], hiddenVideomakers: [...(p.hiddenVideomakers || [])], searches: !!p.searches, unredacted: !!p.unredacted, countFree: !!p.countFree, insecureTLS: !!p.insecureTLS, http1: !!p.http1, limitRestOff: !!p.limitRestOff, passErrors: !!p.passErrors, imageFilesOff: !!p.imageFilesOff, nativeCompaction: !!p.nativeCompaction, passUserAgent: !!p.passUserAgent, pinUpstream: !!p.pinUpstream, authHeader: p.authHeader || "", balanceURL: p.balanceURL || "", balancePath: p.balancePath || "", balanceMethod: p.balanceMethod || "", modelsURL: p.modelsURL || "", contexts: contextsText(p.contexts), outputs: contextsText(p.outputs), compacts: contextsText(p.compacts), keysUrl: p.keysUrl || "", ...proxyDraft(p), ...concurrencyDraft(p), rateWindows: (p.rateWindows || []).map((w) => ({ ...w })) }; } // duplicateProvider opens the Add form on a copy of p, its key p's unless another is pasted (#268). @@ -9605,9 +9605,7 @@ function drawEditor(p, presetID) { keyCount.title = n > 1 ? t("The first is tried first; the other {n} are added to its accounts", { n: n - 1 }) : ""; }; key.oninput = () => { draft.key = key.value; countKeys(); }; - // a curl command from a vendor's docs pasted into the key or the Base URL - // fills the form (@mark_li21 on X), saying what it took; a key it only - // stands for is left out, and the key's box is where to paste one + // a pasted curl command fills the form (@mark_li21 on X) const fromCurl = (e) => { const c = curlOf(e.clipboardData?.getData("text") || ""); if (!c) return false; @@ -9668,10 +9666,7 @@ function drawEditor(p, presetID) { } const keyWrap = el("div", "pair"); keyWrap.append(key, side); - // Google Vertex AI takes no key: it is asked at the user's own Google - // Cloud project with a token their Google credentials mint, so its - // project, location, credentials file and a service account to go as - // are asked in its place, the project first + // Vertex AI: no key, the user's Google Cloud project's token const vertex = p ? !!p.vertex : !!pr?.vertex; let vertexProject = null; if (vertex) draft.vertex = draft.vertex || { project: p?.vertex?.project || "", location: p?.vertex?.location || "", credentials: p?.vertex?.credentials || "", impersonate: p?.vertex?.impersonate || "" }; @@ -9813,6 +9808,12 @@ function drawEditor(p, presetID) { advIn.append(...field(t("Rests"), rtk, t("Off: a 429 or an out-of-quota refusal doesn't rest its keys, and the next request is sent to it as usual. For a relay whose limits pass in a moment."))); } + if (p ? p.takesPassErrors : custom) { + const b = el("button", "sess-pick pass-errors"), d = draft; + import("./passerrors.js").then(() => passErrorsFill(b, d), statusErr); + advIn.append(...field(t("Errors"), b)); + } + // image-files, on DeepSeek's own API (#5407) if (p?.takesImageFiles) { const [itk, icb] = tick(t("Upload images once and send them by file id"), !draft.imageFilesOff); @@ -10171,6 +10172,7 @@ function drawEditor(p, presetID) { if (tlsTakes()) { body.insecureTLS = !!draft.insecureTLS && onHTTPS(); body.http1 = !!draft.http1 && onHTTPS(); } if (custom) body.limitRestOff = !!draft.limitRestOff; if (p?.takesImageFiles) body.imageFilesOff = !!draft.imageFilesOff; + if (p ? p.takesPassErrors : custom) body.passErrors = !!draft.passErrors; if (!decideOnly(p || pr)) body.nativeCompaction = !!draft.nativeCompaction && carriesCompaction(); body.passUserAgent = !!draft.passUserAgent && uaPassable(); const cx = parseContexts(draft.contexts || ""); diff --git a/internal/gui/assets/i18n.js b/internal/gui/assets/i18n.js index c0a990a91..8f8759ac7 100644 --- a/internal/gui/assets/i18n.js +++ b/internal/gui/assets/i18n.js @@ -4038,6 +4038,9 @@ const I18N = { "Set it aside when out of quota or rate limited": "额度用完或被限流时暂停它", "Rests": "暂停", "Off: a 429 or an out-of-quota refusal doesn't rest its keys, and the next request is sent to it as usual. For a relay whose limits pass in a moment.": "关闭后:429 或额度用完的拒绝不会让它的密钥暂停,下一个请求照常发给它。适合限额很快就会恢复的中转。", + "Errors": "错误", + "magpie handles": "由 magpie 处理", + "Pass through": "原样转发", "Upload images once and send them by file id": "图片只上传一次,之后按文件 ID 发送", "Off: an agent's images are sent inline on every turn.": "关闭后:智能体的图片每一轮都直接随请求发送。", "Certificate": "证书", @@ -8651,6 +8654,9 @@ const I18N = { "Set it aside when out of quota or rate limited": "額度用完或被限流時暫停它", "Rests": "暫停", "Off: a 429 or an out-of-quota refusal doesn't rest its keys, and the next request is sent to it as usual. For a relay whose limits pass in a moment.": "關閉後:429 或額度用完的拒絕不會讓它的金鑰暫停,下一個請求照常送給它。適合限額很快就會恢復的中轉。", + "Errors": "錯誤", + "magpie handles": "由 magpie 處理", + "Pass through": "原樣轉發", "Upload images once and send them by file id": "圖片只上傳一次,之後按檔案 ID 傳送", "Off: an agent's images are sent inline on every turn.": "關閉後:代理的圖片每一輪都直接隨請求傳送。", "Certificate": "憑證", @@ -13280,6 +13286,9 @@ const I18N = { "Set it aside when out of quota or rate limited": "クォータ切れやレート制限で一時的に外す", "Rests": "一時停止", "Off: a 429 or an out-of-quota refusal doesn't rest its keys, and the next request is sent to it as usual. For a relay whose limits pass in a moment.": "オフ:429 やクォータ切れで拒否されてもキーを休ませず、次のリクエストはいつも通り送られます。制限がすぐ解けるリレー向けです。", + "Errors": "エラー", + "magpie handles": "magpie が処理", + "Pass through": "そのまま渡す", "Upload images once and send them by file id": "画像は一度だけアップロードし、以降はファイル ID で送る", "Off: an agent's images are sent inline on every turn.": "オフ:エージェントの画像を毎ターンそのまま送ります。", "Certificate": "証明書", @@ -17924,6 +17933,9 @@ const I18N = { "Set it aside when out of quota or rate limited": "Bei aufgebrauchtem Kontingent oder Ratenlimit pausieren", "Rests": "Pausen", "Off: a 429 or an out-of-quota refusal doesn't rest its keys, and the next request is sent to it as usual. For a relay whose limits pass in a moment.": "Aus: Ein 429 oder eine Ablehnung wegen aufgebrauchtem Kontingent pausiert seine Schlüssel nicht, die nächste Anfrage geht wie gewohnt an ihn. Für ein Relay, dessen Limits gleich wieder vorbei sind.", + "Errors": "Fehler", + "magpie handles": "magpie kümmert sich", + "Pass through": "Durchreichen", "Upload images once and send them by file id": "Bilder einmal hochladen und per Datei-ID senden", "Off: an agent's images are sent inline on every turn.": "Aus: Die Bilder eines Agenten werden in jeder Runde direkt mitgeschickt.", "Certificate": "Zertifikat", diff --git a/internal/gui/assets/passerrors.js b/internal/gui/assets/passerrors.js new file mode 100644 index 000000000..ee3cacf37 --- /dev/null +++ b/internal/gui/assets/passerrors.js @@ -0,0 +1,21 @@ +// A provider of a key's Errors menu in its editor's Advanced (ne9ko9 on +// Discord): magpie handles them (asked again, the next provider tried, +// said as the agent's API says it), or they pass through as the vendor +// sent them, asked once. app.js imports this when the editor draws the +// Errors row, so it weighs nothing on the core. +window.passErrorsFill = function fill(b, d) { + const ERR = [["", "magpie handles"], ["pass", "Pass through"]]; + const now = () => ERR[d.passErrors ? 1 : 0]; + b.type = "button"; + b.setAttribute("aria-haspopup", "menu"); + b.setAttribute("aria-expanded", "false"); + b.replaceChildren(el("span", "", t(now()[1])), svg(CHEV, 11, 1.6)); + b.onclick = (e) => { + e.stopPropagation(); + if (b.classList.contains("open")) return closeProtoMenu(); + openProtoMenu(b, ERR.map(([v, name]) => ({ v, name })), now()[0], (v) => { + d.passErrors = v === "pass"; + b.firstChild.textContent = t(now()[1]); + }, "Errors", "sess-menu"); + }; +}; diff --git a/internal/gui/providers.go b/internal/gui/providers.go index 9f22151e0..339a362fd 100644 --- a/internal/gui/providers.go +++ b/internal/gui/providers.go @@ -148,6 +148,11 @@ type providerJSON struct { // editor offers no such choice PassUserAgent bool `json:"passUserAgent"` OwnClient bool `json:"ownClient,omitempty"` + // its errors go to the agent as the vendor sent them, asked once + // (provider.PassErrors, ne9ko9); TakesPassErrors: it is a provider + // of a key, so the editor offers it + PassErrors bool `json:"passErrors"` + TakesPassErrors bool `json:"takesPassErrors,omitempty"` // which header its key goes in on a third-party Anthropic API // (provider.AuthHeader: "" both, "x-api-key", "bearer"), and whether // it is one that sends both by default (provider.BothAuth) @@ -731,7 +736,7 @@ func providerInfoWith(p provider.Provider, ls provider.Listing, agents []agentUs ID: p.ID, Name: p.Name, Icon: p.Icon, IconFrom: p.IconFrom, Preset: p.Preset, Host: p.Host(), Chat: p.Chat, Responses: p.Responses, Anthropic: p.Anthropic, Gemini: p.Gemini, Decide: p.Decide, BaseAPI: p.BaseAPI, ModelTest: p.ModelTest(), TestsAs: p.TestClients(), DecideTest: p.AsksDecideModels(), MarksKinds: p.MarksKinds(), Catalog: p.Catalog, Website: p.Website, KeysURL: p.KeysURL, - Proxy: p.Proxy, AccountProxies: p.AccountProxies, AccountModels: p.AccountModels, AccountCaps: p.AccountCaps, AccountWindowCaps: p.AccountWindowCaps, AccountNames: p.AccountNames, Headers: p.Headers, ExtraBody: p.ExtraBody, ReplyHeaders: p.ReplyHeaders, PassHeaders: p.PassHeaders, Searches: p.Searches, Cline: p.ClinePinnable(), PinUpstream: p.PinUpstream, Unredacted: p.Unredacted, CountFree: p.CountFree, InsecureTLS: p.InsecureTLS, TakesInsecureTLS: p.TakesInsecureTLS(), HTTP1: p.HTTP1, LimitRestOff: p.LimitRestOff, ImageFilesOff: p.ImageFilesOff, TakesImageFiles: p.TakesImageFiles(), NativeCompaction: p.NativeCompaction, CarriesCompaction: p.CarriesCompaction(), PassUserAgent: p.PassUserAgent, OwnClient: p.OwnClient(), AuthHeader: p.AuthHeader, BothAuth: p.BothAuth(), BalanceURL: p.BalanceURL, BalancePath: p.BalancePath, BalanceMethod: p.BalanceMethod, ModelsURL: p.ModelsURL, + Proxy: p.Proxy, AccountProxies: p.AccountProxies, AccountModels: p.AccountModels, AccountCaps: p.AccountCaps, AccountWindowCaps: p.AccountWindowCaps, AccountNames: p.AccountNames, Headers: p.Headers, ExtraBody: p.ExtraBody, ReplyHeaders: p.ReplyHeaders, PassHeaders: p.PassHeaders, Searches: p.Searches, Cline: p.ClinePinnable(), PinUpstream: p.PinUpstream, Unredacted: p.Unredacted, CountFree: p.CountFree, InsecureTLS: p.InsecureTLS, TakesInsecureTLS: p.TakesInsecureTLS(), HTTP1: p.HTTP1, LimitRestOff: p.LimitRestOff, ImageFilesOff: p.ImageFilesOff, TakesImageFiles: p.TakesImageFiles(), NativeCompaction: p.NativeCompaction, CarriesCompaction: p.CarriesCompaction(), PassUserAgent: p.PassUserAgent, OwnClient: p.OwnClient(), PassErrors: p.PassErrors, TakesPassErrors: p.TakesPassErrors(), AuthHeader: p.AuthHeader, BothAuth: p.BothAuth(), BalanceURL: p.BalanceURL, BalancePath: p.BalancePath, BalanceMethod: p.BalanceMethod, ModelsURL: p.ModelsURL, Ready: p.Ready(), Chosen: p.PicksOf(avail), Agents: make([]providerAgent, 0, len(agents)), Fallback: p.Fallback, Routing: p.Routing, Sink: p.Sink, Affinity: p.Affinity, KeepLogin: p.KeepLogin, KeepLoginAs: p.KeepLoginAs, SwitchOnly: p.SwitchOnly, RestartApp: p.RestartApp, Self: p.SelfAnswered(), KeepSelf: p.KeepSelf, CapStop: p.CapStop, CapCareful: p.CapCareful, Unlisted: p.Unlisted, NoModels: p.ServesNone(), BestInFamily: p.BestInFamily && len(p.Models) == 0 && !p.NoModels, Off: p.Off, Contexts: p.Contexts, MaxConcurrency: p.MaxConcurrency, PluginConcurrency: p.PluginConcurrency(), MaxAccounts: p.MaxAccounts, PluginAccounts: p.PluginAtOnce(), PriceRate: p.PriceRate, @@ -1485,6 +1490,10 @@ func providerRoutes(mux *http.ServeMux, w Windows) { // agent's images inline (#5407); a save that leaves it out // keeps it, as `magpie provider set image-files=off` set it ImageFilesOff *bool `json:"imageFilesOff"` + // PassErrors is whether its errors go to the agent as the + // vendor sent them (ne9ko9); a save that leaves it out keeps + // it, as `magpie provider set errors=pass` set it + PassErrors *bool `json:"passErrors"` // MaxConcurrency is how many requests each of its keys or // accounts has out at once: a number (0 none), null for what // its plugin says or none; a save that leaves it out keeps it @@ -1878,6 +1887,9 @@ func providerRoutes(mux *http.ServeMux, w Windows) { if req.ImageFilesOff != nil { in.ImageFilesOff = *req.ImageFilesOff } + if req.PassErrors != nil { + in.PassErrors = *req.PassErrors + } add := provider.Add if req.CopyOf != "" { add = func(p provider.Provider) (string, error) { return provider.AddCopy(p, req.CopyOf) } @@ -1927,6 +1939,11 @@ func providerRoutes(mux *http.ServeMux, w Windows) { } else if old != nil { in.ImageFilesOff = old.ImageFilesOff } + if req.PassErrors != nil { + in.PassErrors = *req.PassErrors + } else if old != nil { + in.PassErrors = old.PassErrors + } if keepCC && old != nil { in.MaxConcurrency = old.MaxConcurrency } diff --git a/internal/gui/tests/old-webkit.test.cjs b/internal/gui/tests/old-webkit.test.cjs index 66145ca78..83e459667 100644 --- a/internal/gui/tests/old-webkit.test.cjs +++ b/internal/gui/tests/old-webkit.test.cjs @@ -158,9 +158,10 @@ test("compat.js is the first of the page's own scripts", async () => { // provider editor draws a key's row, syncfiles.js when Sync's server form, // Export or Import opens, agentcompact.js when an agent sheet holds Long // conversations, balfound.js when the editor draws a relay's balance - // with no Balance URL; the checks above + // with no Balance URL, passerrors.js when it draws a key provider's + // Errors; the checks above // still read them - for (const f of await scripts()) if (!["webfonts.js", "cfgblocked.js", "signsheets.js", "ruleedit.js", "ratewindows.js", "traywindows.js", "autoresetown.js", "registry.js", "navlamp.js", "whatsnew.js", "claudemode.js", "ctxtext.js", "resetask.js", "quotaall.js", "quitask.js", "checkinnow.js", "autobackup.js", "scrollends.js", "profilerename.js", "settingshints.js", "keyspend.js", "syncfiles.js", "agentcompact.js", "balfound.js"].includes(f)) assert(all.includes(f), f + " is not loaded by index.html"); + for (const f of await scripts()) if (!["webfonts.js", "cfgblocked.js", "signsheets.js", "ruleedit.js", "ratewindows.js", "traywindows.js", "autoresetown.js", "registry.js", "navlamp.js", "whatsnew.js", "claudemode.js", "ctxtext.js", "resetask.js", "quotaall.js", "quitask.js", "checkinnow.js", "autobackup.js", "scrollends.js", "profilerename.js", "settingshints.js", "keyspend.js", "syncfiles.js", "agentcompact.js", "balfound.js", "passerrors.js"].includes(f)) assert(all.includes(f), f + " is not loaded by index.html"); }); test("the styles hold up in Safari 15.0", async () => { diff --git a/internal/gui/tests/provider-pass-errors.test.cjs b/internal/gui/tests/provider-pass-errors.test.cjs new file mode 100644 index 000000000..89dc5e69e --- /dev/null +++ b/internal/gui/tests/provider-pass-errors.test.cjs @@ -0,0 +1,161 @@ +// Run with Node's test runner and Playwright on the module path; see README.md. +// ne9ko9 (Discord): a user who wants a provider's errors as the vendor sent +// them, asked once, says so under Advanced: "Errors", magpie handles by +// default, Pass through picked from the app's menu (never a native +// select). Picked and saved, it posts passErrors: true; one saved so opens +// with Advanced open and Pass through shown, and magpie handles posts +// false. A provider of a key, a preset's too, has it; a signed-in account +// has none and its Save sends none. Every language, wide and narrow. +const assert = require("node:assert/strict"); +const fs = require("node:fs/promises"); +const path = require("node:path"); +const { test } = require("node:test"); +const { chromium, webkit } = require("playwright"); + +const assets = path.resolve(__dirname, "../assets"); +const base = { + icon: "generic", chat: "", responses: "", anthropic: "", catalog: "", + models: [{ id: "glm-5", name: "glm-5", on: true }], agents: [], fallback: [], headers: {}, + key: { set: true, masked: "sk-…agg" }, keyList: [], balanceToken: { takes: false, set: false }, proxy: "", searches: false, +}; +const agg = { ...base, id: "agg", name: "Local Aggregator", chat: "http://127.0.0.1:8317/v1", passErrors: false, takesPassErrors: true }; +const kept = { ...base, id: "kept", name: "Kept Relay", chat: "http://127.0.0.1:8318/v1", passErrors: true, takesPassErrors: true }; +const openai = { ...base, id: "openai", name: "OpenAI", preset: "openai", chat: "https://api.openai.example/v1", passErrors: false, takesPassErrors: true }; +const codex = { + id: "codex", name: "Codex", icon: "codex-color", chat: "", responses: "", anthropic: "", catalog: "", + models: [{ id: "gpt-6", name: "GPT-6", on: true }], agents: [], fallback: [], headers: {}, keyList: [], + account: { agent: "codex", agentName: "Codex", user: "me@example.com", plan: "PLUS", logins: [{ user: "me@example.com", plan: "PLUS", active: true, on: true }] }, + proxy: "", +}; + +function serve(lang, posts) { + const providers = { + providers: [agg, kept, openai, codex], + presets: [{ id: "openai", name: "OpenAI", kind: "vendor", icon: "openai", chat: "https://api.openai.example/v1", added: true }], + excluded: [], gateway: { running: true, window: true }, + }; + const state = { agents: [], profiles: [], settings: { lang, theme: "light" } }; + return async (route) => { + const url = new URL(route.request().url()); + const json = (data) => route.fulfill({ json: data }); + if (url.pathname === "/boot.js") return route.fulfill({ contentType: "text/javascript", body: `window.bootPrefs = {lang:"${lang}",theme:"light",web:true};` }); + if (url.pathname === "/wails/runtime.js") return route.fulfill({ contentType: "text/javascript", body: "export const Window = {};" }); + if (url.pathname === "/api/state") return json(state); + if (url.pathname === "/api/providers") return json(providers); + if (url.pathname === "/api/groups") return json({ groups: [] }); + if (url.pathname.startsWith("/api/provider/") && route.request().method() === "POST") { + posts.push({ action: url.pathname.slice("/api/provider/".length), body: route.request().postDataJSON() }); + return json(providers); + } + if (url.pathname.startsWith("/api/")) return json({}); + const file = path.join(assets, url.pathname === "/" ? "index.html" : url.pathname); + const contentType = { ".html": "text/html", ".js": "text/javascript", ".css": "text/css", ".svg": "image/svg+xml", ".png": "image/png" }[path.extname(file)]; + await route.fulfill({ body: await fs.readFile(file), contentType }); + }; +} + +const strings = [ + "Errors", "magpie handles", "Pass through", +]; + +for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) { + for (const lang of ["en", "zh", "zh-TW", "ja", "de"]) { + for (const width of [1100, 420]) { + const open = async (t, name) => { + const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" })); + let page; + t.after(async () => { + if (process.env.ARTIFACT_DIR && page) { + await fs.mkdir(process.env.ARTIFACT_DIR, { recursive: true }); + await page.screenshot({ path: path.join(process.env.ARTIFACT_DIR, `${engine}-${lang}-${width}-${name}-limit-rest.png`), fullPage: true }); + } + await browser.close(); + }); + page = await (await browser.newContext({ viewport: { width, height: 760 }, reducedMotion: "reduce" })).newPage(); + page.setDefaultTimeout(5000); + page.setDefaultNavigationTimeout(60000); + const errors = []; + page.on("pageerror", (e) => errors.push(e.message)); + const posts = []; + await page.route("**/*", serve(lang, posts)); + await page.goto("http://magpie.test/?view=providers"); + const w = await page.evaluate(([lang, ks]) => Object.fromEntries(ks.map((k) => [k, (I18N[lang] || {})[k] || k])), [lang, [...strings, "Save"]]); + await page.locator(".row.provider", { hasText: name }).click(); + await page.locator(".editor .bar").waitFor(); + return { page, errors, posts, w }; + }; + const adv = (page) => page.locator(".editor details.advanced"); + const unfold = async (page) => { + await adv(page).waitFor({ state: "attached" }); + if (!(await adv(page).evaluate((d) => d.open))) await adv(page).locator(":scope > summary").click(); + }; + const pick = (page) => page.locator(".editor button.pass-errors"); + const choose = async (page, w, name) => { + await pick(page).scrollIntoViewIfNeeded(); + await pick(page).click(); + const item = page.locator(".proto-menu .pm-item", { hasText: w[name] }); + assert.equal(await page.locator(".proto-menu .pm-item").count(), 2); + const r = await page.locator(".proto-menu").boundingBox(); + assert.ok(r.x >= 0 && r.x + r.width <= width + 1, `the menu fits: ${JSON.stringify(r)}`); + await item.click(); + await page.locator(".proto-menu").waitFor({ state: "detached" }); + }; + const save = async (page, posts, w) => { + const n = posts.length; + await page.locator(".editor .bar").getByRole("button", { name: w.Save, exact: true }).click(); + for (let i = 0; i < 50 && posts.length === n; i++) await page.waitForTimeout(50); + return posts.at(-1); + }; + + test(`${engine} ${lang} ${width}: a provider of a key has magpie handle its errors by default, and is saved to pass them through`, async (t) => { + const { page, errors, posts, w } = await open(t, "Local Aggregator"); + if (lang !== "en") { + const missing = await page.evaluate(([lang, ks]) => ks.filter((k) => !(I18N[lang] || {})[k]), [lang, strings]); + assert.deepEqual(missing, [], `every string has its ${lang}`); + } + assert.equal(await adv(page).evaluate((d) => d.open), false, "Advanced stays folded while it is as by default"); + await unfold(page); + assert.equal(await pick(page).innerText(), w["magpie handles"]); + assert.equal(await page.locator(".editor select").count(), 0, "no native select"); + await pick(page).scrollIntoViewIfNeeded(); + const r = await pick(page).boundingBox(); + assert.ok(r.width > 40 && r.x >= 0 && r.x + r.width <= width, `the control fits: ${JSON.stringify(r)}`); + assert.equal(await page.evaluate(() => document.documentElement.scrollWidth <= window.innerWidth), true, "no sideways scroll"); + await choose(page, w, "Pass through"); + assert.equal(await pick(page).innerText(), w["Pass through"]); + const saved = await save(page, posts, w); + assert.equal(saved.action, "save"); + assert.equal(saved.body.id, "agg"); + assert.equal(saved.body.passErrors, true); + assert.deepEqual(errors, []); + }); + + test(`${engine} ${lang} ${width}: one saved to pass them opens so with Advanced open, and magpie handles is saved`, async (t) => { + const { page, errors, posts, w } = await open(t, "Kept Relay"); + assert.equal(await adv(page).evaluate((d) => d.open), true, "Advanced opens with it set"); + assert.equal(await pick(page).innerText(), w["Pass through"]); + await choose(page, w, "magpie handles"); + const saved = await save(page, posts, w); + assert.equal(saved.body.id, "kept"); + assert.equal(saved.body.passErrors, false); + assert.deepEqual(errors, []); + }); + + test(`${engine} ${lang} ${width}: a preset of a key has it, a sign-in's has none and sends none`, async (t) => { + { + const { page, errors, posts, w } = await open(t, "OpenAI"); + await unfold(page); + assert.equal(await pick(page).count(), 1); + const saved = await save(page, posts, w); + assert.equal(saved.action, "save"); + assert.equal(saved.body.passErrors, false, `a preset's Save keeps it as it was: ${JSON.stringify(saved.body)}`); + assert.deepEqual(errors, []); + } + const { page, errors, w } = await open(t, "Codex"); + await unfold(page); + assert.equal(await pick(page).count(), 0); + assert.deepEqual(errors, []); + }); + } + } +} diff --git a/internal/provider/pass_errors.go b/internal/provider/pass_errors.go new file mode 100644 index 000000000..68bacc0a4 --- /dev/null +++ b/internal/provider/pass_errors.go @@ -0,0 +1,15 @@ +package provider + +// TakesPassErrors says PassErrors can be set for p: a provider of an API +// key, a preset vendor's or one the user added. A signed-in account and a +// plugin's provider never take it: magpie reads their errors to keep the +// account well (a sign-in to renew, a plan's window to wait out). +func (p Provider) TakesPassErrors() bool { + return p.Account == nil && hasEndpoint(p) && !subscriptionID(p.ID) +} + +// PassesErrors says the gateway hands p's errors to the agent as they came +// and asks it nothing again (PassErrors). +func (p Provider) PassesErrors() bool { + return p.PassErrors && p.TakesPassErrors() +} diff --git a/internal/provider/pass_errors_test.go b/internal/provider/pass_errors_test.go new file mode 100644 index 000000000..78f3bef6a --- /dev/null +++ b/internal/provider/pass_errors_test.go @@ -0,0 +1,22 @@ +package provider + +import "testing" + +// errors=pass is a setting of a provider the user keys; a subscription's +// account or a plugin's isn't asked once, and has none. +func TestPassesErrors(t *testing.T) { + for _, c := range []struct { + name string + p Provider + want bool + }{ + {"keyed", Provider{ID: "relay", Key: "k", Chat: "https://x/v1", PassErrors: true}, true}, + {"keyed, left to magpie", Provider{ID: "relay", Key: "k", Chat: "https://x/v1"}, false}, + {"no endpoint", Provider{ID: "relay", PassErrors: true}, false}, + {"an account", Provider{ID: "codex", Account: &Account{}, Chat: "https://x/v1", PassErrors: true}, false}, + } { + if got := c.p.PassesErrors(); got != c.want { + t.Errorf("%s: PassesErrors = %v, want %v", c.name, got, c.want) + } + } +} diff --git a/internal/provider/provider.go b/internal/provider/provider.go index 184e2d29c..65ba03224 100644 --- a/internal/provider/provider.go +++ b/internal/provider/provider.go @@ -349,6 +349,18 @@ type Provider struct { // the top-level tools even where magpie's default would send the item. AdditionalToolsOff bool `json:"additionalToolsOff,omitempty"` + // PassErrors, `errors=pass`, is the user's word that the client, not + // magpie, deals with what the provider's errors say (ne9ko9 on + // Discord): a request to it is asked once, its error goes to the + // agent as it came (its status, and its body as written where the + // agent's API is the provider's own, else in the agent's shape with + // the vendor's type, code and words), nothing about it is inferred + // (a prompt too long, a busy relay), it is not asked again in place + // or of a fallback or a group's next member, and none of its keys + // rests for it. Off, the default, magpie handles them. Only a provider + // of a key takes it (TakesPassErrors). + PassErrors bool `json:"passErrors,omitempty"` + // Patience is how many seconds more a request to this provider alone, // not through a group, may be kept once it has failed in a way that // passes (overloaded, unavailable, rate limited for a moment) and the