diff --git a/internal/gateway/gateway.go b/internal/gateway/gateway.go index 9a8134ae6..94dc628f4 100644 --- a/internal/gateway/gateway.go +++ b/internal/gateway/gateway.go @@ -2942,6 +2942,11 @@ func (s *Server) passthrough(w http.ResponseWriter, r *http.Request, p provider. if dropImage && !s.fits(p.ID, imageToolRefused, proto) { body, _ = withoutImageTool(body) } + // a tool with a union at its parameters' root, to an upstream that + // takes none (object_root.go, #1271) + if s.foldsRoots(p, model, proto) { + body, _ = objectRootsBody(proto, body) + } // a Grok subscription is given Codex's namespaced functions flat // (grokBody), and Zed's plugin likewise (ZedBody); a call to one goes // back under its namespace (#404) @@ -2968,6 +2973,18 @@ func (s *Server) passthrough(w http.ResponseWriter, r *http.Request, p provider. if proto == provider.Chat { ms = refusedInMessages(res.StatusCode, b, body) } + if len(fs) == 0 && len(ms) == 0 && rootUnionRefusal.Match(b) { + // a tool's parameters refused for a union at their root + // (#1271): asked once more with them folded to an object + if nb, changed := objectRootsBody(proto, body); changed { + refused = append(refused, rootUnionRefused(model)) + body = nb + if res, err = s.forward(r.Context(), p, proto, path, p.Prepare(body), r.Header); err != nil { + return writeError(w, proto, 502, p.Name+": "+err.Error()), err.Error(), true + } + continue + } + } if len(fs) == 0 && len(ms) == 0 && proto == provider.Responses && refusesInput(res.StatusCode, b) { // and reasoning with nothing sealed in it, which a relay in // front of OpenAI turns away as OpenAI does, naming only the @@ -3350,6 +3367,10 @@ func (s *Server) forwardTranslated(ctx context.Context, p provider.Provider, to if mayDropImageTool(p) && !s.fits(p.ID, imageToolRefused, to) { req, _ = withoutImageToolReq(req) } + // Anthropic's Messages are folded as they're built (objectSchema) + if to != provider.Anthropic && s.foldsRoots(p, model, to) { + req, _ = objectRootsReq(req) + } // only a provider that searches by itself is asked to if want := web && searchesFor(p, to, model, req); want != req.WebSearch { r := *req @@ -3443,6 +3464,15 @@ func (s *Server) forwardTranslated(ctx context.Context, p provider.Provider, to s.markUnfit(p.ID, thinkingConfigField, to) continue } + if badRequest(res.StatusCode) && rootUnionRefusal.Match(b) && s.fits(p.ID, rootUnionRefused(model), to) { + if _, changed := objectRootsReq(req); changed { + // a tool's parameters refused for a union at their root + // (#1271): asked again with them folded to an object, and + // so from then on + s.markUnfit(p.ID, rootUnionRefused(model), to) + continue + } + } if req.Format != nil && refusesFormat(res.StatusCode, b) { // structured output turned away by the model or the relay in // front of it (DeepSeek takes json_object only; a schema diff --git a/internal/gateway/object_root.go b/internal/gateway/object_root.go new file mode 100644 index 000000000..1bc0fc6bd --- /dev/null +++ b/internal/gateway/object_root.go @@ -0,0 +1,105 @@ +package gateway + +import ( + "bytes" + "encoding/json" + "regexp" + + "github.com/yetone/magpie/internal/provider" +) + +// A tool whose parameters are an anyOf, oneOf or allOf at the root, as +// Codex desktop's codex_app automation_update is, is turned away by xAI's +// models wherever they are served ("tool parameter root must be an object +// type", #1271: Grok on a relay's key or xAI's own API, not only the Grok +// subscription, whose requests grokBody folds) and by Anthropic's +// ("input_schema does not support oneOf, allOf, or anyOf at the top +// level", #646) behind a relay's Chat API. xAI's own API gets such a tool +// folded to an object root (provider.ObjectRoot) from the start; any other +// upstream that refuses one is asked once more with them folded, and so +// from then on for that model. + +// rootUnionRefusal is an upstream refusing a tool's parameters for a +// union at their root. +var rootUnionRefusal = regexp.MustCompile(`(?i)tool parameter root must be an object type|does not support oneOf, allOf, or anyOf at the top level`) + +// rootUnionRefused is how unfit remembers model refusing one. +func rootUnionRefused(model string) string { return "root union\x00" + model } + +// foldsRoots reports whether p's requests for model go with their tools' +// parameters folded to an object root. +func (s *Server) foldsRoots(p provider.Provider, model string, proto provider.Protocol) bool { + return p.Host() == "api.x.ai" || !s.fits(p.ID, rootUnionRefused(model), proto) +} + +// objectRootsBody is a Chat or Responses body whose function tools' +// parameters have an object root, and whether any was changed. +func objectRootsBody(proto provider.Protocol, body []byte) ([]byte, bool) { + if (proto != provider.Chat && proto != provider.Responses) || !bytes.Contains(body, []byte(`Of"`)) { + return body, false + } + dec := json.NewDecoder(bytes.NewReader(body)) + dec.UseNumber() + var m map[string]any + if dec.Decode(&m) != nil || m == nil { + return body, false + } + tools, _ := m["tools"].([]any) + if !foldTools(proto, tools) { + return body, false + } + out, err := marshalPlain(m) + if err != nil { + return body, false + } + return out, true +} + +// foldTools folds the parameters of the function tools among tools, a +// namespace's included, and reports whether it changed any. +func foldTools(proto provider.Protocol, tools []any) bool { + changed := false + for _, t := range tools { + tm, _ := t.(map[string]any) + if tm == nil { + continue + } + if proto == provider.Responses && tm["type"] == "namespace" { + nested, _ := tm["tools"].([]any) + if foldTools(proto, nested) { + changed = true + } + continue + } + fn := tm + if proto == provider.Chat { + fn, _ = tm["function"].(map[string]any) + } + if ps, _ := fn["parameters"].(map[string]any); ps != nil && provider.ObjectRoot(ps) { + changed = true + } + } + return changed +} + +// objectRootsReq is a translated request whose tools' schemas have an +// object root, and whether any was changed. +func objectRootsReq(req *Request) (*Request, bool) { + var tools []Tool + for i, t := range req.Tools { + s := objectSchema(t.Schema) + if bytes.Equal(s, t.Schema) { + continue + } + if tools == nil { + tools = append([]Tool(nil), req.Tools...) + } + tools[i].Schema = s + } + if tools == nil { + return req, false + } + r := *req + r.Tools = tools + return &r, true +} diff --git a/internal/gateway/object_root_test.go b/internal/gateway/object_root_test.go new file mode 100644 index 000000000..2e22cd873 --- /dev/null +++ b/internal/gateway/object_root_test.go @@ -0,0 +1,161 @@ +package gateway + +import ( + "encoding/json" + "io" + "net/http" + "net/http/httptest" + "os" + "strings" + "sync" + "testing" + + "github.com/yetone/magpie/internal/provider" +) + +// rootUnionUpstream answers as Grok behind a relay does (AiHubMix's +// grok-4.7, 2026-10-08, its bytes): a request offering a function whose +// parameters have no object root is refused, else answered, on Chat or +// Responses as asked. +func rootUnionUpstream(mu *sync.Mutex, got *[]map[string]any) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + b, _ := io.ReadAll(r.Body) + var q map[string]any + json.Unmarshal(b, &q) + mu.Lock() + *got = append(*got, q) + mu.Unlock() + tools, _ := q["tools"].([]any) + for _, t := range tools { + tm, _ := t.(map[string]any) + ps, _ := tm["parameters"].(map[string]any) + if fn, ok := tm["function"].(map[string]any); ok { + ps, _ = fn["parameters"].(map[string]any) + } + if ps != nil && (ps["type"] != "object" || ps["anyOf"] != nil || ps["oneOf"] != nil) { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(400) + io.WriteString(w, `{"error":{"message":"Failed to start sampling: [invalid_client_tool_schema] mcp__codex_app__automation_update: tool parameter root must be an object type (root schema is an anyOf/oneOf union with a non-object branch) (tid: 2026100808425178410684649237042)","type":"upstream_error","param":"400","code":"bad_response_status_code"}}`) + return + } + } + answer(w, r) + } +} + +// answer replies "ok" as a Chat stream or a Responses body. +func answer(w http.ResponseWriter, r *http.Request) { + if strings.HasSuffix(r.URL.Path, "/chat/completions") { + w.Header().Set("Content-Type", "text/event-stream") + io.WriteString(w, "data: {\"id\":\"c1\",\"object\":\"chat.completion.chunk\",\"choices\":[{\"index\":0,\"delta\":{\"role\":\"assistant\",\"content\":\"ok\"}}]}\n\n"+ + "data: {\"id\":\"c1\",\"object\":\"chat.completion.chunk\",\"choices\":[{\"index\":0,\"delta\":{},\"finish_reason\":\"stop\"}]}\n\ndata: [DONE]\n\n") + return + } + w.Header().Set("Content-Type", "application/json") + io.WriteString(w, `{"id":"r1","object":"response","status":"completed","output":[{"type":"message","role":"assistant","content":[{"type":"output_text","text":"ok"}]}],"usage":{"input_tokens":9,"output_tokens":1}}`) +} + +// Codex desktop offers codex_app's automation_update, whose parameters are +// a union at the root (the fixture is what ChatGPT.app 26.930's zod +// builds), flat as mcp__codex_app__automation_update. Grok on a relay's +// key, on its Chat API or its Responses, refused every turn ("tool +// parameter root must be an object type", #1271). It is asked again with +// the parameters folded to an object root, and the next turn goes folded +// at once; a vendor that takes the union still gets it as sent. +func TestRootUnionFoldedWhereRefused(t *testing.T) { + schema, err := os.ReadFile("../provider/testdata/codex_automation_update_schema.json") + if err != nil { + t.Fatal(err) + } + body := `{"model":"%s","stream":false,"store":false,"tools":[{"type":"function","name":"exec_command","parameters":{"type":"object","properties":{"cmd":{"type":"string"}}}},` + + `{"type":"function","name":"mcp__codex_app__automation_update","strict":false,"parameters":` + string(schema) + `}],` + + `"input":[{"type":"message","role":"user","content":[{"type":"input_text","text":"hi"}]}]}` + for name, api := range map[string]string{"passed through": "responses", "translated": "chat"} { + t.Run(name, func(t *testing.T) { + fresh(t) + var mu sync.Mutex + var refusing, taking []map[string]any + strict := httptest.NewServer(rootUnionUpstream(&mu, &refusing)) + t.Cleanup(strict.Close) + lax := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + b, _ := io.ReadAll(r.Body) + var q map[string]any + json.Unmarshal(b, &q) + mu.Lock() + taking = append(taking, q) + mu.Unlock() + answer(w, r) + })) + t.Cleanup(lax.Close) + for _, p := range []provider.Provider{ + {ID: "relay", Name: "Relay", Key: "k", Models: []string{"grok-4.7"}}, + {ID: "lax", Name: "Lax", Key: "k", Models: []string{"m1"}}, + } { + url := strict.URL + "/v1" + if p.ID == "lax" { + url = lax.URL + "/v1" + } + if api == "chat" { + p.Chat = url + } else { + p.Responses = url + } + if err := provider.Save(p); err != nil { + t.Fatal(err) + } + } + s := New() + ask := func(model string) *httptest.ResponseRecorder { + rec := httptest.NewRecorder() + s.Handler().ServeHTTP(rec, httptest.NewRequest("POST", "/v1/responses", strings.NewReader(strings.Replace(body, "%s", model, 1)))) + return rec + } + params := func(q map[string]any) map[string]any { + for _, t := range q["tools"].([]any) { + tm := t.(map[string]any) + if fn, ok := tm["function"].(map[string]any); ok { + tm = fn + } + if tm["name"] == "mcp__codex_app__automation_update" { + return tm["parameters"].(map[string]any) + } + } + return nil + } + rec := ask("relay/grok-4.7") + if rec.Code != 200 || !strings.Contains(rec.Body.String(), "ok") { + t.Fatalf("relay: %d %s", rec.Code, rec.Body) + } + if len(refusing) != 2 { + t.Fatalf("relay was asked %d times", len(refusing)) + } + ps := params(refusing[1]) + props, _ := ps["properties"].(map[string]any) + if ps["type"] != "object" || ps["anyOf"] != nil || props["prompt"] == nil || props["mode"] == nil { + t.Fatalf("asked again with %v", ps) + } + if rec = ask("relay/grok-4.7"); rec.Code != 200 || len(refusing) != 3 || params(refusing[2])["anyOf"] != nil { + t.Fatalf("next turn: %d, asked %d times", rec.Code, len(refusing)) + } + if rec = ask("lax/m1"); rec.Code != 200 || len(taking) != 1 || params(taking[0])["anyOf"] == nil { + t.Fatalf("lax: %d, asked %d times", rec.Code, len(taking)) + } + }) + } +} + +// xAI's own API takes no union at a tool's root on any model, so its +// requests go folded from the first (#1271); another vendor's go as sent +// until one is refused. +func TestRootUnionFoldedForXAI(t *testing.T) { + fresh(t) + s := New() + xai := provider.Provider{ID: "xai", Chat: "https://api.x.ai/v1", Responses: "https://api.x.ai/v1"} + other := provider.Provider{ID: "other", Chat: "https://api.example.com/v1"} + if !s.foldsRoots(xai, "grok-4.7", provider.Responses) || !s.foldsRoots(xai, "grok-4.7", provider.Chat) { + t.Fatal("xAI's API not folded") + } + if s.foldsRoots(other, "m1", provider.Chat) { + t.Fatal("another vendor folded before any refusal") + } +}