gateway: Copilot's Gemini keeps a nullable union untyped, its Grok gets namespaces flat (yuushabu_buyinn on X, #4374)

Copilot's Gemini models still answered 400 "invalid request body" to Codex
Desktop after the oneOf rewrite. RoyShen12's live isolation on #4374: the
cause is geminiToolTypes writing `type: string` beside a nullable union
(move_thread_to_project.projectId = anyOf [string, null]); removing that one
field made the full request 200. For a Copilot Gemini on chat, a union node
(anyOf or oneOf, any shape, nullable or not, at any depth) now goes as its
client wrote it, without the parent type; its branches are typed as ever, and
every other Gemini route (Vertex relays, plugins) is unchanged.

Grok 4.7 behind Copilot (Responses) is turned away over a namespace tool
(mcp__codex_app) and over a function whose parameters are a root union
(automation_update); Copilot's word is a bare 400/422, so nothing teaches
the refusal-learner. For a Copilot Grok the namespaces go flat
(namespace__name, provider.GrokFlatBody, nothing else of the body touched)
and root unions become objects (ObjectRoot); the model's call to a flat name
gets its namespace back through the existing namespacedIn path. GPT on the
same /responses keeps its namespace and unions as they came.

Run (mote, -tags nogui): go vet gateway+provider; go test -run
'TestCopilot|TestGemini|TestGrok|TestObjectRoot' gateway and provider: ok.
New TestCopilotGeminiKeepsNullableUnionsUntyped (anyOf, oneOf, array items,
$ref'd nullable), TestGeminiTypesOtherVendorsKeepTheirs and
TestCopilotGrokTakesNamespacesFlat (GPT unchanged) are red with the two
wiring lines reverted by hand, green with them.
Not tried: a live Copilot account (the fakes refuse with the shapes
#4374's isolation recorded); the full suite, started after the tag.
This commit is contained in:
yetone
2026-11-11 19:42:17 +08:00
parent 6b45130829
commit b1f5806cb3
5 changed files with 237 additions and 8 deletions
@@ -3,6 +3,7 @@ package gateway
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"net/http/httptest"
@@ -270,3 +271,141 @@ func copilotTurnFake(t *testing.T, models map[string]string, refuse func(model s
provider.CopilotTokenURL, provider.CopilotUserURL = ghSrv.URL+"/token", ghSrv.URL+"/user"
t.Cleanup(func() { provider.CopilotTokenURL, provider.CopilotUserURL = oldTok, oldUser })
}
// copilotNullableRequest carries Codex Desktop's real move_thread_to_project
// (#4374, RoyShen12's isolation and yuushabu_buyinn's report): projectId a
// nullable string as anyOf, and the other shapes a nullable takes — oneOf,
// inside an array's items, behind a $def.
const copilotNullableRequest = `{"model":"copilot/gemini-3.8-flash","stream":true,"store":false,
"input":[{"type":"message","role":"user","content":[{"type":"input_text","text":"hi"}]}],
"tools":[{"type":"function","name":"move_thread_to_project","description":"Move a thread.",
"parameters":{"type":"object","properties":{
"projectId":{"anyOf":[{"type":"string"},{"type":"null"}],"description":"Destination, or null."},
"alt":{"oneOf":[{"type":"integer"},{"type":"null"}]},
"many":{"type":"array","items":{"anyOf":[{"type":"string"},{"type":"null"}]}},
"ref":{"$ref":"#/$defs/maybe"}},
"$defs":{"maybe":{"anyOf":[{"type":"number"},{"type":"null"}]}},
"required":["projectId"],"additionalProperties":false}}]}`
// TestCopilotGeminiKeepsNullableUnionsUntyped: the type written beside a
// nullable union (Vertex wants one) is what Copilot's Gemini turns away
// 400 "invalid request body": removing that one field made the live
// request 200 (#4374). Every union goes as its client wrote it.
func TestCopilotGeminiKeepsNullableUnionsUntyped(t *testing.T) {
var mu sync.Mutex
var sent []string
copilotTurnFake(t, map[string]string{
"gemini-3.8-flash": `["/chat/completions"]`,
}, nil, func(m string, b []byte) bool {
bad := false
var walk func(v any)
walk = func(v any) {
switch x := v.(type) {
case map[string]any:
_, a := x["anyOf"]
_, o := x["oneOf"]
if _, ty := x["type"]; (a || o) && ty {
bad = true
}
for _, c := range x {
walk(c)
}
case []any:
for _, c := range x {
walk(c)
}
}
}
var req map[string]any
json.Unmarshal(b, &req)
walk(req["tools"])
return bad
}, "invalid request body", http.StatusBadRequest, &sent)
rec := httptest.NewRecorder()
New().Handler().ServeHTTP(rec, httptest.NewRequest("POST", "/v1/responses", strings.NewReader(copilotNullableRequest)))
if rec.Code != 200 || !strings.Contains(rec.Body.String(), "hi") {
t.Fatalf("%d %s", rec.Code, rec.Body.String())
}
mu.Lock()
defer mu.Unlock()
if len(sent) != 1 || !strings.Contains(sent[0], `"anyOf"`) {
t.Fatalf("Copilot was asked %q", sent)
}
}
// TestGeminiTypesOtherVendorsKeepTheirs: only Copilot's Gemini leaves a
// union untyped; a Vertex-bound Gemini behind any other provider is still
// given the type Vertex requires.
func TestGeminiTypesOtherVendorsKeepTheirs(t *testing.T) {
body := []byte(`{"model":"gemini-3.8-flash","tools":[{"type":"function","function":{"name":"f","parameters":{"type":"object","properties":{"p":{"anyOf":[{"type":"string"},{"type":"null"}]}}}}}]}`)
other := provider.Provider{Account: &provider.Account{Agent: "claude"}}
if copilotGemini(other, body) {
t.Fatal("another provider counted as Copilot")
}
if got := geminiTypes(body, copilotGemini(other, body)); !strings.Contains(string(got), `"p":{"type":"string","anyOf"`) {
t.Errorf("another vendor's union lost its type: %s", got)
}
cp := provider.Provider{Account: &provider.Account{Agent: "copilot"}}
if got := geminiTypes(body, copilotGemini(cp, body)); strings.Contains(string(got), `"type":"string","anyOf"`) {
t.Errorf("Copilot's union was typed: %s", got)
}
}
// copilotNamespaceRequest is Codex Desktop's turn with an ordinary
// namespace (an MCP server's tools) and a function whose parameters are a
// root union.
const copilotNamespaceRequest = `{"model":"copilot/%s","stream":true,"store":false,
"input":[{"role":"user","content":"hi"}],
"tools":[{"type":"namespace","name":"mcp__codex_app","description":"Codex app.",
"tools":[{"type":"function","name":"move_thread_to_project","description":"Move.","parameters":{"type":"object","properties":{"projectId":{"type":"string"}}}}]},
{"type":"function","name":"automation_update","description":"Update.","parameters":{"oneOf":[
{"type":"object","properties":{"mode":{"type":"string","enum":["a"]}},"required":["mode"]},
{"type":"object","properties":{"mode":{"type":"string","enum":["b"]}},"required":["mode"]}]}}]}`
// TestCopilotGrokTakesNamespacesFlat: Grok behind Copilot turns a request
// with a namespace tool, or a function whose parameters are a root union,
// away; flat names and object roots gave 200 (#4374). GPT on the same
// /responses is handed the tools as they came.
func TestCopilotGrokTakesNamespacesFlat(t *testing.T) {
var mu sync.Mutex
var sent []string
copilotTurnFake(t, map[string]string{
"grok-4.7": `["/responses"]`,
"gpt-6.1": `["/responses"]`,
}, func(m string, b []byte) (int, string) {
if m == "grok-4.7" && (bytes.Contains(b, []byte(`"type":"namespace"`)) || bytes.Contains(b, []byte(`"oneOf"`))) {
return http.StatusBadRequest, `{"error":{"message":"Bad Request","type":"invalid_request_error"}}`
}
return 0, ""
}, nil, "", 0, &sent)
turn := func(model string) {
rec := httptest.NewRecorder()
New().Handler().ServeHTTP(rec, httptest.NewRequest("POST", "/v1/responses", strings.NewReader(fmt.Sprintf(copilotNamespaceRequest, model))))
if rec.Code != 200 || !strings.Contains(rec.Body.String(), "DONE") {
t.Fatalf("%s: %d %s", model, rec.Code, rec.Body.String())
}
}
turn("grok-4.7")
turn("gpt-6.1")
mu.Lock()
defer mu.Unlock()
for _, s := range sent {
switch {
case strings.HasPrefix(s, "grok-4.7 "):
if !strings.Contains(s, `"name":"mcp__codex_app__move_thread_to_project"`) || strings.Contains(s, `"namespace"`) {
t.Errorf("Grok's namespace not flat: %s", s)
}
if !strings.Contains(s, `"name":"automation_update"`) {
t.Errorf("a plain function was lost: %s", s)
}
case strings.HasPrefix(s, "gpt-6.1 "):
if !strings.Contains(s, `"type":"namespace"`) || !strings.Contains(s, `"oneOf"`) {
t.Errorf("GPT's tools were changed: %s", s)
}
}
}
if len(sent) != 2 {
t.Fatalf("Copilot took %d turns", len(sent))
}
}
+20
View File
@@ -163,3 +163,23 @@ func schemaStringValues(schema gjson.Result) map[string]bool {
}
return out
}
// copilotGemini is whether body goes to a Gemini model served by a Copilot
// account.
func copilotGemini(p provider.Provider, body []byte) bool {
return p.Account != nil && p.Account.Agent == "copilot" && geminiNamed(gjson.GetBytes(body, "model").String())
}
// copilotGrokFlat is a Responses body to Copilot's Grok with Codex's
// namespaced functions flat and their parameters objects at the root: the
// backend behind Copilot turns a request with either away, and Copilot's
// word for it is a bare status (#4374), so nothing teaches magpie to do it
// after a refusal. The calls come back under their namespaces
// (namespacedIn). Another vendor's tools go as they came.
func copilotGrokFlat(p provider.Provider, to provider.Protocol, body []byte) []byte {
if to != provider.Responses || p.Account == nil || p.Account.Agent != "copilot" ||
!grokModel(gjson.GetBytes(body, "model").String()) {
return body
}
return provider.GrokFlatBody(body)
}
+2 -1
View File
@@ -5949,9 +5949,10 @@ func (s *Server) forwardOnce(ctx context.Context, p provider.Provider, to provid
body = toolOneOfAsAnyOf(p, to, body)
body = copilotGeminiToolsFit(p, to, body)
body = copilotGeminiToolUnions(p, to, body)
body = copilotGrokFlat(p, to, body)
body = kimiToolEnumTypes(p, to, body)
body = kimiToolRefTypes(p, to, body)
body = geminiToolTypes(body)
body = geminiTypes(body, copilotGemini(p, body))
body = kimiLockedSampling(p, to, body)
body = clinePin(p, to, body)
body = codexImagesFit(p, to, body)
+16 -7
View File
@@ -38,7 +38,15 @@ import (
// 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.
func geminiToolTypes(body []byte) []byte {
func geminiToolTypes(body []byte) []byte { return geminiTypes(body, false) }
// geminiTypes is geminiToolTypes, with keepUnions leaving a union node
// (anyOf or oneOf) without the type written beside it: Copilot's Gemini
// turns the request away over `type: string` next to a nullable
// `anyOf: [string, null]` (#4374, isolated by one field in a live request),
// whatever the union's branches say, so a union goes as its client wrote it.
// Its branches are typed as ever.
func geminiTypes(body []byte, keepUnions bool) []byte {
if !geminiNamed(gjson.GetBytes(body, "model").String()) {
return body
}
@@ -51,7 +59,7 @@ func geminiToolTypes(body []byte) []byte {
tools.ForEach(func(_, tool gjson.Result) bool {
for _, at := range []string{"function.parameters", "parameters", "input_schema"} {
if root := tool.Get(at); root.IsObject() {
collectGeminiUntyped(body, root, root, true, &ins)
collectGeminiUntyped(body, root, root, true, keepUnions, &ins)
}
}
return true
@@ -71,15 +79,16 @@ func geminiNamed(id string) bool {
// collectGeminiUntyped adds, for node and each schema under it that has no
// type, where it opens and the type Vertex is told.
func collectGeminiUntyped(body []byte, root, node gjson.Result, isRoot bool, ins *[]typeInsert) {
func collectGeminiUntyped(body []byte, root, node gjson.Result, isRoot, keepUnions bool, ins *[]typeInsert) {
switch {
case node.IsArray():
node.ForEach(func(_, v gjson.Result) bool {
collectGeminiUntyped(body, root, v, false, ins)
collectGeminiUntyped(body, root, v, false, keepUnions, ins)
return true
})
case node.IsObject():
if !node.Get("type").Exists() && node.Index > 0 && node.Index < len(body) && body[node.Index] == '{' {
union := keepUnions && !isRoot && (node.Get("anyOf").Exists() || node.Get("oneOf").Exists())
if !union && !node.Get("type").Exists() && node.Index > 0 && node.Index < len(body) && body[node.Index] == '{' {
if t := geminiSchemaType(root, node, isRoot); t != "" {
*ins = append(*ins, typeInsert{node.Index, `"` + t + `"`})
}
@@ -88,11 +97,11 @@ func collectGeminiUntyped(body []byte, root, node gjson.Result, isRoot bool, ins
switch key.String() {
case "properties", "$defs", "definitions", "dependentSchemas", "patternProperties":
v.ForEach(func(_, s gjson.Result) bool {
collectGeminiUntyped(body, root, s, false, ins)
collectGeminiUntyped(body, root, s, false, keepUnions, ins)
return true
})
case "items", "additionalProperties", "contains", "propertyNames", "then", "else", "allOf", "anyOf", "oneOf", "prefixItems", "unevaluatedProperties", "unevaluatedItems", "contentSchema":
collectGeminiUntyped(body, root, v, false, ins)
collectGeminiUntyped(body, root, v, false, keepUnions, ins)
}
return true
})
+60
View File
@@ -737,3 +737,63 @@ func GrokUser(home string) (string, bool) {
c, ok := readGrokCredential(home)
return c.Email, ok
}
// GrokFlatBody is a Responses body with Codex's namespaced functions flat
// (namespace__name) and every function's parameters an object at the root,
// the two things Grok's backend turns a request away over wherever it is
// served (Copilot's grok-4.7, #4374), and nothing else: tool types, reasoning
// and the rest go as they came. The model's call to a flat name is given its
// namespace back by the gateway (namespacedIn).
func GrokFlatBody(body []byte) []byte {
if !bytes.Contains(body, []byte(`"namespace"`)) && !bytes.Contains(body, []byte(`"anyOf"`)) && !bytes.Contains(body, []byte(`"oneOf"`)) && !bytes.Contains(body, []byte(`"allOf"`)) {
return body
}
dec := json.NewDecoder(bytes.NewReader(body))
dec.UseNumber()
var m map[string]any
if dec.Decode(&m) != nil || m == nil {
return body
}
dirty := false
if tools, ok := m["tools"].([]any); ok {
var out []any
for _, t := range tools {
tm, _ := t.(map[string]any)
switch {
case tm != nil && tm["type"] == "namespace":
dirty = true
for _, f := range grokFlat(tm) {
if fm, ok := f.(map[string]any); ok {
objectRoot(fm)
}
out = append(out, f)
}
case tm != nil && tm["type"] == "function":
if objectRoot(tm) {
dirty = true
}
out = append(out, t)
default:
out = append(out, t)
}
}
m["tools"] = out
}
if tc, ok := m["tool_choice"].(map[string]any); ok && flatCall(tc) {
dirty = true
}
input, _ := m["input"].([]any)
for _, it := range input {
if im, ok := it.(map[string]any); ok && flatCall(im) {
dirty = true
}
}
if !dirty {
return body
}
b, err := json.Marshal(m)
if err != nil {
return body
}
return b
}