providers: errors=pass sends a vendor's error to the agent as it came, asked once
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 <id> 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 on2f660ca86: 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/main2f660ca86without 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)
This commit is contained in:
File diff suppressed because one or more lines are too long
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -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 <id> <key> change the API key
|
||||
magpie provider icon <id> <file|name> give a custom provider a picture (PNG, JPEG, SVG…) or a built-in icon
|
||||
magpie provider fallback <id> <provider/model>… 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
|
||||
|
||||
@@ -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
|
||||
|
||||
+65
-22
@@ -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:
|
||||
|
||||
@@ -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
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
|
||||
@@ -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 || "");
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -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");
|
||||
};
|
||||
};
|
||||
@@ -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 <id> 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 <id> 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
|
||||
}
|
||||
|
||||
@@ -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 () => {
|
||||
|
||||
@@ -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, []);
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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()
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
|
||||
Reference in New Issue
Block a user