codex: Lite requests go without added instructions, and a turn's state stays with its account

legeling567 on X: three ChatGPT Pro accounts behind magpie, Codex on
Astra at high effort, saw frequent 529 "high load", quota spent faster,
and luna replies; CC Switch on the same accounts was fine. Diffed the
official Codex 0.165 against magpie through a recording proxy, both on
the owner's real account (sandbox HOMEs). Two differences:

- Responses Lite (an additional_tools input item, or reasoning.context
  all_turns): Codex sends no top-level instructions and no
  reasoning.summary. codexBody added Codex's full instructions (~21K
  chars) and summary "auto": about 4K input tokens a request more than
  the official client. codexLite now leaves both out; a request that
  isn't Lite still gets them.
- x-codex-turn-state, the backend's routing token for a turn: Codex
  over HTTP sends it back on the turn's next request. Through magpie it
  never was: the pool route didn't hand it to Codex, and Codex over its
  socket to magpie continues a turn by previous_response_id with no
  state. The gateway now keeps the state per account and turn
  (codex_turnstate.go) and sends it on that turn's next request to the
  same account only; a state Codex sends itself goes only to the account
  that issued it. The socket front keeps the last reply's state per turn
  and sends it as the header, and takes it out of client_metadata.

Red on the old code, green now: TestCodexBodyLiteGetsNoInstructions,
TestCodexPoolTurnStateStaysWithItsAccount, TestCodexSocketKeepsTurnState,
TestCodexSocketServed (state left in client_metadata).

Real run (Codex 0.165, gpt-6-astra high, one Pro account, sandbox
magpie built with CodexBase at the recording proxy): request 1 sent no
state and got one; request 2 sent it back and the backend issued no new
one, as with the official client. Neither had instructions or summary;
input tokens ~14.1K-15.5K against the official 15,466 (before: ~19.6K).

Run at this head (run rebased on 8bf9cb99d; pushed on 96d1b93b2, which touches only internal/plugin): go test -timeout 45m
./internal/gateway/ ./internal/provider/ on mote: ok (gateway 961s, provider 144s); gofmt -l
clean; go vet GOOS=darwin, linux, windows on both packages clean.

Not tried: the luna reroute itself (both sides were served gpt-6-astra),
Codex Desktop, three accounts at once, magpie to chatgpt.com over a real
WebSocket (the proxy forced HTTP). OpenAI-Beta: responses=experimental,
which 0.165 no longer sends, is left as is.
This commit is contained in:
yetone
2026-11-15 13:56:58 +08:00
parent 96d1b93b23
commit 45185710e4
10 changed files with 394 additions and 4 deletions
+9 -1
View File
@@ -3029,7 +3029,15 @@ serves it on `/v1/responses`, `/responses` and the Codex backend's
(`TestResponsesSocketStreamsWithoutStreamField`).
`client_metadata`'s turn state and responses-lite flag become the
`X-Codex-Turn-State` and `X-OpenAI-Internal-Codex-Responses-Lite`
headers Codex sends over HTTP. It goes through the whole handler the
headers Codex sends over HTTP; the turn state goes as the header only,
taken out of the body's `client_metadata`. Codex continues a turn on a
socket by `previous_response_id` and sends no turn state, so the socket
keeps the state the last reply of a turn gave and sends it with that
turn's next request (`client_metadata.turn_id` the same), as Codex over
HTTP does (`TestCodexSocketKeepsTurnState`). The pooled Codex route does
the same per account and turn (`codex_turnstate.go`): a state goes back
only to the account that issued it, never to the next account after a
failover (`TestCodexPoolTurnStateStaysWithItsAccount`). It goes through the whole handler the
upgrade came in on (`socketEntry`, outside `Front` and `Handler`), so
the allow list, `rebound`, the key, `corsGuard`, `keyLimited`, routing,
failover, usage and the log judge every turn as an HTTP one: a key
+1
View File
@@ -394,6 +394,7 @@ and `TestHistoricalWindowHoldsUsesEachWindowsOwnReading`.
- A Copilot account is known by its GitHub login and host (`CopilotAccountName`, #1220): `mona` on github.com, `mona@acme.ghe.com` on an enterprise's GHE.com. That name is its `logins.json` user, its row in every list, its usage card and its per-account routing settings, and it is what `SwitchLogin`, `SetLoginOn` and `ForgetLogin` take, so one login on two hosts is two accounts, neither written over by the other nor dropped as the editors' own. One saved before on an enterprise's host under its login alone is read under its name with the host (`copilotSavedName`), keeping its id; the editors' own remembered so is renamed in place, still hidden if it was (`copilotRenamed`). Either rename takes the account's per-account settings in `providers.json` (proxy, models, cap, concurrency) from the bare login to the new name before the new name is written to `logins.json` (`renameSettled`): a setting the new name has already stays, and while `providers.json` can't be read or written the account stays saved under its old name, its settings with it. `magpie accounts switch|forget copilot` takes the full name, the login with `--host <name>.ghe.com`, or the login alone when it names one account.
- A Codex account is known by its email, with the plan for a workspace seat (`codexUser`), and a second seat of one email in another workspace by that name with its workspace after it (`codexName`): `me@example.com · Team · ws-two`. The account Codex is signed in to goes by the name it is saved under (`codexLiveName`) everywhere: its provider's `Account.User` (`codexAccount`), `liveLogin`, and its session identity (`SessionIdentities`). Its allowance, rests and sticks (`restKey`), cap, proxy, model list, a gateway key's account list (`LoginID`) and the Routing page all go by that name, so two seats of one email are never read as one (#1424). One ChatGPT sign-in reaches every workspace of its login with one refresh token, and the Codex app's workspace switch rewrites only `account_id` in `auth.json`, so two saved workspaces can share the sign-in Codex holds. Such an account is renewed where Codex holds it (`heldByCodex`, `codexHeldIn`) but its requests, allowance, plan and resets name its own workspace (`codexOwnWorkspace`), and a sign-in sync carries Codex's sign-in only on the record of its workspace (`codexWorkspacesApart` in `liveCodex` and `applyLogins`). Before, the account not in use read the one in use's (JdAZzzzzz on X: a Team seat read as the personal Prolite with its resets; `TestCodexAppWorkspaceSwitchReadsEachWorkspace`).
- Every request to the ChatGPT backend (`CodexBase`'s host) goes over HTTP/1.1, as Codex itself speaks to it: each transport [`netproxy.Dispatch`](../../internal/netproxy/netproxy.go) makes (`http.DefaultClient`'s, the gateway's) sends a request `netproxy.HTTP1` names through an HTTP/1.1 copy of itself whose TLS hello offers no h2, and the provider package sets `HTTP1` to `codexBackend` ([codex_http1.go](../../internal/provider/codex_http1.go)). That covers the gateway's turns, the models list, the warm-up, the allowance, its resets and spending one, through the proxy in force, an account's own included. Every other vendor is still offered HTTP/2, except a provider held to HTTP/1.1 (`HTTP1`, below), a host whose HTTP/2 broke on a TLS record error, and the requests of a download trying again after its transfer broke off (`netproxy.OverHTTP1`, `AgainOverHTTP1`, `BrokeOff`: magpie's update, from where it stopped, the masking model's files, Bun, Claude Code and the Grok CLI; biubiu8802 on X: a proxy cut every HTTP/2 stream of the update part way, "unexpected EOF", while it carried HTTP/1.1 whole; `TestDownloadBrokenOverHTTP2TriesHTTP1`, `TestAgainOverHTTP1`).
- A Codex Responses Lite request (an `additional_tools` input item, or `reasoning.context` `all_turns`; Codex 0.165 and on) carries its instructions in the input, and Codex sends it with no top-level `instructions` and no `reasoning.summary`. `codexBody` adds neither to it (`codexLite`): before, it added Codex's full instructions and `summary: "auto"`, about 4K input tokens a request more than the official client (legeling567 on X; `TestCodexBodyLiteGetsNoInstructions`). A request that isn't Lite still gets them. The backend's `x-codex-turn-state` stays with the account that issued it: the gateway keeps the state a reply gave for that account and turn (`client_metadata` `thread_id` and `turn_id`) and sends it on the turn's next request to the same account, as Codex over HTTP sends it back; a state Codex sends itself goes only to the account that issued it ([codex_turnstate.go](../../internal/gateway/codex_turnstate.go), `TestCodexPoolTurnStateStaysWithItsAccount`).
- A streamed turn to the ChatGPT backend (POST `CodexBase`/responses with `"stream":true`) goes over the backend's WebSocket, as Codex's own client sends it, and comes back as the server-sent events the HTTP route answers with (`codexSocket` in [codex_socket.go](../../internal/gateway/codex_socket.go), first in the gateway's `upstreamTransport`, so Codex's own sign-in passed through and magpie's ChatGPT accounts both take it, through the proxy in force). On some networks a streamed HTTP reply from chatgpt.com is cut at about 120 s, before `response.completed`, while the WebSocket runs to the end (brickhao on Discord). The handshake carries the turn's headers with `OpenAI-Beta: responses_websockets=2026-02-06`, without `x-codex-turn-state` and the responses-lite header, which go in the message's `client_metadata` as Codex puts them; the message is the body with `"type":"response.create"` ahead of it (a zstd body is decoded first). `codex.rate_limits` and `codex.response.metadata`, read ahead of the reply, are also told as the `x-codex-*` and `x-codex-turn-state` headers the HTTP route carries; `responsesapi.websocket_timing` is dropped. An `error` frame ahead of the reply is that status with its error as the body; `websocket_connection_limit_reached`, a refused handshake or a body that isn't a streamed turn goes over HTTP instead, and a host that refused the handshake (other than 401, 429 or 5xx) is spoken HTTP for 10 minutes (`codexSocketShun`). A socket that ends, or won't take the message, before any frame of the reply was handed on (any close status, a dropped connection, a normal close with no reply) sends the same body over HTTP (`codexSocketEnded`): Lamrfu's long conversation was closed 1009 (message too big) by chatgpt.com and got a 502. A conversation's socket is kept between its turns, and a turn that carries on from the last goes on it as only its new input after `previous_response_id`, as Codex's own client sends it (`codexKept` in [codex_socket_keep.go](../../internal/gateway/codex_socket_keep.go); codex-rs `get_incremental_items`): rem_thank on X saw magpie send the whole conversation on a new socket every turn, which a long one meets as 1009. A socket is kept for a turn that names its conversation (`session-id` or `thread-id`, else `prompt_cache_key`) and ended `response.completed` with an id, keyed by the host, a digest of `Authorization` and `chatgpt-account-id`, the conversation's ids and the subagent headers (`codexKeepKey`), so another account's turn never finds it nor names its response; the next turn takes it out of the pool, so two turns at once each have a socket. It is let go after 10 minutes unused (`codexKeepIdle`), at 55 minutes from its handshake (`codexKeepAge`; the backend ends a connection at 60) and the oldest past 32 (`codexKeepMax`); the gateway's tests drain the pool in their cleanup (`codexKeepDrain`). The turn goes as a delta when every field but `input`, `client_metadata` and `stream_options` is as the last turn sent it, and its input begins with the last turn's input and then that turn's `response.output_item.done` items, each compared without its id, status, nulls, empty lists, annotations and logprobs (`codexSocketItem`); anything else goes whole on the kept socket. What is compared is the body as it goes, after masking and every translation, so a turn masked otherwise than the last goes whole. A kept socket that fails before the reply is handed on (closed while kept, the write fails, or an `error` frame first, such as `previous_response_not_found` or the connection limit) is closed and the turn goes whole on a new socket, and from there over HTTP as before (`errCodexSocketAgain`). A message at least as big as one a host closed 1009 goes to it over HTTP for 10 minutes (`codexTooBig`). A socket closed after the reply began reads as a cut stream (`io.ErrUnexpectedEOF`), and is not asked again. Codex speaks to magpie over its own WebSocket since #4058 ([A Responses WebSocket](gateway-routing.md#a-responses-websocket)), sending a turn as a delta after `previous_response_id`; magpie gives each turn the whole conversation before it goes on, and this leg cuts its own delta for the kept socket. The gateway's tests turn it off in TestMain (`codexSocketOff`); codex_socket_test's fakes speak it.
- A provider the user added may have its certificate left unchecked (`InsecureTLS`, the editor's Certificate row, #2383: a vLLM on the LAN, Ollama behind a self-signed cert, a company CA). Only one with a base URL of the user's own takes it (`TakesInsecureTLS`: no account, no preset, not Vertex, not a subscription's or plugin's id); `Save` refuses it on any other, and one written into providers.json by hand is ignored. `Provider.Via` then adds `netproxy.WithUncheckedTLS` with the hosts of its own base URLs (`UncheckedHosts`: Chat, Responses, Anthropic, Gemini, Decide), so every request made on its behalf through a `Dispatch` transport (the gateway's turns, count_tokens, models, test and detect, balance) skips the check for those hosts alone, on a transport kept apart for each (`route.unchecked`). A redirect or a models, balance or image URL on another host is checked, and `netproxy.With` drops the leave for a request made for another provider. An `https://` proxy would be dialled with the same TLS config, so its certificate would go unchecked too: such a request is refused (`ErrUncheckedOverHTTPSProxy`); an `http://` or `socks5://` proxy is taken. Backup, export and sync carry the field with the provider; an import link doesn't.
- A provider the user added may show a client certificate and trust a CA of its own (`ClientCert`, `ClientKey`, `ServerCA`: absolute PEM paths, a `~` taken as home, the editor's Client certificate rows under Advanced, shown while an address is `https://`; #5596, clxsh: Remote Magpie to a magpie or an Nginx asking for mTLS). It takes the same providers as `InsecureTLS` (`TakesClientCert`), and `Save` refuses half a pair, a pair that doesn't match and a CA file with no certificate (`netproxy.CheckClientCert`). `Provider.Via` adds `netproxy.WithClientCert` with the hosts of its own base URLs, so the gateway's turns, streaming, models and the connection test show the certificate to those hosts alone, on a transport kept apart for each (`clientRoute`), the gateway key still sent; another host, and a request made for another provider, never see it. Through an `https://` proxy such a request is refused (`ErrClientCertOverHTTPSProxy`). The route is keyed on the files' paths, mtimes and sizes, so a certificate renewed in place gets a new transport (`TestRemoteMagpieClientCert`, `TestClientCertSaveChecks`, the `clientcert_test.go` tests).
+90
View File
@@ -8,8 +8,10 @@ import (
"net/http/httptest"
"os"
"path/filepath"
"slices"
"strconv"
"strings"
"sync"
"testing"
"time"
@@ -667,6 +669,94 @@ func TestCodexPoolForwardsCodexHeaders(t *testing.T) {
}
}
// The turn state a pool account's reply says goes back to that account
// with the turn's later requests, as Codex's own client sends it; Codex
// never hears it through the pool, so magpie keeps it by the turn. Without
// it each tool call of a turn was a new turn there, admitted again
// (legeling567 on X: 529s on Astra through magpie, none with Codex's own
// sign-in). Another account, another turn, and a state no reply said get
// the request without it.
func TestCodexPoolTurnStateStaysWithItsAccount(t *testing.T) {
codexSignedIn(t, "spare@example.com")
var mu sync.Mutex
var heads []http.Header
refuse1 := false
up := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
io.ReadAll(r.Body)
acct := r.Header.Get("chatgpt-account-id")
mu.Lock()
heads = append(heads, r.Header.Clone())
n, no := len(heads), refuse1 && acct == "acct-1"
mu.Unlock()
if no {
w.WriteHeader(429)
io.WriteString(w, `{"error":{"type":"usage_limit_reached","message":"The usage limit has been reached","resets_in_seconds":7200}}`)
return
}
w.Header().Set("X-Codex-Turn-State", "state-"+acct+"-"+strconv.Itoa(n))
io.WriteString(w, sse(
`data: {"type":"response.created","response":{"id":"r1","model":"gpt-5.5"}}`,
`data: {"type":"response.output_text.delta","delta":"pong"}`,
`data: {"type":"response.completed","response":{"id":"r1","usage":{"input_tokens":7,"output_tokens":1}}}`))
}))
t.Cleanup(up.Close)
was := provider.CodexBase
provider.CodexBase = up.URL + "/backend-api/codex"
t.Cleanup(func() { provider.CodexBase = was })
s := New()
ask := func(state, turn string) []http.Header {
t.Helper()
mu.Lock()
n := len(heads)
mu.Unlock()
body := `{"model":"gpt-5.5","stream":true,"input":"ping"`
if turn != "" {
body += `,"client_metadata":{"thread_id":"th-1","turn_id":"` + turn + `"}`
}
rec := httptest.NewRecorder()
req := httptest.NewRequest("POST", CodexPath+"/responses", strings.NewReader(body+"}"))
req.Header.Set("Authorization", "Bearer chatgpt-token")
req.Header.Set("chatgpt-account-id", "acct-1")
req.Header.Set("User-Agent", "codex_cli_rs/0.165.0")
if state != "" {
req.Header.Set("x-codex-turn-state", state)
}
s.Handler().ServeHTTP(rec, req)
if rec.Code != 200 || !strings.Contains(rec.Body.String(), "pong") {
t.Fatalf("status %d: %s", rec.Code, rec.Body.String())
}
mu.Lock()
defer mu.Unlock()
return slices.Clone(heads[n:])
}
one := func(what string, got []http.Header, acct, state string) {
t.Helper()
if len(got) != 1 || got[0].Get("chatgpt-account-id") != acct || got[0].Get("x-codex-turn-state") != state {
t.Fatalf("%s: %v", what, got)
}
}
// the turn's first request: acct-1 serves it and says its state
one("first", ask("", "t1"), "acct-1", "")
// the turn's next request goes to acct-1 with it, Codex having sent none
one("same turn", ask("", "t1"), "acct-1", "state-acct-1-1")
// one Codex sends itself goes on when acct-1's reply said it
one("sent", ask("state-acct-1-2", ""), "acct-1", "state-acct-1-2")
one("made up", ask("made-up", ""), "acct-1", "")
one("another turn", ask("", "t2"), "acct-1", "")
// acct-1 out: acct-2 gets the turn without acct-1's state
mu.Lock()
refuse1 = true
mu.Unlock()
got := ask("", "t1")
if len(got) != 2 || got[0].Get("chatgpt-account-id") != "acct-1" || got[1].Get("chatgpt-account-id") != "acct-2" {
t.Fatalf("moved: %v", got)
}
if got[0].Get("x-codex-turn-state") == "" || got[1].Get("x-codex-turn-state") != "" {
t.Errorf("state on the wrong account: %v", got)
}
}
func TestCallKind(t *testing.T) {
for want, h := range map[string]map[string]string{
"": {},
+22
View File
@@ -271,6 +271,28 @@ func codexCreate(body []byte) []byte {
return append(out, rest...)
}
// withoutClientMetadata is body with key gone from its client_metadata,
// every other byte as it was, and body itself when it has no such key.
func withoutClientMetadata(body []byte, key string) []byte {
cm := gjson.GetBytes(body, "client_metadata")
if !cm.IsObject() || cm.Index <= 0 || !cm.Get(gjson.Escape(key)).Exists() {
return body
}
have := map[string]any{}
if json.Unmarshal([]byte(cm.Raw), &have) != nil {
return body
}
delete(have, key)
raw, err := json.Marshal(have)
if err != nil {
return body
}
out := make([]byte, 0, len(body))
out = append(out, body[:cm.Index]...)
out = append(out, raw...)
return append(out, body[cm.Index+len(cm.Raw):]...)
}
// withClientMetadata is body with meta's keys set in its client_metadata,
// every other byte as it was.
func withClientMetadata(body []byte, meta map[string]string) ([]byte, bool) {
+120
View File
@@ -0,0 +1,120 @@
package gateway
import (
"net/http"
"strings"
"sync"
"time"
"github.com/yetone/magpie/internal/provider"
)
// x-codex-turn-state is the ChatGPT backend's routing of a turn: the first
// reply of a turn says it, and Codex sends it back on every later request
// of that turn (each tool call's result), which the backend then serves
// as the same turn. Sent without it, each request of the turn was a new
// one there, admitted again (legeling567 on X: 529s, "high load", on Astra
// with three Pro accounts in magpie, none with Codex's own sign-in).
//
// Through the pool Codex never hears the state (the reply is the pool's),
// and on its socket it continues a turn by previous_response_id with no
// state at all, so magpie keeps it: the state the account's reply said
// for a turn (client_metadata's thread and turn_id) goes with that turn's
// later requests to that account. The state is one account's: another
// account gets the turn without it, as a new turn there. A state Codex
// sends itself goes on only to the account whose reply said it.
// codexTurnStateFor is how long a turn's state is kept after its last
// use: a turn's tool calls come seconds or minutes apart.
const codexTurnStateFor = 2 * time.Hour
var codexTurnStates = struct {
sync.Mutex
byTurn map[string]codexTurnState // account + thread + turn → state
byState map[string]codexTurnState // state → account
}{byTurn: map[string]codexTurnState{}, byState: map[string]codexTurnState{}}
type codexTurnState struct {
acct, state string
at time.Time
}
// codexTurnAccount is who a Codex account's request is signed as: the
// account (agent and user) and the workspace it signs into, two seats of
// one email being two accounts.
func codexTurnAccount(p provider.Provider, signed http.Header) string {
if p.Account == nil || p.Account.Agent != "codex" {
return ""
}
return p.Account.UsageAgent() + "\x00" + strings.ToLower(p.Account.User) + "\x00" + signed.Get("chatgpt-account-id")
}
// codexTurnOf is the turn a Codex request is of, "" when it doesn't say.
func codexTurnOf(in http.Header, body []byte) string {
m := requestSessionMetadata(in, body)
if m.Turn == "" {
return ""
}
return m.Thread + "\x00" + m.Turn
}
// heardCodexTurnState records the turn state acct's reply says for turn.
func heardCodexTurnState(acct, turn string, res *http.Response) {
if acct == "" || res == nil {
return
}
v := res.Header.Get("X-Codex-Turn-State")
if v == "" {
return
}
now := time.Now()
codexTurnStates.Lock()
defer codexTurnStates.Unlock()
if len(codexTurnStates.byState) > 4096 {
for k, o := range codexTurnStates.byState {
if now.Sub(o.at) > codexTurnStateFor {
delete(codexTurnStates.byState, k)
}
}
for k, o := range codexTurnStates.byTurn {
if now.Sub(o.at) > codexTurnStateFor {
delete(codexTurnStates.byTurn, k)
}
}
}
st := codexTurnState{acct: acct, state: v, at: now}
codexTurnStates.byState[v] = st
if turn != "" {
codexTurnStates.byTurn[acct+"\x00"+turn] = st
}
}
// codexTurnStateOf is the turn state a request of turn goes to acct with:
// the one the agent sent (in, its headers) when acct's reply said it, else
// the one acct's reply said for the turn, else "".
func codexTurnStateOf(in http.Header, acct, turn string) string {
if acct == "" {
return ""
}
now := time.Now()
codexTurnStates.Lock()
defer codexTurnStates.Unlock()
if v := in.Get("X-Codex-Turn-State"); v != "" {
if o, ok := codexTurnStates.byState[v]; ok && o.acct == acct && now.Sub(o.at) <= codexTurnStateFor {
o.at = now
codexTurnStates.byState[v] = o
return v
}
}
if turn == "" {
return ""
}
k := acct + "\x00" + turn
o, ok := codexTurnStates.byTurn[k]
if !ok || now.Sub(o.at) > codexTurnStateFor {
return ""
}
o.at = now
codexTurnStates.byTurn[k] = o
return o.state
}
+10
View File
@@ -6427,6 +6427,15 @@ func (s *Server) forwardOnce(ctx context.Context, p provider.Provider, to provid
if err := p.Sign(ctx, req, to, body); err != nil {
return nil, err
}
// the turn's routing goes on to the account that was given it, as
// Codex's own client sends it (codex_turnstate.go)
turnAcct, turnOf := codexTurnAccount(p, req.Header), ""
if turnAcct != "" {
turnOf = codexTurnOf(in, body)
}
if v := codexTurnStateOf(in, turnAcct, turnOf); v != "" {
req.Header.Set("X-Codex-Turn-State", v)
}
// a sign-in its vendor revoked isn't sent again: the next member is
// asked, and the agent told to sign in again (#1793)
if why, ok := provider.RevokedSignIn(p.Account, req); ok {
@@ -6499,6 +6508,7 @@ func (s *Server) forwardOnce(ctx context.Context, p provider.Provider, to provid
}
// what a Codex account's reply says it has used, for its cap (#1295)
heardCodexLimits(p, res)
heardCodexTurnState(turnAcct, turnOf, res)
noteSignIn(ctx, p.Account, req, res)
return res, nil
}
+17
View File
@@ -171,6 +171,13 @@ type responsesSocket struct {
writeMu sync.Mutex
turns []heldTurn // the newest last
// the turn state the last reply said, and the turn it is for
// (client_metadata.turn_id): Codex continues a turn on its socket by
// previous_response_id and sends no state, the socket being the
// routing, while magpie sends each request on whole; the state goes
// with each later request of that turn, as Codex sends it over HTTP
stateTurn, turnState string
mu sync.Mutex
away bool // the gateway is ending: close after this turn
turning bool
@@ -503,7 +510,11 @@ func (rs *responsesSocket) turn(ctx context.Context, t *socketTurnRun, frame []b
if socketTurnBody != nil {
socketTurnBody(body)
}
turnID := gjson.GetBytes(body, "client_metadata.turn_id").String()
req := rs.request(ctx, body)
if req.Header.Get("X-Codex-Turn-State") == "" && turnID != "" && turnID == rs.stateTurn {
req.Header.Set("X-Codex-Turn-State", rs.turnState)
}
out := &socketTurnWriter{rs: rs, ctx: ctx, run: t, h: http.Header{},
codex: fromCodex(req.Header) || agentOf(req) == "codex"}
rs.o.via.ServeHTTP(out, req)
@@ -515,6 +526,9 @@ func (rs *responsesSocket) turn(ctx context.Context, t *socketTurnRun, frame []b
t.cut = true
return
}
if v := out.h.Get("X-Codex-Turn-State"); v != "" && turnID != "" {
rs.stateTurn, rs.turnState = turnID, v
}
if out.id != "" && out.completed {
rs.keep(out.id, held, fresh, out.items)
}
@@ -630,8 +644,11 @@ func (rs *responsesSocket) request(ctx context.Context, body []byte) *http.Reque
req.Header.Set("Accept", "text/event-stream")
// what Codex says in client_metadata here and in a header over HTTP
// (codexSocketMessage, the other way)
// — the turn state in the header alone, which goes on only to the
// account that was given it (codex_turnstate.go)
if v := gjson.GetBytes(body, `client_metadata.x-codex-turn-state`).String(); v != "" {
req.Header.Set("X-Codex-Turn-State", v)
body = withoutClientMetadata(body, "x-codex-turn-state")
}
if strings.EqualFold(gjson.GetBytes(body, `client_metadata.ws_request_header_x_openai_internal_codex_responses_lite`).String(), "true") {
req.Header.Set("X-OpenAI-Internal-Codex-Responses-Lite", "true")
+64
View File
@@ -670,6 +670,65 @@ func TestResponsesSocketDrains(t *testing.T) {
}
}
// Codex continues a turn on its socket by previous_response_id and sends
// no turn state, the socket being the turn's routing; magpie sends each
// request on whole, so the state the turn's last reply said goes with it,
// as Codex sends it over HTTP. A new turn starts without it.
func TestCodexSocketKeepsTurnState(t *testing.T) {
setup(t, provider.Chat, &fake{t: t})
var mu sync.Mutex
var heads []http.Header
n := 0
chatgpt(t, func(w http.ResponseWriter, r *http.Request) {
io.ReadAll(r.Body)
mu.Lock()
heads = append(heads, r.Header.Clone())
n++
id := fmt.Sprintf("resp_k%d", n)
mu.Unlock()
w.Header().Set("Content-Type", "text/event-stream")
w.Header().Set("X-Codex-Turn-State", "ts-"+id)
item := `{"type":"message","role":"assistant","content":[{"type":"output_text","text":"ok"}]}`
io.WriteString(w, sse(
`data: {"type":"response.created","response":{"id":"`+id+`"}}`,
`data: {"type":"response.output_item.done","output_index":0,"item":`+item+`}`,
`data: {"type":"response.completed","response":{"id":"`+id+`","usage":{"input_tokens":9,"output_tokens":2}}}`))
})
_, ts := sockServer(t)
h := http.Header{"Authorization": {"Bearer chatgpt-token"}, "Chatgpt-Account-Id": {"acct-1"},
"Openai-Beta": {"responses_websockets=2026-02-06"}, "User-Agent": {"codex_cli_rs/0.165.0"}}
c, _, err := dialSock(t, ts, CodexPath+"/responses", h)
if err != nil {
t.Fatal(err)
}
frame := func(prev, turn, input string) string {
f := `{"type":"response.create","model":"gpt-5.5","stream":true,"store":false,"input":[` + input + `],` +
`"client_metadata":{"turn_id":"` + turn + `"}`
if prev != "" {
f += `,"previous_response_id":"` + prev + `"`
}
return f + "}"
}
prev := ""
for _, turn := range []string{"t1", "t1", "t2"} {
got := c.turn(frame(prev, turn, userHi))
if last(got).Get("type").String() != "response.completed" {
t.Fatalf("%v", got)
}
prev = last(got).Get("response.id").String()
}
mu.Lock()
defer mu.Unlock()
if len(heads) != 3 {
t.Fatalf("%d calls", len(heads))
}
for i, want := range []string{"", "ts-resp_k1", ""} {
if got := heads[i].Get("X-Codex-Turn-State"); got != want {
t.Errorf("request %d: turn state %q, want %q", i+1, got, want)
}
}
}
// Codex's own route serves its socket too: each turn goes to the ChatGPT
// backend as Codex's HTTP turn would, the sign-in, the turn state and the
// whole conversation with it, and the reply's headers come back as the
@@ -765,6 +824,11 @@ func TestCodexSocketServed(t *testing.T) {
hd.Get("X-Codex-Turn-State") != "ts-prev" || strings.Contains(hd.Get("Openai-Beta"), "responses_websockets") {
t.Errorf("headers %v", hd)
}
// the state in the header alone, which goes on to its account only
if gjson.GetBytes(bodies[1], "client_metadata.x-codex-turn-state").Exists() ||
gjson.GetBytes(bodies[1], "client_metadata.ws_request_header_x_openai_internal_codex_responses_lite").String() != "true" {
t.Errorf("client_metadata: %s", gjson.GetBytes(bodies[1], "client_metadata").Raw)
}
}
// Only Codex's Responses route takes a socket; another of its paths is
+24 -3
View File
@@ -341,8 +341,15 @@ func codexBody(body []byte) []byte {
}
// the client's instructions go first as a developer message, Codex's
// in their place — unless they are Codex's, from Codex itself
codex := codexInstructions(model)
// in their place — unless they are Codex's, from Codex itself. A
// Responses Lite turn (Codex 0.165 on) carries its system prompt as
// developer items in input and no instructions at all; Codex's added
// to it sent the prompt twice, ~4K more input tokens a request
lite := strings.TrimSpace(own) == "" && codexLite(m, input)
codex := ""
if !lite {
codex = codexInstructions(model)
}
if strings.TrimSpace(own) != "" {
if firstLine(own) == firstLine(codex) {
codex = own
@@ -382,7 +389,7 @@ func codexBody(body []byte) []byte {
if effort == "none" {
delete(m, "include")
} else {
if reasoning != nil {
if reasoning != nil && !lite {
if _, ok := reasoning["summary"]; !ok {
reasoning["summary"] = "auto"
}
@@ -577,6 +584,20 @@ func DeclareSearch(body []byte, lite bool) []byte {
// is taken as Lite, too, when it carries an additional_tools item or asks
// for reasoning context "all_turns", which Lite requires; the backend takes
// the item on a request that isn't Lite as well.
// codexLite says m is a Responses Lite turn: Codex's own, with its tools
// in an additional_tools item and reasoning over all turns.
func codexLite(m map[string]any, input []any) bool {
if r, _ := m["reasoning"].(map[string]any); r["context"] == "all_turns" {
return true
}
for _, raw := range input {
if it, _ := raw.(map[string]any); it["type"] == "additional_tools" {
return true
}
}
return false
}
func declareSearch(m map[string]any, lite bool) bool {
input, ok := m["input"].([]any)
if !ok {
+37
View File
@@ -152,6 +152,43 @@ func TestCodexBodyAsCodexSendsIt(t *testing.T) {
}
}
// A Responses Lite turn, as Codex 0.165 sends it (its system prompt as
// developer items, its tools in an additional_tools item, no instructions),
// goes without instructions and without a reasoning summary it didn't ask
// for, as Codex itself sends it to chatgpt.com.
func TestCodexBodyLiteGetsNoInstructions(t *testing.T) {
dir := t.TempDir()
t.Setenv("CODEX_HOME", dir)
t.Setenv("XDG_CACHE_HOME", t.TempDir())
os.WriteFile(filepath.Join(dir, "models_cache.json"), []byte(`{"models":[{"slug":"gpt-6-astra","model_messages":{"instructions_template":"You are Codex, a coding agent.\n{{ personality }}"}}]}`), 0o644)
for name, body := range map[string]string{
"additional_tools": `{"model":"gpt-6-astra","reasoning":{"effort":"high"},"input":[
{"type":"additional_tools","tools":[{"type":"function","name":"exec_command","parameters":{"type":"object"}}]},
{"type":"message","role":"developer","content":[{"type":"input_text","text":"You are Codex, a coding agent."}]},
{"type":"message","role":"user","content":[{"type":"input_text","text":"hi"}]}]}`,
"all_turns": `{"model":"gpt-6-astra","reasoning":{"effort":"high","context":"all_turns"},"input":[
{"type":"message","role":"user","content":[{"type":"input_text","text":"hi"}]}]}`,
} {
var m map[string]any
out := codexBody([]byte(body))
if err := json.Unmarshal(out, &m); err != nil {
t.Fatal(err)
}
if _, ok := m["instructions"]; ok {
t.Errorf("%s: instructions added: %s", name, out)
}
if _, ok := m["reasoning"].(map[string]any)["summary"]; ok {
t.Errorf("%s: summary added: %s", name, out)
}
}
// a request that isn't Lite still gets Codex's
var m map[string]any
json.Unmarshal(codexBody([]byte(`{"model":"gpt-6-astra","reasoning":{"effort":"high"},"input":"hi"}`)), &m)
if m["instructions"] != "You are Codex, a coding agent.\n{{ personality }}" || m["reasoning"].(map[string]any)["summary"] != "auto" {
t.Fatalf("%v", m)
}
}
// A conversation whose client names none gets a key of its own, the same on
// every turn; a client's own key stays.
func TestCodexPromptCacheKey(t *testing.T) {