diff --git a/internal/gateway/codeassist.go b/internal/gateway/codeassist.go index 289870a14..11ca6bebf 100644 --- a/internal/gateway/codeassist.go +++ b/internal/gateway/codeassist.go @@ -1217,6 +1217,14 @@ func plainSchema(raw json.RawMessage) json.RawMessage { out["enum"] = []any{s} } } + if es, ok := out["enum"]; ok && out["type"] == "array" { + // an enum on an array is its items' values; Google takes enum on a string + delete(out, "enum") + if it, ok := out["items"].(map[string]any); ok && it["enum"] == nil && (it["type"] == nil || it["type"] == "string") { + it["type"] = "string" + it["enum"] = es + } + } if out["type"] == nil { switch { case out["properties"] != nil: diff --git a/internal/gateway/copilot_gemini_grok_test.go b/internal/gateway/copilot_gemini_grok_test.go index 51aed3660..c51985da9 100644 --- a/internal/gateway/copilot_gemini_grok_test.go +++ b/internal/gateway/copilot_gemini_grok_test.go @@ -88,7 +88,8 @@ const copilotOverlappingRequest = `{"model":"copilot/gemini-3.8-flash","stream": // TestCopilotGeminiKeepsUnprovenUnions: only what is provably disjoint // goes as oneOf. A union whose branches can't be told apart stays an -// anyOf, and Copilot's refusal of it still reaches the client, as it did +// anyOf (one of mixed types: same-type branches are merged, +// TestCopilotGeminiTakesToolShapes), and Copilot's refusal of it still reaches the client, as it did // before (#4374's Gemini turns were all refused; this union is one the // conversion leaves as it came). func TestCopilotGeminiKeepsUnprovenUnions(t *testing.T) { @@ -101,7 +102,8 @@ func TestCopilotGeminiKeepsUnprovenUnions(t *testing.T) { }, "invalid request body", http.StatusBadRequest, &sent) rec := httptest.NewRecorder() - New().Handler().ServeHTTP(rec, httptest.NewRequest("POST", "/v1/responses", strings.NewReader(copilotOverlappingRequest))) + New().Handler().ServeHTTP(rec, httptest.NewRequest("POST", "/v1/responses", strings.NewReader(strings.Replace(copilotOverlappingRequest, + `{"type":"object","properties":{"square":{"type":"boolean"}}}`, `{"type":"array","items":{"type":"string"}}`, 1)))) if rec.Code != http.StatusBadRequest || !strings.Contains(rec.Body.String(), "invalid request body") { t.Fatalf("%d %s", rec.Code, rec.Body.String()) } diff --git a/internal/gateway/copilot_gemini_shapes.go b/internal/gateway/copilot_gemini_shapes.go new file mode 100644 index 000000000..256e0afe2 --- /dev/null +++ b/internal/gateway/copilot_gemini_shapes.go @@ -0,0 +1,367 @@ +package gateway + +import ( + "bytes" + "encoding/json" + "reflect" + "sort" + + "github.com/tidwall/gjson" + "github.com/yetone/magpie/internal/provider" +) + +// Copilot's Gemini answers 400 to tool schemas of six shapes that other +// vendors take (MCP servers write all of them; ProgCZ and tmhyt1 on X, on +// v0.1.3853): an object with no properties, an anyOf whose branches share +// one type, an anyOf with an untyped branch, an enum on an array, a union +// at the root, and a tuple array (prefixItems). Each is written as the +// nearest schema Gemini takes, keeping what the model can act on: +// +// - object with no properties: properties {} added; +// - anyOf of one type (null apart): that one schema, branches merged +// (object properties joined, string enums joined), nullable kept as an +// anyOf with null; +// - anyOf with a branch whose type can't be told: the union goes, the +// description stays, and the node is typed like any untyped schema +// (geminiTypes, which runs after); +// - enum on an array: moved to items when those are strings, else dropped; +// - union at the root: an object holding the properties of its object +// branches, none of them required; +// - prefixItems (or items as a list): items, the one schema the positions +// share, or an anyOf of them. +// +// A nested oneOf is left: Copilot's Gemini takes it (#4374). A schema with +// none of the six goes byte for byte as it came, and only Copilot's Gemini +// on chat is touched. +func copilotGeminiToolShapes(p provider.Provider, to provider.Protocol, body []byte) []byte { + if to != provider.Chat || !copilotGemini(p, body) { + return body + } + tools := gjson.GetBytes(body, "tools") + if !tools.IsArray() { + return body + } + dec := json.NewDecoder(bytes.NewReader([]byte(tools.Raw))) + dec.UseNumber() + var list []any + if dec.Decode(&list) != nil { + return body + } + changed := false + for _, tool := range list { + m, _ := tool.(map[string]any) + if fn, ok := m["function"].(map[string]any); ok { + m = fn + } + for _, k := range []string{"parameters", "input_schema"} { + if root, ok := m[k].(map[string]any); ok { + changed = shapeForGemini(root, true) || changed + } + } + } + if !changed { + return body + } + raw, err := json.Marshal(list) + if err != nil { + return body + } + out := make([]byte, 0, len(body)) + out = append(out, body[:tools.Index]...) + out = append(out, raw...) + return append(out, body[tools.Index+len(tools.Raw):]...) +} + +// shapeForGemini rewrites schema s in place, below first, and says whether +// it changed anything. +func shapeForGemini(s map[string]any, root bool) bool { + changed := false + // children first, so a union is judged on branches already fit + for _, k := range []string{"properties", "patternProperties", "$defs", "definitions"} { + if m, ok := s[k].(map[string]any); ok { + for _, v := range m { + if c, ok := v.(map[string]any); ok { + changed = shapeForGemini(c, false) || changed + } + } + } + } + for _, k := range []string{"items", "additionalProperties", "not", "contains"} { + if c, ok := s[k].(map[string]any); ok { + changed = shapeForGemini(c, false) || changed + } + } + for _, k := range []string{"anyOf", "oneOf", "allOf", "prefixItems", "items"} { + if l, ok := s[k].([]any); ok { + for _, v := range l { + if c, ok := v.(map[string]any); ok { + changed = shapeForGemini(c, false) || changed + } + } + } + } + + // a tuple: one items schema + tuple, hasPrefix := s["prefixItems"].([]any) + if l, ok := s["items"].([]any); ok { + tuple, hasPrefix = l, true + } + if _, has := s["prefixItems"]; has || hasPrefix { + delete(s, "prefixItems") + if _, isSchema := s["items"].(map[string]any); !isSchema { + s["items"] = tupleItems(tuple) + if m, ok := s["items"].(map[string]any); ok { + shapeForGemini(m, false) + } + } + if s["type"] == nil { + s["type"] = "array" + } + changed = true + } + + // an enum on an array belongs to its items + if _, has := s["enum"]; has && s["type"] == "array" { + if es, ok := s["enum"].([]any); ok && allStrings(es) { + items, _ := s["items"].(map[string]any) + if items == nil && s["items"] == nil { + items = map[string]any{"type": "string"} + s["items"] = items + } + if items != nil && items["enum"] == nil && (items["type"] == nil || items["type"] == "string") { + items["enum"] = es + if items["type"] == nil { + items["type"] = "string" + } + } + } + delete(s, "enum") + changed = true + } + + // a union + if alts, ok := s["oneOf"].([]any); ok && root { + flattenRootUnion(s, "oneOf", alts) + changed = true + } else if alts, ok := s["anyOf"].([]any); ok { + if root && s["type"] == nil { + flattenRootUnion(s, "anyOf", alts) + changed = true + } else { + changed = mergeUnion(s, "anyOf", alts) || changed + } + } + + if s["type"] == "object" { + if _, has := s["properties"]; !has { + s["properties"] = map[string]any{} + changed = true + } + } + return changed +} + +func allStrings(es []any) bool { + for _, e := range es { + if _, ok := e.(string); !ok { + return false + } + } + return true +} + +// tupleItems is the items schema a tuple's positions share. +func tupleItems(prefix []any) any { + var uniq []any + for _, p := range prefix { + m, ok := p.(map[string]any) + if !ok { + continue + } + dup := false + for _, u := range uniq { + dup = dup || reflect.DeepEqual(u, m) + } + if !dup { + uniq = append(uniq, m) + } + } + switch len(uniq) { + case 0: + return map[string]any{} + case 1: + return uniq[0] + } + return map[string]any{"anyOf": uniq} +} + +// flattenRootUnion turns a root union into an object holding every object +// branch's properties; no branch's required list survives, since another +// branch may be the one used. +func flattenRootUnion(s map[string]any, key string, alts []any) { + props := map[string]any{} + for _, a := range alts { + m, _ := a.(map[string]any) + if ps, ok := m["properties"].(map[string]any); ok { + for n, v := range ps { + if _, has := props[n]; !has { + props[n] = v + } + } + } + } + if own, ok := s["properties"].(map[string]any); ok { + for n, v := range own { + props[n] = v + } + } + delete(s, key) + delete(s, "required") + s["type"] = "object" + s["properties"] = props +} + +// mergeUnion folds an anyOf whose branches share one type (null apart) into +// one schema, and drops one with a branch that has no type. It says whether +// it changed s. +func mergeUnion(s map[string]any, key string, alts []any) bool { + var typed []map[string]any + nullable := false + typ := "" + for _, a := range alts { + m, _ := a.(map[string]any) + if m == nil { + delete(s, key) + return true + } + t, _ := m["type"].(string) + if t == "null" { + nullable = true + continue + } + if t == "" { + t = guessType(m) + } + if t == "" { + // nothing says what this branch is: the node goes untyped, to be + // given its type like any other + delete(s, key) + return true + } + m["type"] = t + if typ != "" && typ != t { + return false + } + typ = t + typed = append(typed, m) + } + if len(typed) == 0 || len(typed) == 1 && nullable { + return false // a nullable single schema is what Copilot's Gemini takes + } + merged := map[string]any{} + for _, m := range typed { + for k, v := range m { + switch k { + case "properties": + props, _ := merged[k].(map[string]any) + if props == nil { + props = map[string]any{} + } + pm, _ := v.(map[string]any) + for n, pv := range pm { + if _, has := props[n]; !has { + props[n] = pv + } + } + merged[k] = props + case "enum": + es, _ := merged[k].([]any) + for _, e := range asList(v) { + dup := false + for _, x := range es { + dup = dup || reflect.DeepEqual(x, e) + } + if !dup { + es = append(es, e) + } + } + merged[k] = es + case "required": + // only what every branch requires, below + default: + if _, has := merged[k]; !has { + merged[k] = v + } + } + } + } + for _, m := range typed { + if _, has := m["enum"]; !has { + delete(merged, "enum") // a branch without an enum takes any value + } + } + if req := commonRequired(typed); len(req) > 0 { + merged["required"] = req + } + delete(s, key) + for k, v := range merged { + if _, has := s[k]; !has { + s[k] = v + } + } + if nullable { + inner := map[string]any{} + for _, k := range []string{"type", "properties", "required", "items", "enum"} { + if v, ok := s[k]; ok { + inner[k] = v + delete(s, k) + } + } + s[key] = []any{inner, map[string]any{"type": "null"}} + } + return true +} + +func commonRequired(typed []map[string]any) []any { + count := map[string]int{} + for _, m := range typed { + seen := map[string]bool{} + for _, r := range asList(m["required"]) { + if n, ok := r.(string); ok && !seen[n] { + seen[n] = true + count[n]++ + } + } + } + var names []string + for n, c := range count { + if c == len(typed) { + names = append(names, n) + } + } + sort.Strings(names) + out := make([]any, len(names)) + for i, n := range names { + out[i] = n + } + return out +} + +func asList(v any) []any { l, _ := v.([]any); return l } + +// guessType is the type a branch without one says by its keywords. +func guessType(m map[string]any) string { + switch { + case m["properties"] != nil: + return "object" + case m["items"] != nil: + return "array" + } + if es, ok := m["enum"].([]any); ok && len(es) > 0 && allStrings(es) { + return "string" + } + if _, ok := m["const"].(string); ok { + return "string" + } + return "" +} diff --git a/internal/gateway/copilot_gemini_shapes_test.go b/internal/gateway/copilot_gemini_shapes_test.go new file mode 100644 index 000000000..964557713 --- /dev/null +++ b/internal/gateway/copilot_gemini_shapes_test.go @@ -0,0 +1,143 @@ +package gateway + +import ( + "encoding/json" + "net/http" + "net/http/httptest" + "strings" + "testing" + + "github.com/yetone/magpie/internal/provider" +) + +// badGeminiShape names the shape of a tool schema Copilot's Gemini turns +// away 400 (ProgCZ and tmhyt1 on X), "" for a schema it takes. +func badGeminiShape(node any, root bool) string { + switch v := node.(type) { + case []any: + for _, e := range v { + if s := badGeminiShape(e, false); s != "" { + return s + } + } + case map[string]any: + if _, ok := v["prefixItems"]; ok { + return "prefixItems" + } + if _, ok := v["enum"]; ok && v["type"] == "array" { + return "array enum" + } + if root && (v["oneOf"] != nil || v["anyOf"] != nil) { + return "root union" + } + if v["type"] == "object" && v["properties"] == nil { + return "object without properties" + } + if alts, ok := v["anyOf"].([]any); ok { + types := map[string]bool{} + for _, a := range alts { + m, _ := a.(map[string]any) + t, _ := m["type"].(string) + if t == "" { + return "untyped branch" + } + if t != "null" { + types[t] = true + } + } + n := 0 + for _, a := range alts { + if m, _ := a.(map[string]any); m["type"] != "null" { + n++ + } + } + if len(types) == 1 && n > 1 { + return "same type" + } + } + for _, e := range v { + if s := badGeminiShape(e, false); s != "" { + return s + } + } + } + return "" +} + +func TestCopilotGeminiTakesToolShapes(t *testing.T) { + cases := []struct{ name, schema, want string }{ + {"object without properties", `{"type":"object","properties":{"opts":{"type":"object","description":"o"}}}`, `"opts":{"description":"o","properties":{},"type":"object"}`}, + {"object at the root without properties", `{"type":"object"}`, `"parameters":{"properties":{},"type":"object"}`}, + {"anyOf of one type beside its type", `{"type":"object","properties":{"v":{"description":"d","type":"string","anyOf":[{"type":"string"},{"type":"string"}]}}}`, `"v":{"description":"d","type":"string"}`}, + {"anyOf of one type", `{"type":"object","properties":{"v":{"anyOf":[{"type":"string","enum":["a"]},{"type":"string","enum":["b"]}]}}}`, `"v":{"enum":["a","b"],"type":"string"}`}, + {"anyOf with untyped branches", `{"type":"object","properties":{"v":{"description":"d","anyOf":[{"description":"x"},{"type":"string"}]}}}`, `"v":{"type":"string","description":"d"}`}, + {"enum on an array", `{"type":"object","properties":{"v":{"type":"array","enum":["a","b"]}}}`, `"v":{"items":{"enum":["a","b"],"type":"string"},"type":"array"}`}, + {"oneOf at the root", `{"oneOf":[{"type":"object","properties":{"a":{"type":"string"}},"required":["a"]},{"type":"object","properties":{"b":{"type":"number"}},"required":["b"]}]}`, `{"properties":{"a":{"type":"string"},"b":{"type":"number"}},"type":"object"}`}, + {"prefixItems", `{"type":"object","properties":{"p":{"type":"array","prefixItems":[{"type":"number"},{"type":"number"}]}}}`, `"p":{"items":{"type":"number"},"type":"array"}`}, + } + for _, c := range cases { + t.Run(c.name, func(t *testing.T) { + var sent []string + var refused string + copilotTurnFake(t, map[string]string{"gemini-3.8-flash": `["/chat/completions"]`}, nil, + func(m string, b []byte) bool { + var body struct { + Tools []struct { + Function struct { + Parameters any `json:"parameters"` + } `json:"function"` + } `json:"tools"` + } + json.Unmarshal(b, &body) + for _, tool := range body.Tools { + if s := badGeminiShape(tool.Function.Parameters, true); s != "" { + refused = s + return true + } + } + return false + }, "invalid request body", http.StatusBadRequest, &sent) + req := `{"model":"copilot/gemini-3.8-flash","stream":false,"messages":[{"role":"user","content":"hi"}], + "tools":[{"type":"function","function":{"name":"t","parameters":` + c.schema + `}}]}` + rec := httptest.NewRecorder() + New().Handler().ServeHTTP(rec, httptest.NewRequest("POST", "/v1/chat/completions", strings.NewReader(req))) + if rec.Code != 200 { + t.Fatalf("%d (%s) %s", rec.Code, refused, rec.Body.String()) + } + if len(sent) != 1 || !strings.Contains(sent[0], c.want) { + t.Errorf("want %s in %v", c.want, sent) + } + }) + } +} + +// A schema with none of the six shapes goes as it came, byte for byte, and +// another vendor's body is not touched. +func TestCopilotGeminiToolShapesLeavesFitSchemas(t *testing.T) { + fit := `{"model":"gemini-3.8-flash","tools":[{"type":"function","function":{"name":"t","parameters":{"type":"object","properties":{"n":{"anyOf":[{"type":"string"},{"type":"null"}]},"u":{"oneOf":[{"type":"string"},{"type":"number"}]},"a":{"type":"array","items":{"type":"string"}}}}}}]}` + if got := string(copilotGeminiToolShapes(provider.Provider{Account: &provider.Account{Agent: "copilot"}}, provider.Chat, []byte(fit))); got != fit { + t.Errorf("changed a fit schema: %s", got) + } +} + +// Antigravity's cut-down schema had the same array-level enum: Google takes +// enum on a string, so it belongs to the items. +func TestAntigravitySchemaArrayEnumMovesToItems(t *testing.T) { + var got struct { + Properties map[string]struct { + Enum []string `json:"enum"` + Items struct { + Type string `json:"type"` + Enum []string `json:"enum"` + } `json:"items"` + } `json:"properties"` + } + in := `{"type":"object","properties":{"v":{"type":"array","enum":["a","b"],"items":{"type":"string"}}}}` + if err := json.Unmarshal(plainSchema(json.RawMessage(in)), &got); err != nil { + t.Fatal(err) + } + v := got.Properties["v"] + if len(v.Enum) != 0 || len(v.Items.Enum) != 2 { + t.Errorf("%+v", v) + } +} diff --git a/internal/gateway/gateway.go b/internal/gateway/gateway.go index 61fae61a6..f14bf99a7 100644 --- a/internal/gateway/gateway.go +++ b/internal/gateway/gateway.go @@ -5981,6 +5981,7 @@ 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 = copilotGeminiToolShapes(p, to, body) body = copilotGrokFlat(p, to, body) body = kimiToolEnumTypes(p, to, body) body = kimiToolRefTypes(p, to, body)