From 638b48c876fd2c54ec24b06f86ed63a7e85221bc Mon Sep 17 00:00:00 2001 From: debug-zhang <34176152+debug-zhang@users.noreply.github.com> Date: Tue, 1 Dec 2026 23:00:00 +0800 Subject: [PATCH 1/2] fix(codex): normalize agent context outputs without call_id Root cause: normalizeCodexUntrustedContext only rewrote function_call_output items whose name matched a fixed list of Codex context tools. Newer Codex clients send page/tab context under new names (for example browser_tabs), so the item kept its missing call_id and validateFunctionCallOutputRequest rejected the whole request with HTTP 400. Change: gate agent context by namespace == "agent" and a missing or blank call_id instead of an enumerated name list. Known context names keep their existing tags and format checks; any other agent-namespace name is rendered under the generic tag so client-supplied names are never interpolated into tags unchecked. Items with a call_id, without the agent namespace, with a non-string output, or with duplicate members are left untouched and keep the original validation path. A zero-copy namespace probe replaces the name-literal fast path. Tests: add browser_tabs, unknown/renamed agent context names, escaped namespace, blank call_id, real tool outputs still rejected (400), and call_id regression cases; adapt existing unrelated-tool-result fixtures to model real tool outputs without the agent namespace. Full handler and service unit packages pass; go build and gofmt are clean. --- .../internal/handler/openai_page_context.go | 55 +++++++++-- .../handler/openai_page_context_test.go | 95 +++++++++++++++++-- .../service/hot_path_zero_copy_test.go | 24 +++++ .../service/openai_call_output_probe.go | 26 +++++ 4 files changed, 185 insertions(+), 15 deletions(-) diff --git a/backend/internal/handler/openai_page_context.go b/backend/internal/handler/openai_page_context.go index 4ce0dba35a..93258b13f4 100644 --- a/backend/internal/handler/openai_page_context.go +++ b/backend/internal/handler/openai_page_context.go @@ -7,17 +7,29 @@ import ( "regexp" "strconv" "strings" + + "github.com/Wei-Shaw/sub2api/internal/service" ) var codexSelectedPageName = regexp.MustCompile(`^codex_apps_selected_page_part_([1-9][0-9]*)_of_([1-9][0-9]*)$`) +// mayContainCodexAgentContext is the cheap gate for agent context outputs. +// Names are not enumerated: Codex keeps adding context tools, and any agent +// namespace output without a call_id is injected context, not a tool result. +// The type and namespace are JSON strings, which appear literally unless a +// \u escape spells their letters; without either the body cannot match. +func mayContainCodexAgentContext(body []byte) bool { + if !service.JSONMayEscapePlainASCII(body) && + (!bytes.Contains(body, []byte("function_call_output")) || !bytes.Contains(body, []byte("agent"))) { + return false + } + return service.ResponsesInputHasAgentFunctionCallOutput(body) +} + // Codex injects external context as standalone outputs, without a model tool call. // Use the legacy user-message representation for HTTP Responses interoperability. func normalizeCodexUntrustedContext(body []byte) ([]byte, bool) { - if !mayContainCodexCallOutputCandidate(body, - "codex_apps_open_page", "codex_apps_selected_page_part_", - "browser_info", "terminal_info", "goal_objective", "untrusted_context", "untrusted_content", "ide_context", "proposed_plan", - ) || !hasUniqueJSONMembers(body) { + if !mayContainCodexAgentContext(body) || !hasUniqueJSONMembers(body) { return body, false } var request map[string]json.RawMessage @@ -50,12 +62,12 @@ func normalizeCodexUntrustedContext(body []byte) ([]byte, bool) { } name := readString("name") var output *string - if json.Unmarshal(item["output"], &output) != nil || output == nil || !validCodexUntrustedContext(name, *output) { + if json.Unmarshal(item["output"], &output) != nil || output == nil { continue } - text := "" + *output + "" - if validCodexPageContext(name, *output) { - text = "\n" + *output + "\n" + text, ok := codexUntrustedContextText(name, *output) + if !ok { + continue } message := map[string]any{ "type": "message", @@ -87,6 +99,33 @@ func normalizeCodexUntrustedContext(body []byte) ([]byte, bool) { return encoded, true } +// codexUntrustedContextText renders an agent context output as user text. +// Known context names keep their existing tags and format checks. Any other +// name is still context when it comes from the agent namespace, so it uses a +// generic tag instead of failing the request; the name is client supplied and +// must not be interpolated into the tag unchecked. +func codexUntrustedContextText(name, output string) (string, bool) { + if !knownCodexUntrustedContextName(name) { + return "" + output + "", true + } + if !validCodexUntrustedContext(name, output) { + return "", false + } + text := "" + output + "" + if validCodexPageContext(name, output) { + text = "\n" + output + "\n" + } + return text, true +} + +func knownCodexUntrustedContextName(name string) bool { + switch name { + case "codex_apps_open_page", "browser_info", "terminal_info", "goal_objective", "untrusted_context", "untrusted_content", "ide_context", "proposed_plan": + return true + } + return codexSelectedPageName.MatchString(name) +} + func validCodexUntrustedContext(name, output string) bool { switch name { case "browser_info", "terminal_info", "goal_objective", "untrusted_context", "ide_context": diff --git a/backend/internal/handler/openai_page_context_test.go b/backend/internal/handler/openai_page_context_test.go index fb59bac2a0..558fb4cfc3 100644 --- a/backend/internal/handler/openai_page_context_test.go +++ b/backend/internal/handler/openai_page_context_test.go @@ -89,9 +89,6 @@ func TestNormalizeCodexTerminalInfoBoundaries(t *testing.T) { {"boolean output", "output", false}, {"numeric output", "output", 42}, {"object output", "output", map[string]any{"text": "context"}}, - {"name prefix", "name", "terminal_info_extra"}, - {"name case", "name", "Terminal_info"}, - {"unknown context", "name", "arbitrary_context"}, {"other type", "type", "custom_tool_call_output"}, } { t.Run(testCase.name, func(t *testing.T) { @@ -126,7 +123,7 @@ func TestNormalizeCodexTerminalInfoPreservesUnrelatedResults(t *testing.T) { body := pageContextRequest(t, pageContextItem("terminal_info", "retest context"), map[string]any{"type": "function_call_output", "namespace": "agent", "name": "terminal_info", "call_id": "call_real", "output": "real result"}, - pageContextItem("read_file", "unrelated result")) + map[string]any{"type": "function_call_output", "name": "read_file", "output": "unrelated result"}) got, changed := normalizeCodexUntrustedContext(body) require.True(t, changed) require.Equal(t, "message", gjson.GetBytes(got, "input.0.type").String()) @@ -141,6 +138,91 @@ func TestNormalizeCodexTerminalInfoPreservesUnrelatedResults(t *testing.T) { require.Contains(t, w.Body.String(), "function_call_output requires call_id") } +func TestNormalizeCodexAgentContextUnknownNames(t *testing.T) { + const browserTabs = `{"tabs":[{"title":"Example","url":"https://example.com"}]}` + body := pageContextRequest(t, + map[string]any{"type": "function_call_output", "namespace": "agent", "name": "browser_tabs", "output": browserTabs}, + map[string]any{"type": "function_call_output", "namespace": "agent", "name": "some_new_context", "output": "new context"}, + map[string]any{"type": "function_call_output", "namespace": "agent", "name": "terminal_info_extra", "output": "suffix name"}, + map[string]any{"type": "function_call_output", "namespace": "agent", "name": "Terminal_info", "output": "case name"}, + map[string]any{"role": "user", "content": "hello"}, + ) + h := &OpenAIGatewayHandler{} + w := httptest.NewRecorder() + c, _ := gin.CreateTestContext(w) + require.False(t, h.validateFunctionCallOutputRequest(c, body, zap.NewNop())) + require.Equal(t, 400, w.Code) + require.Contains(t, w.Body.String(), "function_call_output requires call_id") + + got, changed := normalizeCodexUntrustedContext(body) + require.True(t, changed) + w = httptest.NewRecorder() + c, _ = gin.CreateTestContext(w) + require.True(t, h.validateFunctionCallOutputRequest(c, got, zap.NewNop())) + require.False(t, c.Writer.Written()) + for i, output := range []string{browserTabs, "new context", "suffix name", "case name"} { + item := gjson.GetBytes(got, "input").Array()[i] + require.Equal(t, "message", item.Get("type").String()) + require.Equal(t, "user", item.Get("role").String()) + require.Equal(t, ""+output+"", item.Get("content.0.text").String()) + require.False(t, item.Get("call_id").Exists()) + require.False(t, item.Get("id").Exists()) + } + require.Equal(t, "hello", gjson.GetBytes(got, "input.4.content").String()) + again, changed := normalizeCodexUntrustedContext(got) + require.False(t, changed) + require.Equal(t, got, again) +} + +func TestNormalizeCodexAgentContextEscapedAndBlankCallID(t *testing.T) { + for _, body := range []string{ + `{"input":[{"type":"function_call_output","namespace":"\u0061gent","name":"browser_tabs","output":"tabs"}]}`, + `{"input":[{"type":"function_call_output","namespace":"agent","name":"browser_tabs","call_id":" ","output":"tabs"}]}`, + } { + got, changed := normalizeCodexUntrustedContext([]byte(body)) + require.True(t, changed) + require.Equal(t, "tabs", gjson.GetBytes(got, "input.0.content.0.text").String()) + } +} + +func TestNormalizeCodexAgentContextKeepsToolOutputsRejected(t *testing.T) { + for _, testCase := range []struct { + name string + item map[string]any + }{ + {"no namespace", map[string]any{"type": "function_call_output", "name": "read_file", "output": "file body"}}, + {"other namespace", map[string]any{"type": "function_call_output", "namespace": "codex_app", "name": "read_file", "output": "file body"}}, + {"non-string output", map[string]any{"type": "function_call_output", "namespace": "agent", "name": "browser_tabs", "output": []any{map[string]any{"url": "https://example.com"}}}}, + } { + t.Run(testCase.name, func(t *testing.T) { + body := pageContextRequest(t, testCase.item) + got, changed := normalizeCodexUntrustedContext(body) + require.False(t, changed) + require.Equal(t, body, got) + h := &OpenAIGatewayHandler{} + w := httptest.NewRecorder() + c, _ := gin.CreateTestContext(w) + require.False(t, h.validateFunctionCallOutputRequest(c, body, zap.NewNop())) + require.Equal(t, 400, w.Code) + require.Contains(t, w.Body.String(), "function_call_output requires call_id") + }) + } +} + +func TestNormalizeCodexAgentContextLeavesCallIDItems(t *testing.T) { + body := []byte(`{"model":"gpt-5","input":[{"type":"function_call_output","namespace":"agent","name":"browser_tabs","call_id":"call_real","output":"tabs"}]}`) + got, changed := normalizeCodexUntrustedContext(body) + require.False(t, changed) + require.Equal(t, body, got) + // Items with a call_id keep the original validation path. + h := &OpenAIGatewayHandler{} + w := httptest.NewRecorder() + c, _ := gin.CreateTestContext(w) + require.False(t, h.validateFunctionCallOutputRequest(c, body, zap.NewNop())) + require.Equal(t, 400, w.Code) + require.Contains(t, w.Body.String(), "item_reference") +} + func TestNormalizeCodexAdditionalUntrustedContext(t *testing.T) { for _, name := range codexTextContextNamesForTest { t.Run(name, func(t *testing.T) { @@ -209,7 +291,7 @@ func TestNormalizeCodexAdditionalUntrustedContextPreservesRealAndMalformedOutput } // Recognized external context cannot make an unrelated tool result valid. body := pageContextRequest(t, pageContextItem("browser_info", "tab"), - pageContextItem("read_file", "result")) + map[string]any{"type": "function_call_output", "name": "read_file", "output": "result"}) got, changed := normalizeCodexUntrustedContext(body) require.True(t, changed) h := &OpenAIGatewayHandler{} @@ -304,7 +386,7 @@ func TestNormalizeCodexPageContextPreservesHistoryAndToolValidation(t *testing.T require.JSONEq(t, gjson.GetBytes(body, index).Raw, gjson.GetBytes(got, index).Raw) } - badTool := pageContextItem("read_file", "result") + badTool := map[string]any{"type": "function_call_output", "name": "read_file", "output": "result"} body = pageContextRequest(t, pageContextItem("codex_apps_open_page", `{"page_id":null}`), badTool) got, changed = normalizeCodexUntrustedContext(body) require.True(t, changed) @@ -346,7 +428,6 @@ func TestNormalizeCodexPageContextRejectsUnrelatedOrMalformedItems(t *testing.T) {"null call id", "call_id", nil}, {"other namespace", "namespace", "codex_app"}, {"missing namespace", "namespace", ""}, - {"other tool", "name", "read_file"}, {"other type", "type", "custom_tool_call_output"}, {"not JSON", "output", "some text"}, {"not snapshot", "output", `{"other":null}`}, diff --git a/backend/internal/service/hot_path_zero_copy_test.go b/backend/internal/service/hot_path_zero_copy_test.go index 3f1b37e426..bc29039baa 100644 --- a/backend/internal/service/hot_path_zero_copy_test.go +++ b/backend/internal/service/hot_path_zero_copy_test.go @@ -165,6 +165,30 @@ func TestResponsesInputHasFunctionCallOutputNamed(t *testing.T) { } } +func TestResponsesInputHasAgentFunctionCallOutput(t *testing.T) { + cases := []struct { + name string + body string + want bool + }{ + {"unknown name", `{"input":[{"type":"function_call_output","namespace":"agent","name":"browser_tabs","output":"tabs"}]}`, true}, + {"blank call id", `{"input":[{"type":"function_call_output","namespace":"agent","name":"browser_tabs","call_id":" ","output":"tabs"}]}`, true}, + {"no namespace", `{"input":[{"type":"function_call_output","name":"read_file","output":"body"}]}`, false}, + {"other namespace", `{"input":[{"type":"function_call_output","namespace":"codex_app","name":"read_file","output":"body"}]}`, false}, + {"real call id", `{"input":[{"type":"function_call_output","namespace":"agent","name":"browser_tabs","call_id":"call_real","output":"tabs"}]}`, false}, + {"escaped type", `{"input":[{"` + jsonUEscape("0074") + `ype":"function_call_output","namespace":"agent","name":"browser_tabs"}]}`, true}, + {"escaped namespace", `{"input":[{"type":"function_call_output","namespace":"` + jsonUEscape("0061") + `gent","name":"browser_tabs"}]}`, true}, + {"type not output", `{"input":[{"type":"function_call","namespace":"agent","name":"browser_tabs"}]}`, false}, + {"non-object item", `{"input":["function_call_output agent browser_tabs"]}`, false}, + {"input not array", `{"input":{"type":"function_call_output","namespace":"agent","name":"browser_tabs"}}`, false}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + require.Equal(t, tc.want, ResponsesInputHasAgentFunctionCallOutput([]byte(tc.body))) + }) + } +} + // referenceOpenAIRequestBodyHasTools is the scan without the literal gate. func referenceOpenAIRequestBodyHasTools(body []byte) bool { if tools := gjson.GetBytes(body, "tools"); tools.IsArray() && len(tools.Array()) > 0 { diff --git a/backend/internal/service/openai_call_output_probe.go b/backend/internal/service/openai_call_output_probe.go index ff82ea8eb5..33d42c32ad 100644 --- a/backend/internal/service/openai_call_output_probe.go +++ b/backend/internal/service/openai_call_output_probe.go @@ -6,6 +6,32 @@ import ( "github.com/tidwall/gjson" ) +// ResponsesInputHasAgentFunctionCallOutput reports whether the top-level input +// array holds a function_call_output item in the "agent" namespace without a +// call_id. Codex injects external agent context this way, including context +// tools this gateway does not know by name. Keys and string values are compared +// after JSON unescaping, through a zero-copy view of body. When a member is +// duplicated, the first occurrence is read; callers that decode the body treat +// duplicate members separately. +func ResponsesInputHasAgentFunctionCallOutput(body []byte) bool { + input := parseRawJSONView(body).Get("input") + if !input.IsArray() { + return false + } + found := false + input.ForEach(func(_, item gjson.Result) bool { + if !item.IsObject() || item.Get("type").String() != "function_call_output" || item.Get("namespace").String() != "agent" { + return true + } + if strings.TrimSpace(item.Get("call_id").String()) != "" { + return true + } + found = true + return false + }) + return found +} + // ResponsesInputHasFunctionCallOutputNamed reports whether the top-level input // array holds an object item whose type is "function_call_output" and whose // name starts with one of namePrefixes. Keys and string values are compared From f84d1d3eb2e2cc26ec10d88b5e911d3fc504c715 Mon Sep 17 00:00:00 2001 From: shaw Date: Wed, 2 Dec 2026 09:47:40 +0800 Subject: [PATCH 2/2] fix(codex): keep browser_tabs tag and name unknown agent context Rebasing onto #9152 made browser_tabs a known context name; add it to the known list so it keeps its tag and empty-output check instead of falling to the generic branch. Render unknown agent context names the way Codex renders context it does not send as a tool output, , when the name has the shape Codex derives names in ([A-Za-z0-9_]{1,128}). Other names still use the generic tag, so a client supplied name is never embedded unchecked. --- .../internal/handler/openai_page_context.go | 20 ++++++++--- .../handler/openai_page_context_test.go | 34 +++++++++++++++---- 2 files changed, 43 insertions(+), 11 deletions(-) diff --git a/backend/internal/handler/openai_page_context.go b/backend/internal/handler/openai_page_context.go index 784a93b97e..3aa1556943 100644 --- a/backend/internal/handler/openai_page_context.go +++ b/backend/internal/handler/openai_page_context.go @@ -13,6 +13,10 @@ import ( var codexSelectedPageName = regexp.MustCompile(`^codex_apps_selected_page_part_([1-9][0-9]*)_of_([1-9][0-9]*)$`) +// codexContextTagName is the shape of the context names Codex derives from +// its context keys; only such names are safe to embed in a tag. +var codexContextTagName = regexp.MustCompile(`^[A-Za-z0-9_]{1,128}$`) + // mayContainCodexAgentContext is the cheap gate for agent context outputs. // Names are not enumerated: Codex keeps adding context tools, and any agent // namespace output without a call_id is injected context, not a tool result. @@ -101,12 +105,18 @@ func normalizeCodexUntrustedContext(body []byte) ([]byte, bool) { // codexUntrustedContextText renders an agent context output as user text. // Known context names keep their existing tags and format checks. Any other -// name is still context when it comes from the agent namespace, so it uses a -// generic tag instead of failing the request; the name is client supplied and -// must not be interpolated into the tag unchecked. +// name is still context when it comes from the agent namespace, so it is +// rendered the way Codex renders context when it does not send it as a tool +// output: . The name is client supplied, so it is only used +// as a tag when it has the shape Codex derives names in; anything else falls +// back to a generic tag. func codexUntrustedContextText(name, output string) (string, bool) { if !knownCodexUntrustedContextName(name) { - return "" + output + "", true + tag := "agent_context" + if codexContextTagName.MatchString(name) { + tag = name + } + return "" + output + "", true } if !validCodexUntrustedContext(name, output) { return "", false @@ -120,7 +130,7 @@ func codexUntrustedContextText(name, output string) (string, bool) { func knownCodexUntrustedContextName(name string) bool { switch name { - case "codex_apps_open_page", "browser_info", "terminal_info", "goal_objective", "untrusted_context", "untrusted_content", "ide_context", "proposed_plan": + case "codex_apps_open_page", "browser_info", "browser_tabs", "terminal_info", "goal_objective", "untrusted_context", "untrusted_content", "ide_context", "proposed_plan": return true } return codexSelectedPageName.MatchString(name) diff --git a/backend/internal/handler/openai_page_context_test.go b/backend/internal/handler/openai_page_context_test.go index af5fbcd870..c5372f1e1e 100644 --- a/backend/internal/handler/openai_page_context_test.go +++ b/backend/internal/handler/openai_page_context_test.go @@ -3,6 +3,7 @@ package handler import ( "encoding/json" "net/http/httptest" + "strings" "testing" "github.com/Wei-Shaw/sub2api/internal/service" @@ -140,11 +141,15 @@ func TestNormalizeCodexTerminalInfoPreservesUnrelatedResults(t *testing.T) { func TestNormalizeCodexAgentContextUnknownNames(t *testing.T) { const browserTabs = `{"tabs":[{"title":"Example","url":"https://example.com"}]}` + longName := strings.Repeat("a", 129) body := pageContextRequest(t, map[string]any{"type": "function_call_output", "namespace": "agent", "name": "browser_tabs", "output": browserTabs}, map[string]any{"type": "function_call_output", "namespace": "agent", "name": "some_new_context", "output": "new context"}, map[string]any{"type": "function_call_output", "namespace": "agent", "name": "terminal_info_extra", "output": "suffix name"}, map[string]any{"type": "function_call_output", "namespace": "agent", "name": "Terminal_info", "output": "case name"}, + map[string]any{"type": "function_call_output", "namespace": "agent", "name": "bad>name"+output+"", item.Get("content.0.text").String()) + require.Equal(t, ""+want.output+"", item.Get("content.0.text").String()) require.False(t, item.Get("call_id").Exists()) require.False(t, item.Get("id").Exists()) } - require.Equal(t, "hello", gjson.GetBytes(got, "input.4.content").String()) + require.Equal(t, "hello", gjson.GetBytes(got, "input.7.content").String()) again, changed := normalizeCodexUntrustedContext(got) require.False(t, changed) require.Equal(t, got, again) @@ -181,7 +194,7 @@ func TestNormalizeCodexAgentContextEscapedAndBlankCallID(t *testing.T) { } { got, changed := normalizeCodexUntrustedContext([]byte(body)) require.True(t, changed) - require.Equal(t, "tabs", gjson.GetBytes(got, "input.0.content.0.text").String()) + require.Equal(t, "tabs", gjson.GetBytes(got, "input.0.content.0.text").String()) } } @@ -488,8 +501,6 @@ func TestNormalizeCodexBrowserTabsBoundaries(t *testing.T) { }{ {"real call id", "call_id", "call_real"}, {"other namespace", "namespace", "browser"}, - {"name prefix", "name", "browser_tabs_extra"}, - {"name case", "name", "Browser_tabs"}, {"empty output", "output", ""}, {"blank output", "output", " \n\t"}, {"object output", "output", map[string]any{"tabs": 2}}, @@ -504,3 +515,14 @@ func TestNormalizeCodexBrowserTabsBoundaries(t *testing.T) { }) } } + +func TestNormalizeCodexBrowserTabsNameVariantsUseOwnTag(t *testing.T) { + for _, name := range []string{"browser_tabs_extra", "Browser_tabs"} { + t.Run(name, func(t *testing.T) { + body := pageContextRequest(t, pageContextItem(name, "Tab 1: https://example.com/")) + got, changed := normalizeCodexUntrustedContext(body) + require.True(t, changed) + require.Equal(t, "Tab 1: https://example.com/", gjson.GetBytes(got, "input.0.content.0.text").String()) + }) + } +}