Files
magpie/internal/gateway/codex_turnstate.go
T
yetone 45185710e4 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.
2026-11-15 13:56:58 +08:00

121 lines
3.8 KiB
Go

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
}