gateway: a Messages body's tools with a root union go folded to every upstream

ziko on X (11-04): ZCode on Zed's subscription, Claude Sonnet refused
every request. Six of the GoAnyAPI MCP server's tools (goanyapi_adsense,
the 36th, among them) have a oneOf at their input_schema's root, ZCode
sends every tool with every request, and Anthropic's API turns such a
request away: "input_schema does not support oneOf, allOf, or anyOf at
the top level".

Cause: a request translated to Messages always had its tools folded to an
object root (objectSchema, #1271), but a Messages body relayed as it came
(ZCode or Claude Code to an Anthropic-protocol provider, the Zed plugin's
models among them, whose plugin provider has an Anthropic URL) never
was: foldsRoots and objectRootsBody handled Chat and Responses only, so
neither the first ask nor the retry after the refusal folded it.

Change (object_root.go):
- foldsRoots is true for every Anthropic-protocol relay, from the first
  ask, as a translated request already was.
- objectRootsBody takes a Messages body: a client tool's input_schema goes
  through provider.ObjectRoot; a server tool (no input_schema) and a
  schema with no root union go as they came. The translated path
  (to != Anthropic guard at gateway.go's objectRootsReq) is unchanged, so
  nothing is folded twice.
- docs/subsystems/gateway-routing.md gains the root-union bullet.

Test: TestMessagesRootUnionFolded, POST /v1/messages (stream) to a relay
with an Anthropic URL whose fake refuses a root union with Anthropic's
own wording: the union tool goes as an object root on the first ask, its
branches' properties merged; a plain tool's schema goes unchanged, and so
does a body with no union.

Run on mote at 69eb93e0a (origin/main, just fetched) plus this change:
gofmt -l clean; go vet ./internal/gateway on darwin, GOOS=windows and
GOOS=linux -tags nogui, ok; go test -timeout 45m ./internal/gateway:
ok (914s); go test ./internal/masking (reads the
subsystem docs), ok. Not run: the whole ./... suite; CI runs it.

Rebased after the run onto 14f6d10de: its three commits since 69eb93e0a
change catalog, provider/remote_quotas and GUI files, none in
internal/gateway.

Broken by hand: object_root.go back to HEAD, TestMessagesRootUnionFolded
answers 400 "tools.1.custom.input_schema: input_schema does not support
oneOf, allOf, or anyOf at the top level", the reported error.

Not tried: a real Zed account with GoAnyAPI's tools; the fake answers as
Anthropic's documented refusal does.
This commit is contained in:
yetone
2026-11-04 18:26:37 +08:00
parent 14f6d10de0
commit c4245c4c20
3 changed files with 132 additions and 5 deletions
+1
View File
@@ -276,6 +276,7 @@ recorded as a prediction failure (`noPrediction`).
- An assistant turn the user cut off before it said anything (only its thinking, an empty text, nothing; an isolated Codex reasoning item; a Gemini thought alone) stays in the agent's history and is sent on every later turn. DeepSeek and Kimi turn the whole request away over an assistant message with neither content nor tool calls, `reasoning_content` alone included ("Invalid assistant message: content or tool_calls must be set", #2599). Every Chat upstream gets such a turn left out, translated (`buildChat`, before `pairToolMessages`) or relayed (`silentAssistantsOut` in `passthrough`), by one rule (`withoutSilentAssistants` in [`chat.go`](../../internal/gateway/chat.go)): the two user messages it stood between join into one, and after a tool result the user's message follows the tool message. A prefill to go on from (`prefix`, `partial`, a Resume), a legacy `function_call`, a refusal and an audio reply stay, and a relayed body without such a turn goes byte for byte. `TestChatEmptyAssistantLeftOutFromAnthropic`, `…FromResponses`, `…FromGemini`, `TestChatRelayLeavesOutEmptyAssistant`, `TestChatRelaySilentAssistantsOnly`.
- Kimi's Chat API (`isKimi`: the Kimi platform's and a Kimi Code membership's hosts or presets) turns `reasoning_details` in a message away in any shape: an entry with a stream's `index` ("the reasoning_details at position 1 entry 0 must not contain streaming index") and any other entry ("… has an invalid type"), checked against api.kimi.com/coding on 2026-10-12. pi keeps another vendor's thinking there (MiMo's, through Command Code, with `index: 0`), so a conversation routed on to Kimi was refused on every turn (#1765). `passthrough` sends it to Kimi as `reasoning_content` (`reasoningDetailsAsContent`, with the message's `reasoning` left out once its text is there), which Kimi takes; a message with `reasoning_content` of its own keeps that. Another upstream that refuses a thinking field "at position N", as Kimi words it (a relay in front of it), is asked once more the same way and marked (`refusedInMessages`, `withoutMessageReasoning`).
- Vertex AI takes a function declaration's parameters as its own Schema object, whose `type` is required, and turns the whole request away over one schema without it, though the tool is never called: 400 "`mcp__cua-driver__drag` functionDeclaration `parameters.target` schema didn't specify the schema type field." (kthink on Discord: dsh with cua-driver's MCP tools, from before cua's own fix in its #4888, on Command Code's `google/gemini-3.8-flash`, which Command Code's gateway serves on Vertex; `target` was an anyOf of an untyped oneOf and null, `scope` a const). A body whose `model` names Gemini (`geminiNamed`: the id's last `/` segment starts with `gemini`, whoever serves it) has each untyped schema under its tools' `function.parameters`, `parameters` or `input_schema` given its type in place (`geminiToolTypes` in [`gemini_schema.go`](../../internal/gateway/gemini_schema.go), in `forwardOnce`, so a plugin's request too): from its enum or const values, its keywords or its branches, null left out (an object's or array's keywords, `properties` or `items`, before its values: a string enum beside `items` typed `"string"` sent items on a string, and Antigravity turned the turn away with "properties[display].items: field predicate failed: $type == Type.ARRAY", ferock on Discord; `TestGeminiToolTypesItemsBeforeEnum`), `{}` or a description alone a string, a tool's root an object. A node whose branches have more than one type, an unresolved `$ref` or union, and anything under `not` or `if` are left as they came, so such a schema can still be refused; every other model's tools go byte for byte. Google's own Gemini API and Code Assist are sent `parametersJsonSchema` and Antigravity `plainSchema`, so a Gemini-shaped body isn't walked (`TestGeminiToolTypesCuaDriverDrag`, with cua-driver's drag schema as its server listed it, `TestGeminiToolTypes`). `plainSchema` itself keeps an array's keywords (`items`, `minItems`, `maxItems`) on an array only and an object's (`properties`, `required` …) on an object only, and of a type list takes the type its `items` or `properties` are for, so a body a magpie from before sends is taken too (`TestAntigravityItemsOnlyOnArrays`). Google's Schema is an object with a fixed set of fields, so a boolean schema (`items: true`, a property's `true` or `false`) or an `x-` keyword such as MCP's `x-mcp-header` (2026-07-28 spec, SEP-2243) turns the whole request away ("Invalid value at '…items.items' (…aiplatform.master.Schema), true" and 'Unknown name "x-mcp-header" … Cannot find field', han_tiv on Discord). `plainSchema` is an allow-list, so `x-` keys never pass it; a boolean is `{}` for true and left out for false (a false property leaves `required` too, a false `items` is `items {}` with `maxItems 0`). Before typing, `geminiToolTypes` runs `geminiSchemaShapes`, which does the same for the relay's case: true is `{}`, false is left out, `x-` keywords go (a property named `x-…` stays), and `additionalProperties` and the `unevaluated…` keywords keep their booleans; a schema with neither goes byte for byte (`TestAntigravityBooleanSchemaAndXKeys`, `TestPlainSchemaBooleansAndXKeysEverywhere`, `TestGeminiToolTypesDropsBooleansAndXKeys`). What is left is still JSON Schema, so `parametersJsonSchema` (Gemini API, Code Assist, Vertex), which runs after it on a Gemini-named body, takes it as before.
- A tool whose schema has a union (`anyOf`, `oneOf`, `allOf`) at its root is folded to an object root (`provider.ObjectRoot`; `foldsRoots` and `objectRootsBody` in [`object_root.go`](../../internal/gateway/object_root.go), #1271): Anthropic's API turns every request offering one away ("input_schema does not support oneOf, allOf, or anyOf at the top level"). A request translated to Messages always went folded (`objectSchema`); a Chat or Responses body relayed as it came is folded for xAI from the first ask and for any other upstream once it refused one (`rootUnionRefused`, retried folded at once). A Messages body relayed as it came, a client that speaks Messages itself (ZCode, Claude Code) to an Anthropic-protocol provider or plugin, went unfolded until 11-04: ziko on X, ZCode with Zed's subscription, Claude refused every request because six of an MCP server's tools (GoAnyAPI's `goanyapi_adsense` among them) had a root `oneOf`. It is now folded for every such upstream from the first ask; a server tool (no `input_schema`) and a schema with no root union go as they came (`TestMessagesRootUnionFolded`, `TestRootUnionFoldedWhereRefused`, `TestRootUnionFoldedForXAI`).
- A Responses request's top-level `access_programs`, the Cyber program Codex asks the model under (`{"cyber":"standard"}` on a subagent it inherits, OpenAI's Daybreak programs, magpie-releases#18), goes only where Codex itself would send it: codex-rs sends it with a ChatGPT sign-in, or an API key on its provider named `openai`, and to no other provider (`cyber_access_program.rs`, `for_auth`, `for_provider`). In `forwardOnce`, relayed or built (from Chat too), it goes as it came to a ChatGPT (Codex) account, a host ending in `openai.com`, another magpie (`IsRemoteMagpie`, whose own upstream decides) and a relay set `codexAsSent` when Codex sent the request; every other Responses upstream is sent the request without it (`keepsAccessPrograms`, `withoutTopMember`, the rest byte for byte). OpenCode Go answered it, for DeepSeek and GLM, with 503 "Upstream request failed: Endpoint is unavailable." and 200 without it or with null; its Haiku took it (#3172, three reporters' real A/B runs). It is taken out before the user's extraBody is merged, so an `access_programs` written there still goes. Chat and Messages builds never carry it; a Chat request relayed as it came keeps whatever its client wrote. `TestAccessProgramsGoToOpenAIAlone`, `TestWithoutTopMember`, `TestCodexAccessProgramsReachBackend`.
- A client that took the gateway for an Ollama server (its `/api/show` is answered in Ollama's shape) sends Ollama's per-request `options` beside its Chat fields. Gemini's OpenAI-compatible API (`geminiCompat`: AI Studio's, or a local proxy in front of it) reads proto JSON and turns the whole request away over a name it doesn't know (#3097), so a body relayed to one goes without `options`, whose runner settings have no place on a Chat API, as the Ollama route's own body builder leaves them out (`ollamaChatBody`). Another vendor's Chat upstream gets `options` as the client sent it. `TestGeminiCompatRelayLeavesOutOllamaOptions`.
- Claude Code's deferred tools (ToolSearch, MCP tools that come and go) put blocks of their own in a message: a `tool_addition` (`tool` a `tool_reference` naming the tool, or a `tool_definition`), a `tool_removal`, and a `tool_reference`. Kimi's Anthropic endpoint refuses any of them with a whole-request 400 "Invalid request Error" that names nothing, so once a session had loaded a tool every turn failed (#2042); DeepSeek's takes a `tool_addition` naming a tool but refuses one defining it, a `tool_removal` and a message's `tool_reference` with 422 "unknown variant `tool_removal`" (both checked against the real endpoints on 2026-10-14). OpenCode Go also rejects DeepSeek inline definitions with a generic 422 "Upstream request failed: Endpoint is unavailable." (checked on 2026-10-15). Kimi and DeepSeek models on OpenCode are never sent these blocks (`forwardOnce`); a provider that refuses one in those words is asked again at once without them and not sent them again while magpie runs (`refuseShapes`, `shapeDeferred`; the retry loop reads a 422 as well as a 400). `withoutDeferredTools` drops the blocks and a message they leave empty; definitions present only in a `tool_addition.tool.definition` join the request's `tools` once by name (an existing top-level definition wins), and a `tool_reference` inside a `tool_result` (ToolSearch's answer, which both take) stays. Any other provider is sent them as Claude Code wrote them ([`anthropic_shapes.go`](../../internal/gateway/anthropic_shapes.go), `TestKimiIsSentNoDeferredToolBlocks`, `TestDeferredToolBlocksRefusedOnceLeftOut`, `TestOpenCodeDeepSeekInlineTools`, `TestDeferredInlineDefinitionPreserved`).
+18 -5
View File
@@ -21,7 +21,11 @@ import (
// Schema of 'type: "object"', got 'type: "None"'"). 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.
// folded, and so from then on for that model. An Anthropic Messages body is
// folded from the start for every upstream, as one translated to Messages
// is (objectSchema): a client that speaks Messages itself (ZCode, Claude
// Code) had its tools sent as they came, and Claude behind Zed's
// subscription refused every request whose tools had a oneOf at a root.
// rootUnionRefusal is an upstream refusing a tool's parameters for a
// union at their root.
@@ -33,13 +37,14 @@ 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)
return proto == provider.Anthropic || 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.
// objectRootsBody is a Chat, Responses or Messages body whose function
// tools' parameters (a Messages tool's input_schema) 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"`)) {
if (proto != provider.Chat && proto != provider.Responses && proto != provider.Anthropic) || !bytes.Contains(body, []byte(`Of"`)) {
return body, false
}
dec := json.NewDecoder(bytes.NewReader(body))
@@ -75,6 +80,14 @@ func foldTools(proto provider.Protocol, tools []any) bool {
}
continue
}
if proto == provider.Anthropic {
// a client tool; a server tool (web_search_…) has a type and
// no input_schema
if ps, _ := tm["input_schema"].(map[string]any); ps != nil && provider.ObjectRoot(ps) {
changed = true
}
continue
}
fn := tm
if proto == provider.Chat {
fn, _ = tm["function"].(map[string]any)
@@ -0,0 +1,113 @@
package gateway
import (
"bytes"
"encoding/json"
"io"
"net/http"
"net/http/httptest"
"strings"
"sync"
"testing"
"github.com/yetone/magpie/internal/provider"
)
// A client that speaks Messages itself (ZCode) sends its tools as they
// came, and one of them, an MCP server's, has a oneOf at its
// input_schema's root, which Anthropic's API refuses for every request
// that offers it ("input_schema does not support oneOf, allOf, or anyOf at
// the top level"): Claude behind Zed's subscription failed even "reply
// OK" (ziko on X, 2026-11-04). Passed through to an Anthropic-protocol
// upstream, such a tool goes folded to an object root from the first
// request, as a request translated to Messages always went; the other
// tools' schemas go as they came.
func TestMessagesRootUnionFolded(t *testing.T) {
fresh(t)
var mu sync.Mutex
var got [][]byte
up := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
b, _ := io.ReadAll(r.Body)
mu.Lock()
got = append(got, b)
mu.Unlock()
var q struct {
Tools []map[string]any `json:"tools"`
}
json.Unmarshal(b, &q)
for i, tl := range q.Tools {
ps, _ := tl["input_schema"].(map[string]any)
if ps != nil && (ps["oneOf"] != nil || ps["anyOf"] != nil || ps["allOf"] != nil) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(400)
io.WriteString(w, `{"type":"error","error":{"type":"invalid_request_error","message":"tools.`+string(rune('0'+i))+`.custom.input_schema: input_schema does not support oneOf, allOf, or anyOf at the top level"}}`)
return
}
}
w.Header().Set("Content-Type", "text/event-stream")
io.WriteString(w, "event: message_start\ndata: {\"type\":\"message_start\",\"message\":{\"id\":\"msg_1\",\"type\":\"message\",\"role\":\"assistant\",\"model\":\"claude-sonnet-5\",\"content\":[],\"usage\":{\"input_tokens\":9,\"output_tokens\":0}}}\n\n"+
"event: content_block_start\ndata: {\"type\":\"content_block_start\",\"index\":0,\"content_block\":{\"type\":\"text\",\"text\":\"\"}}\n\n"+
"event: content_block_delta\ndata: {\"type\":\"content_block_delta\",\"index\":0,\"delta\":{\"type\":\"text_delta\",\"text\":\"OK\"}}\n\n"+
"event: content_block_stop\ndata: {\"type\":\"content_block_stop\",\"index\":0}\n\n"+
"event: message_delta\ndata: {\"type\":\"message_delta\",\"delta\":{\"stop_reason\":\"end_turn\"},\"usage\":{\"output_tokens\":1}}\n\n"+
"event: message_stop\ndata: {\"type\":\"message_stop\"}\n\n")
}))
t.Cleanup(up.Close)
if err := provider.Save(provider.Provider{ID: "relay", Name: "Relay", Key: "k", Anthropic: up.URL, Models: []string{"claude-sonnet-5"}}); err != nil {
t.Fatal(err)
}
s := New()
plainSchema := `{"type":"object","properties":{"path":{"type":"string"}},"required":["path"]}`
plain := `{"name":"read","description":"Read a file","input_schema":` + plainSchema + `}`
union := `{"name":"goanyapi_adsense","description":"AdSense reports","input_schema":{"oneOf":[` +
`{"type":"object","properties":{"action":{"const":"report"},"range":{"type":"string"}},"required":["action","range"]},` +
`{"type":"object","properties":{"action":{"const":"accounts"}},"required":["action"]}]}}`
ask := func(tools string) map[string]map[string]any {
t.Helper()
n := len(got)
rec := httptest.NewRecorder()
body := `{"model":"relay/claude-sonnet-5","max_tokens":64,"stream":true,"tools":[` + tools + `],"messages":[{"role":"user","content":"reply OK"}]}`
s.Handler().ServeHTTP(rec, httptest.NewRequest("POST", "/v1/messages", strings.NewReader(body)))
if rec.Code != 200 || !strings.Contains(rec.Body.String(), "OK") {
t.Fatalf("answered %d %s", rec.Code, rec.Body)
}
if len(got) != n+1 {
t.Fatalf("upstream asked %d times, want once, folded from the first", len(got)-n)
}
var q struct {
Tools []map[string]any `json:"tools"`
}
if err := json.Unmarshal(got[n], &q); err != nil {
t.Fatal(err)
}
by := map[string]map[string]any{}
for _, tl := range q.Tools {
name, _ := tl["name"].(string)
ps, _ := tl["input_schema"].(map[string]any)
by[name] = ps
}
return by
}
same := func(ps map[string]any, want string) bool {
var w any
json.Unmarshal([]byte(want), &w)
a, _ := json.Marshal(ps)
b, _ := json.Marshal(w)
return bytes.Equal(a, b)
}
by := ask(plain + `,` + union)
ps := by["goanyapi_adsense"]
props, _ := ps["properties"].(map[string]any)
if ps["type"] != "object" || ps["oneOf"] != nil || props["action"] == nil || props["range"] == nil {
t.Fatalf("union sent as %v", ps)
}
if !same(by["read"], plainSchema) {
t.Fatalf("a tool with no union sent as %v", by["read"])
}
// no union anywhere: every schema goes as the client wrote it
if by = ask(plain); !same(by["read"], plainSchema) {
t.Fatalf("no union: sent as %v", by["read"])
}
}