diff --git a/docs/subsystems/gateway-routing.md b/docs/subsystems/gateway-routing.md index 29f33a384..af114a5de 100644 --- a/docs/subsystems/gateway-routing.md +++ b/docs/subsystems/gateway-routing.md @@ -171,6 +171,7 @@ recorded as a prediction failure (`noPrediction`). - Kiro is told where to cache the prompt (plugins#110: a Kiro subscription read 0 from its cache). Its API takes Bedrock's `cachePoint: {"type":"default"}` on a `userInputMessage`, an `assistantResponseMessage` or as a tool entry. The built-in (`buildKiro` in [`kiro.go`](../../internal/gateway/kiro.go)) marks the first message when there is a system prompt, which it folds into that message, and the current message, as `buildAnthropic` marks Anthropic's. A moved Kiro's plugin (opencode-kiro-auth 0.1.10, the mover's `min`) turns each `cache_control` in the Anthropic body it is handed into one, at most 4, the last kept. - A model that refuses a conversation ending with the assistant's message (`refusesPrefill`: OpenCode Go's Claude models over Messages, "This model does not support assistant message prefill"; Volcengine's Agent Plan, "…for a model that does not support prefill"; Gemini's, "Requests ending with a model turn are not supported") is marked for that provider, model and API (`prefillRefused`, #1447); the provider's other models keep their prefill ([`prefill.go`](../../internal/gateway/prefill.go)). A Chat or Responses client's conversation ending with the assistant's message, which those APIs read as a turn already said (`Request.LastIsTurn`), is asked again with a user turn after it (`continueText`), translated (`forwardTranslated`) or relayed (`passthrough`, `userLastBody`), and so from then on. An Anthropic client's prefill is its own ask and gets the refusal as sent. magpie's own continuation of a cut reply (`continuation.go`) isn't asked of that model again; the try the model refused ends the reply with what cut it, not with the refusal. A request magpie builds in Gemini's own shape (`buildCodeAssistSent`: Vertex AI, Gemini CLI's and Antigravity's Code Assist, Factory) never ends with the model's turn, which all of them turn away: a user turn goes after it, `continueText`, or `compactLastText` when an agent is compacting with its ask in the system prompt (`modelLastAsk`), as one goes before a history that opens with the model's. Nor does it send a user turn that mixes a tool's `functionResponse` with text, which Vertex AI answers with the same "ending with a model turn" (#1533: Codex's compaction prompt after a tool's output): what the user said goes in a user turn of its own after the tools' responses (`hasResponse`), except for a Claude model on Antigravity, whose tool_result turn holds both. - A tool's `strict` that an upstream turns away (`toolStrictRefusal` in [`strict_refused.go`](../../internal/gateway/strict_refused.go): "Unsupported Chat Completions API field: tools[0].function.strict", OpenAI-style unknown_parameter, "Extra inputs are not permitted" and pydantic's extra_forbidden on it) is asked once more without it, in Chat's `tools[].function` and Responses' `tools[]` alike, and marked for that provider and API (`toolStrictRefused`): its next requests go without it at once. OpenCode 2 sends `"strict": false` on every tool through `@ai-sdk/openai-compatible`, and a custom provider that refused it ended the session (#1980). An upstream that hasn't refused it still gets it, as the ChatGPT backend needs it (#383). `TestToolStrictLeftOutWhereRefused` (real OpenCode 2.0.25 requests), `TestToolStrictRefusalWordings`. +- A Codex custom tool (exec, apply_patch) that a Responses upstream turns away (`customToolRefusal` in [`custom_tool.go`](../../internal/gateway/custom_tool.go): DeepSeek's 400 "Unsupported custom tool: 'exec'. Only 'apply_patch' is supported.", #2656) ends the relay: `passthrough` marks the model (`customToolRefused`) and returns not done, and `attempt` translates the request on the same API (`ownAPI`), where each custom tool is offered as a function taking its `input` and a call comes back as the `custom_tool_call` Codex runs, its name kept. A marked model's next requests with a custom tool are translated at once; one without stays relayed, and an upstream that never refused them still gets them as sent. A compaction (`keepsCompaction`) isn't translated, and gets the refusal. Where the refusal reaches a group untranslated it is a shape refusal (`shapeRefused`): the next member is asked. `TestCustomToolTranslatedWhereRefused`, `TestCustomToolRefusalInGroup`, `TestCustomToolRefusalWordings`. - A model's reply limit is published within the window beside it (#1438, `provider.OutputWithin`, `Entry.PublishedOutput`): `/v1/models`' `max_output_tokens` (`modelObject`), Cursor Private Inference's `capabilities.max_output_tokens` (`cursorLocalModel`), Muse Code's `limit.output` (`museModels`), the GUI's model and group rows (`providerInfo`, `providersState`), `magpie model output`, and every agent's file (`agent.maxTokens`, #338). The window and the output can come from different sources: Grok's backend lists grok-4.7's 256000 window, and models.dev fills its 500000 output (`catalog.Decorate` and `Provider.replyLimit` fill an output only where the vendor gives none). An unknown window or output is published as it is. The catalog keeps the unclamped `Entry.Output`, and a group's member is still asked for no more than that (`outputLimit`, `withMaxOutput`), so a request isn't lowered by the clamp. A limit the user set stays in their settings as they set it (`TestModelListsKeepOutputWithinTheWindow`). Outside a group, only a Max output the user set for the model (`Entry.OutputSet`) lowers a request (`userOutput`): Claude Code asks a claude-* model for its own full limit (128000 on Opus 5.5) and is told no figure of magpie's for it (`claudeOutput`), and a key whose quota is held per request as max_tokens times the price turned every turn away (YaCo on Discord, `TestUserMaxOutputLowersAPlainProvidersRequest`). A vendor's or models.dev's figure doesn't lower it, since it may be stale. - A request that names no reply limit, translated to Anthropic's Messages API, which needs `max_tokens` (`forwardTranslated`; a Zed subscription's Claude in `serveZed`), is sent the model's published limit (`askedOutput` in [`maxoutput.go`](../../internal/gateway/maxoutput.go)): the user's Max output, else the vendor's list or models.dev, within the window. `anthropicBody`'s `defaultMaxTokens` (16384) is left only for a model whose limit isn't known. Every Codex turn on a Claude went at 16384 before, and a long thinking and tool turn ran out of it: `stop_reason: max_tokens` reaches a Responses client as `incomplete_details.reason: "max_output_tokens"` (#1792, tensornull). A limit the client names goes as it is. The thinking budget fits under the filled limit as under one the client named (`TestAnthropicMaxTokensIsTheModels`). diff --git a/internal/gateway/custom_tool.go b/internal/gateway/custom_tool.go new file mode 100644 index 000000000..da54f83a6 --- /dev/null +++ b/internal/gateway/custom_tool.go @@ -0,0 +1,66 @@ +package gateway + +import ( + "bytes" + "encoding/json" + "regexp" +) + +// Codex offers custom tools on Responses (exec in code mode, apply_patch): +// a tool of type custom whose call carries free-form input. A vendor's +// Responses API may take none of them, or only some: DeepSeek's answers +// 400 "Unsupported custom tool: 'exec'. Only 'apply_patch' is supported." +// to a request that only offers exec (#2656). A relay sends the tools as +// they came, so such a request is translated instead, on the same API: +// the translation offers each custom tool as a function taking its input +// (customSchema) and gives a call to one back as the custom_tool_call +// Codex runs. Once the model has turned them away it is translated from +// the start. + +// customToolRefusal is an upstream turning a custom tool away: DeepSeek's +// "Unsupported custom tool: 'exec'", or the type named unsupported. A +// refusal of anything else about a tool doesn't match. +var customToolRefusal = regexp.MustCompile(`(?i)unsupported custom tool|custom tools? (?:is |are )?not (?:supported|allowed)|(?:unsupported|unknown|invalid) tool type[^\n{}]{0,20}?['"\x60]custom['"\x60]|tool type ['"\x60]custom['"\x60] (?:is )?(?:not supported|unsupported)`) + +// customToolRefused is how unfit remembers model turning custom tools +// away. +func customToolRefused(model string) string { return "custom tools\x00" + model } + +// hasCustomTool reports whether a Responses body offers a custom tool: +// among its tools, in a namespace there, or in an input item that carries +// tools (Responses Lite's additional_tools, a tool search's output). +func hasCustomTool(body []byte) bool { + if !bytes.Contains(body, []byte(`"custom"`)) { + return false + } + var m map[string]any + if json.Unmarshal(body, &m) != nil { + return false + } + if customIn(m["tools"]) { + return true + } + items, _ := m["input"].([]any) + for _, it := range items { + if im, _ := it.(map[string]any); im != nil && customIn(im["tools"]) { + return true + } + } + return false +} + +// customIn reports whether a list of tools has a custom one, a namespace's +// included. +func customIn(v any) bool { + tools, _ := v.([]any) + for _, t := range tools { + tm, _ := t.(map[string]any) + if tm == nil { + continue + } + if tm["type"] == "custom" || tm["type"] == "namespace" && customIn(tm["tools"]) { + return true + } + } + return false +} diff --git a/internal/gateway/custom_tool_test.go b/internal/gateway/custom_tool_test.go new file mode 100644 index 000000000..c3ed67c7d --- /dev/null +++ b/internal/gateway/custom_tool_test.go @@ -0,0 +1,223 @@ +package gateway + +import ( + "encoding/json" + "fmt" + "io" + "net/http" + "net/http/httptest" + "strings" + "sync" + "testing" + + "github.com/yetone/magpie/internal/provider" +) + +// deepSeekCustomRefusal is DeepSeek's Responses API turning Codex's exec +// away, the message as #2656's reporter got it from api.deepseek.com. +const deepSeekCustomRefusal = `{"error":{"message":"Unsupported custom tool: 'exec'. Only 'apply_patch' is supported.","type":"invalid_request_error","param":null,"code":null}}` + +// customExecRequest is #2656's request: Codex's exec offered as a custom +// tool, nothing called yet. +const customExecRequest = `{"model":%q,"stream":%t,"input":[{"role":"user","content":"Return ok."}],` + + `"tools":[{"type":"custom","name":"exec","description":"Execute source text.","format":{"type":"text"}}]}` + +// customUpstream is a Responses API that, like DeepSeek's, takes no custom +// tool but apply_patch, and calls exec when it is offered as a function. +type customUpstream struct { + mu sync.Mutex + asked []map[string]any + paths []string +} + +func (u *customUpstream) ServeHTTP(w http.ResponseWriter, r *http.Request) { + b, _ := io.ReadAll(r.Body) + var q map[string]any + json.Unmarshal(b, &q) + u.mu.Lock() + u.asked = append(u.asked, q) + u.paths = append(u.paths, r.URL.Path) + u.mu.Unlock() + tools, _ := q["tools"].([]any) + for _, t := range tools { + if tm, _ := t.(map[string]any); tm["type"] == "custom" && tm["name"] != "apply_patch" { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(400) + io.WriteString(w, deepSeekCustomRefusal) + return + } + } + call := `{"type":"function_call","id":"fc_1","call_id":"call_1","name":"exec","arguments":"{\"input\":\"print(1)\"}","status":"completed"}` + if q["stream"] == true { + w.Header().Set("Content-Type", "text/event-stream") + io.WriteString(w, sse( + `data: {"type":"response.created","response":{"id":"r1","status":"in_progress","output":[]}}`, + `data: {"type":"response.output_item.added","output_index":0,"item":{"type":"function_call","id":"fc_1","call_id":"call_1","name":"exec","arguments":""}}`, + `data: {"type":"response.function_call_arguments.delta","output_index":0,"item_id":"fc_1","delta":"{\"input\":\"print(1)\"}"}`, + `data: {"type":"response.output_item.done","output_index":0,"item":`+call+`}`, + `data: {"type":"response.completed","response":{"id":"r1","status":"completed","output":[`+call+`],"usage":{"input_tokens":9,"output_tokens":3}}}`)) + return + } + w.Header().Set("Content-Type", "application/json") + io.WriteString(w, `{"id":"r1","object":"response","status":"completed","output":[`+call+`],"usage":{"input_tokens":9,"output_tokens":3}}`) +} + +// A Responses API that takes no custom tool (DeepSeek's, #2656) turned +// every Codex turn offering exec away, and magpie gave the 400 back. The +// turn is now translated on the same API: exec offered as a function +// taking its input, the call back to Codex as the custom_tool_call it +// runs, exec's name kept. The next turn goes translated at once, and an +// upstream that takes custom tools still gets them as sent. +func TestCustomToolTranslatedWhereRefused(t *testing.T) { + for _, stream := range []bool{false, true} { + t.Run(fmt.Sprintf("stream %t", stream), func(t *testing.T) { + fresh(t) + noRests() + t.Cleanup(noRests) + refusing := &customUpstream{} + ds := httptest.NewServer(refusing) + t.Cleanup(ds.Close) + var taking []map[string]any + var mu sync.Mutex + 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{ + // Chat and Responses both, as DeepSeek's preset has them + {ID: "ds", Name: "DeepSeek", Key: "k", Models: []string{"deepseek-flash"}, Chat: ds.URL + "/v1", Responses: ds.URL + "/v1"}, + {ID: "lax", Name: "Lax", Key: "k", Models: []string{"m1"}, Responses: lax.URL + "/v1"}, + } { + 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(fmt.Sprintf(customExecRequest, model, stream)))) + return rec + } + rec := ask("ds/deepseek-flash") + if rec.Code != 200 { + t.Fatalf("ds: %d %s", rec.Code, rec.Body) + } + if len(refusing.asked) != 2 || refusing.paths[1] != "/v1/responses" { + t.Fatalf("ds asked %d times, at %v", len(refusing.asked), refusing.paths) + } + tool, _ := refusing.asked[1]["tools"].([]any)[0].(map[string]any) + props, _ := tool["parameters"].(map[string]any)["properties"].(map[string]any) + if tool["type"] != "function" || tool["name"] != "exec" || props["input"] == nil { + t.Fatalf("asked again with %v", tool) + } + var call map[string]any + if stream { + for _, e := range events(rec.Body.String()) { + if e["type"] == "response.output_item.done" { + call, _ = e["item"].(map[string]any) + } + } + } else { + var out struct{ Output []map[string]any } + json.Unmarshal(rec.Body.Bytes(), &out) + for _, it := range out.Output { + if it["type"] != "reasoning" { + call = it + } + } + } + if call["type"] != "custom_tool_call" || call["name"] != "exec" || call["input"] != "print(1)" || call["call_id"] != "call_1" { + t.Fatalf("Codex got %v\n%s", call, rec.Body) + } + + // the next turn goes translated at once + if rec = ask("ds/deepseek-flash"); rec.Code != 200 || len(refusing.asked) != 3 { + t.Fatalf("next turn: %d, asked %d times: %s", rec.Code, len(refusing.asked), rec.Body) + } + if tool, _ := refusing.asked[2]["tools"].([]any)[0].(map[string]any); tool["type"] != "function" { + t.Fatalf("next turn offered %v", tool) + } + + // an upstream that takes them gets them as sent + if rec = ask("lax/m1"); rec.Code != 200 || len(taking) != 1 { + t.Fatalf("lax: %d, asked %d times", rec.Code, len(taking)) + } + if tool, _ := taking[0]["tools"].([]any)[0].(map[string]any); tool["type"] != "custom" { + t.Fatalf("lax offered %v", tool) + } + }) + } +} + +// In a routing group the refusing member answers translated, and the +// next member isn't asked (#2656: the group gave the 400 back, its +// healthy member never asked). +func TestCustomToolRefusalInGroup(t *testing.T) { + fresh(t) + noRests() + t.Cleanup(noRests) + refusing := &customUpstream{} + ds := httptest.NewServer(refusing) + t.Cleanup(ds.Close) + asked := 0 + next := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + asked++ + answer(w, r) + })) + t.Cleanup(next.Close) + for _, p := range []provider.Provider{ + {ID: "ds", Name: "DeepSeek", Key: "k", Models: []string{"deepseek-flash"}, Responses: ds.URL + "/v1"}, + {ID: "next", Name: "Next", Key: "k", Models: []string{"m1"}, Responses: next.URL + "/v1"}, + } { + if err := provider.Save(p); err != nil { + t.Fatal(err) + } + } + if err := provider.SaveGroup(provider.Group{ID: "repro", Name: "Reproduction", Routing: provider.Ordered, Members: []string{"ds/deepseek-flash", "next/m1"}}); err != nil { + t.Fatal(err) + } + rec := httptest.NewRecorder() + New().Handler().ServeHTTP(rec, httptest.NewRequest("POST", "/v1/responses", strings.NewReader(fmt.Sprintf(customExecRequest, "group/repro", false)))) + if rec.Code != 200 || !strings.Contains(rec.Body.String(), `"custom_tool_call"`) { + t.Fatalf("%d %s", rec.Code, rec.Body) + } + if len(refusing.asked) != 2 || asked != 0 { + t.Fatalf("ds asked %d times, next %d", len(refusing.asked), asked) + } +} + +// The refusal is known as DeepSeek words it, decoded or not, and as a +// vendor may name the type; a 400 over something else about a tool is +// not taken for one. A group's next member is asked over it where it +// reaches the group untranslated. +func TestCustomToolRefusalWordings(t *testing.T) { + for _, b := range []string{ + deepSeekCustomRefusal, + `{"error":{"message":"Unsupported custom tool: 'exec'. Only 'apply_patch' is supported."}}`, + `{"error":{"message":"DeepSeek: Unsupported custom tool: 'exec'. Only 'apply_patch' is supported.","type":"invalid_request_error"}}`, + `{"error":{"message":"Invalid tool type: 'custom'"}}`, + `{"error":{"message":"custom tools are not supported"}}`, + } { + if !customToolRefusal.Match(wordsOf([]byte(b))) { + t.Errorf("not known: %s", b) + } + if !shapeRefused(400, []byte(b)) { + t.Errorf("no next member over: %s", b) + } + } + for _, b := range []string{ + `{"error":{"message":"Invalid schema for function 'exec': 'input' is required"}}`, + `{"error":{"message":"tools[0].function.strict is not supported"}}`, + `{"error":{"message":"Insufficient Balance"}}`, + } { + if customToolRefusal.Match([]byte(b)) { + t.Errorf("taken for one: %s", b) + } + } +} diff --git a/internal/gateway/fallback.go b/internal/gateway/fallback.go index 039c25552..6719cf6ba 100644 --- a/internal/gateway/fallback.go +++ b/internal/gateway/fallback.go @@ -1133,7 +1133,9 @@ func promptRefused(status int, body []byte) bool { // (#350), OpenAI's "Unknown parameter", and a limit of its own on a tool's // JSON schema: OpenCode Go's 400 "JSON schema exceeds the maximum nesting // depth of 10 levels" on muse-spark-1.3-contributor for Claude Code's MCP -// tools (#1870), which another member's model may take as they are. A +// tools (#1870), which another member's model may take as they are; and a +// custom tool turned away (customToolRefusal, DeepSeek's "Unsupported +// custom tool: 'exec'", #2656) where no translation took it in. A // request missing what every API requires ("field required") or too long // for the model isn't one. var shapeWords = regexp.MustCompile(`(?i)failed to deserialize|unknown (item |content |input )?(type|variant|field|parameter)|unknown_parameter|unrecognized (request argument|field|parameter)|extra (inputs|fields) are not permitted|additional properties are not allowed|schema exceeds the maximum (nesting )?depth|schema[^"]{0,60}\bnesting depth\b`) @@ -1160,7 +1162,7 @@ var unsaidWords = regexp.MustCompile(`(?i)(^|"|\\"|: )invalid request error trac func shapeRefused(status int, body []byte) bool { // the words are matched decoded, too (#1669) body = wordsOf(body) - return (status == 400 || status == 422) && (shapeWords.Match(body) || unsaidWords.Match(body)) && + return (status == 400 || status == 422) && (shapeWords.Match(body) || unsaidWords.Match(body) || customToolRefusal.Match(body)) && !quotaWords.Match(body) && !unservedWords.Match(body) && !refusedWords.Match(body) } diff --git a/internal/gateway/gateway.go b/internal/gateway/gateway.go index fd84ed6ed..914444c3a 100644 --- a/internal/gateway/gateway.go +++ b/internal/gateway/gateway.go @@ -3572,15 +3572,33 @@ func (s *Server) attempt(w http.ResponseWriter, r *http.Request, from provider.P // compaction is on, goes as it came: a translation would leave it out // (#1099) keep := s.keepsCompaction(from, p, model, body) + // Codex's custom tools, to a model that turned them away before + // (custom_tool.go, #2656): translated on the client's own API, which + // offers them as functions + customOff := func() bool { + return from == provider.Responses && !s.fits(p.ID, customToolRefused(model), from) && hasCustomTool(body) + } + if relay && !keep && customOff() { + relay, ownAPI = false, true + } if keep && relayable { relay, ownAPI = true, false } if relay { call.To = from - if status, msg, done := s.passthrough(w, r, p, from, model, body, &call.Usage); done { + status, msg, done := s.passthrough(w, r, p, from, model, body, &call.Usage) + if done { return status, msg } - // the model isn't served on the client's own API: speak another + // the model isn't served on the client's own API: speak another; + // or it turned the custom tools away just now: speak it translated, + // except a compaction, which a translation would leave out + if customOff() { + if keep { + return writeError(w, from, status, msg), msg + } + ownAPI = true + } } if keep { msg := fmt.Sprintf("%s doesn't serve %s on the Responses API, so Codex's native compaction can't be asked of it", p.Name, model) @@ -4243,6 +4261,15 @@ func (s *Server) passthrough(w http.ResponseWriter, r *http.Request, p provider. b, _ := io.ReadAll(io.LimitReader(res.Body, 1<<20)) res.Body.Close() res.Body = io.NopCloser(bytes.NewReader(b)) + if proto == provider.Responses && customToolRefusal.Match(wordsOf(b)) && hasCustomTool(body) { + // a custom tool turned away (DeepSeek's "Unsupported custom + // tool: 'exec'", #2656): the request is translated on the same + // API, its custom tools offered as functions (custom_tool.go), + // and from then on + res.Body.Close() + s.markUnfit(p.ID, customToolRefused(model), proto) + return res.StatusCode, p.Name + ": " + provider.APIError(b, res.Status), false + } fs := refusedOptional(res.StatusCode, b, body) // and an earlier turn's thinking sent back inside messages, which // DeepSeek and Kimi want and a stricter vendor turns away (#494)