provider: several Claude Code and Codex subscriptions — magpie remembers each account it sees signed in, and switches the agent between them in the editor or with magpie accounts (#15)

This commit is contained in:
yetone
2026-09-24 13:55:25 +08:00
parent a6a3ffbe4b
commit 5da0d0d973
9 changed files with 632 additions and 2 deletions
+71
View File
@@ -0,0 +1,71 @@
package main
import (
"fmt"
"strings"
"github.com/yetone/magpie/internal/provider"
)
// accountsCmd: `magpie accounts [agent]`, `magpie accounts switch|forget <agent> <email>`
// — the Claude Code and Codex subscriptions magpie remembers, and switching
// the agent between them.
func accountsCmd(args []string) error {
const usage = "usage: magpie accounts [claude|codex] | magpie accounts switch|forget <claude|codex> <email>"
agentID := func(s string) (string, error) {
switch strings.ToLower(s) {
case "claude", "cc":
return "claude", nil
case "codex":
return "codex", nil
}
return "", fmt.Errorf("%q: only Claude Code and Codex accounts can be switched\n%s", s, usage)
}
if len(args) > 1 && (args[1] == "switch" || args[1] == "forget") {
if len(args) != 4 {
return fmt.Errorf("%s", usage)
}
id, err := agentID(args[2])
if err != nil {
return err
}
if args[1] == "forget" {
if err := provider.ForgetLogin(id, args[3]); err != nil {
return err
}
fmt.Println(green.Render("✓"), "forgot", args[3])
return nil
}
if err := provider.SwitchLogin(id, args[3]); err != nil {
return err
}
fmt.Println(green.Render("✓"), id, "is now signed in as", args[3], muted.Render("· sessions already running keep their account until restarted"))
return nil
}
which := ""
if len(args) > 1 {
id, err := agentID(args[1])
if err != nil {
return err
}
which = id
}
ls := provider.Logins(which)
if len(ls) == 0 {
fmt.Println(muted.Render("no accounts yet ·"), "sign in to Claude Code or Codex and magpie remembers the account")
return nil
}
for _, l := range ls {
mark := " "
if l.Active {
mark = green.Render("● ")
}
plan := ""
if l.Plan != "" {
plan = muted.Render(" · " + l.Plan)
}
fmt.Printf("%s%-7s %s%s\n", mark, l.Agent, l.User, plan)
}
fmt.Println(faint.Render(" add one: sign in to it in the agent (codex login · claude → /login); switch: magpie accounts switch <agent> <email>"))
return nil
}
+3
View File
@@ -508,6 +508,9 @@ body.window .foot { padding-left: 18px; }
.acct { display: flex; align-items: center; gap: 8px; min-height: 26px; font-size: 12.5px; }
.acct .n { font-weight: 500; }
.acct .plan { color: var(--muted); font-size: 11.5px; padding: 1px 6px; border-radius: 5px; background: var(--pill-hover); }
.logins { display: grid; gap: 2px; }
.logins .acct .grow { flex: 1; }
.logins .none { color: var(--muted); font-size: 12.5px; min-height: 26px; display: flex; align-items: center; }
.after-list { display: flex; align-items: center; gap: 8px; padding: 8px 4px 0; flex: none; }
.excluded { display: flex; align-items: flex-start; gap: 10px; padding: 10px 14px 2px; font-size: 11.5px; line-height: 1.45; color: var(--muted); }
.excluded .ic { width: 16px; height: 16px; margin-top: 1px; opacity: .7; }
+24 -2
View File
@@ -1411,6 +1411,7 @@ function renderEditor(p, presetID) {
const acct = el("div", "acct");
acct.append(icon(a.agentIcon), el("span", "n", a.user), el("span", "plan", accountPlan(a)));
ed.append(...field(t("Account"), acct, t("{agent}'s sign-in, read from its own files. Sign out there and this provider goes away.", { agent: a.agentName })));
if (a.logins) ed.append(...field(t("Other accounts"), renderLogins(a), t("To add one, sign in to it in {agent} ({how}); magpie remembers every account it sees there. Sessions already running keep their account until restarted.", { agent: a.agentName, how: a.agent === "codex" ? "codex login" : "claude → /login" })));
ed.append(...field(t("Models"), renderModels(p), ""));
ed.append(...field(t("Endpoints"), renderEndpoints(p, p)));
const bar = el("div", "bar");
@@ -1708,9 +1709,30 @@ function renderModels(p) {
return box;
}
async function providerAction(action, body, okMsg) {
// renderLogins: the agent's other accounts magpie remembers, each one a
// click away from being the one the agent is signed in to.
function renderLogins(a) {
const list = el("div", "logins");
const others = a.logins.filter((l) => !l.active);
if (!others.length) list.append(el("div", "none", t("None yet")));
for (const l of others) {
const row = el("div", "acct");
row.append(el("span", "n", l.user), el("span", "plan", accountPlan({ agent: a.agent, plan: l.plan })), el("span", "grow"));
const forget = el("button", "text", t("Forget"));
forget.title = t("magpie forgets this account's sign-in; the account itself is untouched");
forget.onclick = () => providerAction("forget", { agent: a.agent, user: l.user }, t("{user} forgotten", { user: l.user }), "login/");
const use = el("button", "text", t("Switch"));
use.title = t("Sign {agent} in to this account", { agent: a.agentName });
use.onclick = () => { use.classList.add("busy"); providerAction("switch", { agent: a.agent, user: l.user }, t("{agent} is now signed in as {user}", { agent: a.agentName, user: l.user }), "login/"); };
row.append(forget, use);
list.append(row);
}
return list;
}
async function providerAction(action, body, okMsg, base = "provider/") {
try {
providers = await api("provider/" + action, body);
providers = await api(base + action, body);
editing = null;
draft = null;
importing = null;
+9
View File
@@ -120,6 +120,15 @@ const I18N = {
"Anthropic compatible": "Anthropic 兼容",
"the root URL, what ANTHROPIC_BASE_URL would take": "根地址,即 ANTHROPIC_BASE_URL 的值",
"Account": "账号",
"Other accounts": "其他账号",
"To add one, sign in to it in {agent} ({how}); magpie remembers every account it sees there. Sessions already running keep their account until restarted.": "要添加账号,在 {agent} 里登录它({how});magpie 会记住在那里见过的每个账号。已在运行的会话会保持原账号,重启后才切换。",
"None yet": "暂无",
"Forget": "忘记",
"magpie forgets this account's sign-in; the account itself is untouched": "magpie 忘掉这个账号的登录信息;账号本身不受影响",
"{user} forgotten": "已忘记 {user}",
"Switch": "切换",
"Sign {agent} in to this account": "让 {agent} 登录到这个账号",
"{agent} is now signed in as {user}": "{agent} 已切换为 {user}",
"{agent}'s sign-in, read from its own files. Sign out there and this provider goes away.": "{agent} 的登录信息,读取自它自己的文件。在那里退出登录,此供应商即消失。",
"Models": "模型",
"Endpoints": "端点",
+27
View File
@@ -58,6 +58,8 @@ type accountJSON struct {
Agent string `json:"agent"` // the agent's id
Name string `json:"agentName"` // the agent's name, for "from Codex CLI's sign-in"
Icon string `json:"agentIcon"`
// Logins are the agent's accounts magpie remembers, to switch between
Logins []provider.Login `json:"logins,omitempty"`
}
type providerAgent struct {
@@ -133,6 +135,7 @@ func providerInfo(p provider.Provider, agents []*agent.Agent) providerJSON {
if ag, err := agent.Find(a.Agent); err == nil {
out.Account.Name, out.Account.Icon = ag.Name, ag.Icon
}
out.Account.Logins = provider.Logins(a.Agent)
}
exposed := map[string]bool{}
for _, m := range p.Exposed() {
@@ -321,6 +324,30 @@ func providerRoutes(mux *http.ServeMux, w Windows, gw *gateway.Server) {
}
writeJSON(rw, providersState(gw))
})
// Switching the account an agent is signed in to, among those magpie
// remembers, and forgetting one.
mux.HandleFunc("POST /api/login/{action}", func(rw http.ResponseWriter, r *http.Request) {
var in struct{ Agent, User string }
if err := json.NewDecoder(r.Body).Decode(&in); err != nil {
fail(rw, err)
return
}
var err error
switch r.PathValue("action") {
case "switch":
err = provider.SwitchLogin(in.Agent, in.User)
case "forget":
err = provider.ForgetLogin(in.Agent, in.User)
default:
http.NotFound(rw, r)
return
}
if err != nil {
fail(rw, err)
return
}
writeJSON(rw, providersState(gw))
})
mux.HandleFunc("POST /api/open", func(rw http.ResponseWriter, r *http.Request) {
var in struct{ URL string }
_ = json.NewDecoder(r.Body).Decode(&in)
+1
View File
@@ -514,6 +514,7 @@ func claudeToken(ctx context.Context) (string, error) {
// Accounts lists the signed-in agents as providers.
func Accounts() []Provider {
rememberLogins(false)
home, _ := os.UserHomeDir()
cfg := os.Getenv("XDG_CONFIG_HOME")
if cfg == "" {
+367
View File
@@ -0,0 +1,367 @@
package provider
// Several subscriptions per agent. magpie keeps following each agent's own
// sign-in; it also remembers every Codex and Claude Code account it has
// seen signed in, so the user can switch back to one without signing in
// again. A switch moves the saved credentials into the agent's own store
// and saves the ones they replace, so each account's refresh token lives in
// exactly one place: the vendor rotates it on every refresh, and two holders
// of the same one would sign each other out.
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"os"
"path/filepath"
"sort"
"strings"
"sync"
"time"
)
// Login is a remembered subscription account, without its secrets.
type Login struct {
Agent string `json:"agent"`
User string `json:"user"`
Plan string `json:"plan,omitempty"`
Seen time.Time `json:"seen"`
Active bool `json:"active"` // the agent is signed in to this one now
}
type savedLogin struct {
Agent string `json:"agent"`
User string `json:"user"`
Plan string `json:"plan,omitempty"`
Seen time.Time `json:"seen"`
// Auth is the agent's credential blob as the agent stores it: Codex's
// auth.json, Claude Code's keychain item / .credentials.json.
Auth json.RawMessage `json:"auth"`
// Profile is Claude Code's oauthAccount from .claude.json, which says
// whose credentials those are.
Profile json.RawMessage `json:"profile,omitempty"`
}
var (
loginsMu sync.Mutex
loginsSeenAt time.Time
)
// switchable agents: those whose sign-in magpie can save and put back.
var loginAgents = []string{"claude", "codex"}
func loginsPath() string { return filepath.Join(filepath.Dir(Path()), "logins.json") }
func readLogins() []savedLogin {
var out []savedLogin
b, err := os.ReadFile(loginsPath())
if err == nil {
_ = json.Unmarshal(b, &out)
}
return out
}
func writeLogins(ls []savedLogin) error {
sort.SliceStable(ls, func(i, j int) bool {
if ls[i].Agent != ls[j].Agent {
return ls[i].Agent < ls[j].Agent
}
return strings.ToLower(ls[i].User) < strings.ToLower(ls[j].User)
})
b, err := json.MarshalIndent(ls, "", " ")
if err != nil {
return err
}
return writePrivate(loginsPath(), append(b, '\n'))
}
// writePrivate replaces a file readable by the user alone, atomically, so
// an agent reading it at that moment sees either version, never half.
func writePrivate(path string, b []byte) error {
if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil {
return err
}
tmp, err := os.CreateTemp(filepath.Dir(path), "."+filepath.Base(path)+".*")
if err != nil {
return err
}
defer os.Remove(tmp.Name())
if _, err := tmp.Write(b); err != nil {
tmp.Close()
return err
}
if err := tmp.Chmod(0o600); err != nil {
tmp.Close()
return err
}
if err := tmp.Close(); err != nil {
return err
}
return os.Rename(tmp.Name(), path)
}
func upsertLogin(ls []savedLogin, l savedLogin) []savedLogin {
for i := range ls {
if ls[i].Agent == l.Agent && strings.EqualFold(ls[i].User, l.User) {
ls[i] = l
return ls
}
}
return append(ls, l)
}
func codexAuthPath() string {
home, _ := os.UserHomeDir()
return filepath.Join(home, ".codex", "auth.json")
}
// claudeProfilePath is Claude Code's global state file, which holds the
// signed-in account's identity next to much else.
func claudeProfilePath() string {
if dir := os.Getenv("CLAUDE_CONFIG_DIR"); dir != "" {
return filepath.Join(dir, ".claude.json")
}
home, _ := os.UserHomeDir()
return filepath.Join(home, ".claude.json")
}
func readClaudeProfile() (map[string]any, error) {
b, err := os.ReadFile(claudeProfilePath())
if err != nil {
return nil, err
}
d := json.NewDecoder(bytes.NewReader(b))
d.UseNumber() // numbers go back exactly as they came
var m map[string]any
if err := d.Decode(&m); err != nil {
return nil, err
}
return m, nil
}
// liveLogin reads the account an agent is signed in to now.
func liveLogin(agent string) (savedLogin, bool) {
switch agent {
case "codex":
b, err := os.ReadFile(codexAuthPath())
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 := claimString(id, "email")
if user == "" {
user = a.Tokens.AccountID
}
if user == "" {
return savedLogin{}, false
}
return savedLogin{Agent: agent, User: user, Plan: claimString(id, "https://api.openai.com/auth", "chatgpt_plan_type"),
Auth: json.RawMessage(bytes.TrimSpace(b))}, true
case "claude":
c, _, ok := claudeCredential()
if !ok {
return savedLogin{}, false
}
b, err := c.marshal()
if err != nil {
return savedLogin{}, false
}
l := savedLogin{Agent: agent, Plan: c.OAuth.SubscriptionType, Auth: b}
if m, err := readClaudeProfile(); err == nil {
if acct, ok := m["oauthAccount"].(map[string]any); ok {
l.User, _ = acct["emailAddress"].(string)
l.Profile, _ = json.Marshal(acct)
}
}
if l.User == "" {
user, _, signedOut := claudeIdentity()
if signedOut {
return savedLogin{}, false
}
l.User = user
}
if l.User == "" {
return savedLogin{}, false
}
return l, true
}
return savedLogin{}, false
}
// 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.
func rememberLogins(force bool) {
loginsMu.Lock()
defer loginsMu.Unlock()
if !force && time.Since(loginsSeenAt) < 30*time.Second {
return
}
loginsSeenAt = time.Now()
ls := readLogins()
changed := false
for _, agent := range loginAgents {
l, ok := liveLogin(agent)
if !ok {
continue
}
l.Seen = time.Now().UTC().Truncate(time.Second)
ls = upsertLogin(ls, l)
changed = true
}
if changed {
_ = writeLogins(ls)
}
}
// Logins lists the remembered accounts of an agent ("" for every one),
// the active one flagged.
func Logins(agent string) []Login {
rememberLogins(false)
loginsMu.Lock()
defer loginsMu.Unlock()
active := map[string]string{}
for _, a := range loginAgents {
if l, ok := liveLogin(a); ok {
active[a] = l.User
}
}
var out []Login
for _, l := range readLogins() {
if agent != "" && l.Agent != agent {
continue
}
out = append(out, Login{Agent: l.Agent, User: l.User, Plan: l.Plan, Seen: l.Seen,
Active: strings.EqualFold(active[l.Agent], l.User)})
}
return out
}
// SwitchLogin signs an agent in to a remembered account. Sessions of the
// agent that are already running keep the account they started with until
// they restart.
func SwitchLogin(agent, user string) error {
loginsMu.Lock()
defer loginsMu.Unlock()
ls := readLogins()
var target *savedLogin
for i := range ls {
if ls[i].Agent == agent && strings.EqualFold(ls[i].User, user) {
target = &ls[i]
}
}
if target == nil {
return fmt.Errorf("no saved %s account %q", agent, user)
}
want := *target
if live, ok := liveLogin(agent); ok {
if strings.EqualFold(live.User, want.User) {
return nil
}
// the credentials being replaced, as fresh as the agent has them
live.Seen = time.Now().UTC().Truncate(time.Second)
ls = upsertLogin(ls, live)
if err := writeLogins(ls); err != nil {
return err
}
}
var err error
switch agent {
case "codex":
err = writePrivate(codexAuthPath(), append(bytes.TrimSpace(want.Auth), '\n'))
case "claude":
err = putClaudeLogin(want)
default:
err = fmt.Errorf("%s accounts can't be switched", agent)
}
if err != nil {
return err
}
loginsSeenAt = time.Time{}
forgetAccountCaches()
return nil
}
func putClaudeLogin(l savedLogin) error {
c, ok := parseClaudeCredentials(l.Auth)
if !ok {
return errors.New("the saved Claude Code sign-in is unreadable")
}
_, loc, found := readClaudeCredential()
if !found {
// signed out: put it where Claude Code keeps it on this system
dir := os.Getenv("CLAUDE_CONFIG_DIR")
if dir == "" {
home, _ := os.UserHomeDir()
dir = filepath.Join(home, ".claude")
}
loc = claudeCredentialLocation{path: filepath.Join(dir, ".credentials.json")}
if claudeKeychain {
loc = claudeCredentialLocation{keychain: true, account: os.Getenv("USER")}
}
}
if err := saveClaudeCredential(loc, c); err != nil {
return err
}
if len(l.Profile) == 0 {
return nil
}
m, err := readClaudeProfile()
if err != nil {
if !os.IsNotExist(err) {
return err
}
m = map[string]any{}
}
d := json.NewDecoder(bytes.NewReader(l.Profile))
d.UseNumber()
var acct map[string]any
if err := d.Decode(&acct); err != nil {
return err
}
m["oauthAccount"] = acct
b, err := json.MarshalIndent(m, "", " ")
if err != nil {
return err
}
return writePrivate(claudeProfilePath(), append(b, '\n'))
}
// ForgetLogin drops a remembered account. The one an agent is signed in to
// now can't be forgotten; it would only be remembered again.
func ForgetLogin(agent, user string) error {
loginsMu.Lock()
defer loginsMu.Unlock()
if live, ok := liveLogin(agent); ok && strings.EqualFold(live.User, user) {
return fmt.Errorf("%s is signed in to %s now; switch to another account first", agent, user)
}
ls := readLogins()
out := ls[:0]
found := false
for _, l := range ls {
if l.Agent == agent && strings.EqualFold(l.User, user) {
found = true
continue
}
out = append(out, l)
}
if !found {
return fmt.Errorf("no saved %s account %q", agent, user)
}
return writeLogins(out)
}
// forgetAccountCaches makes the next look at the accounts read them afresh.
func forgetAccountCaches() {
forgetClaudeCredential()
forgetClaudeStatus()
subscriptionUsageCache.Lock()
subscriptionUsageCache.at = time.Time{}
subscriptionUsageCache.data = nil
subscriptionUsageCache.Unlock()
}
+126
View File
@@ -0,0 +1,126 @@
package provider
import (
"encoding/json"
"os"
"path/filepath"
"strings"
"testing"
"time"
)
func codexSignIn(t *testing.T, home, email, refresh string) {
t.Helper()
exp := float64(time.Now().Add(time.Hour).Unix())
writeFile(t, filepath.Join(home, ".codex", "auth.json"), map[string]any{
"auth_mode": "chatgpt",
"tokens": map[string]any{
"id_token": fakeJWT(map[string]any{"email": email, "https://api.openai.com/auth": map[string]any{"chatgpt_plan_type": "plus"}}),
"access_token": fakeJWT(map[string]any{"exp": exp}),
"refresh_token": refresh, "account_id": "acct-" + email,
},
})
}
func loginUsers(ls []Login) (users []string, active string) {
for _, l := range ls {
users = append(users, l.User)
if l.Active {
active = l.User
}
}
return
}
func TestCodexLogins(t *testing.T) {
home := signIn(t)
rememberLogins(true)
codexSignIn(t, home, "work@example.com", "r-work")
rememberLogins(true)
users, active := loginUsers(Logins("codex"))
if strings.Join(users, ",") != "me@example.com,work@example.com" || active != "work@example.com" {
t.Fatalf("logins %v, active %q", users, active)
}
if fi, err := os.Stat(loginsPath()); err != nil || fi.Mode().Perm() != 0o600 {
t.Fatalf("logins.json mode: %v %v", fi, err)
}
// the agent refreshes the active login in place; a switch keeps that
codexSignIn(t, home, "work@example.com", "r-work-2")
if err := SwitchLogin("codex", "ME@example.com"); err != nil {
t.Fatal(err)
}
var a codexAuth
readJSON(filepath.Join(home, ".codex", "auth.json"), &a)
if a.Tokens.RefreshToken != "r" {
t.Fatalf("auth.json not switched: %q", a.Tokens.RefreshToken)
}
if _, active := loginUsers(Logins("codex")); active != "me@example.com" {
t.Fatalf("active after switch: %q", active)
}
for _, l := range readLogins() {
if l.User == "work@example.com" && !strings.Contains(string(l.Auth), "r-work-2") {
t.Fatalf("the replaced login lost its refreshed token: %s", l.Auth)
}
}
if err := ForgetLogin("codex", "me@example.com"); err == nil {
t.Fatal("forgot the active login")
}
if err := ForgetLogin("codex", "work@example.com"); err != nil {
t.Fatal(err)
}
if users, _ := loginUsers(Logins("codex")); strings.Join(users, ",") != "me@example.com" {
t.Fatalf("after forget: %v", users)
}
if err := SwitchLogin("codex", "nobody@example.com"); err == nil {
t.Fatal("switched to an unknown login")
}
}
func TestClaudeLogins(t *testing.T) {
home := claudeHome(t)
cred := claudeSignIn(t, home, time.Now().Add(time.Hour))
profile := filepath.Join(home, ".claude.json")
writeFile(t, profile, map[string]any{
"numStartups": 1234567890123,
"oauthAccount": map[string]any{"emailAddress": "a@example.com", "accountUuid": "u-a"},
})
rememberLogins(true)
// signing in to another account in Claude Code
writeFile(t, cred, map[string]any{
"claudeAiOauth": map[string]any{"accessToken": "sk-ant-oat01-b", "refreshToken": "sk-ant-ort01-b",
"expiresAt": time.Now().Add(time.Hour).UnixMilli(), "subscriptionType": "pro"},
"mcpOAuth": map[string]any{"keep": true},
})
writeFile(t, profile, map[string]any{
"numStartups": 1234567890123,
"oauthAccount": map[string]any{"emailAddress": "b@example.com", "accountUuid": "u-b"},
})
forgetClaudeCredential()
rememberLogins(true)
users, active := loginUsers(Logins("claude"))
if strings.Join(users, ",") != "a@example.com,b@example.com" || active != "b@example.com" {
t.Fatalf("logins %v, active %q", users, active)
}
if err := SwitchLogin("claude", "a@example.com"); err != nil {
t.Fatal(err)
}
var c map[string]any
readJSON(cred, &c)
if o, _ := c["claudeAiOauth"].(map[string]any); o["refreshToken"] != "sk-ant-ort01-old" {
t.Fatalf("credentials not switched: %v", o)
}
b, _ := os.ReadFile(profile)
var p map[string]json.RawMessage
json.Unmarshal(b, &p)
if string(p["numStartups"]) != "1234567890123" || !strings.Contains(string(p["oauthAccount"]), "a@example.com") {
t.Fatalf(".claude.json after switch: %s", b)
}
if _, active := loginUsers(Logins("claude")); active != "a@example.com" {
t.Fatalf("active after switch: %q", active)
}
}
+4
View File
@@ -46,6 +46,8 @@ const usage = `magpie — one place to pick every agent's model
magpie provider key|models|test|rm <id>
magpie import [-y] <link> add the provider a magpie://import?… link describes
magpie models every model agents can pick, as provider/model
magpie accounts [agent] the Claude Code and Codex subscriptions magpie remembers
magpie accounts switch <agent> <email> sign the agent in to another of them
magpie serve run the gateway alone (the app runs it too)
magpie usage [today|7d|30d|all] tokens and cost per agent and model (30d)
@@ -130,6 +132,8 @@ func run(args []string) error {
return models()
case "serve":
return serve()
case "accounts", "account":
return accountsCmd(args)
case "usage":
return usageCmd(args)
case "update":