Merge pull request #8769 from Undertone0809/codex/fix-codex-http-context

fix(openai): normalize additional Codex context on HTTP Responses
This commit is contained in:
Wesley Liddick authored and GitHub committed 2026-11-16 16:33:07 +08:00
commit d31a87a4e2
3 files changed
+145 -16

No files matched your search

@@ -489,9 +489,9 @@ func (h *OpenAIGatewayHandler) Responses(c *gin.Context) {
} else if changed {
body = cappedBody
}
if normalizedBody, changed := normalizeCodexPageContext(body); changed {
if normalizedBody, changed := normalizeCodexUntrustedContext(body); changed {
body = normalizedBody
reqLog.Info("openai.codex_page_context_normalized",
reqLog.Info("openai.codex_untrusted_context_normalized",
zap.String("normalization", "call_output_to_user_message"),
)
}
@@ -11,10 +11,10 @@ import (
var codexSelectedPageName = regexp.MustCompile(`^codex_apps_selected_page_part_([1-9][0-9]*)_of_([1-9][0-9]*)$`)
// Desktop injects page snapshots as standalone outputs, without a model tool call.
// Keep them as untrusted user text, including on history replay and mixed bootstrap turns.
func normalizeCodexPageContext(body []byte) ([]byte, bool) {
if !mayContainCodexCallOutputCandidate(body, "codex_apps_open_page", "codex_apps_selected_page_part_") || !hasUniqueJSONMembers(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", "goal_objective", "untrusted_context") || !hasUniqueJSONMembers(body) {
return body, false
}
var request map[string]json.RawMessage
@@ -46,15 +46,19 @@ func normalizeCodexPageContext(body []byte) ([]byte, bool) {
}
}
name, output := readString("name"), readString("output")
if !validCodexPageContext(name, output) {
if !validCodexUntrustedContext(name, output) {
continue
}
text := "<external_" + name + ">" + output + "</external_" + name + ">"
if validCodexPageContext(name, output) {
text = "<external_" + name + ">\n" + output + "\n</external_" + name + ">"
}
message := map[string]any{
"type": "message",
"role": "user",
"content": []map[string]string{{
"type": "input_text",
"text": "<external_" + name + ">\n" + output + "\n</external_" + name + ">",
"text": text,
}},
}
encoded, err := json.Marshal(message)
@@ -79,6 +83,15 @@ func normalizeCodexPageContext(body []byte) ([]byte, bool) {
return encoded, true
}
func validCodexUntrustedContext(name, output string) bool {
switch name {
case "browser_info", "goal_objective", "untrusted_context":
return strings.TrimSpace(output) != ""
default:
return validCodexPageContext(name, output)
}
}
func validCodexPageContext(name, output string) bool {
if name == "codex_apps_open_page" {
return validCodexPageSnapshot(output)
@@ -34,7 +34,7 @@ func TestNormalizeCodexPageContextFirstMessage(t *testing.T) {
require.Equal(t, 400, w.Code)
require.Contains(t, w.Body.String(), "function_call_output requires call_id")
got, changed := normalizeCodexPageContext(body)
got, changed := normalizeCodexUntrustedContext(body)
require.True(t, changed)
w = httptest.NewRecorder()
c, _ = gin.CreateTestContext(w)
@@ -49,14 +49,130 @@ func TestNormalizeCodexPageContextFirstMessage(t *testing.T) {
require.False(t, item.Get("id").Exists())
}
require.Equal(t, "hello", gjson.GetBytes(got, "input.2.content").String())
again, changed := normalizeCodexPageContext(got)
again, changed := normalizeCodexUntrustedContext(got)
require.False(t, changed)
require.Equal(t, got, again)
}
func TestNormalizeCodexAdditionalUntrustedContext(t *testing.T) {
// AdditionalContextToolOutput derives names from caller-provided context keys.
// Codex 0.169.0 enables this representation by default (openai/codex#60487).
for _, name := range []string{"browser_info", "goal_objective", "untrusted_context"} {
t.Run(name, func(t *testing.T) {
output := "external context\nline two"
body := pageContextRequest(t, pageContextItem(name, output),
map[string]any{"role": "user", "content": "continue"})
h := &OpenAIGatewayHandler{}
w := httptest.NewRecorder()
c, _ := gin.CreateTestContext(w)
require.False(t, h.validateFunctionCallOutputRequest(c, body, zap.NewNop()))
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())
item := gjson.GetBytes(got, "input.0")
require.Equal(t, "message", item.Get("type").String())
require.Equal(t, "user", item.Get("role").String())
require.Equal(t, "<external_"+name+">"+output+"</external_"+name+">", item.Get("content.0.text").String())
require.False(t, item.Get("call_id").Exists())
require.Equal(t, "continue", gjson.GetBytes(got, "input.1.content").String())
again, changed := normalizeCodexUntrustedContext(got)
require.False(t, changed)
require.Equal(t, got, again)
})
}
}
func TestNormalizeCodexAdditionalUntrustedContextPreservesRealAndMalformedOutputs(t *testing.T) {
for _, name := range []string{"browser_info", "goal_objective", "untrusted_context"} {
for _, override := range []map[string]any{
{"call_id": "call_real"},
{"call_id": nil},
{"call_id": 42},
{"namespace": "other"},
{"namespace": nil},
{"namespace": 42},
{"output": []any{map[string]any{"type": "encrypted_content", "encrypted_content": "sealed"}}},
{"output": " "},
{"output": nil},
} {
item := pageContextItem(name, "context")
for key, value := range override {
item[key] = value
}
body := pageContextRequest(t, item)
got, changed := normalizeCodexUntrustedContext(body)
require.False(t, changed, "name=%s override=%v", name, override)
require.Equal(t, body, got)
}
item := pageContextItem(name, "context")
delete(item, "namespace")
body := pageContextRequest(t, item)
got, changed := normalizeCodexUntrustedContext(body)
require.False(t, changed)
require.Equal(t, body, got)
}
// Recognized external context cannot make an unrelated tool result valid.
body := pageContextRequest(t, pageContextItem("browser_info", "tab"),
pageContextItem("read_file", "result"))
got, changed := normalizeCodexUntrustedContext(body)
require.True(t, changed)
h := &OpenAIGatewayHandler{}
w := httptest.NewRecorder()
c, _ := gin.CreateTestContext(w)
require.False(t, h.validateFunctionCallOutputRequest(c, got, zap.NewNop()))
require.Equal(t, 400, w.Code)
// Keep historical calls, prior response and exact numeric metadata intact.
body = []byte(`{"model":"gpt-5","previous_response_id":"resp_history","metadata":{"large":9007199254740993},"input":[{"type":"function_call","name":"read_file","call_id":"call_real","arguments":"{}"},{"type":"function_call_output","call_id":"call_real","output":"result"},{"type":"function_call_output","namespace":"agent","name":"goal_objective","output":"finish"}]}`)
got, changed = normalizeCodexUntrustedContext(body)
require.True(t, changed)
require.Equal(t, "resp_history", gjson.GetBytes(got, "previous_response_id").String())
require.Equal(t, "9007199254740993", gjson.GetBytes(got, "metadata.large").Raw)
for _, index := range []string{"input.0", "input.1"} {
require.JSONEq(t, gjson.GetBytes(body, index).Raw, gjson.GetBytes(got, index).Raw)
}
}
func TestNormalizeCodexAdditionalUntrustedContextBlankCallIDsAndMixedInput(t *testing.T) {
names := []string{"browser_info", "goal_objective", "untrusted_context"}
for _, callID := range []string{"", " \t\n"} {
items := make([]any, 0, len(names))
for _, name := range names {
item := pageContextItem(name, "context for "+name)
item["call_id"] = callID
delete(item, "id")
items = append(items, item)
}
got, changed := normalizeCodexUntrustedContext(pageContextRequest(t, items...))
require.True(t, changed)
require.Len(t, gjson.GetBytes(got, "input").Array(), len(names))
for i, item := range gjson.GetBytes(got, "input").Array() {
require.Equal(t, "user", item.Get("role").String())
require.Equal(t, "<external_"+names[i]+">context for "+names[i]+"</external_"+names[i]+">", item.Get("content.0.text").String())
}
}
}
func TestNormalizeCodexAdditionalUntrustedContextRejectsDuplicateMembers(t *testing.T) {
for _, name := range []string{"browser_info", "goal_objective", "untrusted_context"} {
for _, body := range []string{
`{"input":[{"type":"function_call_output","namespace":"agent","name":"` + name + `","call_id":"real","call_id":"","output":"context"}]}`,
`{"input":[{"type":"function_call_output","namespace":"agent","name":"` + name + `","output":"first","output":"second"}]}`,
} {
got, changed := normalizeCodexUntrustedContext([]byte(body))
require.False(t, changed)
require.Equal(t, body, string(got))
}
}
}
func TestNormalizeCodexPageContextPreservesHistoryAndToolValidation(t *testing.T) {
body := []byte(`{"model":"gpt-5","previous_response_id":"resp_history","metadata":{"large":9007199254740993},"input":[{"type":"function_call","name":"read_file","call_id":"call_real","arguments":"{}"},{"type":"function_call_output","call_id":"call_real","output":"result"},{"type":"function_call_output","namespace":"agent","name":"codex_apps_open_page","output":"{\"page_id\":\"page_1\"}"}]}`)
got, changed := normalizeCodexPageContext(body)
got, changed := normalizeCodexUntrustedContext(body)
require.True(t, changed)
require.Equal(t, "resp_history", gjson.GetBytes(got, "previous_response_id").String())
require.Equal(t, "9007199254740993", gjson.GetBytes(got, "metadata.large").Raw)
@@ -66,7 +182,7 @@ func TestNormalizeCodexPageContextPreservesHistoryAndToolValidation(t *testing.T
badTool := pageContextItem("read_file", "result")
body = pageContextRequest(t, pageContextItem("codex_apps_open_page", `{"page_id":null}`), badTool)
got, changed = normalizeCodexPageContext(body)
got, changed = normalizeCodexUntrustedContext(body)
require.True(t, changed)
require.True(t, service.ValidateFunctionCallOutputContextBytes(got).HasFunctionCallOutputMissingCallID)
}
@@ -77,7 +193,7 @@ func TestNormalizeCodexPageContextMixedBootstrap(t *testing.T) {
{"type": "function_call_output", "namespace": "codex_app", "name": "automation_update", "output": "<heartbeat><automation_id>test</automation_id></heartbeat>"},
} {
body := pageContextRequest(t, pageContextItem("codex_apps_open_page", `{"page_id":null}`), item)
got, changed := normalizeCodexPageContext(body)
got, changed := normalizeCodexUntrustedContext(body)
require.True(t, changed)
got, _ = normalizeCodexAutomationBootstrap(got)
got, _ = normalizeCodexDelegationBootstrap(got)
@@ -89,7 +205,7 @@ func TestNormalizeCodexPageContextMultipart(t *testing.T) {
first := "Companion Page snapshot part 1 of 2:\n" + `{"page_id":"page1","document_view":"hello`
second := "Companion Page snapshot part 2 of 2:\n" + ` world"}`
body := pageContextRequest(t, pageContextItem("codex_apps_selected_page_part_1_of_2", first), pageContextItem("codex_apps_selected_page_part_2_of_2", second))
got, changed := normalizeCodexPageContext(body)
got, changed := normalizeCodexUntrustedContext(body)
require.True(t, changed)
require.Contains(t, gjson.GetBytes(got, "input.0.content.0.text").String(), first)
require.Contains(t, gjson.GetBytes(got, "input.1.content.0.text").String(), second)
@@ -119,7 +235,7 @@ func TestNormalizeCodexPageContextRejectsUnrelatedOrMalformedItems(t *testing.T)
item := pageContextItem("codex_apps_open_page", `{"page_id":null}`)
item[tc.key] = tc.value
body := pageContextRequest(t, item)
got, changed := normalizeCodexPageContext(body)
got, changed := normalizeCodexUntrustedContext(body)
require.False(t, changed)
require.Equal(t, body, got)
})
@@ -128,7 +244,7 @@ func TestNormalizeCodexPageContextRejectsUnrelatedOrMalformedItems(t *testing.T)
`{"input":[{"type":"function_call_output","namespace":"agent","name":"codex_apps_open_page","call_id":"real","call_id":"","output":"{\"page_id\":null}"}]}`,
`{"input":[{"type":"function_call_output","namespace":"agent","name":"codex_apps_open_page","output":"{\"page_id\":null}"}]} trailing`,
} {
got, changed := normalizeCodexPageContext([]byte(body))
got, changed := normalizeCodexUntrustedContext([]byte(body))
require.False(t, changed)
require.Equal(t, body, string(got))
}