Skip to content

Every agent's model. One place. Codex on DeepSeek, Claude Code on Kimi, from the menu bar.

gateway: a long Codex request's facts, tier and metadata skip the walks over its conversation (#3394)

yetoned08803031525
diff --git a/internal/gateway/gateway.go b/internal/gateway/gateway.go
index d5b88e953..0208afcf2 100644
--- a/internal/gateway/gateway.go
+++ b/internal/gateway/gateway.go
@@ -6313,13 +6313,18 @@ func upstreamPath(p provider.Provider, proto provider.Protocol, model string) st
// Only the allowlist contracts below promise a required callable function:
// other protocols have server, custom and MCP tools the IR cannot render.
func parse(proto provider.Protocol, body []byte) (*Request, error) {
+ return parseIn(proto, body, false)
+}
+
+// parseIn is parse, for facts only as readResponses says.
+func parseIn(proto provider.Protocol, body []byte, facts bool) (*Request, error) {
var req *Request
var err error
switch proto {
case provider.Chat:
req, err = parseChat(body)
case provider.Responses:
- req, err = parseResponses(body)
+ req, err = readResponses(body, facts)
case provider.Gemini:
req, err = parseGemini(body)
default:
diff --git a/internal/gateway/parse_memo.go b/internal/gateway/parse_memo.go
index 78c12e214..f6daab7ac 100644
--- a/internal/gateway/parse_memo.go
+++ b/internal/gateway/parse_memo.go
@@ -63,7 +63,7 @@ func readFacts(proto provider.Protocol, body []byte) bodyFacts {
if f := factsParsed.Load(); f != nil {
(*f)(body)
}
- req, err := parse(proto, body)
+ req, err := parseIn(proto, body, true)
if err != nil {
return bodyFacts{}
}
diff --git a/internal/gateway/parse_memo_test.go b/internal/gateway/parse_memo_test.go
index 9798cf673..1c6be0b7b 100644
--- a/internal/gateway/parse_memo_test.go
+++ b/internal/gateway/parse_memo_test.go
@@ -5,6 +5,8 @@ import (
"context"
"net/http"
"net/url"
+ "os"
+ "path/filepath"
"strings"
"testing"
"time"
@@ -127,3 +129,37 @@ func TestHeldFactsGoWithTheirBody(t *testing.T) {
t.Fatal("a held body's prefix got facts listed under the body")
}
}
+
+// The facts of a Responses body read without the assistant's words and the
+// tools' outputs (readResponses for facts) are those its whole parse says:
+// real Codex requests, and the items that move a turn or a folder.
+func TestResponsesFactsAsTheWholeParse(t *testing.T) {
+ bodies := map[string][]byte{
+ "large": largeConversation(provider.Responses, "gpt-5.5", 20_000),
+ "reminder after a reply": []byte(`{"model":"m","input":[{"role":"user","content":"fix it"},{"type":"function_call","call_id":"c1","name":"sh","arguments":"{}"},` +
+ `{"type":"function_call_output","call_id":"c1","output":"Current working directory: /not/this"},{"role":"developer","content":"<cwd>/work/b</cwd>"},{"role":"user","content":"and now"}]}`),
+ "standalone output": []byte(`{"model":"m","input":[{"role":"user","content":"go"},{"type":"function_call_output","output":[{"type":"input_text","text":"done"}]}]}`),
+ "sealed reasoning": []byte(`{"model":"m","input":[{"role":"user","content":"go"},{"type":"reasoning","summary":[],"encrypted_content":"x"},` +
+ `{"type":"reasoning","summary":[]},{"role":"assistant","content":[{"type":"output_text","text":"<cwd>/said/by/model</cwd>"}]},{"role":"user","content":[{"type":"input_image","image_url":"data:image/png;base64,AA=="}]}]}`),
+ "required, no tools": []byte(`{"model":"m","tool_choice":"required","input":[{"role":"user","content":"<cwd>/w</cwd> go"}]}`),
+ "bad allowed_tools": []byte(`{"model":"m","tool_choice":{"type":"allowed_tools","mode":"none","tools":[]},"input":[{"role":"user","content":"go"}]}`),
+ "string input": []byte(`{"model":"m","instructions":"Current working directory: /w/s","input":"hello"}`),
+ }
+ for _, name := range []string{"workdir/codex-0.162.0.json", "workdir/codex-0.162.1-tool-search.json", "context/codex.json", "codex-26.1007-compaction.json", "upstream_bodies/responses.json"} {
+ b, err := os.ReadFile(filepath.Join("testdata", name))
+ if err != nil {
+ t.Fatal(err)
+ }
+ bodies[name] = b
+ }
+ for name, body := range bodies {
+ var want bodyFacts
+ if req, err := parse(provider.Responses, body); err == nil {
+ want.turn, want.within = turnIn(req)
+ want.dir, want.git = workPlace(req)
+ }
+ if got := readFacts(provider.Responses, body); got != want {
+ t.Errorf("%s: facts %+v, the whole parse's %+v", name, got, want)
+ }
+ }
+}
diff --git a/internal/gateway/prompt.go b/internal/gateway/prompt.go
index 57cc914ef..50854569c 100644
--- a/internal/gateway/prompt.go
+++ b/internal/gateway/prompt.go
@@ -738,9 +738,18 @@ var (
// without the reminders in it, and after the Codex app's context. Routing
// (turnIn, userText, firstWords) and the prompt's turns go by it alike.
func userWords(text string) string {
- t := strings.TrimSpace(reminders.ReplaceAllString(text, ""))
- if at := myRequest.FindAllStringIndex(t, -1); len(at) > 0 {
- t = strings.TrimSpace(t[at[len(at)-1][1]:])
+ // each pattern is looked for only where its words are: run over every
+ // user text of a long conversation on each request, the line-anchored
+ // myRequest alone took a seventh of a Codex request's CPU (#3394)
+ t := text
+ if strings.Contains(t, "<system-reminder") {
+ t = reminders.ReplaceAllString(t, "")
+ }
+ t = strings.TrimSpace(t)
+ if strings.Contains(t, "## My request") {
+ if at := myRequest.FindAllStringIndex(t, -1); len(at) > 0 {
+ t = strings.TrimSpace(t[at[len(at)-1][1]:])
+ }
}
if t == "" || agentsFor.MatchString(t) {
return ""
diff --git a/internal/gateway/responses.go b/internal/gateway/responses.go
index 79343c22e..8834be3f6 100644
--- a/internal/gateway/responses.go
+++ b/internal/gateway/responses.go
@@ -307,11 +307,22 @@ func sentRaw(v json.RawMessage) json.RawMessage {
return v
}
-func parseResponses(body []byte) (*Request, error) {
+func parseResponses(body []byte) (*Request, error) { return readResponses(body, false) }
+
+// readResponses is parseResponses; for facts (readFacts) it leaves out what
+// they never read: the assistant's words, its calls' arguments and the
+// tools' outputs, each decoded into strings of their own, and the copies
+// of raw values a parse kept would need. Run on every request, a long
+// Codex conversation's tool outputs were most of the parse (#3394).
+func readResponses(body []byte, facts bool) (*Request, error) {
+ decode := decodeJSON
+ if facts {
+ decode = decodeJSONView
+ }
// Responses Lite's tools, sent as the first input item (#350)
body = liftAdditionalTools(body)
var q rRequest
- if err := decodeJSON(body, &q); err != nil {
+ if err := decode(body, &q); err != nil {
return nil, fmt.Errorf("invalid request: %v", err)
}
r := &Request{Model: q.Model, System: q.Instructions, MaxTokens: q.MaxOutputTokens, Temp: q.Temperature,
@@ -329,7 +340,7 @@ func parseResponses(body []byte) (*Request, error) {
r.Messages = append(r.Messages, Message{Role: "user", Parts: []Part{{Kind: Text, Text: s}}})
} else {
var items []rItem
- if err := decodeJSON(q.Input, &items); err != nil {
+ if err := decode(q.Input, &items); err != nil {
return nil, fmt.Errorf("invalid input: %v", err)
}
// replied: the conversation has had a turn answered. Codex adds a
@@ -350,7 +361,10 @@ func parseResponses(body []byte) (*Request, error) {
if it.Role == "assistant" {
role = "assistant"
}
- parts := responsesParts(it.Content)
+ var parts []Part
+ if !facts || role != "assistant" {
+ parts = responsesParts(it.Content)
+ }
if (it.Role == "system" || it.Role == "developer") && replied {
// in place, told as the system's, not the user's words
if t := text(parts); t != "" {
@@ -393,6 +407,8 @@ func parseResponses(body []byte) (*Request, error) {
case it.Type == "tool_search_output":
found = append(found, it.Tools...)
r.Messages = append(r.Messages, Message{Role: "user", Parts: []Part{{Kind: ToolResult, CallID: it.CallID, Text: searchFound(it.Tools)}}})
+ case (it.Type == "function_call_output" || it.Type == "custom_tool_call_output") && facts:
+ r.Messages = append(r.Messages, Message{Role: "user", Parts: []Part{{Kind: ToolResult, CallID: it.CallID}}})
case it.Type == "function_call_output" || it.Type == "custom_tool_call_output":
out, images := toolOutput(it.Output)
part := Part{Kind: ToolResult, CallID: it.CallID, Text: out, Images: images}
diff --git a/internal/gateway/session_parent.go b/internal/gateway/session_parent.go
index bfd4634e1..98ccd2998 100644
--- a/internal/gateway/session_parent.go
+++ b/internal/gateway/session_parent.go
@@ -43,8 +43,10 @@ func requestSessionMetadata(h http.Header, body []byte) sessionMetadata {
var m sessionMetadata
// Every Codex request asks this four or five times, so only the member
// is decoded: decoding the whole body walked the conversation each time
- // (#3394). A long body is checked and split once (topMember).
- if bytes.Contains(body, []byte("client_metadata")) && metadataOf(body, &metadata) {
+ // (#3394). A long body is checked and split once (topMember), so it is
+ // asked straight away: Codex sends client_metadata last, after the
+ // conversation, and looking for the word walked all of it each time.
+ if (len(body) >= validMemoMin || bytes.Contains(body, []byte("client_metadata"))) && metadataOf(body, &metadata) {
if raw := metadata["x-codex-turn-metadata"]; len(raw) > 0 {
var text string
if json.Unmarshal(raw, &text) == nil {
diff --git a/internal/gateway/tier_record.go b/internal/gateway/tier_record.go
index 62dc39d64..d00bd51b0 100644
--- a/internal/gateway/tier_record.go
+++ b/internal/gateway/tier_record.go
@@ -24,18 +24,33 @@ import (
func bodyTier(proto provider.Protocol, body []byte) string {
switch proto {
case provider.Anthropic:
- if gjson.GetBytes(body, "speed").String() == "fast" {
+ if topValue(body, "speed").String() == "fast" {
return "fast"
}
fallthrough
case provider.Chat, provider.Responses:
- if t := gjson.GetBytes(body, "service_tier"); t.Type == gjson.String {
+ if t := topValue(body, "service_tier"); t.Type == gjson.String {
return tierWord(t.String())
}
}
return ""
}
+// topValue is gjson's value of body's top-level member key. A long body is
+// asked through its split (topMember), made once a request: gjson walked
+// the whole conversation for a member Codex sends after it (#3394).
+func topValue(body []byte, key string) gjson.Result {
+ if len(body) >= validMemoMin {
+ if v, found, ok := topMember(body, key); ok {
+ if !found {
+ return gjson.Result{}
+ }
+ return gjson.ParseBytes(v)
+ }
+ }
+ return gjson.GetBytes(body, key)
+}
+
// tierWord is a tier as the log keeps it: short, and nothing else.
func tierWord(t string) string {
t = strings.TrimSpace(t)
diff --git a/internal/gateway/tier_record_test.go b/internal/gateway/tier_record_test.go
index e389e4443..b01f91662 100644
--- a/internal/gateway/tier_record_test.go
+++ b/internal/gateway/tier_record_test.go
@@ -41,6 +41,12 @@ func TestUpstreamTierShapes(t *testing.T) {
{provider.Responses, `{"service_tier":"ultrafast"}`, "ultrafast"},
{provider.Chat, `{"service_tier":1}`, ""},
{provider.Gemini, `{"service_tier":"priority"}`, ""},
+ // a long body, asked through its split (topValue): the tier after the
+ // conversation, one inside it that isn't the request's, none at all
+ {provider.Responses, `{"input":[{"role":"user","content":"` + strings.Repeat("words ", 8000) + `"}],"service_tier":"priority"}`, "priority"},
+ {provider.Responses, `{"input":[{"role":"user","content":"x","service_tier":"flex","pad":"` + strings.Repeat("words ", 8000) + `"}]}`, ""},
+ {provider.Anthropic, `{"messages":[{"role":"user","content":"` + strings.Repeat("words ", 8000) + `"}],"speed":"fast"}`, "fast"},
+ {provider.Chat, `{"messages":[{"role":"user","content":"` + strings.Repeat("words ", 8000) + `"}],"service_tier":1}`, ""},
} {
if got := bodyTier(c.proto, []byte(c.body)); got != c.want {
t.Errorf("%s %s: %q", c.proto, c.body, got)