diff --git a/docs/subsystems/providers-accounts.md b/docs/subsystems/providers-accounts.md index 1a76e0d49..6b48b7bed 100644 --- a/docs/subsystems/providers-accounts.md +++ b/docs/subsystems/providers-accounts.md @@ -34,6 +34,7 @@ keys and accounts per request is in [Gateway routing and fallback](gateway-routi | Subscription accounts | `Accounts` reads the credentials each agent keeps on disk or in the macOS Keychain; nothing is stored twice. With account discovery off (#1535, below) none of them is read. A built-in that has moved to its plugin is dropped (`Moved`), and plugin accounts are placed in its slot (`placeMoved`). `Sign` adds the account's own auth, then the user's `Headers`. | [`account.go`](../../internal/provider/account.go) | | Token refresh | Each account refreshes through its vendor. For example, `codexToken` refreshes within 5 minutes of expiry and writes the rotated tokens back where it read them (`codexStore.write`: `~/.codex/auth.json`, or Codex's keychain item), every other field kept, for Codex CLI. Before refreshing a sign-in read from the keychain it asks the item again, so a rotation Codex made since isn't spent twice. A 400 or 401 from the vendor's refresh endpoint means it was refused (`refreshFailed`). | [`account.go`](../../internal/provider/account.go) | | Codex's credential store | Codex 0.162 keeps its ChatGPT sign-in where `cli_auth_credentials_store` in `$CODEX_HOME/config.toml` says (`codex-rs/login/src/auth/storage.rs`): `file` (default) is `auth.json`; `keyring` the system keychain alone; `auto` the keychain, else `auth.json`, on read and on save; `ephemeral` Codex's memory. Saved to the keychain, Codex removes `auth.json` (#2312, #2367, Dony2050). On macOS magpie reads that item through `security`, as it reads Claude Code's: service `Codex Auth`, account `cli|` + the first 16 hex digits of SHA-256 of the canonical CODEX_HOME (`codexKeychainAccount`), the value auth.json's JSON on one line. `readCodexLogin` is the one reader: `codexAccount`, `codexToken`, `liveLogin`, `CodexAPIKeySignedIn`, `codexLoginAuth`, the usage card's `codexUntil`, session identities and the agent's wiring (`provider.CodexSignIn`: `codexChatGPT`, `Agent.Source`) go through it. `keyring` with no item is signed out; `auto` with no item, or one the keychain wouldn't give, is `auth.json`, as Codex does. An item the keychain wouldn't give under `keyring` is not known (`codexStoreError`), never signed out. With `[features] secret_auth_storage` on (Codex's default on Windows) keyring and auto mean Codex's encrypted auth storage, which magpie doesn't read; nor does it read the Linux or Windows keychain. There `keyring` and `ephemeral` are not known, `auto` is `auth.json` when Codex left one, and the saved accounts' reason says to set `file` (`codexSignedOutWhy`). Requirements an admin manages (`requirements.cli_auth_credentials_store`) aren't read. Reading the secret can put up to two macOS prompts in front of the user, who may type their password, so one read per item is in flight at a time and waits up to 2 minutes for them (`keychainAsk`, `askCodexKeychain`), outside the cache's lock. A reader waits at most 5s from when that ask started (`keychainHold`) and is otherwise told magpie is waiting for an answer (`errKeychainWaiting`); no request or page waits out the prompt. `security` exit 44 is no item; 51 (errSecAuthFailed) or 128 (errSecUserCanceled) is denied or cancelled (`errKeychainRefused`); the 2 minutes running out is no answer (`errKeychainNoAnswer`); anything else is `errKeychainUnread`. Each says so in the saved accounts' reason, and none of them is signed out. A read the keychain gave is kept while the item is unchanged: after 10s a reader asks only the item's modification date (`Stat`, `find-generic-password` without `-w`, which shows no prompt) and reads the secret again only when Codex or magpie changed it (#2367: with "Allow" once, background polls asked again every ~30s). A refusal or no answer is kept 10 minutes (#2408). magpie's own writes (`codexStore.write`, `keepCodexKeychain`) keep the date of what they wrote; a switch, sign-out or refresh forgets a read (`forgetCodexKeychain`) so the next one checks the date, but keeps a refusal; switching and refreshing read afresh. Beside a refusal, no answer or waiting, the saved accounts' line has Try again (`Exclusion.Retry`, `keychain-retry`, `RetryCodexKeychain`), which reads once past the refusal, and the reason says "Always Allow" lets `/usr/bin/security` read the item, so macOS stops asking each time Codex changes it. A switch or a first sign-in (`saveCodexLogin`) writes the store Codex reads, and refuses when that store couldn't be read, when config.toml doesn't parse, or when it is one magpie doesn't read; it leaves an `auth.json` beside the item to Codex. Signing the last account out (`deleteCodexLogin`) removes the item, then `auth.json`, as `codex logout`. Not tried against an item Codex itself wrote: macOS may ask whether magpie can read it, and Codex whether it can read one magpie rewrote. | [`codex_store.go`](../../internal/provider/codex_store.go), [`codex_store_test.go`](../../internal/provider/codex_store_test.go), [`codex_keychain_ask_unix_test.go`](../../internal/provider/codex_keychain_ask_unix_test.go) | +| Codex's other folders | Codex keeps one ChatGPT sign-in a folder (`codex-rs/login/src/auth/storage.rs`: `$CODEX_HOME/auth.json`, or the keychain item named by the folder) and writes its sessions there (`rollout/src/lib.rs`); `--profile` only lays `$CODEX_HOME/.config.toml` over `config.toml`, the sign-in shared (`config/src/loader/mod.rs`). So a second account is Codex run with `CODEX_HOME=~/.codex-work`. `appdir.CodexHomes` finds those folders: `CodexHome` first, then folders in the home folder or beside `CodexHome` named `codex*` or `.codex*`, or one folder down in one (`~/.codex-profiles/work`), that hold `auth.json` or `sessions/`. Sessions and the usage ledger read every one (`sessions.codexFiles`, `Dirs`). `rememberLogins` saves each folder's account with `Home` set to it (`codexHomeLogins`); the one `~/.codex` is signed in to is that one's. Such an account is renewed in its folder, as Codex's own (`codexHeldIn` in `renewSaved`, as `heldByCodex` does for `~/.codex`), so the quota, the gateway and the keep-alive never spend a copy's refresh token under that folder's Codex. It isn't switched into `~/.codex` (`switchSavedLogin`, `NextLogin`'s spares) nor removed (`forgetLogin`): each error names the folder and the `CODEX_HOME=… codex` command. phantom3792 on X: only the default folder's sessions counted, and an account added from another folder read no quota (`TestCodexOtherHome*`, `TestCodexHomesIn`). Not done: Codex's thread names (`session_index.jsonl`) and a `sqlite_home` are read from `CodexHome` only (#3530). | [`codex.go`](../../internal/appdir/codex.go), [`logins.go`](../../internal/provider/logins.go), [`codex_homes_test.go`](../../internal/provider/codex_homes_test.go) | | A revoked sign-in | A 401 whose words say the sign-in itself is gone (`SignInRevoked`: ChatGPT's `token_revoked`, `invalid_grant`, `refresh_token_reused`; never `token_expired`, a 403, a 5xx or a network error) marks the account for the credential it was sent with (`NoteRevokedSignIn`, #1793). A saved ChatGPT account is refreshed first, as Codex does on a 401, and a refresh that goes through marks nothing. The mark is a hash of the header, never the credential, kept in `logins.json` as `Refused: "revoked:"` with the account's `Lapsed`, and read back after a restart. While the account has that credential, the gateway doesn't send its requests (`RevokedSignIn`); its row says Sign-in required with Sign in again. Signed in anew (`upsertLogin` with another credential, `addSideLogin`), refreshed, or served a request (`ServedSignIn`), it is clear. Claude (`claude_auth.go`), Copilot (`copilot_lapsed.go`: GitHub's 401/403 on the token exchange, the CLI's stand-in or the usage read, cleared when a token is served) and plugins keep their own marks. | [`signin_revoked.go`](../../internal/provider/signin_revoked.go), [`copilot_lapsed.go`](../../internal/provider/copilot_lapsed.go) | | A token called expired | A ChatGPT 401 whose words say the access token has expired and ask for a refresh (`SignInExpired`: `token_expired`, "Provided authentication token is expired. Please try refreshing it."; never `refresh_token_expired`, which is revoked) while the token's own `exp` is still ahead (willz on Discord, #2973: two saved Team accounts) is mended by one refresh. `codexToken` refreshes only as `exp` nears, so before this the token went out as it was until the user signed in again, and the card said only Unauthorized. The usage read (`codexWindowsRenewing`: `loginQuota`, `codexSubscriptionUsage`, and the reset spenders through `codexUserWindows`) refreshes once and reads once more, never again: a refresh refused says to sign in again (a saved account is marked lapsed, `savedRefreshFailed`; Codex's own says `codex login`), and a token refreshed for it and still called expired says so too (`errCodexStillExpired`). The gateway renews the account a request went with (`NoteExpiredSignIn` from `noteSignIn`, 20s at most); the request itself fails over as before, and the next goes with the new token. Each refresh is keyed on the token turned away (`codexTokenRenewing`, `renewSavedLoginFrom`), under the lock signing waits on: a sign-in holding another token by then, renewed by Codex or another reply, is used as it is, so two replies for one token spend one rotation. Codex's own sign-in is read from its store afresh for it and written back through `codexStore.write` (temp and rename), a saved one's through `writeLogins`. Not tried against the real backend. | [`codex_expired.go`](../../internal/provider/codex_expired.go), [`account.go`](../../internal/provider/account.go), [`logins_on.go`](../../internal/provider/logins_on.go) | | Saved accounts | `logins.json` remembers every Codex and Claude Code account seen signed in. A switch moves the credentials into the agent's own store and saves the ones it replaces. A saved account that is on (`SetLoginOn`) stands behind the agent's own. Its tokens stay in `logins.json`. While Claude Code is signed out, a saved Claude account stands in for its own (`claudeStandIn`); with every saved account's sign-in gone, Claude Code is still listed, on the one seen last, signed out (`claudeListed`), its accounts each saying to sign in again, so it never leaves the Providers list (LeeHom on Discord). Claude Code's own account while still `Held` is never listed that way, since the sign-in it may have left on disk would be served. An account whose every login in use has lapsed is `Provider.SignedOut`: `magpie providers` and the TUI say " is signed out", as the app's row does. | [`logins.go`](../../internal/provider/logins.go), [`logins_on.go`](../../internal/provider/logins_on.go), [`claude_dirs.go`](../../internal/provider/claude_dirs.go) | diff --git a/internal/appdir/codex.go b/internal/appdir/codex.go index 433b4c21f..cfb9b1ecb 100644 --- a/internal/appdir/codex.go +++ b/internal/appdir/codex.go @@ -3,6 +3,7 @@ package appdir import ( "os" "path/filepath" + "strings" ) // CodexHome is the folder Codex CLI keeps its files in: config.toml, @@ -26,3 +27,86 @@ func CodexHomeIn(home string) string { } return filepath.Join(home, ".codex") } + +// CodexHomes are every Codex folder of the user's on this computer: +// CodexHome first, then the others. Codex keeps one ChatGPT sign-in a +// folder (codex-rs login/src/auth/storage.rs: auth.json, or the keychain +// item named by the folder, under CODEX_HOME) and writes its sessions +// there too (rollout/src/lib.rs: sessions/, archived_sessions/), and +// `--profile ` only lays $CODEX_HOME/.config.toml over +// config.toml (config/src/loader/mod.rs), the sign-in shared. So more than +// one account is Codex run with CODEX_HOME set to a folder of each's, +// ~/.codex-work beside ~/.codex, and magpie read only the one it runs +// with (phantom3792 on X: only the default profile's sessions counted, +// and the others' accounts read no quota). +// +// Nothing records those folders, so they are looked for where they are +// made: in the home folder, and beside CodexHome, a folder whose name +// starts with "codex" or ".codex", or one folder down in such a folder +// (~/.codex-profiles/work), that holds auth.json or sessions/. +func CodexHomes() []string { + home, _ := os.UserHomeDir() + return CodexHomesIn(home) +} + +// CodexHomesIn is CodexHomes with home as the user's home folder. +func CodexHomesIn(home string) []string { + main := CodexHomeIn(home) + out := []string{main} + seen := map[string]bool{sameDir(main): true} + add := func(dir string) { + if k := sameDir(dir); !seen[k] { + seen[k] = true + out = append(out, dir) + } + } + roots := []string{home} + if p := filepath.Dir(main); sameDir(p) != sameDir(home) { + roots = append(roots, p) + } + for _, root := range roots { + if root == "" { + continue + } + es, _ := os.ReadDir(root) + for _, e := range es { + name := strings.ToLower(strings.TrimPrefix(e.Name(), ".")) + if !strings.HasPrefix(name, "codex") { + continue + } + dir := filepath.Join(root, e.Name()) + if fi, err := os.Stat(dir); err != nil || !fi.IsDir() { + continue + } + if codexHomeAt(dir) { + add(dir) + continue + } + subs, _ := os.ReadDir(dir) + for _, s := range subs { + if sub := filepath.Join(dir, s.Name()); codexHomeAt(sub) { + add(sub) + } + } + } + } + return out +} + +// codexHomeAt says dir is a folder Codex has run in: it signed in there +// (auth.json) or kept a session there. +func codexHomeAt(dir string) bool { + if fi, err := os.Stat(filepath.Join(dir, "auth.json")); err == nil && fi.Mode().IsRegular() { + return true + } + fi, err := os.Stat(filepath.Join(dir, "sessions")) + return err == nil && fi.IsDir() +} + +// sameDir is the key two names of one folder share: where its links lead. +func sameDir(dir string) string { + if r, err := filepath.EvalSymlinks(dir); err == nil { + dir = r + } + return filepath.Clean(dir) +} diff --git a/internal/appdir/codex_homes_test.go b/internal/appdir/codex_homes_test.go new file mode 100644 index 000000000..4cb3bfc28 --- /dev/null +++ b/internal/appdir/codex_homes_test.go @@ -0,0 +1,43 @@ +package appdir + +import ( + "os" + "path/filepath" + "slices" + "testing" +) + +// The folders Codex is run in with CODEX_HOME set, one account each, are +// found beside ~/.codex: ~/.codex-work, one folder down in +// ~/.codex-profiles, and not a folder Codex never signed in or kept a +// session in, nor ~/.codex a second time through a link. +func TestCodexHomesIn(t *testing.T) { + t.Setenv("CODEX_HOME", "") + home := t.TempDir() + mk := func(rel string) string { + p := filepath.Join(home, rel) + if err := os.MkdirAll(filepath.Dir(p), 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(p, []byte("{}"), 0o600); err != nil { + t.Fatal(err) + } + return filepath.Dir(p) + } + main := mk(".codex/auth.json") + work := mk(".codex-work/auth.json") + nested := filepath.Join(home, ".codex-profiles", "b") + if err := os.MkdirAll(filepath.Join(nested, "sessions"), 0o755); err != nil { + t.Fatal(err) + } + mk(".codex-notes/todo.txt") + mk("projects/auth.json") + if err := os.Symlink(main, filepath.Join(home, ".codex-link")); err != nil { + t.Skip(err) + } + got := CodexHomesIn(home) + if want := []string{main, nested, work}; !slices.Equal(got[:1], want[:1]) || len(got) != 3 || + !slices.Contains(got, nested) || !slices.Contains(got, work) { + t.Fatalf("CodexHomesIn = %v, want %v", got, want) + } +} diff --git a/internal/provider/codex_homes_test.go b/internal/provider/codex_homes_test.go new file mode 100644 index 000000000..b109a76fc --- /dev/null +++ b/internal/provider/codex_homes_test.go @@ -0,0 +1,133 @@ +package provider + +import ( + "context" + "encoding/json" + "io" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "strings" + "sync" + "testing" + "time" +) + +// Codex keeps one ChatGPT sign-in a folder (codex-rs login/src/auth/ +// storage.rs: $CODEX_HOME/auth.json), so a second account is Codex run +// with CODEX_HOME=~/.codex-work. phantom3792 on X: magpie read only the +// default folder's account, and an account added from another folder read +// no quota. This is that layout: ~/.codex signed in to me@example.com (as +// signIn writes it), ~/.codex-work to work@example.com with an access +// token about to run out, and logins.json holding the copy an earlier add +// made, whose refresh token the vendor has since refused. +func TestCodexOtherHomeAccountReadsQuota(t *testing.T) { + home := signIn(t) + t.Setenv("CODEX_HOME", "") + resetLoginUsage(t) + work := filepath.Join(home, ".codex-work") + soon := float64(time.Now().Add(time.Minute).Unix()) + idTok := fakeJWT(map[string]any{"email": "work@example.com", + "https://api.openai.com/auth": map[string]any{"chatgpt_plan_type": "plus", "chatgpt_account_id": "acct-work"}}) + writeFile(t, filepath.Join(work, "auth.json"), map[string]any{ + "auth_mode": "chatgpt", "OPENAI_API_KEY": nil, "last_refresh": "2026-10-20T00:00:00Z", + "tokens": map[string]any{"id_token": idTok, "access_token": fakeJWT(map[string]any{"exp": soon}), + "refresh_token": "r-work", "account_id": "acct-work"}, + }) + // the copy an earlier add kept, its refresh token spent since + dead, _ := json.Marshal(map[string]any{"auth_mode": "chatgpt", + "tokens": map[string]any{"id_token": idTok, "access_token": fakeJWT(map[string]any{"exp": soon}), + "refresh_token": "r-dead", "account_id": "acct-work"}}) + if err := writeLogins([]savedLogin{{Agent: "codex", User: "work@example.com", Plan: "plus", Auth: dead}}); err != nil { + t.Fatal(err) + } + mainAuth, _ := os.ReadFile(filepath.Join(home, ".codex", "auth.json")) + + fresh := fakeJWT(map[string]any{"exp": float64(time.Now().Add(time.Hour).Unix()), "n": "work-2"}) + var mu sync.Mutex + var refreshed []string + fake := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path == "/backend-api/wham/usage" { + if r.Header.Get("Authorization") != "Bearer "+fresh { + w.WriteHeader(http.StatusUnauthorized) + return + } + io.WriteString(w, `{"plan_type":"plus","rate_limit":{"allowed":true,"primary_window":{"used_percent":40,"limit_window_seconds":18000,"reset_after_seconds":600}}}`) + return + } + var body map[string]string + json.NewDecoder(r.Body).Decode(&body) + mu.Lock() + refreshed = append(refreshed, body["refresh_token"]) + mu.Unlock() + if body["refresh_token"] != "r-work" { + w.WriteHeader(http.StatusUnauthorized) + io.WriteString(w, `{"error":"refresh_token_reused"}`) + return + } + json.NewEncoder(w).Encode(map[string]any{"id_token": idTok, "access_token": fresh, "refresh_token": "r-work-2"}) + })) + defer fake.Close() + oldTok, oldBase := codexTokenURL, CodexBase + t.Cleanup(func() { codexTokenURL, CodexBase = oldTok, oldBase }) + codexTokenURL, CodexBase = fake.URL, fake.URL+"/backend-api/codex" + + ForgetAccounts() + var got *Login + for _, l := range Logins("codex") { + if l.User == "work@example.com" { + l := l + got = &l + } + } + if got == nil || got.Active { + t.Fatalf("the ~/.codex-work account isn't listed as a saved one: %+v", Logins("codex")) + } + q := LoginUsage(context.Background(), "codex")["work@example.com"] + if q.Error != "" || len(q.Windows) == 0 { + t.Fatalf("no quota for the ~/.codex-work account: %+v (refreshed with %v)", q, refreshed) + } + mu.Lock() + for _, r := range refreshed { + if r == "r-dead" { + t.Errorf("refreshed with the spent copy's token: %v", refreshed) + } + } + mu.Unlock() + // renewed where Codex keeps it: Codex there goes on with the new one + b, _ := os.ReadFile(filepath.Join(work, "auth.json")) + var a codexAuth + if json.Unmarshal(b, &a) != nil || a.Tokens.RefreshToken != "r-work-2" || a.Tokens.AccessToken != fresh { + t.Errorf("~/.codex-work/auth.json not renewed in place: %s", b) + } + // never written into ~/.codex: one sign-in in two places signs one out + if err := SwitchLogin("codex", "work@example.com"); err == nil || !strings.Contains(err.Error(), work) { + t.Errorf("switch to the other folder's account: %v", err) + } + if now, _ := os.ReadFile(filepath.Join(home, ".codex", "auth.json")); string(now) != string(mainAuth) { + t.Errorf("~/.codex/auth.json was rewritten: %s", now) + } + if err := ForgetLogin("codex", "work@example.com"); err == nil || !strings.Contains(err.Error(), "codex logout") { + t.Errorf("remove the other folder's account: %v", err) + } +} + +// The same account signed in in ~/.codex and in another folder is +// ~/.codex's, listed once. +func TestCodexOtherHomeSameAccountListedOnce(t *testing.T) { + home := signIn(t) + t.Setenv("CODEX_HOME", "") + b, _ := os.ReadFile(filepath.Join(home, ".codex", "auth.json")) + if err := os.MkdirAll(filepath.Join(home, ".codex-copy"), 0o700); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(home, ".codex-copy", "auth.json"), b, 0o600); err != nil { + t.Fatal(err) + } + ForgetAccounts() + ls := Logins("codex") + if len(ls) != 1 || !ls[0].Active || ls[0].home != "" { + t.Fatalf("logins %+v", ls) + } +} diff --git a/internal/provider/codex_switch.go b/internal/provider/codex_switch.go index aa0e5cf1c..913c4ee1a 100644 --- a/internal/provider/codex_switch.go +++ b/internal/provider/codex_switch.go @@ -156,7 +156,8 @@ func NextLogin(ctx context.Context, agent string) (from, to string, back, ok boo case l.Returns: first = &ls[i] } - if !l.Active && l.On && l.Lapsed == "" { + // never one Codex keeps signed in in another folder (switchSavedLogin) + if !l.Active && l.On && l.Lapsed == "" && l.home == "" { spares = append(spares, l) } } diff --git a/internal/provider/login_usage.go b/internal/provider/login_usage.go index 085f0c54c..c24fece61 100644 --- a/internal/provider/login_usage.go +++ b/internal/provider/login_usage.go @@ -450,6 +450,12 @@ func codexLoginAuth(l Login) []byte { defer loginsMu.Unlock() for _, x := range readLogins() { if x.Agent == "codex" && strings.EqualFold(x.User, l.User) { + // as Codex keeps it in its other folder, when it is signed in there + if home := codexHeldIn(x); home != "" { + if b, _, err := readCodexLogin(home, false); err == nil { + return b + } + } return x.Auth } } diff --git a/internal/provider/logins.go b/internal/provider/logins.go index e7e3ef58a..da534af71 100644 --- a/internal/provider/logins.go +++ b/internal/provider/logins.go @@ -61,6 +61,9 @@ type Login struct { // first is the saved Claude account served in the place of Claude // Code's own while it is signed out (claudeStandIn). first bool + // home is the other Codex folder a ChatGPT account is signed in to + // in, Codex's own there (codexHomeLogins): not one to switch ~/.codex to. + home string } type savedLogin struct { @@ -670,26 +673,7 @@ func liveLogin(agent string) (savedLogin, bool) { } switch agent { case "codex": - b, _, err := readCodexLogin(codexHome(), false) - if err != nil { - return savedLogin{}, false - } - var a codexAuth - if json.Unmarshal(b, &a) != nil || a.Tokens.AccessToken == "" || a.AuthMode == "apikey" { - return savedLogin{}, false - } - id := jwtClaims(a.Tokens.IDToken) - user := codexUser(id) - if user == "" { - user = a.Tokens.AccountID - } - if user == "" { - return savedLogin{}, false - } - l := savedLogin{Agent: agent, User: user, Plan: claimString(id, "https://api.openai.com/auth", "chatgpt_plan_type"), - Auth: json.RawMessage(bytes.TrimSpace(b))} - l.User = codexLiveName(user, l.Auth) - return l, true + return codexLoginIn(codexHome()) case "claude": c, _, ok := claudeCredential() if !ok { @@ -718,6 +702,79 @@ func liveLogin(agent string) (savedLogin, bool) { return savedLogin{}, false } +// codexLoginIn is the ChatGPT account Codex is signed in to in its folder +// home, as Codex keeps it there (auth.json, or the keychain item named by +// the folder). +func codexLoginIn(home string) (savedLogin, bool) { + b, _, err := readCodexLogin(home, false) + if err != nil { + return savedLogin{}, false + } + var a codexAuth + if json.Unmarshal(b, &a) != nil || a.Tokens.AccessToken == "" || a.AuthMode == "apikey" { + return savedLogin{}, false + } + id := jwtClaims(a.Tokens.IDToken) + user := codexUser(id) + if user == "" { + user = a.Tokens.AccountID + } + if user == "" { + return savedLogin{}, false + } + l := savedLogin{Agent: "codex", User: user, Plan: claimString(id, "https://api.openai.com/auth", "chatgpt_plan_type"), + Auth: json.RawMessage(bytes.TrimSpace(b))} + l.User = codexLiveName(user, l.Auth) + return l, true +} + +// codexOtherHomes are the user's Codex folders but the one magpie and +// Codex run with (appdir.CodexHomes): one ChatGPT account each, Codex run +// in it with CODEX_HOME set. +func codexOtherHomes() []string { return appdir.CodexHomes()[1:] } + +// codexHomeLogins are the accounts Codex is signed in to in the user's +// other Codex folders, each with its folder as Home: one Codex keeps +// signed in itself, as it does the one in ~/.codex. The one ~/.codex is +// signed in to is that one's, wherever else it is too, and an account in +// two other folders is the first's. +func codexHomeLogins(live savedLogin, haveLive bool) []savedLogin { + var out []savedLogin + for _, home := range codexOtherHomes() { + l, ok := codexLoginIn(home) + if !ok || haveLive && sameLogin(live, l) || slices.ContainsFunc(out, func(o savedLogin) bool { return sameLogin(o, l) }) { + continue + } + l.Home = home + out = append(out, l) + } + return out +} + +// codexHeldIn is the other Codex folder the saved account l is signed in +// to now, as rememberLogins recorded it in Home: the same login, or the +// same refresh token. "" when it is in none. +func codexHeldIn(l savedLogin) string { + if l.Agent != "codex" || l.Home == "" { + return "" + } + in, ok := codexLoginIn(l.Home) + if !ok { + return "" + } + if sameLogin(in, l) || sameRefresh(in.Auth, l.Auth) { + return l.Home + } + return "" +} + +// sameRefresh says two Codex auth.json hold one refresh token. +func sameRefresh(x, y json.RawMessage) bool { + var a, b codexAuth + return json.Unmarshal(x, &a) == nil && json.Unmarshal(y, &b) == nil && + a.Tokens.RefreshToken != "" && a.Tokens.RefreshToken == b.Tokens.RefreshToken +} + // rememberLogins saves the accounts the agents are signed in to now. The // copy of an active account is only a bookmark: the agent keeps refreshing // its own, and a switch saves that fresher one first. @@ -754,6 +811,15 @@ func rememberLogins(force bool) { continue } l, ok := liveLogin(agent) + if agent == "codex" { + // Codex's other folders' accounts (phantom3792 on X: only the + // default profile's account read a quota) + for _, h := range codexHomeLogins(l, ok) { + h.Seen = now + ls = upsertLogin(ls, h) + changed = true + } + } if !ok { if agent == "claude" && claudeLoggedOut(ls) { changed = true @@ -926,6 +992,9 @@ func Logins(agent string) []Login { first := l.Agent == "claude" && strings.EqualFold(standIn, l.User) lg := Login{Agent: l.Agent, User: l.User, Plan: l.Plan, Seen: l.Seen, Active: using, On: using || first || l.On, Paused: (using || first) && pausedOwn(ls, l.Agent, l.User), first: first} + if !using && l.Agent == "codex" { + lg.home = l.Home + } if l.Agent == "claude" { lg.Lapsed = claudeSignedOut(l) } else { @@ -1123,6 +1192,12 @@ func switchSavedLogin(agent, user string) (from string, _ error) { if target == nil { return "", fmt.Errorf("no saved %s account %q", agent, user) } + if home := codexHeldIn(*target); home != "" { + // Codex there keeps it signed in and refreshes it: a copy in + // ~/.codex would be a second holder of one refresh token, and + // whichever refreshed first would sign the other out + return "", fmt.Errorf("%s is signed in to Codex in %s: run Codex there (CODEX_HOME=%s codex) to use it, or turn it on for magpie's requests", target.User, home, home) + } if agent == "claude" { // as Claude Code keeps it, if it has run on the account beside the // one it is signed in to; never one that can't be used, which @@ -1314,6 +1389,14 @@ func forgetLogin(agent, user string) (signedOut bool, err error) { } signedOut = true } + for _, l := range ls { + if l.Agent == agent && strings.EqualFold(l.User, user) { + if home := codexHeldIn(l); home != "" { + // it would be read again from there at the next look + return false, fmt.Errorf("%s is signed in to Codex in %s: sign it out there (CODEX_HOME=%s codex logout) to remove it", l.User, home, home) + } + } + } out := ls[:0] found := false for _, l := range ls { diff --git a/internal/provider/logins_on.go b/internal/provider/logins_on.go index dbc1d65f4..824ab639a 100644 --- a/internal/provider/logins_on.go +++ b/internal/provider/logins_on.go @@ -245,6 +245,17 @@ func renewSaved(ctx context.Context, agent, user string, force bool, stale strin // a switch away saves it afresh from Codex's. return codexTokenRenewing(ctx, codexHome(), stale) } + if home := codexHeldIn(*l); home != "" { + // the same for an account Codex is signed in to in another of + // its folders (CODEX_HOME=~/.codex-work): Codex there refreshes + // it too, so magpie renews it in that folder, never in a copy + // whose refresh token would sign that Codex out + tok, accountID, err := codexTokenRenewing(ctx, home, stale) + if err != nil { + return "", "", fmt.Errorf("%s, signed in to Codex in %s: %w; to sign in again there, run CODEX_HOME=%s codex login", user, home, err, home) + } + return tok, accountID, nil + } var auth []byte switch agent { case "codex": @@ -298,9 +309,7 @@ func heldByCodex(l savedLogin) bool { if sameLogin(live, l) { return true } - var a, b codexAuth - return json.Unmarshal(live.Auth, &a) == nil && json.Unmarshal(l.Auth, &b) == nil && - a.Tokens.RefreshToken != "" && a.Tokens.RefreshToken == b.Tokens.RefreshToken + return sameRefresh(live.Auth, l.Auth) } // savedRefreshFailed words a saved account's failed refresh. One the vendor diff --git a/internal/sessions/codex_homes_test.go b/internal/sessions/codex_homes_test.go new file mode 100644 index 000000000..60482846a --- /dev/null +++ b/internal/sessions/codex_homes_test.go @@ -0,0 +1,45 @@ +package sessions + +import ( + "path/filepath" + "slices" + "testing" + "time" +) + +// A second ChatGPT account is Codex run with its own CODEX_HOME +// (~/.codex-work), which writes that account's rollouts there +// (codex-rs rollout/src/lib.rs: $CODEX_HOME/sessions). phantom3792 on X: +// only the default folder's sessions were counted. Both folders' sessions +// are listed, and both's calls go into the usage ledger. +func TestCodexOtherHomeSessionsCounted(t *testing.T) { + d := setupCalls(t) + home := filepath.Join(filepath.Dir(d.codex), "home") + work := filepath.Join(home, ".codex-work") + writeLines(t, filepath.Join(work, "auth.json"), `{"auth_mode":"chatgpt","tokens":{}}`) + for i, dir := range []string{d.codex, work} { + name := []string{"rollout-2026-10-20T10-00-00-0190aaaa-1111-7222-8333-444455556666.jsonl", + "rollout-2026-10-21T11-00-00-0190bbbb-1111-7222-8333-444455556666.jsonl"}[i] + writeLines(t, filepath.Join(dir, "sessions", "2026", "10", "2"+string(rune('0'+i)), name), + append(cxTurnLines(1, "turn-1", "gpt-6-astra", "low"), + tokenCountLine(3, cxUse(1000, 0, 0, 50, 0), cxUse(1000, 0, 0, 50, 0)))...) + } + // a folder named like one that Codex never ran in is no Codex folder + writeLines(t, filepath.Join(home, ".codex-notes", "todo.txt"), "x") + Reset() + n := 0 + for _, s := range List(0) { + if s.Agent == "codex" { + n++ + } + } + if n != 2 { + t.Fatalf("codex sessions listed: %d, want 2 (~/.codex and ~/.codex-work)", n) + } + if calls := Calls(time.Time{}); len(calls) != 2 { + t.Fatalf("codex calls counted: %d, want 2", len(calls)) + } + if ds := Dirs(); !slices.Contains(ds, work) || slices.Contains(ds, filepath.Join(home, ".codex-notes")) { + t.Fatalf("dirs %v", ds) + } +} diff --git a/internal/sessions/sessions.go b/internal/sessions/sessions.go index 00b047431..4dfa6e6d8 100644 --- a/internal/sessions/sessions.go +++ b/internal/sessions/sessions.go @@ -562,7 +562,8 @@ func distinctPaths(fs []file) []file { // Dirs are the folders the sessions are read from: Claude Code's and // Codex's, and the other agents' where they keep sessions on this computer. func Dirs() []string { - out := []string{ClaudeDir(), CodexDir()} + out := []string{ClaudeDir()} + out = append(out, CodexDirs()...) var named []os.FileInfo for _, d := range []struct{ dir, sessions string }{ {OpenCodeDir(), OpenCodeDir()}, @@ -609,7 +610,21 @@ var rolloutName = regexp.MustCompile(`^rollout-\d{4}-\d{2}-\d{2}T\d{2}-\d{2}-\d{ // zstSuffix ends a rollout the Codex app has compressed. const zstSuffix = ".zst" -func codexFiles() []file { return codexFilesIn(CodexDir()) } +// codexFiles are the rollouts in every Codex folder of the user's +// (appdir.CodexHomes): one ChatGPT account is one CODEX_HOME, and a +// session is written into the folder of the account it ran under, so +// reading CodexDir alone left out every other account's sessions and +// calls (phantom3792 on X). +func codexFiles() []file { + var out []file + for _, dir := range CodexDirs() { + out = append(out, codexFilesIn(dir)...) + } + return distinctPaths(out) +} + +// CodexDirs are every Codex folder of the user's, CodexDir first. +func CodexDirs() []string { return appdir.CodexHomes() } // walkLinked is filepath.WalkDir over root, which can be a link to the // folder: the Codex CLI keeps .codex on another drive by making