gateway: a vendor's error reaches the agent in its own words first (@gptchan404)
@gptchan404 on X: magpie wrapped a vendor's error in its own words, e.g.
Factory's refusal arrived as "claude-opus-5-5 refused this request
(safety filter: content_policy_rejected — <Factory's words>) via
Factory", so there was no error of the vendor's own to take back to it.
Now the message the agent reads starts with the vendor:
Factory: This request was blocked by Factory's usage policy check.
(upstream request id …, code content_policy_rejected) (HTTP 400)
magpie: claude-opus-5-5 refused this request (safety filter:
content_policy_rejected) via Factory — <the plugin's advice>
Line 1 is the provider's name, the vendor's words verbatim
(provider.VendorWords), then (HTTP status, code, request id), each
left out when the words already hold it. magpie's own notes go on a
second line that starts "magpie: ". A plugin's advice after " — " goes
on magpie's line (pluginWords). The vendor's JSON error fields
(type/code/param/request_id) still pass through as before
(writeVendorErrorFrom).
Covered: Anthropic messages, OpenAI chat, Responses and Gemini, each
whole and streamed, for any vendor error (writeVendorErrorFrom ->
upstreamTold) and for a safety-filter refusal no one else answered
(failTo -> refusalTold).
Only the client sees the new text. A try's held bytes and call.Error
keep magpie's reading, because the rest scope, the rate hold, the
retired model, the verify hold and failover all classify them. The
holdWriter retells them on output only (retold, in release and in
passing writes). codex_backend's summaryEndedShort now reads the
vendor line only.
Tests whose pinned text changed on purpose: kept_error_test,
zcode_blocked_test, verify_test (sameVerify: a held verify answer is
magpie's own and keeps its one-line form),
remote_magpie_restricted_test. Doc: docs/subsystems/gateway-routing.md.
Run (mote, at this tree):
- go test ./internal/gateway -run
'Told|Refus|Factory|Kept|Relay|Verify|Codex|Plugin|Retired|Rate|Zcode|ZCode|Restricted':
ok (346s).
- Red on old code: TestRefusalToldWithTheVendorsWordsFirst and
TestVendorErrorToldWithItsOwnWordsFirst, 32 of 32 subtests red at
origin/main 76868bad6. TestPluginAdviceToldOnMagpiesLine red with
pluginWords broken by hand.
- Earlier gateway run: only TestOpenCodeGoOwnFreeModelGetsNothingOfOpenCodes
red, also red on clean origin/main (#7117).
- gofmt -l clean. GOOS=windows go vet ./... ok. GOOS=linux go vet of
./internal/gateway and ./internal/provider ok (a cross ./... vet stops
in Wails' cgo files).
- Full suite: queued on mote at this tree, pushed before it finishes
per the owner's rule (10-22); any red gets an issue.
Not tried: a real Factory account (the case comes from the plugin's
own message format, packages/factory index.mjs); the GUI request view
shows the client's body, so it shows this text, and has no separate
vendor-raw view; a remote magpie chained in front of another would
show the inner magpie's first line inside the outer's.
This commit is contained in:
File diff suppressed because one or more lines are too long
@@ -4123,9 +4123,15 @@ func lacksEndpoint(status int) bool {
|
||||
|
||||
// summaryEndedShort is a summary ask answered 502 because the reply
|
||||
// stopped before its end: a translated one serve held whole and found
|
||||
// cut (errEndedShort, #3526, Edward4226's third shape).
|
||||
// cut (errEndedShort, #3526, Edward4226's third shape). The words end
|
||||
// the vendor's line of the error, before what upstreamTold names it by.
|
||||
func summaryEndedShort(rec *recorder) bool {
|
||||
return rec.status == http.StatusBadGateway && strings.HasSuffix(provider.APIError(rec.body.Bytes(), ""), errEndedShort.Error())
|
||||
if rec.status != http.StatusBadGateway {
|
||||
return false
|
||||
}
|
||||
line, _, _ := strings.Cut(provider.APIError(rec.body.Bytes(), ""), magpieSays)
|
||||
line = strings.TrimSuffix(line, " (HTTP 502)")
|
||||
return strings.HasSuffix(line, errEndedShort.Error())
|
||||
}
|
||||
|
||||
// upstreamFailed is a relay's own word that the provider behind it turned
|
||||
|
||||
@@ -2789,6 +2789,11 @@ type holdWriter struct {
|
||||
// one in the same stream (refusalHandover); handedOver says it was
|
||||
over *refusalHandover
|
||||
handedOver bool
|
||||
|
||||
// retold is how the vendor's error the try wrote is told to the
|
||||
// agent (retell): the held bytes keep magpie's reading of it, which
|
||||
// the rest, the rate hold and the retired model are read from
|
||||
retold []retelling
|
||||
}
|
||||
|
||||
// onLoop sets what is told of a loop before it ends the reply (reask),
|
||||
@@ -2936,7 +2941,10 @@ func (h *holdWriter) Write(b []byte) (int, error) {
|
||||
}
|
||||
if h.passing {
|
||||
h.sent(b)
|
||||
return h.w.Write(b)
|
||||
if n, err := h.w.Write(retell(h.retold, b)); err != nil {
|
||||
return n, err
|
||||
}
|
||||
return len(b), nil
|
||||
}
|
||||
n, err := h.held.Write(b)
|
||||
if h.stream && h.failure == 0 {
|
||||
@@ -3734,7 +3742,7 @@ func (h *holdWriter) release() {
|
||||
streamError(h.w, h.alive.proto, h.alive.model, h.failure, who+" "+h.failMsg)
|
||||
case h.status >= 400:
|
||||
// an error status, once the agent has a stream: told as its error
|
||||
streamError(h.w, h.alive.proto, h.alive.model, h.status, provider.APIError(h.held.Bytes(), http.StatusText(h.status)))
|
||||
streamError(h.w, h.alive.proto, h.alive.model, h.status, retellText(h.retold, provider.APIError(h.held.Bytes(), http.StatusText(h.status))))
|
||||
default:
|
||||
// a reply given whole by a vendor that ignored stream:true,
|
||||
// after the agent was kept alive: sent as the stream it asked
|
||||
@@ -3744,7 +3752,7 @@ func (h *holdWriter) release() {
|
||||
return
|
||||
}
|
||||
h.pass()
|
||||
h.w.Write(h.held.Bytes())
|
||||
h.w.Write(retell(h.retold, h.held.Bytes()))
|
||||
h.flush()
|
||||
}
|
||||
|
||||
|
||||
@@ -5737,7 +5737,8 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro
|
||||
// nobody is left: the agent is told it was refused, as a
|
||||
// request it shouldn't send again as it is, not handed an empty
|
||||
// reply it would ask again for, paying for each
|
||||
failTo(w, kept, from, refusedStatus, call.Error)
|
||||
// told with the vendor's own words first (refusalTold)
|
||||
failTo(w, kept, from, refusedStatus, refusalTold(c.p, c.model, hw.status, call.Usage.RequestID, hw.failMsg, c.p.IsPlugin()))
|
||||
} else if hw.turnedAway && hw.failed() {
|
||||
// nobody is left to answer what Antigravity turned away: the
|
||||
// agent is told why, at a status it doesn't retry, not the 429
|
||||
|
||||
@@ -2,6 +2,7 @@ package gateway
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"cmp"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"strings"
|
||||
@@ -39,6 +40,17 @@ func errorShape(proto provider.Protocol) int {
|
||||
// the agent compact). Every other byte is the vendor's. A body not in the client's
|
||||
// shape is rebuilt in it, as before.
|
||||
func writeVendorErrorFrom(w http.ResponseWriter, proto, upstream provider.Protocol, p provider.Provider, res *http.Response, msg string, body []byte) int {
|
||||
// the agent is told the vendor's words first, as it said them, and
|
||||
// magpie's after (upstreamTold); a try's held reply keeps magpie's
|
||||
// reading, which what follows the try reads, and is told so only on
|
||||
// its way to the agent (retell)
|
||||
msg = cmp.Or(msg, p.Name+": "+provider.APIError(body, res.Status))
|
||||
told := upstreamTold(p.Name, res.StatusCode, res.Header, body, msg, p.IsPlugin())
|
||||
if h := holdOf(w); h != nil {
|
||||
h.retellAs(msg, told)
|
||||
} else {
|
||||
msg = told
|
||||
}
|
||||
if status, ok := writeKeptError(w, proto, upstream, p, res, msg, body); ok {
|
||||
return status
|
||||
}
|
||||
|
||||
@@ -12,7 +12,8 @@ import (
|
||||
// ne9ko9 on Discord: a vendor that speaks the client's own API has its
|
||||
// error reach the client as it came: its status, its own type, a numeric
|
||||
// code and the fields magpie knows nothing of, every byte but the message,
|
||||
// which names the provider. It was rebuilt from the status, with only a
|
||||
// which names the provider, and its status, code and request id after the
|
||||
// vendor's words (upstreamTold). It was rebuilt from the status, with only a
|
||||
// string code kept.
|
||||
func TestSameAPIErrorKeptAsSent(t *testing.T) {
|
||||
for _, c := range []struct {
|
||||
@@ -23,13 +24,13 @@ func TestSameAPIErrorKeptAsSent(t *testing.T) {
|
||||
}{
|
||||
{"chat", "/v1/chat/completions", `{"model":"a/m","messages":[{"role":"user","content":"hi"}]}`, provider.Chat, 400,
|
||||
`{"error":{"message":"Request rejected by gateway rule (FX-1214)","type":"upstream_rule","code":1214,"param":null,"extra":{"trace":"t-9"}},"request_id":"req-77"}`,
|
||||
`{"error":{"message":"A: Request rejected by gateway rule (FX-1214)","type":"upstream_rule","code":1214,"param":null,"extra":{"trace":"t-9"}},"request_id":"req-77"}`},
|
||||
`{"error":{"message":"A: Request rejected by gateway rule (FX-1214) (HTTP 400, request id req-77)","type":"upstream_rule","code":1214,"param":null,"extra":{"trace":"t-9"}},"request_id":"req-77"}`},
|
||||
{"anthropic", "/v1/messages", `{"model":"a/m","max_tokens":10,"messages":[{"role":"user","content":"hi"}]}`, provider.Anthropic, 403,
|
||||
`{"type":"error","error":{"type":"upstream_rule","message":"Request rejected by gateway rule","code":20031,"details":["region"]},"request_id":"req_01"}`,
|
||||
`{"type":"error","error":{"type":"upstream_rule","message":"A: Request rejected by gateway rule","code":20031,"details":["region"]},"request_id":"req_01"}`},
|
||||
`{"type":"error","error":{"type":"upstream_rule","message":"A: Request rejected by gateway rule (HTTP 403, 20031, request id req_01)","code":20031,"details":["region"]},"request_id":"req_01"}`},
|
||||
{"responses", "/v1/responses", `{"model":"a/m","input":"hi"}`, provider.Responses, 400,
|
||||
`{"error":{"message":"Request rejected by gateway rule","type":"upstream_rule","code":1214,"param":"input","extra":true}}`,
|
||||
`{"error":{"message":"A: Request rejected by gateway rule","type":"upstream_rule","code":1214,"param":"input","extra":true}}`},
|
||||
`{"error":{"message":"A: Request rejected by gateway rule (HTTP 400, 1214)","type":"upstream_rule","code":1214,"param":"input","extra":true}}`},
|
||||
} {
|
||||
t.Run(c.name, func(t *testing.T) {
|
||||
fresh(t)
|
||||
@@ -57,7 +58,7 @@ func TestSameAPIOverflowKeepsTheRest(t *testing.T) {
|
||||
if w.Code != 400 || gjson.Get(b, "error.code").String() != "context_length_exceeded" || gjson.Get(b, "error.type").String() != "invalid_request_error" {
|
||||
t.Fatalf("overflow not said as Chat says it: %d %s", w.Code, b)
|
||||
}
|
||||
if gjson.Get(b, "error.extra").String() != "x" || gjson.Get(b, "request_id").String() != "r1" || gjson.Get(b, "error.message").String() != "A: Prompt exceeds max length" {
|
||||
if gjson.Get(b, "error.extra").String() != "x" || gjson.Get(b, "request_id").String() != "r1" || gjson.Get(b, "error.message").String() != "A: Prompt exceeds max length (HTTP 400, 1261, request id r1)" {
|
||||
t.Fatalf("the vendor's other fields were lost: %s", b)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -128,7 +128,7 @@ func TestRemoteMagpieVerifyHeldOnTheModel(t *testing.T) {
|
||||
t.Fatalf("%d %s", code, body)
|
||||
}
|
||||
for range 2 {
|
||||
if code, again := postAs(t, s, "", req); code != 403 || provider.APIError([]byte(again), "") != msg {
|
||||
if code, again := postAs(t, s, "", req); code != 403 || !sameVerify(provider.APIError([]byte(again), ""), msg) {
|
||||
t.Fatalf("held: %d %s", code, again)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,224 @@
|
||||
package gateway
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"github.com/tidwall/gjson"
|
||||
|
||||
"github.com/yetone/magpie/internal/provider"
|
||||
)
|
||||
|
||||
// magpieSays begins the line of an error told to the agent that is
|
||||
// magpie's own, after the vendor's: what magpie read of the error and
|
||||
// what to do, kept apart from the vendor's words so a user can copy
|
||||
// those as they were said, to the vendor (@gptchan404 on X).
|
||||
const magpieSays = "\nmagpie: "
|
||||
|
||||
// upstreamTold is a vendor's error as the agent is told it: on its first
|
||||
// line the provider's name, the vendor's own words as it said them and
|
||||
// what it named the error by — its HTTP status, its code and its request
|
||||
// id, each left out when its words already say it — and after it, on a
|
||||
// line of its own, whatever magpie said beyond those words (msg, the
|
||||
// error as explained, less the provider's name and the vendor's words it
|
||||
// begins with). An agent that shows only an error's first line shows the
|
||||
// vendor's. A plugin's error (plugin) is its vendor's words with the
|
||||
// plugin's advice after a " — ", as provider.Explain joins them: only the
|
||||
// words before it are the vendor's, and the advice is told on magpie's
|
||||
// line (pluginWords).
|
||||
func upstreamTold(name string, status int, header http.Header, b []byte, msg string, plugin bool) string {
|
||||
words := provider.VendorWords(b)
|
||||
if plugin {
|
||||
words = pluginWords(words)
|
||||
}
|
||||
head := name + ": "
|
||||
rest := strings.TrimPrefix(msg, head)
|
||||
// APIError's status line ("403 Forbidden: …"), which the first
|
||||
// line says as HTTP 403
|
||||
rest = strings.TrimPrefix(rest, fmt.Sprintf("%d %s: ", status, http.StatusText(status)))
|
||||
if words != "" && strings.HasPrefix(rest, words) {
|
||||
rest = rest[len(words):]
|
||||
}
|
||||
rest = strings.TrimLeft(rest, " —-:")
|
||||
named := upstreamNamed(status, vendorCode(b), vendorRequestID(header, b), words)
|
||||
line := head + words
|
||||
switch {
|
||||
case words == "" && named != "":
|
||||
line = head + named
|
||||
case named != "":
|
||||
line += " (" + named + ")"
|
||||
}
|
||||
if rest == "" || rest == words {
|
||||
return line
|
||||
}
|
||||
return line + magpieSays + rest
|
||||
}
|
||||
|
||||
// upstreamNamed is what a vendor named its error by, as the first line
|
||||
// of upstreamTold says it: "HTTP 403, content_policy_rejected, request id
|
||||
// …", each part the vendor's words don't already hold, and no code that
|
||||
// is only the status again (Google's "code": 403).
|
||||
func upstreamNamed(status int, code, reqID, words string) string {
|
||||
var parts []string
|
||||
if status >= 400 {
|
||||
parts = append(parts, fmt.Sprintf("HTTP %d", status))
|
||||
}
|
||||
if code != "" && code != fmt.Sprint(status) && !strings.Contains(words, code) {
|
||||
parts = append(parts, code)
|
||||
}
|
||||
if reqID != "" && !strings.Contains(words, reqID) {
|
||||
parts = append(parts, "request id "+reqID)
|
||||
}
|
||||
return strings.Join(parts, ", ")
|
||||
}
|
||||
|
||||
// vendorCode is the code a vendor's error body names its error by: the
|
||||
// error's code (a string or a number), else its type, else its status
|
||||
// (Gemini's RESOURCE_EXHAUSTED…), at the top level for a body with no
|
||||
// error object. "" for none, and for the bare type "error".
|
||||
func vendorCode(b []byte) string {
|
||||
e := gjson.GetBytes(b, "error")
|
||||
if !e.IsObject() {
|
||||
e = gjson.ParseBytes(b)
|
||||
if !e.IsObject() {
|
||||
return ""
|
||||
}
|
||||
}
|
||||
for _, k := range []string{"code", "type", "status"} {
|
||||
v := e.Get(k)
|
||||
if v.Type != gjson.String && v.Type != gjson.Number {
|
||||
continue
|
||||
}
|
||||
if s := strings.TrimSpace(v.String()); s != "" && s != "error" && s != "0" {
|
||||
return s
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// vendorRequestID is the id a vendor gave the failed request, for the
|
||||
// user to quote to it: the reply's Request-Id or X-Request-Id, else the
|
||||
// body's request_id (Anthropic's).
|
||||
func vendorRequestID(h http.Header, b []byte) string {
|
||||
if id := requestID(h); id != "" {
|
||||
return id
|
||||
}
|
||||
for _, k := range []string{"request_id", "error.request_id", "requestId"} {
|
||||
if v := gjson.GetBytes(b, k); v.Type == gjson.String && strings.TrimSpace(v.String()) != "" {
|
||||
return strings.TrimSpace(v.String())
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// refusalTold is what the agent is told of a request the vendor's safety
|
||||
// filter refused and nobody else answered: the vendor's own words first,
|
||||
// as upstreamTold puts them (status the vendor's, when it answered with
|
||||
// an error status), and magpie's line after them, which names the model
|
||||
// and the filter's reason (refusedError). why is the refusal's note,
|
||||
// "safety filter: <reason> — <the vendor's words>" (refusedNote) or the
|
||||
// reason with what Anthropic's stop_details said (refusedDetail).
|
||||
func refusalTold(p provider.Provider, model string, status int, reqID, why string, plugin bool) string {
|
||||
reason, words, said := strings.Cut(why, " — ")
|
||||
reason = strings.TrimPrefix(reason, "safety filter: ")
|
||||
if !said {
|
||||
// a stop reason, with nothing said beside it but what
|
||||
// stop_details may give, in the reason's parentheses
|
||||
words = reason
|
||||
}
|
||||
advice := ""
|
||||
if plugin && said {
|
||||
// the plugin's advice goes on magpie's line (pluginWords)
|
||||
if w := pluginWords(words); w != words {
|
||||
words, advice = w, " — "+strings.TrimSpace(words[len(w)+len(" — "):])
|
||||
}
|
||||
}
|
||||
code := reason
|
||||
if i := strings.IndexByte(code, ' '); i > 0 {
|
||||
code = code[:i]
|
||||
}
|
||||
line := p.Name + ": " + words
|
||||
if named := upstreamNamed(status, code, reqID, words); named != "" {
|
||||
line += " (" + named + ")"
|
||||
}
|
||||
return line + magpieSays + refusedError(p, model, "safety filter: "+code) + advice
|
||||
}
|
||||
|
||||
// pluginWords is the vendor's part of a plugin's error message: what comes
|
||||
// before the first " — ", after which a plugin puts its own advice
|
||||
// (Factory's "… (upstream request id …, code …) — Factory's usage policy
|
||||
// check reads the whole conversation, …").
|
||||
func pluginWords(said string) string {
|
||||
w, _, _ := strings.Cut(said, " — ")
|
||||
return w
|
||||
}
|
||||
|
||||
// retelling is one error's text as magpie read it (from) and as the agent
|
||||
// is told it (to).
|
||||
type retelling struct{ from, to string }
|
||||
|
||||
// holdOf is the try's holdWriter under w and the writers wrapped around
|
||||
// it, nil for none.
|
||||
func holdOf(w http.ResponseWriter) *holdWriter {
|
||||
for w != nil {
|
||||
if h, ok := w.(*holdWriter); ok {
|
||||
return h
|
||||
}
|
||||
u, ok := w.(interface{ Unwrap() http.ResponseWriter })
|
||||
if !ok {
|
||||
return nil
|
||||
}
|
||||
w = u.Unwrap()
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// retellAs has the try's reply tell the agent to where it says from.
|
||||
func (h *holdWriter) retellAs(from, to string) {
|
||||
if from == "" || from == to {
|
||||
return
|
||||
}
|
||||
h.mu.Lock()
|
||||
h.retold = append(h.retold, retelling{from, to})
|
||||
h.mu.Unlock()
|
||||
}
|
||||
|
||||
// retell is b with each error magpie wrote in it told as rs say, in each
|
||||
// way a JSON string of it can be written (with and without HTML's
|
||||
// characters escaped); b itself, never written to, when none is in it.
|
||||
func retell(rs []retelling, b []byte) []byte {
|
||||
for _, r := range rs {
|
||||
from, to := jsonStringBody(r.from, true), jsonStringBody(r.to, true)
|
||||
if bytes.Contains(b, from) {
|
||||
b = bytes.ReplaceAll(b, from, to)
|
||||
continue
|
||||
}
|
||||
// once only: to holds from, so a second pass of the same bytes
|
||||
// would tell it twice
|
||||
if from, to = jsonStringBody(r.from, false), jsonStringBody(r.to, false); bytes.Contains(b, from) {
|
||||
b = bytes.ReplaceAll(b, from, to)
|
||||
}
|
||||
}
|
||||
return b
|
||||
}
|
||||
|
||||
// retellText is s told as rs say.
|
||||
func retellText(rs []retelling, s string) string {
|
||||
for _, r := range rs {
|
||||
s = strings.ReplaceAll(s, r.from, r.to)
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
// jsonStringBody is s as a JSON string's contents, its HTML characters escaped
|
||||
// as encoding/json does by default or not.
|
||||
func jsonStringBody(s string, escapeHTML bool) []byte {
|
||||
var buf bytes.Buffer
|
||||
e := json.NewEncoder(&buf)
|
||||
e.SetEscapeHTML(escapeHTML)
|
||||
e.Encode(s)
|
||||
return bytes.TrimSuffix(bytes.TrimSuffix(bytes.TrimPrefix(buf.Bytes(), []byte(`"`)), []byte("\n")), []byte(`"`))
|
||||
}
|
||||
@@ -0,0 +1,144 @@
|
||||
package gateway
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strconv"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/yetone/magpie/internal/provider"
|
||||
)
|
||||
|
||||
// toldAsks are an error's ask in each protocol the gateway answers, whole
|
||||
// and streamed.
|
||||
var toldAsks = []struct{ name, path, body string }{
|
||||
{"messages", "/v1/messages", `{"model":"f/m","max_tokens":64,"messages":[{"role":"user","content":"hi"}]}`},
|
||||
{"messages stream", "/v1/messages", `{"model":"f/m","max_tokens":64,"stream":true,"messages":[{"role":"user","content":"hi"}]}`},
|
||||
{"chat", "/v1/chat/completions", `{"model":"f/m","messages":[{"role":"user","content":"hi"}]}`},
|
||||
{"chat stream", "/v1/chat/completions", `{"model":"f/m","stream":true,"messages":[{"role":"user","content":"hi"}]}`},
|
||||
{"responses", "/v1/responses", `{"model":"f/m","input":"hi"}`},
|
||||
{"responses stream", "/v1/responses", `{"model":"f/m","stream":true,"input":"hi"}`},
|
||||
{"gemini", "/v1beta/models/f/m:generateContent", `{"contents":[{"role":"user","parts":[{"text":"hi"}]}]}`},
|
||||
{"gemini stream", "/v1beta/models/f/m:streamGenerateContent?alt=sse", `{"contents":[{"role":"user","parts":[{"text":"hi"}]}]}`},
|
||||
}
|
||||
|
||||
// inJSON is s as it reads inside a JSON string.
|
||||
func inJSON(s string) string {
|
||||
b, _ := json.Marshal(s)
|
||||
return strings.ReplaceAll(strings.Trim(string(b), `"`), `\u0026`, "&")
|
||||
}
|
||||
|
||||
// @gptchan404 on X: a vendor's refusal reached the agent wrapped in
|
||||
// magpie's words ("claude-opus-5-5 refused this request (safety filter:
|
||||
// content_policy_rejected — <Factory's words>) via Factory"), so the user
|
||||
// had no error of the vendor's own to take back to it. Every protocol,
|
||||
// whole and streamed, is now told the vendor's words first, with its
|
||||
// status, on a line of their own, and magpie's after them.
|
||||
func TestRefusalToldWithTheVendorsWordsFirst(t *testing.T) {
|
||||
for _, up := range []provider.Protocol{provider.Anthropic, provider.Chat} {
|
||||
for _, ask := range toldAsks {
|
||||
t.Run(string(up)+"/"+ask.name, func(t *testing.T) {
|
||||
fresh(t)
|
||||
f := &scripted{replies: []reply{{403, "application/json", factoryPolicy403(up == provider.Anthropic)}}}
|
||||
scriptedOn(t, "f", up, f)
|
||||
_, out := sendTo(New(), ask.path, ask.body)
|
||||
first := "F: " + factoryPolicyMsg + " (HTTP 403)"
|
||||
if !strings.Contains(out, inJSON(first+"\nmagpie: m refused this request (safety filter: content_policy_rejected) via F")) {
|
||||
t.Errorf("not the vendor's words first, then magpie's:\n%s", out)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Any other error of a vendor's is told the same way: its words, status,
|
||||
// code and request id first, as it said them; and a client of OpenAI's
|
||||
// shape keeps the vendor's code on the error.
|
||||
func TestVendorErrorToldWithItsOwnWordsFirst(t *testing.T) {
|
||||
for _, up := range []provider.Protocol{provider.Anthropic, provider.Chat} {
|
||||
for _, ask := range toldAsks {
|
||||
t.Run(string(up)+"/"+ask.name, func(t *testing.T) {
|
||||
fresh(t)
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
io.ReadAll(r.Body)
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.Header().Set("Request-Id", "req_7Hq2")
|
||||
w.WriteHeader(http.StatusBadRequest)
|
||||
if up == provider.Anthropic {
|
||||
io.WriteString(w, `{"type":"error","error":{"type":"invalid_request_error","message":"messages.0.content: Input should be a valid list"}}`)
|
||||
return
|
||||
}
|
||||
io.WriteString(w, `{"error":{"message":"messages.0.content: Input should be a valid list","type":"invalid_request_error","code":"invalid_value"}}`)
|
||||
}))
|
||||
t.Cleanup(srv.Close)
|
||||
p := provider.Provider{ID: "f", Name: "F", Key: "k", Models: []string{"m"}}
|
||||
if up == provider.Anthropic {
|
||||
p.Anthropic = srv.URL
|
||||
} else {
|
||||
p.Chat = srv.URL + "/v1"
|
||||
}
|
||||
if err := provider.Save(p); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
_, out := sendTo(New(), ask.path, ask.body)
|
||||
code := "invalid_value"
|
||||
if up == provider.Anthropic {
|
||||
code = "invalid_request_error"
|
||||
}
|
||||
first := "F: messages.0.content: Input should be a valid list (HTTP 400, " + code + ", request id req_7Hq2)"
|
||||
if !strings.Contains(out, inJSON(first)) {
|
||||
t.Errorf("not the vendor's words, status, code and request id first:\n%s", out)
|
||||
}
|
||||
oai := strings.HasPrefix(ask.path, "/v1/chat") || strings.HasPrefix(ask.path, "/v1/responses")
|
||||
if oai && up == provider.Chat && !strings.Contains(out, `"invalid_value"`) {
|
||||
t.Errorf("the vendor's code left out of the error: %s", out)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestUpstreamTold(t *testing.T) {
|
||||
b := []byte(`{"error":{"message":"Your credit balance is too low","type":"invalid_request_error"}}`)
|
||||
h := http.Header{"X-Request-Id": {"r1"}}
|
||||
for _, c := range []struct{ msg, want string }{
|
||||
{"P: Your credit balance is too low", "P: Your credit balance is too low (HTTP 400, invalid_request_error, request id r1)"},
|
||||
{"P: Your credit balance is too low — top up at example.com", "P: Your credit balance is too low (HTTP 400, invalid_request_error, request id r1)\nmagpie: top up at example.com"},
|
||||
{"", "P: Your credit balance is too low (HTTP 400, invalid_request_error, request id r1)"},
|
||||
} {
|
||||
if got := upstreamTold("P", 400, h, b, c.msg, false); got != c.want {
|
||||
t.Errorf("%q:\n got %q\nwant %q", c.msg, got, c.want)
|
||||
}
|
||||
}
|
||||
// an empty body: who, and its status, first; magpie's reading after
|
||||
if got := upstreamTold("P", 403, http.Header{}, nil, "P: 403 Forbidden: "+provider.NoDetails, false); got != "P: HTTP 403\nmagpie: "+provider.NoDetails {
|
||||
t.Errorf("empty body: %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
// The Factory plugin's refusal (packages/factory, @gptchan404's case):
|
||||
// Factory's words and its request id and code on the first line, the
|
||||
// plugin's advice on magpie's, after the refusal.
|
||||
func TestPluginAdviceToldOnMagpiesLine(t *testing.T) {
|
||||
advice := factoryPolicyMsg[strings.Index(factoryPolicyMsg, " — ")+len(" — "):]
|
||||
factory := "This request was blocked by Factory's usage policy check. (upstream request id 8d1f0c2a3b4e5f60::LAX, code content_policy_rejected)"
|
||||
p := provider.Provider{ID: "factory", Name: "Factory"}
|
||||
got := refusalTold(p, "claude-opus-5-5", 400, "", "safety filter: content_policy_rejected — "+factoryPolicyMsg, true)
|
||||
want := "Factory: " + factory + " (HTTP 400)\nmagpie: claude-opus-5-5 refused this request (safety filter: content_policy_rejected) via Factory — " + advice
|
||||
if got != want {
|
||||
t.Errorf("refusal:\n got %q\nwant %q", got, want)
|
||||
}
|
||||
b := []byte(`{"error":{"type":"permission_error","message":` + strconv.Quote(factoryPolicyMsg) + `}}`)
|
||||
got = upstreamTold("Factory", 403, http.Header{}, b, "Factory: "+factoryPolicyMsg, true)
|
||||
if want := "Factory: " + factory + " (HTTP 403, permission_error)\nmagpie: " + advice; got != want {
|
||||
t.Errorf("error:\n got %q\nwant %q", got, want)
|
||||
}
|
||||
// a vendor's own words keep their dash when no plugin wrote them
|
||||
got = upstreamTold("Factory", 403, http.Header{}, b, "Factory: "+factoryPolicyMsg, false)
|
||||
if want := "Factory: " + factoryPolicyMsg + " (HTTP 403, permission_error)"; got != want {
|
||||
t.Errorf("not a plugin's:\n got %q\nwant %q", got, want)
|
||||
}
|
||||
}
|
||||
@@ -31,9 +31,11 @@ func TestVerifyRefusalRestsTheLastOne(t *testing.T) {
|
||||
t.Fatalf("try %+v rest %+v", try, try.Rest)
|
||||
}
|
||||
|
||||
// the agent reconnects at once: held, not sent on
|
||||
// the agent reconnects at once: held, not sent on, and told the same:
|
||||
// the vendor's words and where to verify (the first reply puts the
|
||||
// vendor's words first, upstreamTold; a held one is magpie's own)
|
||||
for range 3 {
|
||||
if code, again := postAs(t, s, "", req); code != 403 || provider.APIError([]byte(again), "") != msg {
|
||||
if code, again := postAs(t, s, "", req); code != 403 || !sameVerify(provider.APIError([]byte(again), ""), msg) {
|
||||
t.Fatalf("%d %s", code, again)
|
||||
}
|
||||
}
|
||||
@@ -122,7 +124,7 @@ func TestAgyCLIVerifyWords(t *testing.T) {
|
||||
s := New()
|
||||
code, got := postAs(t, s, "", `{"model":"a/m","messages":[{"role":"user","content":"hi"}]}`)
|
||||
msg := provider.APIError([]byte(got), "")
|
||||
if code != 403 || strings.Count(msg, "needs to be verified") != 1 || !strings.HasSuffix(msg, c.tail) {
|
||||
if code != 403 || strings.Count(msg, "needs to be verified") != 1 || !strings.Contains(msg, c.tail) {
|
||||
t.Fatalf("%d: %s", code, msg)
|
||||
}
|
||||
r := s.trace.routes[len(s.trace.routes)-1]
|
||||
@@ -132,3 +134,14 @@ func TestAgyCLIVerifyWords(t *testing.T) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// sameVerify says whether two answers to an account Google wants verified
|
||||
// tell the same: Google's words, and the link to verify it at.
|
||||
func sameVerify(a, b string) bool {
|
||||
for _, w := range []string{"Verify your account to continue.", "open https://accounts.google.com/signin/continue?sarp=1&x=2 in a browser"} {
|
||||
if !strings.Contains(a, w) || !strings.Contains(b, w) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
@@ -147,9 +147,9 @@ func TestRelayRefusalSaysWhatItWas(t *testing.T) {
|
||||
name, ct, body string
|
||||
want []string
|
||||
}{
|
||||
{"cloudflare", "text/html; charset=UTF-8", cf, []string{"403 Forbidden: a web page, not an API reply: “Attention Required! | Cloudflare”", provider.BlockedHint}},
|
||||
{"page", "text/html", "<html><head><title>403 Forbidden</title></head><body><center><h1>403 Forbidden</h1></center><hr><center>nginx</center></body></html>", []string{"403 Forbidden: a web page, not an API reply: “403 Forbidden”"}},
|
||||
{"empty", "", "", []string{"403 Forbidden: " + provider.NoDetails}},
|
||||
{"cloudflare", "text/html; charset=UTF-8", cf, []string{"Relay: a web page, not an API reply: “Attention Required! | Cloudflare” (HTTP 403)", provider.BlockedHint}},
|
||||
{"page", "text/html", "<html><head><title>403 Forbidden</title></head><body><center><h1>403 Forbidden</h1></center><hr><center>nginx</center></body></html>", []string{"Relay: a web page, not an API reply: “403 Forbidden” (HTTP 403)"}},
|
||||
{"empty", "", "", []string{"Relay: HTTP 403\nmagpie: " + provider.NoDetails}},
|
||||
{"json", "application/json", `{"error":{"message":"this key may not use gpt-5.5","type":"forbidden"}}`, []string{"this key may not use gpt-5.5"}},
|
||||
} {
|
||||
t.Run(c.name, func(t *testing.T) {
|
||||
@@ -194,18 +194,19 @@ func TestRelayRefusalSaysWhatItWas(t *testing.T) {
|
||||
// (maralica on Discord, "magpie-grok"): it is asked for its own model id,
|
||||
// never one magpie named, with WorkBuddy's User-Agent as sent, and
|
||||
// whatever reason its 403 gives reaches the agent: plain text, JSON, a
|
||||
// page with no title, a page's fragment, an XML error.
|
||||
// page with no title, a page's fragment, an XML error. The relay's words
|
||||
// come first, with its status, as upstreamTold says them.
|
||||
func TestChatRelayRefusalSaysWhy(t *testing.T) {
|
||||
const ua = "WorkBuddy/5.9.2 WorkBuddy/5.9.2 CLI/2.165.0"
|
||||
for _, c := range []struct {
|
||||
name, ct, body, want string
|
||||
}{
|
||||
{"text", "text/plain", "only Claude Code and Codex CLI are allowed", "magpie-grok: 403 Forbidden: only Claude Code and Codex CLI are allowed"},
|
||||
{"json", "application/json", `{"error":{"message":"client WorkBuddy is not allowed","type":"forbidden"}}`, "magpie-grok: client WorkBuddy is not allowed"},
|
||||
{"untitled page", "text/html", "<html><body><h1>403</h1><p>only Claude Code & Codex CLI are allowed</p></body></html>", "magpie-grok: 403 Forbidden: a web page, not an API reply: “403 only Claude Code & Codex CLI are allowed”"},
|
||||
{"fragment", "text/html", "<h1>Forbidden</h1>\n<p>client not allowed</p>", "magpie-grok: 403 Forbidden: Forbidden client not allowed"},
|
||||
{"xml", "application/xml", `<?xml version="1.0"?><Error><Code>ClientNotAllowed</Code><Message>client not allowed</Message></Error>`, "magpie-grok: 403 Forbidden: ClientNotAllowed client not allowed"},
|
||||
{"empty", "", "", "magpie-grok: 403 Forbidden: " + provider.NoDetails},
|
||||
{"text", "text/plain", "only Claude Code and Codex CLI are allowed", "magpie-grok: only Claude Code and Codex CLI are allowed (HTTP 403)"},
|
||||
{"json", "application/json", `{"error":{"message":"client WorkBuddy is not allowed","type":"forbidden"}}`, "magpie-grok: client WorkBuddy is not allowed (HTTP 403, forbidden)"},
|
||||
{"untitled page", "text/html", "<html><body><h1>403</h1><p>only Claude Code & Codex CLI are allowed</p></body></html>", "magpie-grok: a web page, not an API reply: “403 only Claude Code & Codex CLI are allowed” (HTTP 403)"},
|
||||
{"fragment", "text/html", "<h1>Forbidden</h1>\n<p>client not allowed</p>", "magpie-grok: Forbidden client not allowed (HTTP 403)"},
|
||||
{"xml", "application/xml", `<?xml version="1.0"?><Error><Code>ClientNotAllowed</Code><Message>client not allowed</Message></Error>`, "magpie-grok: ClientNotAllowed client not allowed (HTTP 403)"},
|
||||
{"empty", "", "", "magpie-grok: HTTP 403\nmagpie: " + provider.NoDetails},
|
||||
} {
|
||||
for _, model := range []string{"magpie-grok/grok-4.7", "group/g"} {
|
||||
t.Run(c.name+" "+model, func(t *testing.T) {
|
||||
|
||||
@@ -1174,6 +1174,15 @@ func APIError(b []byte, fallback string) string {
|
||||
return apiError(b, fallback)
|
||||
}
|
||||
|
||||
// VendorWords is what a vendor's error body says in its own words, as
|
||||
// APIError reads them but with none of magpie's hints after them: the
|
||||
// error's message (with its type and code when the message is only a
|
||||
// status line), or the body itself cut short. "" for a body that says
|
||||
// nothing (empty), for the caller to say so.
|
||||
func VendorWords(b []byte) string {
|
||||
return strings.TrimPrefix(apiError(b, ""), ": ")
|
||||
}
|
||||
|
||||
// cmdGoNoAPI is Command Code's Provider API refusing a Go plan's key:
|
||||
// "Your Go plan doesn't include API access. Upgrade to Provider or higher
|
||||
// …" (#969). Go's key is only taken where Command Code's CLI asks, which
|
||||
|
||||
Reference in New Issue
Block a user