Skip to content

Every agent's model. One place. Codex on DeepSeek, Claude Code on Kimi, from the menu bar.

library: a skill named in another script goes by its folder's name, so every one is listed

yetone4db65681c170
diff --git a/docs/subsystems/gateway-routing.md b/docs/subsystems/gateway-routing.md
index 299ef20df..e8df252d0 100644
--- a/docs/subsystems/gateway-routing.md
+++ b/docs/subsystems/gateway-routing.md
@@ -246,7 +246,7 @@ recorded as a prediction failure (`noPrediction`).
- A message content that is a list of plain text parts (`[{"type":"text","text":…}]`, nothing else in a part) is relayed to a Chat upstream as the string it says, the parts joined by a newline (`textPartsAsString` in [`chat_text_parts.go`](../../internal/gateway/chat_text_parts.go), in `passthrough` before `silentAssistantsOut`). OpenAI takes either, but a vendor's own server may take a string alone: the Intern discovery API (a custom provider on OpenAI compatible, Atria-Dawn, Discord) answered DeepSeek Harness, whose pi-ai sends every user message as such a list, 422 with an "Input should be a valid string" per message. A list with an image, a file, a thinking part or a `cache_control` mark stays a list, and every other byte of the body stays as sent; `buildChat` already writes text as a string. `TestChatRelayTextPartsAsString`, `TestTextPartsAsStringOnlyPlainText`.
- 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`).
+- 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 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`.
- 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`).
- ToolSearch's answer is a `tool_result` whose content is `tool_reference` blocks alone. OpenDesign's Anthropic endpoint can't read one: 422 "Failed to deserialize the JSON body into the target type: messages[4]: missing field `content`" (#2124, the reporter's direct request without magpie fails the same way; the same result with a text block beside the references is taken). A provider that refuses in those words while the request holds such a result is asked again at once with a text block first in each, "Tool <name> is loaded and can be called now." (`toolLoadedText`, the words a translated route already gives a model in `stringOrText`), the references and the `tool_use`/`tool_result` pairing kept, and is sent it that way while magpie runs (`refuseShapes`, `shapeRefsOnly`, `withRefsSaid`). This is in `forward`, so `/v1/messages`, `count_tokens` and a group's member all get it; a request translated to another API already carries the references as that text. Any other provider is sent the bare references (`TestRefsOnlyToolResultRefusedGetsText`, `TestRefsSaidLeavesOtherResults`).
diff --git a/internal/gateway/codeassist.go b/internal/gateway/codeassist.go
index 3bc2163f0..f74be1699 100644
--- a/internal/gateway/codeassist.go
+++ b/internal/gateway/codeassist.go
@@ -811,6 +811,18 @@ func plainSchema(raw json.RawMessage) json.RawMessage {
var walk func(v any, depth int) any
walk = func(v any, depth int) any {
switch x := v.(type) {
+ case bool:
+ // a boolean schema, which JSON Schema has wherever a schema
+ // goes: true is any value, the schema {}; false is none, nil,
+ // and whoever holds it leaves it out. Google's Schema is an
+ // object only, and turns the whole request away over a
+ // boolean ("…items.items (…aiplatform.master.Schema), true",
+ // han_tiv on Discord: an MCP tool's array of arrays of
+ // anything)
+ if x {
+ return map[string]any{}
+ }
+ return nil
case []any:
out := make([]any, len(x))
for i, e := range x {
@@ -947,12 +959,23 @@ func plainSchema(raw json.RawMessage) json.RawMessage {
props := map[string]any{}
if m, ok := v.(map[string]any); ok {
for pk, pv := range m {
- props[pk] = walk(pv, depth+1)
+ // a property whose schema is false is one the
+ // call may not have: it is left out, and so is
+ // its name in required
+ if w := walk(pv, depth+1); w != nil {
+ props[pk] = w
+ }
}
}
out[k] = props
case "items":
- out[k] = walk(v, depth+1)
+ if w := walk(v, depth+1); w != nil {
+ out[k] = w
+ } else if x["maxItems"] == nil {
+ // items false: an array with nothing in it
+ out[k] = map[string]any{}
+ out["maxItems"] = 0
+ }
case "enum":
// Google takes string enums only
if es, ok := v.([]any); ok {
diff --git a/internal/gateway/gemini_bool_schema_test.go b/internal/gateway/gemini_bool_schema_test.go
new file mode 100644
index 000000000..bc432d3c7
--- /dev/null
+++ b/internal/gateway/gemini_bool_schema_test.go
@@ -0,0 +1,167 @@
+package gateway
+
+import (
+ "encoding/json"
+ "strings"
+ "testing"
+
+ "github.com/tidwall/gjson"
+)
+
+// boolSchemaAsk is han_tiv's case (Discord, v0.1.1982 and v0.1.1989):
+// gemini-3.8-flash on Antigravity with MCP tools, one of which has, as its
+// fourth property, an array of arrays of anything (items.items true), and
+// as its third a property carrying MCP's x-mcp-header (the 2026-07-28
+// spec). Google's answers were:
+//
+// Invalid value at 'request.tools[0].function_declarations[174].parameters.properties[3].value.items.items' (type.googleapis.com/google.cloud.aiplatform.master.Schema), true
+// Unknown name "x-mcp-header" at 'tools[0].function_declarations[47]...properties[2].value': Cannot find field
+const boolSchemaAsk = `{"model":"antigravity/gemini-3.8-flash","max_tokens":32,"messages":[{"role":"user","content":"reply with OK only"}],
+ "tools":[{"name":"mcp__sheets__write_rows","description":"write rows","input_schema":{"type":"object","$schema":"https://json-schema.org/draft/2020-12/schema",
+ "properties":{
+ "spreadsheet":{"type":"string"},
+ "sheet":{"type":"string"},
+ "region":{"type":"string","x-mcp-header":"Region"},
+ "rows":{"type":"array","items":{"type":"array","items":true},"description":"rows of cells"}
+ },"required":["spreadsheet","rows"],"additionalProperties":false}}]}`
+
+// geminiSchemaFields is what Google's Schema object holds
+// (ai.google.dev/api/caching#Schema); a key outside it is "Cannot find
+// field".
+var geminiSchemaFields = map[string]bool{
+ "type": true, "format": true, "title": true, "description": true, "nullable": true, "enum": true,
+ "maxItems": true, "minItems": true, "properties": true, "required": true, "minProperties": true,
+ "maxProperties": true, "minLength": true, "maxLength": true, "pattern": true, "example": true,
+ "anyOf": true, "propertyOrdering": true, "default": true, "items": true, "minimum": true, "maximum": true,
+}
+
+// geminiSchemaFaults lists where s, a Gemini Schema, has a node that is no
+// object or a key the Schema has no field for.
+func geminiSchemaFaults(s gjson.Result, at string) []string {
+ if !s.IsObject() {
+ return []string{at + " = " + s.Raw}
+ }
+ var bad []string
+ s.ForEach(func(k, v gjson.Result) bool {
+ key := k.String()
+ switch {
+ case !geminiSchemaFields[key]:
+ bad = append(bad, at+"."+key)
+ case key == "items":
+ bad = append(bad, geminiSchemaFaults(v, at+".items")...)
+ case key == "properties":
+ v.ForEach(func(n, p gjson.Result) bool {
+ bad = append(bad, geminiSchemaFaults(p, at+".properties["+n.String()+"]")...)
+ return true
+ })
+ case key == "anyOf":
+ v.ForEach(func(i, p gjson.Result) bool {
+ bad = append(bad, geminiSchemaFaults(p, at+".anyOf["+i.String()+"]")...)
+ return true
+ })
+ }
+ return true
+ })
+ return bad
+}
+
+func TestAntigravityBooleanSchemaAndXKeys(t *testing.T) {
+ r, err := parseAnthropic([]byte(boolSchemaAsk))
+ if err != nil {
+ t.Fatal(err)
+ }
+ env := gjson.ParseBytes(buildCodeAssist(r, "gemini-3.8-flash", "antigravity"))
+ params := env.Get("request.tools.0.functionDeclarations.0.parameters")
+ if bad := geminiSchemaFaults(params, "parameters"); len(bad) > 0 {
+ t.Fatalf("Google would refuse %v in %s", bad, params.Raw)
+ }
+ rows := params.Get("properties.rows")
+ if rows.Get("type").String() != "array" || rows.Get("items.type").String() != "array" || rows.Get("items.items").Raw != "{}" {
+ t.Errorf("rows: %s", rows.Raw)
+ }
+ if params.Get("properties.region.type").String() != "string" {
+ t.Errorf("region: %s", params.Get("properties.region").Raw)
+ }
+}
+
+// Every place JSON Schema takes a schema takes a boolean too, and every
+// level may carry an x- keyword; none of them reaches Google, and a
+// property named x-… is a name, not a keyword, so it stays.
+func TestPlainSchemaBooleansAndXKeysEverywhere(t *testing.T) {
+ in := `{"type":"object","x-root":1,"$defs":{"Any":true,"None":false,"Cell":{"type":"array","items":true,"x-def":"d"}},
+ "properties":{
+ "any":true,
+ "gone":false,
+ "x-region":{"type":"string","x-mcp-header":"Region"},
+ "grid":{"type":"array","items":{"type":"array","items":{"type":"array","items":true}}},
+ "empty":{"type":"array","items":false},
+ "ref":{"$ref":"#/$defs/Any"},
+ "cell":{"$ref":"#/$defs/Cell"},
+ "never":{"$ref":"#/$defs/None"},
+ "either":{"anyOf":[true,{"type":"null"}]},
+ "first":{"anyOf":[false,{"type":"integer","x-k":1}]},
+ "merged":{"allOf":[true,{"type":"object","properties":{"a":true,"b":{"type":"string","x-b":2}}}]},
+ "obj":{"type":"object","properties":{"deep":{"type":"array","items":{"type":"object","properties":{"v":true},"x-n":{"a":1}}}}}
+ },"required":["any","gone","never","x-region"]}`
+ out := plainSchema(json.RawMessage(in))
+ g := gjson.ParseBytes(out)
+ if bad := geminiSchemaFaults(g, "parameters"); len(bad) > 0 {
+ t.Fatalf("Google would refuse %v in %s", bad, out)
+ }
+ for _, p := range []string{"properties.gone", "properties.never"} {
+ if g.Get(p).Exists() {
+ t.Errorf("%s (false) kept: %s", p, g.Get(p).Raw)
+ }
+ }
+ if req := g.Get("required").Raw; strings.Contains(req, "gone") || strings.Contains(req, "never") || !strings.Contains(req, "x-region") {
+ t.Errorf("required %s", req)
+ }
+ if g.Get(`properties.x-region.type`).String() != "string" {
+ t.Errorf("x-region property lost: %s", out)
+ }
+ if e := g.Get("properties.empty"); e.Get("items").Raw != "{}" || e.Get("maxItems").Int() != 0 || !e.Get("maxItems").Exists() {
+ t.Errorf("items false: %s", e.Raw)
+ }
+ if g.Get("properties.grid.items.items.items").Raw != "{}" {
+ t.Errorf("grid: %s", g.Get("properties.grid").Raw)
+ }
+ if g.Get("properties.first.type").String() != "integer" {
+ t.Errorf("first: %s", g.Get("properties.first").Raw)
+ }
+}
+
+// The same tools sent on to whoever turns them into Vertex's Schema (a
+// relay's or plugin's gemini-3.8-flash) go without booleans or x-
+// keywords, a property named x-… and additionalProperties kept, and a
+// schema with neither goes byte for byte.
+func TestGeminiToolTypesDropsBooleansAndXKeys(t *testing.T) {
+ body := []byte(`{"model":"google/gemini-3.8-flash","tools":[{"type":"function","function":{"name":"w","parameters":{"type":"object",
+ "properties":{"x-region":{"type":"string","x-mcp-header":"Region"},"rows":{"type":"array","items":{"type":"array","items":true}},
+ "gone":false,"u":{"anyOf":[false,{"type":"string"}]}},"additionalProperties":false}}},
+ {"type":"function","function":{"name":"plain","parameters":{"type":"object", "properties":{"a":{"type":"string"}}}}}]}`)
+ out := geminiToolTypes(body)
+ if !json.Valid(out) {
+ t.Fatalf("invalid: %s", out)
+ }
+ p := gjson.GetBytes(out, "tools.0.function.parameters")
+ if strings.Contains(p.Raw, "x-mcp-header") || strings.Contains(p.Raw, "true") || p.Get("properties.gone").Exists() {
+ t.Errorf("left in: %s", p.Raw)
+ }
+ if p.Get("properties.x-region.type").String() != "string" || p.Get("additionalProperties").Raw != "false" {
+ t.Errorf("lost: %s", p.Raw)
+ }
+ if it := p.Get("properties.rows.items.items"); !it.IsObject() {
+ t.Errorf("items.items: %s", it.Raw)
+ }
+ if u := p.Get("properties.u.anyOf").Array(); len(u) != 1 {
+ t.Errorf("u: %s", p.Get("properties.u").Raw)
+ }
+ if !strings.Contains(string(out), `{"type":"object", "properties":{"a":{"type":"string"}}}`) {
+ t.Errorf("an untouched schema was written again: %s", out)
+ }
+ // another model's body goes as it came
+ other := []byte(strings.Replace(string(body), "google/gemini-3.8-flash", "gpt-5.5", 1))
+ if string(geminiToolTypes(other)) != string(other) {
+ t.Error("a non-Gemini body was changed")
+ }
+}
diff --git a/internal/gateway/gemini_schema.go b/internal/gateway/gemini_schema.go
index 9d7249793..9e2706fb6 100644
--- a/internal/gateway/gemini_schema.go
+++ b/internal/gateway/gemini_schema.go
@@ -32,6 +32,9 @@ import (
// after the schema's brace, so the rest of the body and a cache's prefix
// stay as they were; every other model's body goes as it came.
//
+// Boolean schemas and x- keywords, which a Schema object can't hold
+// either, are taken out first (geminiSchemaShapes).
+//
// Google's own Gemini API and Code Assist are sent parametersJsonSchema,
// which takes JSON Schema whole, and Antigravity its own cut-down schema
// (plainSchema), so a Gemini-shaped body isn't walked.
@@ -39,6 +42,7 @@ func geminiToolTypes(body []byte) []byte {
if !geminiNamed(gjson.GetBytes(body, "model").String()) {
return body
}
+ body = geminiSchemaShapes(body)
tools := gjson.GetBytes(body, "tools")
if !tools.IsArray() || tools.Index <= 0 {
return body
@@ -153,3 +157,180 @@ func geminiSchemaType(root, s gjson.Result, isRoot bool) string {
}
return "string"
}
+
+// geminiSchemaShapes is body with each tool schema a Gemini model is
+// sent cut to what a Schema object can hold, wherever it is turned into
+// one. Two things in valid JSON Schema have no place there, and Google
+// turns the whole request away over either:
+//
+// - a boolean schema (items: true, a property's true or false): "Invalid
+// value at '…items.items' (…aiplatform.master.Schema), true" (han_tiv
+// on Discord, an MCP tool's array of arrays of anything). True is {},
+// any value, and is typed below like any other {}; false, no value, is
+// left out: a property of it, a branch of it, a keyword of it.
+// additionalProperties and the unevaluated ones keep theirs, which a
+// relay already knows to drop.
+// - an x- keyword, a vendor's own annotation, which no model reads: MCP's
+// x-mcp-header (the 2026-07-28 spec, SEP-2243) on a property, which a
+// relay to Vertex answered 'Unknown name "x-mcp-header" at …
+// properties[2].value: Cannot find field'. Only a schema's own keys
+// are keywords: a property named x-… stays.
+//
+// A schema with neither goes byte for byte as it came; one with either is
+// written again in its own order.
+func geminiSchemaShapes(body []byte) []byte {
+ tools := gjson.GetBytes(body, "tools")
+ if !tools.IsArray() {
+ return body
+ }
+ type cut struct {
+ from, to int
+ raw string
+ }
+ var cuts []cut
+ tools.ForEach(func(_, tool gjson.Result) bool {
+ for _, at := range []string{"function.parameters", "parameters", "input_schema"} {
+ root := tool.Get(at)
+ if !root.IsObject() || root.Index <= 0 || !schemaNeedsShape(root, true) {
+ continue
+ }
+ if raw, keep := shapeSchema(root); keep && root.Index+len(root.Raw) <= len(body) && string(body[root.Index:root.Index+len(root.Raw)]) == root.Raw {
+ cuts = append(cuts, cut{root.Index, root.Index + len(root.Raw), raw})
+ }
+ }
+ return true
+ })
+ if len(cuts) == 0 {
+ return body
+ }
+ out := make([]byte, 0, len(body))
+ last := 0
+ for _, c := range cuts {
+ if c.from < last {
+ continue
+ }
+ out = append(out, body[last:c.from]...)
+ out = append(out, c.raw...)
+ last = c.to
+ }
+ return append(out, body[last:]...)
+}
+
+// schemaMaps are the keywords whose value is a map of names to schemas,
+// schemaOne those whose value is one schema, schemaList a list of them.
+// additionalProperties, unevaluatedProperties and unevaluatedItems are
+// left out on purpose: their false is the common "nothing else", which
+// every converter knows.
+var (
+ schemaMaps = map[string]bool{"properties": true, "patternProperties": true, "$defs": true, "definitions": true, "dependentSchemas": true}
+ schemaOne = map[string]bool{"items": true, "contains": true, "propertyNames": true, "not": true, "if": true, "then": true, "else": true, "contentSchema": true}
+ schemaList = map[string]bool{"anyOf": true, "oneOf": true, "allOf": true, "prefixItems": true}
+)
+
+// schemaNeedsShape is whether node, a schema when isSchema, holds a
+// boolean schema or an x- keyword anywhere under it.
+func schemaNeedsShape(node gjson.Result, isSchema bool) bool {
+ if isSchema && (node.Type == gjson.True || node.Type == gjson.False) {
+ return true
+ }
+ if !node.IsObject() || !isSchema {
+ return false
+ }
+ need := false
+ node.ForEach(func(key, v gjson.Result) bool {
+ k := key.String()
+ switch {
+ case strings.HasPrefix(k, "x-"):
+ need = true
+ case schemaMaps[k]:
+ v.ForEach(func(_, s gjson.Result) bool {
+ need = schemaNeedsShape(s, true)
+ return !need
+ })
+ case schemaOne[k]:
+ need = schemaNeedsShape(v, true)
+ case schemaList[k]:
+ v.ForEach(func(_, s gjson.Result) bool {
+ need = schemaNeedsShape(s, true)
+ return !need
+ })
+ }
+ return !need
+ })
+ return need
+}
+
+// shapeSchema is schema s written again without its boolean schemas and
+// x- keywords; keep is false when s itself is false, no schema at all.
+func shapeSchema(s gjson.Result) (raw string, keep bool) {
+ switch s.Type {
+ case gjson.True:
+ return "{}", true
+ case gjson.False:
+ return "", false
+ }
+ if !s.IsObject() || !schemaNeedsShape(s, true) {
+ return s.Raw, true
+ }
+ var b strings.Builder
+ b.WriteByte('{')
+ first := true
+ put := func(key, val string) {
+ if !first {
+ b.WriteByte(',')
+ }
+ first = false
+ b.WriteString(key)
+ b.WriteByte(':')
+ b.WriteString(val)
+ }
+ s.ForEach(func(key, v gjson.Result) bool {
+ k := key.String()
+ switch {
+ case strings.HasPrefix(k, "x-"):
+ case schemaMaps[k] && v.IsObject():
+ var m strings.Builder
+ m.WriteByte('{')
+ n := 0
+ v.ForEach(func(name, sub gjson.Result) bool {
+ if r, ok := shapeSchema(sub); ok {
+ if n > 0 {
+ m.WriteByte(',')
+ }
+ n++
+ m.WriteString(name.Raw)
+ m.WriteByte(':')
+ m.WriteString(r)
+ }
+ return true
+ })
+ m.WriteByte('}')
+ put(key.Raw, m.String())
+ case schemaOne[k]:
+ if r, ok := shapeSchema(v); ok {
+ put(key.Raw, r)
+ }
+ case schemaList[k] && v.IsArray():
+ var m strings.Builder
+ m.WriteByte('[')
+ n := 0
+ v.ForEach(func(_, sub gjson.Result) bool {
+ if r, ok := shapeSchema(sub); ok {
+ if n > 0 {
+ m.WriteByte(',')
+ }
+ n++
+ m.WriteString(r)
+ }
+ return true
+ })
+ m.WriteByte(']')
+ put(key.Raw, m.String())
+ default:
+ put(key.Raw, v.Raw)
+ }
+ return true
+ })
+ b.WriteByte('}')
+ return b.String(), true
+}