From 6faa8d20b2673404cff70a2f2d9537ae0d0e684d Mon Sep 17 00:00:00 2001 From: Luis Pater Date: Thu, 19 Nov 2026 20:56:43 +0800 Subject: [PATCH] fix(codex): strip uniqueItems keyword from tool parameter schemas - Add "uniqueItems" to the stripIncompatiblePatternsFromJSON fast-path guard and remove schema-level uniqueItems keys in stripIncompatiblePatterns while preserving literal properties.uniqueItems fields and non-schema user data. - Update NormalizeCodexToolSchemas documentation and add regression tests across tool-schema, helps, and Codex HTTP and WebSocket executors. Closes: #7690 --- .../client/codex/tool-schema/tool_schema.go | 11 +- .../codex/tool-schema/tool_schema_test.go | 157 ++++++++++++++ .../codex_executor_tool_schema_test.go | 198 ++++++++++++++++++ .../executor/helps/codex_tool_schema.go | 4 +- .../executor/helps/codex_tool_schema_test.go | 58 +++++ 5 files changed, 423 insertions(+), 5 deletions(-) diff --git a/internal/client/codex/tool-schema/tool_schema.go b/internal/client/codex/tool-schema/tool_schema.go index e769f7f6cf..14b4e255a6 100644 --- a/internal/client/codex/tool-schema/tool_schema.go +++ b/internal/client/codex/tool-schema/tool_schema.go @@ -363,7 +363,7 @@ func normalizeToolIntegerTypesInElementDoc(doc *ojson.Doc, tool ojson.Result, to // NormalizeCodexToolSchemas inspects function tools in a Codex request payload // and simplifies pure constant union combinations (e.g. large oneOf branch sets // representing enums with descriptions, as emitted by MCP servers) into semantically -// equivalent enum lists, and sanitizes unsupported schema patterns. +// equivalent enum lists, and sanitizes unsupported schema keywords and patterns. // It does not normalize tool integer types because upstream OpenAI Codex models // strictly validate reserved tool schemas (e.g. collaboration.wait_agent). func NormalizeCodexToolSchemas(body []byte) []byte { @@ -378,7 +378,7 @@ func NormalizeCodexToolSchemas(body []byte) []byte { } // NormalizeCodexToolSchemasDoc inspects function tools in doc and simplifies -// pure constant union combinations and sanitizes unsupported schema patterns in place. +// pure constant union combinations and sanitizes unsupported schema keywords and patterns in place. func NormalizeCodexToolSchemasDoc(doc *ojson.Doc) bool { if doc == nil || doc.Len() == 0 { return false @@ -481,7 +481,8 @@ func normalizeCodexParametersDoc(doc *ojson.Doc, paramsPath string, params ojson func stripIncompatiblePatternsFromJSON(rawStr string) (string, bool) { if !strings.Contains(rawStr, `\p{`) && !strings.Contains(rawStr, `\P{`) && !strings.Contains(rawStr, `\u`) && - !strings.Contains(rawStr, `\\0`) && !strings.Contains(rawStr, "inimum") && !strings.Contains(rawStr, "aximum") { + !strings.Contains(rawStr, `\\0`) && !strings.Contains(rawStr, "inimum") && !strings.Contains(rawStr, "aximum") && + !strings.Contains(rawStr, `"uniqueItems"`) { return rawStr, false } var root any @@ -606,6 +607,10 @@ func stripIncompatiblePatterns(v any) bool { changed = true } } + if _, exists := schema["uniqueItems"]; exists { + delete(schema, "uniqueItems") + changed = true + } // Inspect regex keys under patternProperties if patternProps, ok := schema["patternProperties"].(map[string]any); ok { diff --git a/internal/client/codex/tool-schema/tool_schema_test.go b/internal/client/codex/tool-schema/tool_schema_test.go index 90e4e48890..4deee25ed9 100644 --- a/internal/client/codex/tool-schema/tool_schema_test.go +++ b/internal/client/codex/tool-schema/tool_schema_test.go @@ -1,6 +1,7 @@ package toolschema import ( + "bytes" "net/http" "testing" @@ -409,3 +410,159 @@ func TestNormalizeCodexToolSchemasDocCrossMethod(t *testing.T) { t.Fatalf("expected field.pattern to be removed: %s", fieldProp.Raw) } } + +func TestNormalizeCodexToolSchemasDoc_StripsUniqueItems(t *testing.T) { + raw := []byte(`{ + "model": "gpt-6.2-astra", + "tools": [ + { + "type": "function", + "name": "ask_user", + "description": "Ask the user a structured question.", + "parameters": { + "type": "object", + "properties": { + "question": {"type": "string"}, + "options": { + "type": "array", + "items": {"type": "string"}, + "uniqueItems": true + } + }, + "required": ["question"] + } + }, + { + "type": "function", + "name": "strict_tool", + "strict": true, + "parameters": { + "type": "object", + "properties": { + "nested_array": { + "type": "array", + "uniqueItems": false, + "items": { + "type": "array", + "items": {"type": "string"}, + "uniqueItems": true + } + }, + "union_array": { + "anyOf": [ + {"type": "array", "items": {"type": "string"}, "uniqueItems": true}, + {"type": "null"} + ] + }, + "escaped": { + "type": "array", + "items": {"type": "string"}, + "\u0075niqueItems": true + }, + "uniqueItems": { + "type": "boolean", + "description": "User property literally named uniqueItems" + }, + "user_data": { + "type": "object", + "default": {"uniqueItems": true}, + "enum": [{"uniqueItems": true}] + } + }, + "additionalProperties": { + "type": "array", + "items": {"type": "string"}, + "uniqueItems": true + }, + "$defs": { + "tag_list": { + "type": "array", + "items": {"type": "string"}, + "uniqueItems": true + } + } + } + }, + { + "type": "namespace", + "name": "workspace", + "tools": [ + { + "type": "function", + "name": "tag_items", + "parameters": { + "type": "object", + "properties": { + "tags": { + "type": "array", + "items": {"type": "string"}, + "uniqueItems": true + } + } + } + } + ] + } + ] + }`) + + doc := ojson.NewDoc(raw) + if !NormalizeCodexToolSchemasDoc(doc) { + t.Fatal("expected NormalizeCodexToolSchemasDoc to report changes") + } + if NormalizeCodexToolSchemasDoc(doc) { + t.Fatal("expected second NormalizeCodexToolSchemasDoc call to be idempotent") + } + got := doc.Bytes() + + askTool := ojson.GetBytesNoCopy(got, "tools.0") + if askTool.Get("strict").Exists() { + t.Fatalf("expected omitted strict on tools.0 to stay omitted, got %s", askTool.Get("strict").Raw) + } + if askTool.Get("parameters.properties.options.uniqueItems").Exists() { + t.Fatalf("expected ask_user options.uniqueItems to be removed, got %s", askTool.Get("parameters.properties.options").Raw) + } + if gotType := askTool.Get("parameters.properties.options.items.type").String(); gotType != "string" { + t.Fatalf("ask_user options.items.type = %q, want string", gotType) + } + + strictTool := ojson.GetBytesNoCopy(got, "tools.1") + if strictTool.Get("strict").Type != ojson.True { + t.Fatalf("expected strict=true preserved on tools.1, got %s", strictTool.Get("strict").Raw) + } + strictParams := strictTool.Get("parameters") + for _, removedPath := range []string{ + "properties.nested_array.uniqueItems", + "properties.nested_array.items.uniqueItems", + "properties.union_array.anyOf.0.uniqueItems", + "properties.escaped.uniqueItems", + "additionalProperties.uniqueItems", + "$defs.tag_list.uniqueItems", + } { + if strictParams.Get(removedPath).Exists() { + t.Errorf("expected %s to be removed, got %s", removedPath, strictParams.Get(removedPath).Raw) + } + } + if gotType := strictParams.Get("properties.uniqueItems.type").String(); gotType != "boolean" { + t.Errorf("expected literal property named uniqueItems preserved, got type=%q (%s)", gotType, strictParams.Get("properties.uniqueItems").Raw) + } + if gotDefault := strictParams.Get("properties.user_data.default.uniqueItems"); gotDefault.Type != ojson.True { + t.Errorf("expected user_data.default.uniqueItems preserved, got %s", strictParams.Get("properties.user_data.default").Raw) + } + if gotEnum := strictParams.Get("properties.user_data.enum.0.uniqueItems"); gotEnum.Type != ojson.True { + t.Errorf("expected user_data.enum.0.uniqueItems preserved, got %s", strictParams.Get("properties.user_data.enum").Raw) + } + + if ojson.GetBytesNoCopy(got, "tools.2.tools.0.parameters.properties.tags.uniqueItems").Exists() { + t.Errorf("expected namespace nested tags.uniqueItems to be removed") + } + + unchanged := []byte(`{"model":"gpt-6.2-astra","tools":[{"type":"function","name":"prose_only","parameters":{"type":"object","properties":{"items":{"type":"array","items":{"type":"string"},"description":"Keep uniqueItems semantics in prose"}}}}]}`) + unchangedDoc := ojson.NewDoc(unchanged) + if NormalizeCodexToolSchemasDoc(unchangedDoc) { + t.Fatalf("expected prose-only mention of uniqueItems not to mutate schema") + } + if !bytes.Equal(unchangedDoc.Bytes(), unchanged) { + t.Fatalf("expected unchanged schema bytes to stay identical") + } +} diff --git a/internal/runtime/executor/codex_executor_tool_schema_test.go b/internal/runtime/executor/codex_executor_tool_schema_test.go index 4f1873e346..6bd056cb66 100644 --- a/internal/runtime/executor/codex_executor_tool_schema_test.go +++ b/internal/runtime/executor/codex_executor_tool_schema_test.go @@ -972,3 +972,201 @@ func TestOpenAICompatExecutor_NormalizesToolIntegerTypesForCodexUserAgent_NonCod t.Fatalf("expected non-Codex executor to normalize timeout_ms to integer, got: %s (body=%s)", got, string(gotBody)) } } + +// Issue #7690: Codex Responses rejects function tool schemas containing "uniqueItems" +// on gpt-6.2-astra when "strict" is omitted or true. All Codex HTTP and WebSocket +// execution paths must strip uniqueItems while preserving strict semantics and literal +// properties named "uniqueItems". +func TestCodexExecutor_StripsUniqueItemsFromToolSchemas(t *testing.T) { + requestPayload := []byte(`{ + "model": "gpt-6.2-astra", + "instructions": "Reply with ok", + "input": [{"role": "user", "content": [{"type": "input_text", "text": "Say ok"}]}], + "tools": [ + { + "type": "function", + "name": "ask_user", + "description": "Ask the user a structured question.", + "parameters": { + "type": "object", + "properties": { + "question": {"type": "string"}, + "options": { + "type": "array", + "items": {"type": "string"}, + "uniqueItems": true + } + }, + "required": ["question"] + } + }, + { + "type": "function", + "name": "strict_tags", + "strict": true, + "parameters": { + "type": "object", + "properties": { + "tags": { + "type": "array", + "items": {"type": "string"}, + "uniqueItems": false + }, + "uniqueItems": {"type": "boolean"} + }, + "required": ["tags", "uniqueItems"], + "additionalProperties": false + } + } + ], + "stream": true, + "store": false + }`) + + assertPayload := func(t *testing.T, mode string, body []byte) { + t.Helper() + askTool := ojson.GetBytes(body, `tools.#(name=="ask_user")`) + if !askTool.Exists() { + t.Fatalf("%s: ask_user tool missing in body: %s", mode, string(body)) + } + if askTool.Get("strict").Exists() { + t.Fatalf("%s: expected omitted strict on ask_user to remain omitted, got %s", mode, askTool.Get("strict").Raw) + } + if askTool.Get("parameters.properties.options.uniqueItems").Exists() { + t.Fatalf("%s: expected ask_user options.uniqueItems to be stripped, got %s", mode, askTool.Get("parameters.properties.options").Raw) + } + strictTool := ojson.GetBytes(body, `tools.#(name=="strict_tags")`) + if !strictTool.Exists() { + t.Fatalf("%s: strict_tags tool missing in body: %s", mode, string(body)) + } + if strictTool.Get("strict").Type != ojson.True { + t.Fatalf("%s: expected strict=true preserved on strict_tags, got %s", mode, strictTool.Get("strict").Raw) + } + if strictTool.Get("parameters.properties.tags.uniqueItems").Exists() { + t.Fatalf("%s: expected strict_tags tags.uniqueItems to be stripped, got %s", mode, strictTool.Get("parameters.properties.tags").Raw) + } + if gotType := strictTool.Get("parameters.properties.uniqueItems.type").String(); gotType != "boolean" { + t.Fatalf("%s: expected literal property uniqueItems preserved, got %q", mode, gotType) + } + } + + t.Run("http", func(t *testing.T) { + var gotBody []byte + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + body, errRead := io.ReadAll(r.Body) + if errRead != nil { + t.Errorf("read request body: %v", errRead) + http.Error(w, errRead.Error(), http.StatusInternalServerError) + return + } + gotBody = bytes.Clone(body) + if r.URL.Path == "/responses/compact" { + w.Header().Set("Content-Type", "application/json") + _, _ = w.Write([]byte(`{"id":"resp_compact","object":"response.compaction","output":[]}`)) + return + } + w.Header().Set("Content-Type", "text/event-stream") + _, _ = w.Write([]byte("data: {\"type\":\"response.completed\",\"response\":{\"id\":\"resp_1\",\"object\":\"response\",\"status\":\"completed\",\"output\":[],\"usage\":{\"input_tokens\":0,\"output_tokens\":0,\"total_tokens\":0}}}\n\n")) + })) + defer server.Close() + + executor := NewCodexExecutor(&config.Config{}) + auth := &cliproxyauth.Auth{ + Provider: "codex", + Attributes: map[string]string{ + "api_key": "test", + "base_url": server.URL, + "plan_type": "pro", + }, + } + req := cliproxyexecutor.Request{Model: "gpt-6.2-astra", Payload: requestPayload} + opts := cliproxyexecutor.Options{SourceFormat: sdktranslator.FromString("openai-response")} + + gotBody = nil + if _, errExec := executor.Execute(context.Background(), auth, req, opts); errExec != nil { + t.Fatalf("Execute() error = %v", errExec) + } + assertPayload(t, "http execute", gotBody) + + gotBody = nil + streamRes, errStream := executor.ExecuteStream(context.Background(), auth, req, opts) + if errStream != nil { + t.Fatalf("ExecuteStream() error = %v", errStream) + } + for range streamRes.Chunks { + } + assertPayload(t, "http stream", gotBody) + + gotBody = nil + compactOpts := opts + compactOpts.Alt = "responses/compact" + if _, errCompact := executor.Execute(context.Background(), auth, req, compactOpts); errCompact != nil { + t.Fatalf("Execute(compact) error = %v", errCompact) + } + assertPayload(t, "http compact", gotBody) + }) + + t.Run("websocket", func(t *testing.T) { + upgrader := websocket.Upgrader{CheckOrigin: func(*http.Request) bool { return true }} + capturedPayload := make(chan []byte, 2) + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + conn, errUpgrade := upgrader.Upgrade(w, r, nil) + if errUpgrade != nil { + t.Errorf("upgrade websocket: %v", errUpgrade) + return + } + defer func() { _ = conn.Close() }() + + _, payload, errRead := conn.ReadMessage() + if errRead != nil { + t.Errorf("read upstream websocket message: %v", errRead) + return + } + capturedPayload <- bytes.Clone(payload) + + completed := []byte(`{"type":"response.completed","response":{"id":"resp-1","output":[],"usage":{"input_tokens":0,"output_tokens":0,"total_tokens":0}}}`) + if errWrite := conn.WriteMessage(websocket.TextMessage, completed); errWrite != nil { + t.Errorf("write completed websocket message: %v", errWrite) + } + })) + defer server.Close() + + exec := NewCodexWebsocketsExecutor(&config.Config{}) + auth := &cliproxyauth.Auth{ + Provider: "codex", + Attributes: map[string]string{ + "api_key": "sk-test", + "base_url": server.URL, + "plan_type": "pro", + }, + } + req := cliproxyexecutor.Request{Model: "gpt-6.2-astra", Payload: requestPayload} + opts := cliproxyexecutor.Options{SourceFormat: sdktranslator.FromString("openai-response")} + + streamRes, errStream := exec.ExecuteStream(context.Background(), auth, req, opts) + if errStream != nil { + t.Fatalf("WS ExecuteStream() error = %v", errStream) + } + for chunk := range streamRes.Chunks { + if chunk.Err != nil { + t.Fatalf("WS stream chunk error = %v", chunk.Err) + } + } + select { + case payload := <-capturedPayload: + assertPayload(t, "ws stream", payload) + case <-time.After(5 * time.Second): + t.Fatal("timed out waiting for ws stream payload") + } + + if _, errExec := exec.Execute(context.Background(), auth, req, opts); errExec != nil { + t.Fatalf("WS Execute() error = %v", errExec) + } + select { + case payload := <-capturedPayload: + assertPayload(t, "ws execute", payload) + case <-time.After(5 * time.Second): + t.Fatal("timed out waiting for ws execute payload") + } + }) +} diff --git a/internal/runtime/executor/helps/codex_tool_schema.go b/internal/runtime/executor/helps/codex_tool_schema.go index 9b7315b877..dbef5416f5 100644 --- a/internal/runtime/executor/helps/codex_tool_schema.go +++ b/internal/runtime/executor/helps/codex_tool_schema.go @@ -27,7 +27,7 @@ func NormalizeCodexToolIntegerTypesDoc(doc *ojson.Doc, headers http.Header) bool // NormalizeCodexToolSchemas inspects function tools in a Codex request payload // and simplifies pure constant union combinations (e.g. large oneOf branch sets // representing enums with descriptions, as emitted by MCP servers) into semantically -// equivalent enum lists, and sanitizes unsupported schema patterns. +// equivalent enum lists, and sanitizes unsupported schema keywords and patterns. // It does not normalize tool integer types because upstream OpenAI Codex models // strictly validate reserved tool schemas (e.g. collaboration.wait_agent). func NormalizeCodexToolSchemas(body []byte) []byte { @@ -35,7 +35,7 @@ func NormalizeCodexToolSchemas(body []byte) []byte { } // NormalizeCodexToolSchemasDoc inspects function tools in doc and simplifies -// pure constant union combinations and sanitizes unsupported schema patterns in place. +// pure constant union combinations and sanitizes unsupported schema keywords and patterns in place. func NormalizeCodexToolSchemasDoc(doc *ojson.Doc) bool { return toolschema.NormalizeCodexToolSchemasDoc(doc) } diff --git a/internal/runtime/executor/helps/codex_tool_schema_test.go b/internal/runtime/executor/helps/codex_tool_schema_test.go index 2beb8be513..8fa860efaa 100644 --- a/internal/runtime/executor/helps/codex_tool_schema_test.go +++ b/internal/runtime/executor/helps/codex_tool_schema_test.go @@ -1422,3 +1422,61 @@ func TestNormalizeCodexToolSchemas_StripsOutOfRangeInt64Bounds(t *testing.T) { t.Errorf("expected NormalizeCodexToolSchemas to be idempotent") } } + +func TestNormalizeCodexToolSchemas_StripsUniqueItems(t *testing.T) { + input := []byte(`{ + "model": "gpt-6.2-astra", + "tools": [{ + "type": "function", + "name": "ask_user", + "description": "Ask the user a structured question.", + "parameters": { + "type": "object", + "properties": { + "question": {"type": "string"}, + "options": { + "type": "array", + "items": {"type": "string"}, + "uniqueItems": true + }, + "uniqueItems": { + "type": "boolean" + }, + "user_data": { + "type": "object", + "default": {"uniqueItems": true}, + "enum": [{"uniqueItems": false}] + } + }, + "required": ["question"] + } + }] + }`) + + out := NormalizeCodexToolSchemas(input) + params := ojson.GetBytes(out, "tools.0.parameters") + + if params.Get("properties.options.uniqueItems").Exists() { + t.Errorf("expected properties.options.uniqueItems to be removed, got %s", params.Get("properties.options").Raw) + } + if got := params.Get("properties.options.type").String(); got != "array" { + t.Errorf("expected properties.options.type == 'array', got %q", got) + } + if got := params.Get("properties.options.items.type").String(); got != "string" { + t.Errorf("expected properties.options.items.type == 'string', got %q", got) + } + if got := params.Get("properties.uniqueItems.type").String(); got != "boolean" { + t.Errorf("expected literal property 'uniqueItems' preserved, got %q", got) + } + if params.Get("properties.user_data.default.uniqueItems").Type != ojson.True { + t.Errorf("expected user_data.default.uniqueItems preserved, got %s", params.Get("properties.user_data.default").Raw) + } + if params.Get("properties.user_data.enum.0.uniqueItems").Type != ojson.False { + t.Errorf("expected user_data.enum.0.uniqueItems preserved, got %s", params.Get("properties.user_data.enum").Raw) + } + + outAgain := NormalizeCodexToolSchemas(out) + if string(outAgain) != string(out) { + t.Errorf("expected NormalizeCodexToolSchemas to be idempotent") + } +}