From 8dcdfff22a7ad9568a1c2f88900809dd8eeb4f56 Mon Sep 17 00:00:00 2001 From: r266-tech Date: Fri, 13 Nov 2026 20:16:55 +0800 Subject: [PATCH] fix(codex): normalize UUID additional tool declaration IDs --- .../openai_codex_additional_tools_test.go | 110 +++++++++++++++++- .../service/openai_codex_transform.go | 91 ++++++++++++++- .../service/openai_gateway_request_body.go | 6 + 3 files changed, 203 insertions(+), 4 deletions(-) diff --git a/backend/internal/service/openai_codex_additional_tools_test.go b/backend/internal/service/openai_codex_additional_tools_test.go index c6c2e1bacf..d11fe49480 100644 --- a/backend/internal/service/openai_codex_additional_tools_test.go +++ b/backend/internal/service/openai_codex_additional_tools_test.go @@ -48,6 +48,108 @@ func TestFilterCodexInput_AdditionalToolsDeclarationID(t *testing.T) { } } +func TestFilterCodexInput_AdditionalToolsUUID(t *testing.T) { + const uuidID = "at_00112233-4455-4677-8899-aabbccddeeff" + const compactID = "at_00112233445546778899aabbccddeeff" + for _, tc := range []struct { + name string + id any + want any + }{ + {"hyphenated", uuidID, compactID}, + {"uppercase", "at_00112233-4455-4677-8899-AABBCCDDEEFF", "at_00112233445546778899AABBCCDDEEFF"}, + {"compact", compactID, compactID}, + {"opaque", "at_discovery", "at_discovery"}, + {"wrong_prefix", "xx_00112233-4455-4677-8899-aabbccddeeff", "xx_00112233-4455-4677-8899-aabbccddeeff"}, + {"non_hex", "at_z0112233-4455-4677-8899-aabbccddeeff", "at_z0112233-4455-4677-8899-aabbccddeeff"}, + {"misplaced_hyphen", "at_0011223-34455-4677-8899-aabbccddeeff", "at_0011223-34455-4677-8899-aabbccddeeff"}, + {"extra_hyphens", "at_0011223--4455-4677-8899-aabbccddeef-", "at_0011223--4455-4677-8899-aabbccddeef-"}, + {"short", "at_00112233-4455-4677-8899-aabbccddee", "at_00112233-4455-4677-8899-aabbccddee"}, + {"whitespace", " " + uuidID, " " + uuidID}, + {"numeric", 42, 42}, + {"null", nil, nil}, + } { + for _, preserveReferences := range []bool{false, true} { + t.Run(fmt.Sprintf("%s/references=%t", tc.name, preserveReferences), func(t *testing.T) { + declaration := map[string]any{ + "type": "additional_tools", "id": tc.id, "role": "developer", + "tools": []any{map[string]any{"type": "tool_search", "execution": "client"}}, + } + reference := map[string]any{"type": "item_reference", "id": tc.id} + input := []any{declaration, reference} + filtered := filterCodexInput(input, preserveReferences) + want := map[string]any{ + "type": "additional_tools", "id": tc.want, "role": "developer", "tools": declaration["tools"], + } + require.Equal(t, want, filtered[0]) + if preserveReferences { + require.Equal(t, map[string]any{"type": "item_reference", "id": tc.want}, filtered[1]) + } else { + require.Len(t, filtered, 1) + } + require.Equal(t, tc.id, declaration["id"], "normalization must not mutate the declaration") + require.Equal(t, tc.id, reference["id"], "normalization must not mutate references") + require.Equal(t, filtered, filterCodexInput(filtered, preserveReferences), "normalization must be idempotent") + }) + } + } + + t.Run("only_declared_tools", func(t *testing.T) { + input := []any{ + map[string]any{"type": "additional_tools", "tools": []any{}}, + map[string]any{"type": "message", "id": "msg_00112233-4455-4677-8899-aabbccddeeff", "role": "user", "content": "hello"}, + map[string]any{"type": "item_reference", "id": uuidID}, + map[string]any{"type": "item_reference", "id": "at_11112233-4455-4677-8899-aabbccddeeff"}, + } + require.Equal(t, input, filterCodexInput(input, true), "do not invent IDs or rewrite unrelated history/references") + }) +} + +func TestOpenAIResponsesCompatibility_AdditionalToolsUUID(t *testing.T) { + const uuidID = "at_00112233-4455-4677-8899-aabbccddeeff" + const compactID = "at_00112233445546778899aabbccddeeff" + for _, accountType := range []string{AccountTypeOAuth, AccountTypeAPIKey} { + t.Run(accountType, func(t *testing.T) { + body := []byte(`{"model":"gpt-6.1-sol","marker":"\u0061","number":9007199254740993,"input":[` + + `{"type":"item_reference","id":"` + uuidID + `"},` + + `{"type":"additional_tools","id":"` + uuidID + `","role":"developer","tools":[{"type":"tool_search","execution":"client"}]},` + + `{"type":"future_item","id":"` + uuidID + `"},` + + `{"type":"additional_tools","id":"at_discovery","tools":[]},` + + `{"type":"additional_tools","id":"at_z0112233-4455-4677-8899-aabbccddeeff","tools":[]},` + + `{"type":"message","id":"msg_test","role":"user","content":"` + uuidID + `"}]}`) + original := bytes.Clone(body) + account := &Account{Platform: PlatformOpenAI, Type: accountType} + normalized, changed, err := normalizeOpenAIResponsesCompatibilityBodyWithOptions(body, account, openAIResponsesCompatibilityOptions{}) + require.NoError(t, err) + require.Equal(t, accountType == AccountTypeOAuth, changed) + wantID := uuidID + if accountType == AccountTypeOAuth { + wantID = compactID + } + require.Equal(t, wantID, gjson.GetBytes(normalized, "input.0.id").String(), "references can precede declarations") + require.Equal(t, wantID, gjson.GetBytes(normalized, "input.1.id").String()) + for _, index := range []int{2, 3, 4, 5} { + path := fmt.Sprintf("input.%d", index) + require.Equal(t, gjson.GetBytes(body, path).Raw, gjson.GetBytes(normalized, path).Raw) + } + require.Equal(t, `"\u0061"`, gjson.GetBytes(normalized, "marker").Raw) + require.Equal(t, "9007199254740993", gjson.GetBytes(normalized, "number").Raw) + require.Equal(t, original, body) + again, changed, err := normalizeOpenAIResponsesCompatibilityBodyWithOptions(normalized, account, openAIResponsesCompatibilityOptions{}) + require.NoError(t, err) + require.False(t, changed) + require.Equal(t, normalized, again) + }) + } + t.Run("undeclared_reference", func(t *testing.T) { + body := []byte(`{"model":"gpt-6.1-sol","input":[{"type":"item_reference","id":"` + uuidID + `"}]}`) + normalized, changed, err := normalizeOpenAIResponsesCompatibilityBodyWithOptions(body, &Account{Platform: PlatformOpenAI, Type: AccountTypeOAuth}, openAIResponsesCompatibilityOptions{}) + require.NoError(t, err) + require.False(t, changed) + require.Equal(t, body, normalized) + }) +} + func TestOpenAIGatewayService_OAuthAdditionalToolsDeclarationID(t *testing.T) { gin.SetMode(gin.TestMode) for _, passthrough := range []bool{false, true} { @@ -57,7 +159,7 @@ func TestOpenAIGatewayService_OAuthAdditionalToolsDeclarationID(t *testing.T) { body := []byte(fmt.Sprintf(`{ "model":"gpt-6.1-sol","stream":%t,"store":false,"instructions":"test instructions", "input":[ - {"type":"additional_tools","id":"at_discovery","role":"developer","tools":[ + {"type":"additional_tools","id":"at_00112233-4455-4677-8899-aabbccddeeff","role":"developer","tools":[ {"type":"tool_search","execution":"client"}, {"type":"namespace","name":"multi_agent_v1","tools":[{"type":"function","name":"spawn_agent","parameters":{"type":"object"},"defer_loading":true}]} ]}, @@ -98,8 +200,10 @@ func TestOpenAIGatewayService_OAuthAdditionalToolsDeclarationID(t *testing.T) { require.NoError(t, err) require.NotNil(t, result) require.Equal(t, "https://chatgpt.com/backend-api/codex/responses", upstream.lastReq.URL.String()) - require.Equal(t, "at_discovery", gjson.GetBytes(upstream.lastBody, "input.0.id").String()) - require.JSONEq(t, gjson.GetBytes(body, "input.0").Raw, gjson.GetBytes(upstream.lastBody, "input.0").Raw) + wantID := "at_00112233445546778899aabbccddeeff" + require.Equal(t, wantID, gjson.GetBytes(upstream.lastBody, "input.0.id").String()) + require.Equal(t, "at_00112233-4455-4677-8899-aabbccddeeff", gjson.GetBytes(body, "input.0.id").String()) + require.JSONEq(t, gjson.GetBytes(body, "input.0.tools").Raw, gjson.GetBytes(upstream.lastBody, "input.0.tools").Raw) require.Equal(t, passthrough, gjson.GetBytes(upstream.lastBody, "input.1.id").Exists()) require.Equal(t, passthrough, gjson.GetBytes(upstream.lastBody, "input.2.id").Exists()) require.Equal(t, "sealed", gjson.GetBytes(upstream.lastBody, "input.2.encrypted_content").String()) diff --git a/backend/internal/service/openai_codex_transform.go b/backend/internal/service/openai_codex_transform.go index bbc60f7555..1d369c3f23 100644 --- a/backend/internal/service/openai_codex_transform.go +++ b/backend/internal/service/openai_codex_transform.go @@ -8,6 +8,8 @@ import ( "strings" "github.com/Wei-Shaw/sub2api/internal/pkg/openai" + "github.com/tidwall/gjson" + "github.com/tidwall/sjson" ) var codexModelMap = map[string]string{ @@ -1607,9 +1609,84 @@ func codexInputCallIDs(input []any) map[string]struct{} { return callIDs } +// Only compact UUID-shaped declaration IDs; other provider IDs are opaque. +func normalizeCodexAdditionalToolsID(id string) string { + if len(id) != 39 || !strings.HasPrefix(id, "at_") || + id[11] != '-' || id[16] != '-' || id[21] != '-' || id[26] != '-' { + return id + } + compactUUID := strings.ReplaceAll(id[3:], "-", "") + if len(compactUUID) != 32 { + return id + } + if _, err := hex.DecodeString(compactUUID); err != nil { + return id + } + return "at_" + compactUUID +} + +func codexAdditionalToolsIDMappings(input []any) map[string]string { + mappings := make(map[string]string) + for _, rawItem := range input { + item, ok := rawItem.(map[string]any) + if !ok || item["type"] != "additional_tools" { + continue + } + if id, ok := item["id"].(string); ok { + if normalizedID := normalizeCodexAdditionalToolsID(id); normalizedID != id { + mappings[id] = normalizedID + } + } + } + return mappings +} + +// The passthrough/WebSocket compatibility path must not decode and re-encode +// whole requests. Patch only declaration IDs and references to those declarations. +func normalizeCodexAdditionalToolsIDsBody(body []byte) ([]byte, bool, error) { + input := parseRawJSONView(body).Get("input") + if !input.IsArray() { + return body, false, nil + } + mappings := make(map[string]string) + input.ForEach(func(_, item gjson.Result) bool { + if id := item.Get("id"); item.Get("type").String() == "additional_tools" && id.Type == gjson.String { + if normalizedID := normalizeCodexAdditionalToolsID(id.Str); normalizedID != id.Str { + mappings[id.Str] = normalizedID + } + } + return true + }) + if len(mappings) == 0 { + return body, false, nil + } + items := make([]string, 0) + var patchErr error + input.ForEach(func(_, item gjson.Result) bool { + raw := item.Raw + if typ := item.Get("type").String(); typ == "additional_tools" || typ == "item_reference" { + if id := item.Get("id"); id.Type == gjson.String { + if normalizedID, mapped := mappings[id.Str]; mapped { + raw, patchErr = sjson.Set(raw, "id", normalizedID) + if patchErr != nil { + return false + } + } + } + } + items = append(items, raw) + return true + }) + if patchErr != nil { + return body, false, fmt.Errorf("normalize additional_tools ID: %w", patchErr) + } + return replaceOpenAIRawInput(body, input, items), true, nil +} + func filterCodexInputWithOptions(input []any, opts codexInputFilterOptions) []any { filtered := make([]any, 0, len(input)) referenceIDMappings := codexItemReferenceIDMappings(input, opts.PreserveCallIDs) + additionalToolsIDMappings := codexAdditionalToolsIDMappings(input) inputItemIDs := codexInputItemIDs(input) inputCallIDs := codexInputCallIDs(input) for _, item := range input { @@ -1672,6 +1749,11 @@ func filterCodexInputWithOptions(input []any, opts codexInputFilterOptions) []an for key, value := range m { newItem[key] = value } + if id, ok := newItem["id"].(string); ok { + if normalizedID, mapped := additionalToolsIDMappings[id]; mapped { + newItem["id"] = normalizedID + } + } if id, ok := newItem["id"].(string); ok && strings.HasPrefix(strings.TrimSpace(id), "call_") { trimmedID := strings.TrimSpace(id) _, referencesExistingItem := inputItemIDs[trimmedID] @@ -1746,7 +1828,14 @@ func filterCodexInputWithOptions(input []any, opts codexInputFilterOptions) []an // additional_tools IDs identify declarations carried in this request, // not stored history. Removing them can change native tool discovery // into ordinary function calls even with store=false. - if !opts.PreserveReferences && typ != "additional_tools" { + if typ == "additional_tools" { + if id, ok := m["id"].(string); ok { + if normalizedID, mapped := additionalToolsIDMappings[id]; mapped { + ensureCopy() + newItem["id"] = normalizedID + } + } + } else if !opts.PreserveReferences { ensureCopy() delete(newItem, "id") } else if id, ok := m["id"].(string); ok && shouldStripOpenAIResponsesInputItemID(typ, id) { diff --git a/backend/internal/service/openai_gateway_request_body.go b/backend/internal/service/openai_gateway_request_body.go index b7e4514405..c664e78399 100644 --- a/backend/internal/service/openai_gateway_request_body.go +++ b/backend/internal/service/openai_gateway_request_body.go @@ -1622,6 +1622,12 @@ func normalizeOpenAIResponsesCompatibilityBodyWithOptions(body []byte, account * if err != nil { return body, false, err } + if next, idsChanged, err := normalizeCodexAdditionalToolsIDsBody(normalized); err != nil { + return body, false, err + } else if idsChanged { + normalized = next + changed = true + } } if next, normalizedReasoningContent, err := normalizeOpenAIResponsesReasoningContentReplay(normalized); err != nil { return body, false, err