Files
shaw f84d1d3eb2 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 <external_browser_tabs> 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, <external_{name}>, when the name has the shape
Codex derives names in ([A-Za-z0-9_]{1,128}). Other names still use the
generic <external_agent_context> tag, so a client supplied name is never
embedded unchecked.
2026-12-02 09:47:40 +08:00

196 lines
6.0 KiB
Go

package handler
import (
"bytes"
"encoding/json"
"fmt"
"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 !mayContainCodexAgentContext(body) || !hasUniqueJSONMembers(body) {
return body, false
}
var request map[string]json.RawMessage
if json.Unmarshal(body, &request) != nil {
return body, false
}
var input []json.RawMessage
if json.Unmarshal(request["input"], &input) != nil {
return body, false
}
changed := false
for i, raw := range input {
var item map[string]json.RawMessage
if json.Unmarshal(raw, &item) != nil {
continue
}
readString := func(key string) string {
var value string
_ = json.Unmarshal(item[key], &value)
return value
}
if readString("type") != "function_call_output" || readString("namespace") != "agent" {
continue
}
if callID, exists := item["call_id"]; exists {
var value string
if bytes.Equal(bytes.TrimSpace(callID), []byte("null")) || json.Unmarshal(callID, &value) != nil || strings.TrimSpace(value) != "" {
continue
}
}
name := readString("name")
var output *string
if json.Unmarshal(item["output"], &output) != nil || output == nil {
continue
}
text, ok := codexUntrustedContextText(name, *output)
if !ok {
continue
}
message := map[string]any{
"type": "message",
"role": "user",
"content": []map[string]string{{
"type": "input_text",
"text": text,
}},
}
encoded, err := json.Marshal(message)
if err != nil {
return body, false
}
input[i] = encoded
changed = true
}
if !changed {
return body, false
}
encodedInput, err := json.Marshal(input)
if err != nil {
return body, false
}
request["input"] = encodedInput
encoded, err := json.Marshal(request)
if err != nil {
return body, false
}
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: <external_{name}>. 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 "<external_" + tag + ">" + output + "</external_" + tag + ">", true
}
if !validCodexUntrustedContext(name, output) {
return "", false
}
text := "<external_" + name + ">" + output + "</external_" + name + ">"
if validCodexPageContext(name, output) {
text = "<external_" + name + ">\n" + output + "\n</external_" + name + ">"
}
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":
return strings.TrimSpace(output) != ""
case "untrusted_content":
// Codex's fallback for an unnamed context source can carry any text, including an empty value.
return true
case "proposed_plan":
// Codex splits an approved plan by byte length, so a chunk can be all whitespace.
return output != ""
default:
return validCodexPageContext(name, output)
}
}
func validCodexPageContext(name, output string) bool {
if name == "codex_apps_open_page" {
return validCodexPageSnapshot(output)
}
parts := codexSelectedPageName.FindStringSubmatch(name)
if len(parts) != 3 {
return false
}
part, err := strconv.Atoi(parts[1])
if err != nil {
return false
}
total, err := strconv.Atoi(parts[2])
if err != nil || part > total {
return false
}
header, snapshot, ok := strings.Cut(output, "\n")
if !ok || strings.TrimSuffix(header, "\r") != fmt.Sprintf("Companion Page snapshot part %d of %d:", part, total) || strings.TrimSpace(snapshot) == "" {
return false
}
// A multi-part snapshot may split inside a JSON string; preserve each chunk verbatim.
return total > 1 || validCodexPageSnapshot(snapshot)
}
func validCodexPageSnapshot(text string) bool {
if !hasUniqueJSONMembers([]byte(text)) {
return false
}
var snapshot map[string]json.RawMessage
if json.Unmarshal([]byte(text), &snapshot) != nil {
return false
}
id, exists := snapshot["page_id"]
if !exists {
return false
}
if bytes.Equal(bytes.TrimSpace(id), []byte("null")) {
return true
}
var value string
return json.Unmarshal(id, &value) == nil && strings.TrimSpace(value) != ""
}