codex: a turn relayed through Codex accounts says it is the Codex client it came from, or newer, so a model Codex CLI reaches on its own is no longer refused through magpie (Discord, lantern2077 / TuskerManshu: gpt-6.1-sol through a routing group answered 400 "The 'gpt-6.1-sol' model is not supported when using Codex with a ChatGPT account" while Codex CLI alone could use it) — the ChatGPT backend serves a model only to a client new enough for it. Re-signing a pool turn, codexSign set User-Agent codex_cli_rs/<codexVersion()>, the newest of a constant 0.154.0, ~/.codex/models_cache.json's client_version (written by the Codex before the last update) and codex --version when codex was on PATH, ~/.local/bin or Homebrew's — nvm, mise, fnm, npm prefixes, pnpm and Volta were out of reach, above all in magpie serve — while the client's own version header was relayed: one turn saying two versions, the older in the User-Agent. Now codexSign writes one version in both, never older than the relayed one; the gateway notes the newest version a Codex client (originator or codex… User-Agent) has come with (SawCodexClient) and codexVersion, also asked by the accounts' model lists, takes it; the fallback is 0.159.0; the models cache is read from CODEX_HOME when set; codexExecutable also looks in proc.UserBinDirs() (every Node of nvm, mise and fnm, ~/.npmrc's prefix, pnpm, bun, Volta; %APPDATA%\npm and the like on Windows; codex.cmd/.exe there). Tested with TestCodexPoolSaysTheClientsVersion against a fake backend refusing gpt-6.1-sol below 0.161.0: Codex CLI 0.161.0 through the pool failed on main with codex_cli_rs/0.154.0 and passes; TestCodexVersionSeen (Claude Code's User-Agent ignored, CLI and Desktop versions read, never lowered, the model list asked with it), TestCodexVersion with CODEX_HOME, TestCodexExecutableOffPath (nvm, mise, an .npmrc prefix with PATH /usr/bin:/bin). go vet ./internal/..., go build -tags nogui (and GOOS=linux, GOOS=windows) and go test -tags nogui ./... pass. Not tried against the real backend: the version gating is read from the error and the models cache, not seen on the wire.

This commit is contained in:
yetone
2026-09-30 10:06:15 +08:00
parent 872bba3c92
commit dd12c75bff
8 changed files with 376 additions and 55 deletions
+68
View File
@@ -8,6 +8,7 @@ import (
"net/http/httptest"
"os"
"path/filepath"
"strconv"
"strings"
"testing"
"time"
@@ -249,3 +250,70 @@ func TestCallKind(t *testing.T) {
}
}
}
// The ChatGPT backend serves a model only to a Codex that knows it: a turn
// signed by the pool says it comes from a Codex CLI at least as new as the
// one that sent it, in the User-Agent and the version header alike, so a
// model Codex CLI reaches on its own isn't refused through magpie
// (Discord: "The 'gpt-6.1-sol' model is not supported when using Codex
// with a ChatGPT account"). 0.161.0 is newer than any installed here or
// magpie's own fallback, so only the client's own version can pass.
func TestCodexPoolSaysTheClientsVersion(t *testing.T) {
codexSignedIn(t, "spare@example.com")
var uas, vers []string
up := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
b, _ := io.ReadAll(r.Body)
ua := r.Header.Get("User-Agent")
uas, vers = append(uas, ua), append(vers, r.Header.Get("version"))
v, _, _ := strings.Cut(strings.TrimPrefix(ua, "codex_cli_rs/"), " ")
if modelOf(b) == "gpt-6.1-sol" && (!strings.HasPrefix(ua, "codex_cli_rs/") || older(v, "0.161.0")) {
w.WriteHeader(400)
io.WriteString(w, `{"detail":"The 'gpt-6.1-sol' model is not supported when using Codex with a ChatGPT account."}`)
return
}
io.WriteString(w, sse(
`data: {"type":"response.created","response":{"id":"r1","model":"gpt-6.1-sol"}}`,
`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()
rec := httptest.NewRecorder()
req := httptest.NewRequest("POST", CodexPath+"/responses", strings.NewReader(`{"model":"gpt-6.1-sol","stream":true,"input":"ping"}`))
req.Header.Set("Authorization", "Bearer chatgpt-token")
req.Header.Set("chatgpt-account-id", "acct-1")
req.Header.Set("originator", "codex_cli_rs")
req.Header.Set("User-Agent", "codex_cli_rs/0.161.0 (Mac OS 26.6.0; arm64) ghostty/1.2.0")
req.Header.Set("version", "0.161.0")
s.Handler().ServeHTTP(rec, req)
if rec.Code != 200 || !strings.Contains(rec.Body.String(), "pong") {
t.Fatalf("status %d: %s (User-Agent %q, version %q)", rec.Code, rec.Body.String(), uas, vers)
}
for i := range uas {
if !strings.HasPrefix(uas[i], "codex_cli_rs/0.161.0 (") || vers[i] != "0.161.0" {
t.Errorf("request %d: User-Agent %q, version %q", i, uas[i], vers[i])
}
}
}
// older reports whether version a is before b ("0.159.0" before "0.161.0").
func older(a, b string) bool {
pa, pb := strings.Split(a, "."), strings.Split(b, ".")
for i := 0; i < 3; i++ {
var x, y int
if i < len(pa) {
x, _ = strconv.Atoi(pa[i])
}
if i < len(pb) {
y, _ = strconv.Atoi(pb[i])
}
if x != y {
return x < y
}
}
return false
}
+3
View File
@@ -57,6 +57,9 @@ func (s *Server) codexBackend(w http.ResponseWriter, r *http.Request) {
http.Error(w, "magpie speaks HTTP", http.StatusUpgradeRequired)
return
}
// the pool's accounts and their model lists say they are this Codex, or
// newer: the backend serves a model only to a client that knows it
provider.SawCodexClient(r.Header)
rest := strings.TrimPrefix(r.URL.Path, CodexPath)
body, err := codexBody(r)
if err != nil {
+66 -16
View File
@@ -6,6 +6,7 @@ import (
"context"
"os"
"path/filepath"
"slices"
"strings"
"time"
)
@@ -19,22 +20,7 @@ import (
// exist; the login shell's own PATH is asked for in the background and
// added after, since a slow profile mustn't hold the window up.
func UserPath() {
home, _ := os.UserHomeDir()
var known []string
for _, d := range []string{".local/bin", ".npm-global/bin", ".npm/bin", ".bun/bin", ".volta/bin", ".asdf/shims", ".local/share/mise/shims", ".cargo/bin", ".deno/bin", "Library/pnpm"} {
known = append(known, filepath.Join(home, d))
}
if nvm, _ := filepath.Glob(filepath.Join(home, ".nvm/versions/node/*/bin")); len(nvm) > 0 {
known = append(known, nvm[len(nvm)-1])
}
known = append(known, "/opt/homebrew/bin", "/usr/local/bin")
var have []string
for _, d := range known {
if st, err := os.Stat(d); err == nil && st.IsDir() {
have = append(have, d)
}
}
addPath(have)
addPath(userDirs(false))
go func() {
if p := shellPath(); p != "" {
addPath(filepath.SplitList(p))
@@ -42,6 +28,70 @@ func UserPath() {
}()
}
// UserBinDirs are the folders a user's command-line tools are installed in
// that exist here — npm's prefixes, each Node version of nvm, fnm and mise,
// bun, volta, pnpm, asdf, the standalone installers' ~/.local/bin,
// Homebrew — for finding one PATH doesn't reach.
func UserBinDirs() []string { return userDirs(true) }
func userDirs(everyNode bool) []string {
home, _ := os.UserHomeDir()
var known []string
for _, d := range []string{".local/bin", ".npm-global/bin", ".npm/bin", ".bun/bin", ".volta/bin", ".asdf/shims", ".local/share/mise/shims", ".cargo/bin", ".deno/bin", "Library/pnpm"} {
known = append(known, filepath.Join(home, d))
}
nodes := func(pattern string) {
vs, _ := filepath.Glob(filepath.Join(home, pattern))
if len(vs) == 0 {
return
}
if !everyNode {
known = append(known, vs[len(vs)-1])
return
}
slices.Reverse(vs)
known = append(known, vs...)
}
nodes(".nvm/versions/node/*/bin")
if everyNode {
known = append(known, filepath.Join(home, ".local/share/pnpm"), npmPrefix(home))
nodes(".local/share/mise/installs/node/*/bin")
nodes(".local/share/fnm/node-versions/*/installation/bin")
nodes("Library/Application Support/fnm/node-versions/*/installation/bin")
}
known = append(known, "/opt/homebrew/bin", "/usr/local/bin")
var have []string
for _, d := range known {
if st, err := os.Stat(d); d != "" && err == nil && st.IsDir() {
have = append(have, d)
}
}
return have
}
// npmPrefix is the bin folder of the npm prefix ~/.npmrc names, "" when it
// names none.
func npmPrefix(home string) string {
b, err := os.ReadFile(filepath.Join(home, ".npmrc"))
if err != nil {
return ""
}
for _, line := range strings.Split(string(b), "\n") {
k, v, ok := strings.Cut(line, "=")
if !ok || strings.TrimSpace(k) != "prefix" {
continue
}
v = strings.Trim(strings.TrimSpace(v), `"'`)
if strings.HasPrefix(v, "~/") {
v = filepath.Join(home, v[2:])
}
if filepath.IsAbs(v) {
return filepath.Join(v, "bin")
}
}
return ""
}
// shellPath asks the user's login shell for its PATH; "" when it can't say
// within a few seconds.
func shellPath() string {
+26
View File
@@ -1,5 +1,31 @@
package proc
import (
"os"
"path/filepath"
)
// UserPath has nothing to do on Windows: an app started from the Start menu
// gets the user's PATH from the registry, as a terminal does.
func UserPath() {}
// UserBinDirs are the folders a user's command-line tools are installed in
// that exist here — npm's global one, bun's, volta's, pnpm's, the
// standalone installers' — for finding one PATH doesn't reach.
func UserBinDirs() []string {
home, _ := os.UserHomeDir()
known := []string{
filepath.Join(os.Getenv("APPDATA"), "npm"),
filepath.Join(home, ".local", "bin"),
filepath.Join(home, ".bun", "bin"),
filepath.Join(os.Getenv("LOCALAPPDATA"), "Volta", "bin"),
filepath.Join(os.Getenv("LOCALAPPDATA"), "pnpm"),
}
var have []string
for _, d := range known {
if st, err := os.Stat(d); filepath.IsAbs(d) && err == nil && st.IsDir() {
have = append(have, d)
}
}
return have
}
+101 -28
View File
@@ -11,6 +11,7 @@ import (
"os"
"os/exec"
"path/filepath"
"runtime"
"slices"
"sort"
"strings"
@@ -24,7 +25,7 @@ import (
// codexClientVersion is the Codex CLI version the models list is asked for
// when Codex CLI has not asked itself yet: the list leaves out models newer
// than the client asking.
const codexClientVersion = "0.154.0"
const codexClientVersion = "0.159.0"
// codexModels asks the ChatGPT backend which Codex models the account's own
// plan has — a Free account lists fewer than a Plus or Pro one, and one it
@@ -72,42 +73,114 @@ var codexVersionCache struct {
func codexVersion() string {
codexVersionCache.Lock()
defer codexVersionCache.Unlock()
if time.Since(codexVersionCache.at) < 10*time.Minute {
return codexVersionCache.v
}
v := codexClientVersion
newer := func(c string) {
if c = claudeSemverRE.FindString(c); c != "" && compareClaudeVersion(c, v) > 0 {
v = c
if time.Since(codexVersionCache.at) >= 10*time.Minute {
v := codexClientVersion
newer := func(c string) {
if c = claudeSemverRE.FindString(c); c != "" && compareClaudeVersion(c, v) > 0 {
v = c
}
}
}
home, _ := os.UserHomeDir()
var c struct {
ClientVersion string `json:"client_version"`
}
if b, err := os.ReadFile(filepath.Join(home, ".codex", "models_cache.json")); err == nil && json.Unmarshal(b, &c) == nil {
newer(c.ClientVersion)
}
if exe := codexExecutable(); exe != "" {
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
if out, err := proc.CommandContext(ctx, exe, "--version").Output(); err == nil {
newer(string(out)) // "codex-cli 0.155.1"
var c struct {
ClientVersion string `json:"client_version"`
}
cancel()
if b, err := os.ReadFile(filepath.Join(codexCLIHome(), "models_cache.json")); err == nil && json.Unmarshal(b, &c) == nil {
newer(c.ClientVersion)
}
if exe := codexExecutable(); exe != "" {
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
if out, err := proc.CommandContext(ctx, exe, "--version").Output(); err == nil {
newer(string(out)) // "codex-cli 0.155.1"
}
cancel()
}
codexVersionCache.v, codexVersionCache.at = v, time.Now()
}
codexVersionCache.v, codexVersionCache.at = v, time.Now()
return v
return newerVersion(codexVersionCache.v, codexSeen.get())
}
// codexExecutable finds the codex CLI; a var so tests can fake it.
// codexCLIHome is where Codex CLI keeps its state: CODEX_HOME, else ~/.codex.
func codexCLIHome() string {
if dir := os.Getenv("CODEX_HOME"); dir != "" {
return dir
}
home, _ := os.UserHomeDir()
return filepath.Join(home, ".codex")
}
// newerVersion is the later of two versions, a when b isn't one.
func newerVersion(a, b string) string {
if b = claudeSemverRE.FindString(b); b != "" && (a == "" || compareClaudeVersion(b, a) > 0) {
return b
}
return a
}
// codexSeen is the newest version a Codex client that came through the
// gateway said it was. Codex CLI is often out of magpie's reach — installed
// where a desktop app's PATH doesn't go, its models_cache.json written by
// the version before an update — and the backend serves a model only to a
// client new enough for it: signed by the pool as an older Codex, a model
// Codex CLI reaches on its own answers 400 "The 'gpt-6.1-sol' model is not
// supported when using Codex with a ChatGPT account".
var codexSeen seenVersion
type seenVersion struct {
sync.Mutex
v string
}
func (s *seenVersion) get() string {
s.Lock()
defer s.Unlock()
return s.v
}
func (s *seenVersion) saw(v string) {
s.Lock()
s.v = newerVersion(s.v, v)
s.Unlock()
}
// SawCodexClient notes the version a Codex client's request says it is —
// its `version` header, else the one in its User-Agent (codex_cli_rs/0.159.0,
// Codex Desktop/0.159.0) — when the request is Codex's (it names an
// originator, or its User-Agent is codex_…).
func SawCodexClient(h http.Header) {
ua := h.Get("User-Agent")
if h.Get("originator") == "" && !strings.HasPrefix(strings.ToLower(ua), "codex") {
return
}
v := claudeSemverRE.FindString(h.Get("version"))
if v == "" {
if _, rest, ok := strings.Cut(ua, "/"); ok {
if m := claudeSemverRE.FindStringIndex(rest); m != nil && m[0] == 0 {
v = rest[:m[1]]
}
}
}
if v == "" {
return
}
codexSeen.saw(v)
}
// codexExecutable finds the codex CLI; a var so tests can fake it. Beyond
// PATH it looks where npm, nvm, bun, volta, pnpm, mise and the standalone
// installer put it, which a desktop app's PATH lacks.
var codexExecutable = func() string {
if p, err := exec.LookPath("codex"); err == nil {
return p
}
home, _ := os.UserHomeDir()
for _, p := range []string{filepath.Join(home, ".local", "bin", "codex"), "/opt/homebrew/bin/codex", "/usr/local/bin/codex"} {
if st, err := os.Stat(p); err == nil && !st.IsDir() {
return p
names := []string{"codex"}
if runtime.GOOS == "windows" {
names = []string{"codex.cmd", "codex.exe", "codex"}
}
for _, d := range proc.UserBinDirs() {
for _, n := range names {
p := filepath.Join(d, n)
if st, err := os.Stat(p); err == nil && !st.IsDir() {
return p
}
}
}
return ""
+102 -4
View File
@@ -6,6 +6,8 @@ import (
"net/http/httptest"
"os"
"path/filepath"
"runtime"
"strings"
"testing"
"time"
)
@@ -50,20 +52,116 @@ func TestCodexModelsOfTheAccount(t *testing.T) {
func TestCodexVersion(t *testing.T) {
home := t.TempDir()
t.Setenv("HOME", home)
writeFile(t, filepath.Join(home, ".codex", "models_cache.json"), map[string]any{"client_version": "0.154.0"})
writeFile(t, filepath.Join(home, ".codex", "models_cache.json"), map[string]any{"client_version": "0.160.0"})
exe := filepath.Join(t.TempDir(), "codex")
if err := os.WriteFile(exe, []byte("#!/bin/sh\necho codex-cli 0.155.1\n"), 0o755); err != nil {
if err := os.WriteFile(exe, []byte("#!/bin/sh\necho codex-cli 0.161.1\n"), 0o755); err != nil {
t.Fatal(err)
}
old := codexExecutable
t.Cleanup(func() { codexExecutable = old; codexVersionCache.at = time.Time{} })
for _, c := range []struct{ exe, want string }{{exe, "0.155.1"}, {"", "0.154.0"}} {
t.Cleanup(func() { codexExecutable = old; codexVersionCache.at = time.Time{}; codexSeen = seenVersion{} })
codexSeen = seenVersion{}
for _, c := range []struct{ exe, want string }{{exe, "0.161.1"}, {"", "0.160.0"}} {
codexExecutable = func() string { return c.exe }
codexVersionCache.at = time.Time{}
if got := codexVersion(); got != c.want {
t.Errorf("with %q: %s, want %s", c.exe, got, c.want)
}
}
// Codex CLI's state under CODEX_HOME, when that is set
t.Setenv("CODEX_HOME", t.TempDir())
codexVersionCache.at = time.Time{}
if got := codexVersion(); got != codexClientVersion {
t.Errorf("CODEX_HOME with no cache: %s", got)
}
writeFile(t, filepath.Join(os.Getenv("CODEX_HOME"), "models_cache.json"), map[string]any{"client_version": "0.160.2"})
codexVersionCache.at = time.Time{}
if got := codexVersion(); got != "0.160.2" {
t.Errorf("CODEX_HOME's cache: %s", got)
}
}
// A Codex that came through the gateway newer than any magpie can find
// counts at once, the cached lookup notwithstanding: the account's model
// list is asked for as that Codex, and its turns say they are it. Only
// Codex's requests count, and never an older version.
func TestCodexVersionSeen(t *testing.T) {
t.Setenv("HOME", t.TempDir())
t.Setenv("CODEX_HOME", "")
old := codexExecutable
codexExecutable = func() string { return "" }
codexSeen = seenVersion{}
codexVersionCache.at = time.Time{}
t.Cleanup(func() { codexExecutable = old; codexVersionCache.at = time.Time{}; codexSeen = seenVersion{} })
if got := codexVersion(); got != codexClientVersion {
t.Fatalf("nothing seen: %s", got)
}
h := func(kv ...string) http.Header {
out := http.Header{}
for i := 0; i < len(kv); i += 2 {
out.Set(kv[i], kv[i+1])
}
return out
}
for _, c := range []struct {
h http.Header
want string
}{
{h("User-Agent", "claude-cli/2.1.300 (external, cli)"), codexClientVersion},
{h("User-Agent", "Mozilla/5.0", "version", "9.9.9"), codexClientVersion},
{h("User-Agent", "codex_cli_rs/0.160.0 (Mac OS 26.6.0; arm64) ghostty/1.2.0"), "0.160.0"},
{h("User-Agent", "Codex Desktop/0.162.3 (Windows 10.0.26100; x86_64) unknown", "originator", "Codex Desktop"), "0.162.3"},
{h("User-Agent", "codex_cli_rs/0.150.0", "version", "0.150.0"), "0.162.3"},
} {
SawCodexClient(c.h)
if got := codexVersion(); got != c.want {
t.Fatalf("after %v: %s, want %s", c.h, got, c.want)
}
}
var asked, ua, ver string
fake := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
asked, ua, ver = r.URL.Query().Get("client_version"), r.Header.Get("User-Agent"), r.Header.Get("version")
w.Write([]byte(`{"models":[{"slug":"gpt-6.1-sol","visibility":"list"}]}`))
}))
defer fake.Close()
was := CodexBase
CodexBase = fake.URL + "/backend-api/codex"
t.Cleanup(func() { CodexBase = was })
sign := codexSign(func(context.Context) (string, string, error) { return "tok", "acct-1", nil })
if _, err := codexModels(context.Background(), sign); err != nil {
t.Fatal(err)
}
if asked != "0.162.3" || !strings.HasPrefix(ua, "codex_cli_rs/0.162.3 (") || ver != "0.162.3" {
t.Fatalf("models asked as client_version %q, User-Agent %q, version %q", asked, ua, ver)
}
}
// Codex CLI installed where a desktop app's PATH doesn't reach — under an
// nvm Node, or an npm prefix ~/.npmrc names — is found.
func TestCodexExecutableOffPath(t *testing.T) {
if runtime.GOOS == "windows" {
t.Skip("unix install locations")
}
for name, dir := range map[string]string{
"nvm": ".nvm/versions/node/v22.3.0/bin",
"mise": ".local/share/mise/installs/node/24.14.0/bin",
"npm prefix": "custom-npm/bin",
} {
t.Run(name, func(t *testing.T) {
home := t.TempDir()
t.Setenv("HOME", home)
t.Setenv("PATH", "/usr/bin:/bin")
os.WriteFile(filepath.Join(home, ".npmrc"), []byte("registry=https://registry.npmjs.org/\nprefix = ~/custom-npm\n"), 0o644)
exe := filepath.Join(home, dir, "codex")
os.MkdirAll(filepath.Dir(exe), 0o755)
if err := os.WriteFile(exe, []byte("#!/bin/sh\necho codex-cli 0.161.0\n"), 0o755); err != nil {
t.Fatal(err)
}
if got := codexExecutable(); got != exe {
t.Fatalf("found %q, want %q", got, exe)
}
})
}
}
// A model that takes more than its window when asked keeps that most, so
+8 -5
View File
@@ -40,7 +40,11 @@ func codexSign(token func(context.Context) (tok, accountID string, err error)) f
}
req.Header.Set("OpenAI-Beta", "responses=experimental")
req.Header.Set("originator", "codex_cli_rs")
req.Header.Set("User-Agent", codexUserAgent())
// the version and the User-Agent name one Codex, never older than
// the client whose request this is (its version header, relayed)
ver := newerVersion(codexVersion(), req.Header.Get("version"))
req.Header.Set("version", ver)
req.Header.Set("User-Agent", codexUserAgent(ver))
if body == nil {
return nil
}
@@ -65,10 +69,9 @@ var codexUA struct {
os string
}
// codexUserAgent is the User-Agent Codex CLI sends, of the version magpie
// asks the model list with:
// codexUserAgent is the User-Agent Codex CLI of version v sends:
// "codex_cli_rs/0.155.1 (Mac OS 26.6.0; arm64) Apple_Terminal/455".
func codexUserAgent() string {
func codexUserAgent(v string) string {
codexUA.Do(func() { codexUA.os = codexOS() })
arch := map[string]string{"arm64": "arm64", "amd64": "x86_64"}[runtime.GOARCH]
if arch == "" {
@@ -78,7 +81,7 @@ func codexUserAgent() string {
if term == "" {
term = "xterm-256color"
}
return "codex_cli_rs/" + codexVersion() + " (" + codexUA.os + "; " + arch + ") " + term
return "codex_cli_rs/" + v + " (" + codexUA.os + "; " + arch + ") " + term
}
var versionRE = regexp.MustCompile(`\d+(\.\d+)+`)
+2 -2
View File
@@ -125,8 +125,8 @@ func TestCodexPromptCacheKey(t *testing.T) {
}
func TestCodexUserAgent(t *testing.T) {
ua := codexUserAgent()
if !strings.HasPrefix(ua, "codex_cli_rs/") || !strings.Contains(ua, " (") || !strings.Contains(ua, "; ") {
ua := codexUserAgent("0.159.0")
if !strings.HasPrefix(ua, "codex_cli_rs/0.159.0 (") || !strings.Contains(ua, " (") || !strings.Contains(ua, "; ") {
t.Fatalf("%q", ua)
}
}