diff --git a/backend/internal/handler/openai_page_context.go b/backend/internal/handler/openai_page_context.go
index e8856a38fc..3aa1556943 100644
--- a/backend/internal/handler/openai_page_context.go
+++ b/backend/internal/handler/openai_page_context.go
@@ -7,17 +7,33 @@ 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]*)$`)
+// 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.
+// 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", "browser_tabs", "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 +66,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 +103,39 @@ 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 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) {
+ tag := "agent_context"
+ if codexContextTagName.MatchString(name) {
+ tag = 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", "browser_tabs", "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", "browser_tabs", "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 e7ac8ae2b3..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"
@@ -89,9 +90,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 +124,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 +139,103 @@ 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"}]}`
+ 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"+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.7.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 +304,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 +399,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 +441,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}`},
@@ -407,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}},
@@ -423,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())
+ })
+ }
+}
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