gateway: a Codex websocket turn sent to a Responses relay leaves Lite's client_metadata marker behind (#4853)

A Codex title request through a Responses relay (CPA) failed with
"X-OpenAI-Internal-Codex-Responses-Lite requires reasoning.context to be
all_turns". fromLite took Lite's shape off for a backend that isn't
OpenAI's: it lifted additional_tools, left reasoning.context out and
didn't send the Lite header on. But over a websocket Codex says it is
Lite a second way, in client_metadata
(ws_request_header_x_openai_internal_codex_responses_lite: "true",
codex-rs client.rs build_ws_client_metadata). magpie left that marker
in, so the relay still read the request as Lite and passed it to the
ChatGPT backend without the context it had been told to expect.

fromLite now also drops that one client_metadata key
(withoutLiteMetadata). Every other client_metadata entry, the
instructions and the identity line go as Codex sent them.

Reported by ChangQiu on Discord and filed as #4853 by ZyphrZero. The
withoutLiteMetadata patch and its two tests are ported from
ZyphrZero's fork commit 7f67c732. TestCodexSocketLiteTurnLeavesLiteForARelay
is new: it sends #4853's title request through passthrough to a fake
relay and checks that the marker, the context and the header are all gone.

Run on mote at this head:
- the three new tests plus TestLiteSubagentLeavesLite and the
  additional_tools tests: ok
- go test -timeout 45m ./internal/gateway: one red,
  TestCodexPoolSaysTheClientsVersion (#4807). It passes 3/3 alone here
  and on origin/main.
- go vet ./internal/gateway with GOOS=linux, windows and darwin: clean.
  gofmt -l: clean.
Broken by hand: with withoutLiteMetadata stubbed to return its input,
all three new tests went red.
Not tried: a real CPA, or a real Codex websocket session through magpie.
This commit is contained in:
yetone
2026-11-02 14:06:01 +08:00
parent 225d521cde
commit a4916aec10
3 changed files with 198 additions and 11 deletions
File diff suppressed because one or more lines are too long
+40 -10
View File
@@ -22,23 +22,53 @@ import (
// Lite also asks for reasoning context "all_turns" (the ChatGPT backend
// turns a Lite request away without it, #534) and says it is Lite in the
// X-OpenAI-Internal-Codex-Responses-Lite header. Neither is in the
// Responses API anyone else serves. A subagent a GPT lead spawns on another
// model is sent in the lead's Lite shape, its model name alone changed
// (codex-rs builds the child's request from the lead's catalog entry), and
// OpenCode Go's DeepSeek answered it with 503 "Endpoint is unavailable"
// while the same subagent under a DeepSeek lead, not Lite, was answered
// (TangForX on X). So a request leaving Lite has both taken off too
// (fromLite, liteHeaderKept).
// Responses API anyone else serves. A Codex websocket turn also repeats the
// header in client_metadata. A subagent a GPT lead spawns on another model
// is sent in the lead's Lite shape, its model name alone changed (codex-rs
// builds the child's request from the lead's catalog entry), and OpenCode
// Go's DeepSeek answered it with 503 "Endpoint is unavailable" while the
// same subagent under a DeepSeek lead, not Lite, was answered (TangForX on
// X). So a request leaving Lite has all three taken off too (fromLite,
// liteHeaderKept).
// liteHeader says a Codex request is Responses Lite.
const liteHeader = "X-OpenAI-Internal-Codex-Responses-Lite"
// fromLite is a Responses request Codex sent as Responses Lite in the shape
// it sends a model that isn't Lite: its additional_tools in its tools
// (liftAdditionalTools) and no reasoning context. A request that isn't
// Lite is returned as it was.
// (liftAdditionalTools), no reasoning context, and no Lite marker in
// client_metadata. A request that isn't Lite is returned as it was.
func fromLite(body []byte) []byte {
return withoutReasoningContext(liftAdditionalTools(body))
return withoutLiteMetadata(withoutReasoningContext(liftAdditionalTools(body)))
}
// withoutLiteMetadata is body without the Lite marker a Codex websocket
// turn repeats in client_metadata, the rest of client_metadata and every
// other member byte for byte as they were. The marker is removed whatever
// its value, as the header is: a request leaving Lite must not still claim
// to be one.
func withoutLiteMetadata(body []byte) []byte {
const marker = "ws_request_header_x_openai_internal_codex_responses_lite"
if !bytes.Contains(body, []byte(marker)) {
return body
}
r, found, ok := topMember(body, "client_metadata")
if !found || !ok || len(r) == 0 || r[0] != '{' {
return body
}
var m map[string]json.RawMessage
if json.Unmarshal(r, &m) != nil || m == nil {
return body
}
if _, has := m[marker]; !has {
return body
}
delete(m, marker)
nb, err := json.Marshal(m)
if err != nil {
return body
}
return withMembers(body, map[string][]byte{"client_metadata": nb})
}
// withoutReasoningContext is body without reasoning.context, the rest of
@@ -0,0 +1,157 @@
package gateway
import (
"encoding/json"
"net/http"
"net/http/httptest"
"strings"
"testing"
"github.com/tidwall/gjson"
"github.com/yetone/magpie/internal/provider"
)
func TestFromLiteRemovesOnlyTheWebsocketLiteMarker(t *testing.T) {
tests := []struct {
name string
body string
want string
}{
{
name: "metadata with other fields",
body: `{"client_metadata":{"session_id":"s","ws_request_header_x_openai_internal_codex_responses_lite":"true","x-codex-turn-metadata":"{\"thread_source\":\"thread_title\"}"},"reasoning":{"effort":"low","context":"all_turns"},"input":[]}`,
want: `{"client_metadata":{"session_id":"s","x-codex-turn-metadata":"{\"thread_source\":\"thread_title\"}"},"reasoning":{"effort":"low"},"input":[]}`,
},
{
name: "boolean marker",
body: `{"client_metadata":{"ws_request_header_x_openai_internal_codex_responses_lite":true,"session_id":"s"},"input":[]}`,
want: `{"client_metadata":{"session_id":"s"},"input":[]}`,
},
{
name: "false marker",
body: `{"client_metadata":{"ws_request_header_x_openai_internal_codex_responses_lite":false},"input":[]}`,
want: `{"client_metadata":{},"input":[]}`,
},
{
name: "without marker",
body: `{"client_metadata":{"session_id":"s"},"input":[]}`,
want: `{"client_metadata":{"session_id":"s"},"input":[]}`,
},
{
name: "non object metadata",
body: `{"client_metadata":"opaque","input":[]}`,
want: `{"client_metadata":"opaque","input":[]}`,
},
{
name: "malformed body",
body: `{"client_metadata":{"ws_request_header_x_openai_internal_codex_responses_lite":true}`,
want: `{"client_metadata":{"ws_request_header_x_openai_internal_codex_responses_lite":true}`,
},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
if got := string(fromLite([]byte(test.body))); got != test.want {
t.Fatalf("fromLite:\n got %s\nwant %s", got, test.want)
}
})
}
}
func TestCodexTitleRelayKeepsLiteShapeConsistent(t *testing.T) {
for _, asSent := range []bool{false, true} {
name := "default"
if asSent {
name = "as sent"
}
t.Run(name, func(t *testing.T) {
upstream := &fake{t: t}
upstream.refuse = func([]byte) (int, string) {
return http.StatusBadRequest, `{"error":{"message":"diagnostic upstream rejection"}}`
}
setup(t, provider.Responses, upstream)
relay, err := provider.Find("fake")
if err != nil {
t.Fatal(err)
}
relay.CodexAsSent = asSent
if err := provider.Save(*relay); err != nil {
t.Fatal(err)
}
body := strings.Replace(liteRequest, `"model":"fake/m1",`,
`"model":"fake/m1","reasoning":{"effort":"low","context":"all_turns"},"client_metadata":{"session_id":"title-session","ws_request_header_x_openai_internal_codex_responses_lite":"true","x-codex-turn-metadata":"{\"thread_source\":\"thread_title\"}"},`, 1)
req := liteSent(body)
req.URL.Path = CodexPath + "/responses"
req.RequestURI = ""
req.RemoteAddr = "127.0.0.1:51000"
req.Header.Set("session_id", "title-session")
req.Header.Set("x-codex-turn-metadata", `{"thread_source":"thread_title"}`)
recorder := httptest.NewRecorder()
New().Handler().ServeHTTP(recorder, req)
if recorder.Code != http.StatusBadRequest {
t.Fatalf("upstream diagnostic status = %d, want 400: %s", recorder.Code, recorder.Body)
}
var got struct {
Reasoning map[string]any `json:"reasoning"`
ClientMetadata map[string]any `json:"client_metadata"`
Input []map[string]any `json:"input"`
}
if err := json.Unmarshal(upstream.got, &got); err != nil {
t.Fatalf("decode upstream request: %v", err)
}
if got.ClientMetadata["session_id"] != "title-session" ||
got.ClientMetadata["x-codex-turn-metadata"] != `{"thread_source":"thread_title"}` {
t.Fatalf("unrelated client metadata changed: %v", got.ClientMetadata)
}
_, hasContext := got.Reasoning["context"]
_, hasMarker := got.ClientMetadata["ws_request_header_x_openai_internal_codex_responses_lite"]
hasHeader := upstream.head.Get(liteHeader) != ""
hasAdditionalTools := len(got.Input) > 0 && got.Input[0]["type"] == "additional_tools"
if hasContext != asSent || hasMarker != asSent || hasHeader != asSent || hasAdditionalTools != asSent {
t.Fatalf("asSent=%t: context=%t marker=%t header=%t additional_tools=%t; body=%s",
asSent, hasContext, hasMarker, hasHeader, hasAdditionalTools, upstream.got)
}
})
}
}
// Codex over its socket says it is Lite in client_metadata, not a header
// (codex-rs build_ws_client_metadata), and the socket's turn carried the
// marker on to a relay after its reasoning context was taken off: a CPA in
// front of the ChatGPT backend read it as Lite and was refused
// "X-OpenAI-Internal-Codex-Responses-Lite requires `reasoning.context` to be
// `all_turns`" (#4853, ChangQiu on Discord). The turn reaches the relay
// with none of the three.
func TestCodexSocketLiteTurnLeavesLiteForARelay(t *testing.T) {
fresh(t)
u := &respUp{}
sockUp(t, u)
_, ts := sockServer(t)
c, _, err := dialSock(t, ts, CodexPath+"/responses", http.Header{"Openai-Beta": {"responses_websockets=2026-02-06"}})
if err != nil {
t.Fatal(err)
}
got := c.turn(create("", userHi,
`"reasoning":{"effort":"low","context":"all_turns"}`,
`"client_metadata":{"session_id":"s","ws_request_header_x_openai_internal_codex_responses_lite":"true"}`))
if last(got).Get("type").String() != "response.completed" {
t.Fatalf("%v", got)
}
if u.calls() != 1 {
t.Fatalf("%d calls", u.calls())
}
body := u.body(0)
u.mu.Lock()
head := u.head[0]
u.mu.Unlock()
if gjson.GetBytes(body, "reasoning.context").Exists() ||
gjson.GetBytes(body, "client_metadata.ws_request_header_x_openai_internal_codex_responses_lite").Exists() ||
head.Get(liteHeader) != "" {
t.Errorf("still Lite: header %q, body %s", head.Get(liteHeader), body)
}
if gjson.GetBytes(body, "reasoning.effort").String() != "low" || gjson.GetBytes(body, "client_metadata.session_id").String() != "s" {
t.Errorf("the rest changed: %s", body)
}
}