Skip to content

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

provider: ChatGPT account calls go with Codex's headers, and saved accounts are listed once a day

yetoned3898ca8d388
diff --git a/docs/subsystems/providers-accounts.md b/docs/subsystems/providers-accounts.md
index d88811aa5..16469fdb2 100644
--- a/docs/subsystems/providers-accounts.md
+++ b/docs/subsystems/providers-accounts.md
@@ -143,7 +143,7 @@ no decision model was discovered (`Test` in
Account discovery can be turned off (#1535): Settings → Privacy → *Subscription accounts*, `magpie accounts discovery off`, or `MAGPIE_NO_ACCOUNTS=1` for one process. The first two save `noAccountDiscovery: true`, which this computer keeps through a sync or a restored backup (`KeepOwn`); the variable only ever turns discovery off, never on what the user saved off (`settings.AccountDiscoveryOff`). It is on by default. In the GUI, Off asks first and names the subscriptions in use that it stops (`discoveryOffWarning` in `app.js`, #1761: a user turned it off without meaning to and was left with no subscription working). While it is off, magpie reads no agent's sign-in: no credential file (`~/.claude/.credentials.json`, `~/.claude.json`'s account, `~/.codex/auth.json` or Codex's keychain item, Copilot's, Cursor's, Devin's, Kiro's, Gemini's, ZCode's, Command Code's, OpenCode's `auth.json`), no Keychain or Secret Service item (`security`, `secret-tool`), and no agent CLI asked who is signed in. The gates sit at each reader (`readAccountFile`, `discoveryOff` in [`discovery.go`](../../internal/provider/discovery.go)) and at each route that would read or write a sign-in: `Accounts` and `All`, `Logins`, usage, renewal, warm-up, session identities, check-ins, switching, forgetting, `SetLoginOn`, `StartSignIn`, the imports, and moves onto plugins (`MoveCandidates`, `HandOver`, `KeepRetiringMoved`). Those that write refuse with `errAccountDiscoveryOff`, which says how to turn it back on. The agents' side is gated too: the Agents page's *runs on* line (`Agent.Source`), OpenCode's own providers (`readOwnAuth`), and wiring Codex, which goes by magpie's stash instead of `auth.json` (`chatGPT` in [`codex.go`](../../internal/agent/codex.go)). Subscriptions aren't served; API-key providers, middleware plugins and Pi extensions run as before. So does a public plugin, one whose every way in is keyless (`publicPlugin` in [`plugin_accounts.go`](../../internal/provider/plugin_accounts.go), OpenCode Zen Free): it holds no account of the user's, so it stays listed and served, and its sign-in goes through (lileo0668: it signed in, then was listed nowhere). Any other plugin's key is refused in `PluginAPIKey`, as its browser sign-in is, rather than saved and listed nowhere. What magpie kept of its own (`logins.json`, `plugin-auth.json`, `migrations.json`) is left as it is, unread for accounts, and serves again once discovery is on. A change takes effect at once (`ForgetAccounts`); no restart is needed.
-A signed-in account's model list exists only at its vendor (the ChatGPT backend's `/models` for a Codex sign-in, …), so `FetchNew` asks for the lists not fetched yet. Every front end calls it at start: the window (`startBackend`, then `FetchNewSoon` behind `/api/state`), the TUI (`fetchModelsCmd` in `Init`) and `magpie serve` (#1789, reyoung: the terminal and a headless gateway had offered the built-in Cursor's fallback `auto` alone until the list was fetched by hand). Listing the accounts asks a CLI who is signed in, and a look waits `firstAsk` (3s) for that; `cursor-agent about` asks Cursor's servers and can take longer, so `FetchNew` waits for each CLI asked for the first time (`awaitIdentities` in [`cli_identity.go`](../../internal/provider/cli_identity.go)) and lists the accounts again. It reports whether an account was left without its list (failed, or waiting `newFetchRetry` after a failure): the TUI then asks again a minute later (`modelsRetry`) and `serve` loops the same way, while the window asks again from its pages. A TUI model picker open when the list arrives is filled in place (`relist`), keeping its filter and the model under the cursor. `TestFetchNewAccount` and the TUI's `TestTUIFetchesSubscriptionModels` / `TestTUIAsksAgainForAMissingList` cover it. A list fetched once is not left as it was: the magpie serving the gateway looks every hour ([`KeepAccountsListed`](../../internal/provider/account_relist.go), first two minutes after it starts) and fetches again each signed-in built-in account's list that is 45 minutes old (`accountListAge`, `relistAccounts`), so a model the vendor adds to the plan is served without Refresh or a magpie release (cliff_26651 on Discord: GPT-6.1 Terra, served to ChatGPT accounts from 10-26, missing from Codex through a magpie whose Codex list was fetched on 10-12). A plugin's accounts are `KeepPluginsListed`'s, one switched off isn't asked, and a fetch that fails keeps the list there was. `TestAccountListFollowsTheVendor` and `TestKeepAccountsListedAsks` cover it.
+A signed-in account's model list exists only at its vendor (the ChatGPT backend's `/models` for a Codex sign-in, …), so `FetchNew` asks for the lists not fetched yet. Every front end calls it at start: the window (`startBackend`, then `FetchNewSoon` behind `/api/state`), the TUI (`fetchModelsCmd` in `Init`) and `magpie serve` (#1789, reyoung: the terminal and a headless gateway had offered the built-in Cursor's fallback `auto` alone until the list was fetched by hand). Listing the accounts asks a CLI who is signed in, and a look waits `firstAsk` (3s) for that; `cursor-agent about` asks Cursor's servers and can take longer, so `FetchNew` waits for each CLI asked for the first time (`awaitIdentities` in [`cli_identity.go`](../../internal/provider/cli_identity.go)) and lists the accounts again. It reports whether an account was left without its list (failed, or waiting `newFetchRetry` after a failure): the TUI then asks again a minute later (`modelsRetry`) and `serve` loops the same way, while the window asks again from its pages. A TUI model picker open when the list arrives is filled in place (`relist`), keeping its filter and the model under the cursor. `TestFetchNewAccount` and the TUI's `TestTUIFetchesSubscriptionModels` / `TestTUIAsksAgainForAMissingList` cover it. A list fetched once is not left as it was: the magpie serving the gateway looks every hour ([`KeepAccountsListed`](../../internal/provider/account_relist.go), first two minutes after it starts) and fetches again each signed-in built-in account's list that is 45 minutes old (`accountListAge`, `relistAccounts`), so a model the vendor adds to the plan is served without Refresh or a magpie release (cliff_26651 on Discord: GPT-6.1 Terra, served to ChatGPT accounts from 10-26, missing from Codex through a magpie whose Codex list was fetched on 10-12). A plugin's accounts are `KeepPluginsListed`'s, one switched off isn't asked, and a fetch that fails keeps the list there was. `TestAccountListFollowsTheVendor` and `TestKeepAccountsListedAsks` cover it. The saved ChatGPT accounts behind the one Codex is signed in to are listed with that fetch (`codexFetchSaved`), but not each time: one with no list yet is asked at once, the others once a day (`codexSavedListAge`) and one a look (`codexSavedAtOnce`), the one asked longest ago first, and one that failed waits its day too (`codexSavedAsked`). Asking every switched-on saved account each hour was a burst of `/codex/models` calls from one address for accounts no Codex used (`TestSavedCodexListsOnceADay`). Every call magpie makes about a ChatGPT account, not only `/codex/models` and `/responses` (`codexSign`), carries Codex's `originator` and User-Agent (`codexClientHeaders`, codex-rs `default_headers`): `/wham/usage`, the reset credits and their use (`codexAccountHeaders`), and the token endpoint's refresh and sign-in exchange. The refresh's body is codex-rs's: `client_id`, `grant_type`, `refresh_token` and a `refresh_reason` (`proactive_expiry`, `scheduled` from the keep-alive, `unauthorized_recovery` after a 401, `forced`), with no `scope` (`TestCodexAccountCallsGoAsCodex`, `TestCodexRefreshSaysWhy`).
## Runtime path
diff --git a/internal/provider/account.go b/internal/provider/account.go
index b42d1a358..c307b942a 100644
--- a/internal/provider/account.go
+++ b/internal/provider/account.go
@@ -1127,7 +1127,11 @@ func codexTokenRenewing(ctx context.Context, dir, stale string) (tok, accountID
return "", "", errors.New("Codex is signed out; run codex login")
}
accountID = codexAccountID(a)
- tok, err = codexRefresh(ctx, raw)
+ reason := codexRefreshExpiry
+ if stale != "" {
+ reason = codexRefreshRecovery
+ }
+ tok, err = codexRefresh(ctx, raw, reason)
if err != nil {
// OpenAI refused this sign-in for good: Codex is signed out to
// magpie's wiring until it is signed in again (#4308)
@@ -1164,9 +1168,39 @@ func codexAccountID(a codexAuth) string {
return claimString(jwtClaims(a.Tokens.IDToken), "https://api.openai.com/auth", "chatgpt_account_id")
}
+// Why a ChatGPT sign-in is refreshed, in the words codex-rs sends with
+// its own refresh (refresh_reason, login/src/oauth/client.rs).
+const (
+ codexRefreshExpiry = "proactive_expiry" // its access token is about to run out
+ codexRefreshScheduled = "scheduled" // not refreshed for keepAliveEvery
+ codexRefreshRecovery = "unauthorized_recovery" // the backend called its token expired
+ codexRefreshForced = "forced" // asked for: an import, a check
+)
+
+type refreshReasonKey struct{}
+
+// refreshingFor has a forced refresh made under ctx say why it is made,
+// when it is more than "forced" (the keep-alive's "scheduled").
+func refreshingFor(ctx context.Context, reason string) context.Context {
+ return context.WithValue(ctx, refreshReasonKey{}, reason)
+}
+
+// forcedReason is why ctx forces a refresh: what refreshingFor said, else
+// "forced".
+func forcedReason(ctx context.Context) string {
+ if r, _ := ctx.Value(refreshReasonKey{}).(string); r != "" {
+ return r
+ }
+ return codexRefreshForced
+}
+
// codexRefresh renews the tokens of an auth.json-shaped sign-in in place,
// every other field left as it was, and returns the new access token.
-func codexRefresh(ctx context.Context, raw map[string]any) (string, error) {
+// It is asked as codex-rs asks it (request_chatgpt_token_refresh): a JSON
+// body of client_id, grant_type, refresh_token and refresh_reason, with
+// no scope (a refresh keeps the scopes granted), and Codex's originator
+// and User-Agent.
+func codexRefresh(ctx context.Context, raw map[string]any, reason string) (string, error) {
toks, _ := raw["tokens"].(map[string]any)
if toks == nil {
toks = map[string]any{}
@@ -1185,12 +1219,13 @@ func codexRefresh(ctx context.Context, raw map[string]any) (string, error) {
ctx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 30*time.Second)
defer cancel()
body, _ := json.Marshal(map[string]string{"client_id": codexClientID, "grant_type": "refresh_token",
- "refresh_token": refresh, "scope": "openid profile email"})
+ "refresh_token": refresh, "refresh_reason": reason})
req, err := http.NewRequestWithContext(ctx, http.MethodPost, codexTokenURL, bytes.NewReader(body))
if err != nil {
return "", err
}
req.Header.Set("Content-Type", "application/json")
+ codexClientHeaders(req.Header, codexVersion())
res, err := http.DefaultClient.Do(req)
if err != nil {
return "", errors.New("Codex token refresh: " + err.Error())
diff --git a/internal/provider/account_test.go b/internal/provider/account_test.go
index f5b605f6b..5009ee797 100644
--- a/internal/provider/account_test.go
+++ b/internal/provider/account_test.go
@@ -103,6 +103,10 @@ func isolate(t testing.TB) {
// a minute, and CachedCards hands them on whatever their age
forgetPlanQuotas()
ForgetBalances()
+ // nor when another test asked a saved account's list
+ codexSavedAsked.Lock()
+ codexSavedAsked.m = map[string]time.Time{}
+ codexSavedAsked.Unlock()
t.Cleanup(func() {
claudeKeychain, claudeBase, claudeExecutable = oldKeychain, oldBase, oldExe
DevinExecutable = oldDevin
diff --git a/internal/provider/codex_models.go b/internal/provider/codex_models.go
index 14384ae71..6bd05df6f 100644
--- a/internal/provider/codex_models.go
+++ b/internal/provider/codex_models.go
@@ -422,16 +422,70 @@ func levelRank(e string) int {
return len(Levels)
}
-// codexFetchSaved asks for the models of each saved ChatGPT account that
-// stands behind the one Codex is signed in to, with that account's own
-// sign-in, so the gateway doesn't send one a model its plan lacks. One that
-// can't be asked now keeps what it listed last.
+// codexSavedListAge is how old a saved account's list is before it is
+// asked for again, and codexSavedAtOnce how many of those one fetch of the
+// active account's list asks. The active account's list is asked every
+// accountListAge (KeepAccountsListed) as Codex asks its own; asking every
+// switched-on saved account's beside it each hour was a burst of N
+// /codex/models calls from one address for accounts no Codex was using
+// (the audit after owl's deactivated accounts, 10-30). A plan's models
+// change seldom: once a day, one account a look, so they drift apart.
+const (
+ codexSavedListAge = 24 * time.Hour
+ codexSavedAtOnce = 1
+)
+
+// codexSavedAsked is when each saved account's list was last asked for,
+// fetched or not, so one that keeps failing (a deactivated account) waits
+// its day like the others instead of being first every look.
+var codexSavedAsked = struct {
+ sync.Mutex
+ m map[string]time.Time
+}{m: map[string]time.Time{}}
+
+// codexSavedNow is codexFetchSaved's clock; a var so tests can move it.
+var codexSavedNow = time.Now
+
+// codexFetchSaved asks for the models of the saved ChatGPT accounts that
+// stand behind the one Codex is signed in to, with each account's own
+// sign-in, so the gateway doesn't send one a model its plan lacks. An
+// account with no list yet is asked at once; of the rest, the one asked
+// longest ago, once codexSavedListAge has passed, and no more than
+// codexSavedAtOnce of them. One that can't be asked now keeps what it
+// listed last.
func codexFetchSaved(ctx context.Context) {
- for _, l := range Logins("codex") {
+ now := codexSavedNow()
+ type due struct {
+ user string
+ at time.Time
+ }
+ var fresh, stale []due
+ ls := Logins("codex")
+ codexSavedAsked.Lock()
+ for _, l := range ls {
if l.Active || !l.On {
continue
}
- user := l.User
+ _, at, ok := catalog.Live(accountModels("codex", l.User))
+ if !ok {
+ fresh = append(fresh, due{l.User, at})
+ continue
+ }
+ if a := codexSavedAsked.m[strings.ToLower(l.User)]; a.After(at) {
+ at = a
+ }
+ if now.Sub(at) >= codexSavedListAge {
+ stale = append(stale, due{l.User, at})
+ }
+ }
+ sort.SliceStable(stale, func(i, j int) bool { return stale[i].at.Before(stale[j].at) })
+ ask := append(fresh, stale[:min(len(stale), codexSavedAtOnce)]...)
+ for _, d := range ask {
+ codexSavedAsked.m[strings.ToLower(d.user)] = now
+ }
+ codexSavedAsked.Unlock()
+ for _, d := range ask {
+ user := d.user
sign := codexSign(func(ctx context.Context) (string, string, error) { return savedLoginToken(ctx, "codex", user) })
// through the account's own proxy, if it has one
if ms, err := codexModels(ViaLogin(ctx, "codex", user), sign); err == nil {
diff --git a/internal/provider/codex_quiet_test.go b/internal/provider/codex_quiet_test.go
index 5dd68a7d5..49d36de4a 100644
--- a/internal/provider/codex_quiet_test.go
+++ b/internal/provider/codex_quiet_test.go
@@ -3,10 +3,13 @@ package provider
import (
"context"
"encoding/json"
+ "io"
"net/http"
"net/http/httptest"
+ "slices"
"strings"
"sync"
+ "sync/atomic"
"testing"
"time"
)
@@ -128,3 +131,234 @@ func TestKeepAliveRenewsOneALook(t *testing.T) {
t.Fatalf("one look renewed %d of %+v, refreshed %v", renewed, rs, got)
}
}
+
+// Every call magpie makes about a ChatGPT account goes as Codex makes it:
+// its originator and User-Agent on /wham/usage, the reset credits and the
+// token endpoint, as on /codex/models and /responses already. They went
+// with Go's "Go-http-client/1.1" and no originator, unlike any request the
+// official client sends. The refresh's body is codex-rs's too: a
+// refresh_reason, and no scope.
+func TestCodexAccountCallsGoAsCodex(t *testing.T) {
+ signIn(t)
+ type call struct {
+ ua, originator, ctype string
+ body []byte
+ }
+ var mu sync.Mutex
+ calls := map[string][]call{}
+ fake := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ b, _ := io.ReadAll(r.Body)
+ mu.Lock()
+ calls[r.Method+" "+r.URL.Path] = append(calls[r.Method+" "+r.URL.Path], call{r.UserAgent(), r.Header.Get("originator"), r.Header.Get("Content-Type"), b})
+ mu.Unlock()
+ switch r.URL.Path {
+ case "/backend-api/wham/usage":
+ json.NewEncoder(w).Encode(map[string]any{"plan_type": "plus",
+ "rate_limit": map[string]any{"primary_window": map[string]any{"used_percent": 10, "limit_window_seconds": 18000}},
+ "rate_limit_reset_credits": map[string]any{"available_count": 1}})
+ case "/backend-api/wham/rate-limit-reset-credits":
+ json.NewEncoder(w).Encode(map[string]any{"available_count": 1, "credits": []any{map[string]any{"id": "c1", "reset_type": "all", "status": "available"}}})
+ case "/backend-api/wham/rate-limit-reset-credits/consume":
+ json.NewEncoder(w).Encode(map[string]any{"code": "ok", "windows_reset": 1})
+ case "/oauth/token":
+ json.NewEncoder(w).Encode(map[string]any{"access_token": fakeJWT(map[string]any{"exp": float64(time.Now().Add(time.Hour).Unix())}),
+ "refresh_token": "r-2", "id_token": fakeJWT(map[string]any{"email": "[email protected]"})})
+ default:
+ w.WriteHeader(404)
+ }
+ }))
+ defer fake.Close()
+ codexListedAt(t, fake.URL) // CodexBase, and the machine's own Codex CLI out of the version
+ old := codexTokenURL
+ codexTokenURL = fake.URL + "/oauth/token"
+ t.Cleanup(func() { codexTokenURL = old })
+
+ ctx := context.Background()
+ if _, _, resets, _, _, err := codexWindows(ctx, "tok", "acct-1"); err != nil || resets == nil {
+ t.Fatalf("usage: resets %+v, %v", resets, err)
+ }
+ if _, err := consumeCodexReset(ctx, fake.URL+"/backend-api", "tok", "acct-1", "c1", newRedeemID()); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := codexRefresh(ctx, map[string]any{"tokens": map[string]any{"refresh_token": "r-1"}}, codexRefreshScheduled); err != nil {
+ t.Fatal(err)
+ }
+ codexExchange(ctx, "code", "verifier", "http://localhost:1455/auth/callback") // the request is what is checked
+
+ want := map[string]int{"GET /backend-api/wham/usage": 1, "GET /backend-api/wham/rate-limit-reset-credits": 1,
+ "POST /backend-api/wham/rate-limit-reset-credits/consume": 1, "POST /oauth/token": 2}
+ ua := codexUserAgent(codexVersion())
+ mu.Lock()
+ defer mu.Unlock()
+ for k, n := range want {
+ if len(calls[k]) != n {
+ t.Errorf("%s asked %d times, want %d (%v)", k, len(calls[k]), n, calls)
+ }
+ for _, c := range calls[k] {
+ if c.ua != ua || c.originator != "codex_cli_rs" {
+ t.Errorf("%s sent User-Agent %q, originator %q; Codex sends %q, codex_cli_rs", k, c.ua, c.originator, ua)
+ }
+ }
+ }
+ if len(calls) != len(want) {
+ t.Errorf("asked %v", calls)
+ }
+ if tok := calls["POST /oauth/token"]; len(tok) == 2 {
+ var refresh map[string]any
+ if tok[0].ctype != "application/json" || json.Unmarshal(tok[0].body, &refresh) != nil {
+ t.Fatalf("refresh sent as %q: %s", tok[0].ctype, tok[0].body)
+ }
+ keys := []string{}
+ for k := range refresh {
+ keys = append(keys, k)
+ }
+ slices.Sort(keys)
+ if strings.Join(keys, ",") != "client_id,grant_type,refresh_reason,refresh_token" ||
+ refresh["refresh_reason"] != "scheduled" || refresh["grant_type"] != "refresh_token" || refresh["client_id"] != codexClientID {
+ t.Errorf("refresh body %s; codex-rs sends client_id, grant_type, refresh_token and refresh_reason", tok[0].body)
+ }
+ if tok[1].ctype != "application/x-www-form-urlencoded" || !strings.Contains(string(tok[1].body), "grant_type=authorization_code") {
+ t.Errorf("sign-in exchange sent as %q: %s", tok[1].ctype, tok[1].body)
+ }
+ }
+}
+
+// A refresh says why it is made, in codex-rs's words: the keep-alive's is
+// "scheduled", one after the backend called the token expired
+// "unauthorized_recovery", one asked for otherwise "forced", and one for
+// a token about to run out "proactive_expiry".
+func TestCodexRefreshSaysWhy(t *testing.T) {
+ home := signIn(t)
+ rememberLogins(true) // me@ saved
+ codexSignIn(t, home, "[email protected]", "r-work")
+ rememberLogins(true) // Codex on work@
+ var mu sync.Mutex
+ var why []string
+ fake := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ var body map[string]string
+ json.NewDecoder(r.Body).Decode(&body)
+ mu.Lock()
+ why = append(why, body["refresh_reason"])
+ mu.Unlock()
+ json.NewEncoder(w).Encode(map[string]any{"access_token": fakeJWT(map[string]any{"exp": float64(time.Now().Add(time.Hour).Unix()), "n": len(why)}),
+ "refresh_token": body["refresh_token"] + "-2"})
+ }))
+ defer fake.Close()
+ old := codexTokenURL
+ codexTokenURL = fake.URL
+ t.Cleanup(func() { codexTokenURL = old })
+
+ ctx := context.Background()
+ // me@ was last seen nine days ago: the keep-alive renews it, as due
+ loginsMu.Lock()
+ ls := readLogins()
+ for i := range ls {
+ if ls[i].User == "[email protected]" {
+ ls[i].Seen = time.Now().Add(-9 * 24 * time.Hour)
+ }
+ }
+ err := writeLogins(ls)
+ loginsMu.Unlock()
+ if err != nil {
+ t.Fatal(err)
+ }
+ if rs := renewLogins(ctx, keepAliveEvery, keepAliveAtOnce); len(rs) != 1 || !rs[0].Renewed {
+ t.Fatalf("keep-alive: %+v", rs)
+ }
+ tok, _, err := renewSavedLogin(ctx, "codex", "[email protected]", true)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, _, err := renewSavedLoginFrom(ctx, "codex", "[email protected]", tok); err != nil {
+ t.Fatal(err)
+ }
+ mu.Lock()
+ defer mu.Unlock()
+ if strings.Join(why, ",") != "scheduled,forced,unauthorized_recovery" {
+ t.Fatalf("refreshes said %v", why)
+ }
+}
+
+// A saved ChatGPT account's model list is asked for once a day, one
+// account a look; the hourly relist asked every switched-on saved
+// account's beside the active one's, a burst of /codex/models calls from
+// one address for accounts no Codex was using. An account with no list
+// yet is asked at once, and one that fails waits its day like the rest.
+func TestSavedCodexListsOnceADay(t *testing.T) {
+ home := signIn(t) // [email protected], acct-1
+ rememberLogins(true)
+ codexSignIn(t, home, "[email protected]", "r-spare")
+ rememberLogins(true)
+ codexSignIn(t, home, "[email protected]", "r-work")
+ rememberLogins(true) // Codex on work@
+ for _, u := range []string{"[email protected]", "[email protected]"} {
+ if err := SetLoginOn("codex", u, true); err != nil {
+ t.Fatal(err)
+ }
+ }
+ var mu sync.Mutex
+ hits := map[string]int{}
+ var down atomic.Bool
+ fake := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if r.URL.Path != "/backend-api/codex/models" {
+ w.WriteHeader(404)
+ return
+ }
+ mu.Lock()
+ hits[r.Header.Get("chatgpt-account-id")]++
+ mu.Unlock()
+ if down.Load() {
+ w.WriteHeader(401)
+ return
+ }
+ w.Write(codexListOf("gpt-6.1-sol"))
+ }))
+ defer fake.Close()
+ codexListedAt(t, fake.URL)
+ now := time.Now()
+ oldNow := codexSavedNow
+ codexSavedNow = func() time.Time { return now }
+ t.Cleanup(func() { codexSavedNow = oldNow })
+ look := func(at time.Duration) map[string]int {
+ t.Helper()
+ now = time.Now().Add(at)
+ mu.Lock()
+ hits = map[string]int{}
+ mu.Unlock()
+ codexFetchSaved(context.Background())
+ mu.Lock()
+ defer mu.Unlock()
+ got := map[string]int{}
+ for k, v := range hits {
+ got[k] = v
+ }
+ return got
+ }
+ // no list yet: both saved accounts are asked, never the active one here
+ if got := look(0); len(got) != 2 || got["acct-1"] != 1 || got["[email protected]"] != 1 {
+ t.Fatalf("first look: %v", got)
+ }
+ // within the day: none
+ if got := look(time.Hour); len(got) != 0 {
+ t.Fatalf("an hour on: %v", got)
+ }
+ if codexSavedListAge < 24*time.Hour || codexSavedAtOnce != 1 {
+ t.Fatalf("saved lists asked every %v, %d a look", codexSavedListAge, codexSavedAtOnce)
+ }
+ // a day on: one a look, then the other, then none till the next day
+ first := look(25 * time.Hour)
+ second := look(26 * time.Hour)
+ if len(first) != 1 || len(second) != 1 || first["acct-1"]+second["acct-1"] != 1 {
+ t.Fatalf("a day on: %v, then %v", first, second)
+ }
+ if got := look(27 * time.Hour); len(got) != 0 {
+ t.Fatalf("both asked today, asked again: %v", got)
+ }
+ // failing: still once a day each, not first in every look
+ down.Store(true)
+ look(50 * time.Hour)
+ look(51 * time.Hour)
+ if got := look(52 * time.Hour); len(got) != 0 {
+ t.Fatalf("failing accounts asked again within the day: %v", got)
+ }
+}
diff --git a/internal/provider/codex_request.go b/internal/provider/codex_request.go
index 89e15e164..5374d2eeb 100644
--- a/internal/provider/codex_request.go
+++ b/internal/provider/codex_request.go
@@ -39,12 +39,11 @@ func codexSign(token func(context.Context) (tok, accountID string, err error)) f
req.Header.Set("chatgpt-account-id", accountID)
}
req.Header.Set("OpenAI-Beta", "responses=experimental")
- req.Header.Set("originator", "codex_cli_rs")
// 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))
+ codexClientHeaders(req.Header, ver)
if body == nil {
return nil
}
@@ -54,6 +53,31 @@ func codexSign(token func(context.Context) (tok, accountID string, err error)) f
}
}
+// codexClientHeaders are what every request Codex CLI makes carries,
+// whatever it is for: its originator and its User-Agent, naming Codex of
+// version ver (codex-rs login/src/auth/default_client.rs default_headers,
+// which its token refresh, its /wham reads and its model requests are all
+// sent with). The ChatGPT account's own calls that aren't a model's
+// (/wham/usage, the reset credits, the token refresh) went with Go's
+// User-Agent and no originator, unlike any request Codex makes.
+func codexClientHeaders(h http.Header, ver string) {
+ h.Set("originator", "codex_cli_rs")
+ h.Set("User-Agent", codexUserAgent(ver))
+}
+
+// codexAccountHeaders are the headers of a call Codex makes about the
+// ChatGPT account (its /wham reads): the account it is about and
+// codexClientHeaders. Codex sends no version header with them.
+func codexAccountHeaders(accountID string) map[string]string {
+ h := http.Header{}
+ codexClientHeaders(h, codexVersion())
+ m := map[string]string{"chatgpt-account-id": accountID}
+ for k := range h {
+ m[k] = h.Get(k)
+ }
+ return m
+}
+
// sessionHeaders names the conversation body belongs to (its
// prompt_cache_key) in the headers Codex CLI 0.162 sends it in, session-id
// and thread-id. The ChatGPT backend finds a conversation's cached prompt
diff --git a/internal/provider/codex_resets.go b/internal/provider/codex_resets.go
index a6095ea44..313db435d 100644
--- a/internal/provider/codex_resets.go
+++ b/internal/provider/codex_resets.go
@@ -159,7 +159,7 @@ func codexResets(ctx context.Context, base, token, accountID string, count int)
ctx, cancel := context.WithTimeout(ctx, codexResetDetailsTimeout)
defer cancel()
var w codexResetCreditsWire
- if accountJSON(ctx, base+"/wham/rate-limit-reset-credits", token, map[string]string{"chatgpt-account-id": accountID}, &w) == nil {
+ if accountJSON(ctx, base+"/wham/rate-limit-reset-credits", token, codexAccountHeaders(accountID), &w) == nil {
out.Until = w.soonest()
// listed only when they are the ones counted: a list that says
// otherwise isn't put on the card as if it were
@@ -218,7 +218,7 @@ func useCodexReset(ctx context.Context, user, why string) (ResetOutcome, error)
// which of them to spend is named, as Codex itself does: left to the
// vendor, it may be one that lasts longer
var w codexResetCreditsWire
- if err := accountJSON(ctx, base+"/wham/rate-limit-reset-credits", tok, map[string]string{"chatgpt-account-id": accountID}, &w); err != nil {
+ if err := accountJSON(ctx, base+"/wham/rate-limit-reset-credits", tok, codexAccountHeaders(accountID), &w); err != nil {
return ResetOutcome{}, fmt.Errorf("couldn't read which reset runs out first, so none was used: %w", err)
}
credit, _ := w.first()
@@ -297,8 +297,10 @@ func consumeCodexReset(ctx context.Context, base, token, accountID, credit, id s
req.Header.Set("Authorization", "Bearer "+token)
req.Header.Set("Accept", "application/json")
req.Header.Set("Content-Type", "application/json")
- if accountID != "" {
- req.Header.Set("chatgpt-account-id", accountID)
+ for k, v := range codexAccountHeaders(accountID) {
+ if v != "" {
+ req.Header.Set(k, v)
+ }
}
res, err := http.DefaultClient.Do(req)
if err != nil {
diff --git a/internal/provider/keepalive.go b/internal/provider/keepalive.go
index d5600096c..42bde71b2 100644
--- a/internal/provider/keepalive.go
+++ b/internal/provider/keepalive.go
@@ -82,7 +82,11 @@ func renewLogins(ctx context.Context, every time.Duration, atOnce int) []Renewal
continue
}
tried++
- if _, _, err := renewSavedLogin(ctx, l.Agent, l.User, true); err != nil {
+ why := ctx
+ if every > 0 {
+ why = refreshingFor(ctx, codexRefreshScheduled)
+ }
+ if _, _, err := renewSavedLogin(why, l.Agent, l.User, true); err != nil {
r.Err = err.Error()
var refused refreshRefused
r.Lapsed = errors.As(err, &refused)
diff --git a/internal/provider/login_import.go b/internal/provider/login_import.go
index d4ea8c7f2..7bd61e8b4 100644
--- a/internal/provider/login_import.go
+++ b/internal/provider/login_import.go
@@ -378,7 +378,7 @@ func importLogin(ctx context.Context, agent string, e loginImport, name string,
switch agent {
case "codex":
raw := map[string]any{"tokens": map[string]any{"refresh_token": e.refreshToken}}
- if _, err := codexRefresh(ctx, raw); err != nil {
+ if _, err := codexRefresh(ctx, raw, codexRefreshForced); err != nil {
return refused("ChatGPT", err)
}
t := raw["tokens"].(map[string]any)
diff --git a/internal/provider/logins_on.go b/internal/provider/logins_on.go
index 824ab639a..0b5ebe850 100644
--- a/internal/provider/logins_on.go
+++ b/internal/provider/logins_on.go
@@ -275,7 +275,13 @@ func renewSaved(ctx context.Context, agent, user string, force bool, stale strin
} else if exp, _ := jwtClaims(a.Tokens.AccessToken)["exp"].(float64); !force && (exp == 0 || time.Until(time.Unix(int64(exp), 0)) > 5*time.Minute) {
return a.Tokens.AccessToken, accountID, nil
}
- if tok, err = codexRefresh(ctx, raw); err != nil {
+ reason := codexRefreshExpiry
+ if stale != "" {
+ reason = codexRefreshRecovery
+ } else if force {
+ reason = forcedReason(ctx)
+ }
+ if tok, err = codexRefresh(ctx, raw, reason); err != nil {
return "", "", savedRefreshFailed(agent, user, err)
}
if auth, err = json.MarshalIndent(raw, "", " "); err != nil {
diff --git a/internal/provider/signin.go b/internal/provider/signin.go
index 7b6acfec7..3180c4130 100644
--- a/internal/provider/signin.go
+++ b/internal/provider/signin.go
@@ -753,10 +753,19 @@ func postToken(ctx context.Context, tokenURL, ctype string, body []byte, out any
// postTokenAs is postToken asked with bearer, a token already had, when it
// isn't "" (Google's IAM Credentials, which trades one for another).
func postTokenAs(ctx context.Context, tokenURL, ctype, bearer string, body []byte, out any) error {
+ return postTokenWith(ctx, tokenURL, ctype, bearer, nil, body, out)
+}
+
+// postTokenWith is postTokenAs sent with the headers in h too (Codex's
+// own, codexClientHeaders).
+func postTokenWith(ctx context.Context, tokenURL, ctype, bearer string, h http.Header, body []byte, out any) error {
req, err := http.NewRequestWithContext(ctx, http.MethodPost, tokenURL, bytes.NewReader(body))
if err != nil {
return err
}
+ for k, v := range h {
+ req.Header[k] = v
+ }
req.Header.Set("Content-Type", ctype)
req.Header.Set("Accept", "application/json")
if bearer != "" {
@@ -830,7 +839,10 @@ func codexExchange(ctx context.Context, code, verifier, redirect string) (savedL
AccessToken string `json:"access_token"`
RefreshToken string `json:"refresh_token"`
}
- if err := postToken(ctx, codexTokenURL, "application/x-www-form-urlencoded", []byte(form.Encode()), &tok); err != nil {
+ // sent as Codex sends it (codex-rs OAuthClient::exchange_code)
+ h := http.Header{}
+ codexClientHeaders(h, codexVersion())
+ if err := postTokenWith(ctx, codexTokenURL, "application/x-www-form-urlencoded", "", h, []byte(form.Encode()), &tok); err != nil {
return savedLogin{}, err
}
if tok.AccessToken == "" || tok.RefreshToken == "" || tok.IDToken == "" {
diff --git a/internal/provider/subscription_usage.go b/internal/provider/subscription_usage.go
index d087253a8..4138e5c88 100644
--- a/internal/provider/subscription_usage.go
+++ b/internal/provider/subscription_usage.go
@@ -965,7 +965,7 @@ func codexWindows(ctx context.Context, token, accountID string) (plan string, ou
var data codexUsage
base := strings.TrimSuffix(CodexBase, "/codex")
out = []QuotaWindow{}
- if err = accountJSON(ctx, base+"/wham/usage", token, map[string]string{"chatgpt-account-id": accountID}, &data); err != nil {
+ if err = accountJSON(ctx, base+"/wham/usage", token, codexAccountHeaders(accountID), &data); err != nil {
return "", out, nil, "", false, err
}
if c := data.Credits; c != nil && c.Has && !c.Unlimited {