diff --git a/docs/subsystems/claude-subscription-bridge.md b/docs/subsystems/claude-subscription-bridge.md index fadfcc184..a3b57c0f5 100644 --- a/docs/subsystems/claude-subscription-bridge.md +++ b/docs/subsystems/claude-subscription-bridge.md @@ -53,6 +53,8 @@ to use an http:// proxy. The `settings.json` env that magpie writes for the user's own Claude Code sessions leaves a SOCKS proxy out (see [Providers and accounts](providers-accounts.md)). +A saved account added by a setup-token (see [Providers and accounts](providers-accounts.md)) has no sign-in in its config directory. `inClaudeDir`, which builds the env of every run in a saved account's directory (a turn's run, the warm-up, `askClaude`, `/usage`), drops any `CLAUDE_CODE_OAUTH_TOKEN` it was given and sets it to `provider.ClaudeDirToken(configDir)` when that directory is a token account's: the token reaches the real Claude Code there and nowhere else, never on its command line, never in a log, and never to Claude Code's own account. magpie asks Anthropic nothing with it; the entrypoint and everything else about the run are as for any account. + The helper offers each of the client's tools under `bridgeToolName` (`bridgeTools`), which Claude Code calls `mcp__magpie__`. Claude Code keeps only `[A-Za-z0-9_-]` of an MCP tool's name, so a name it would change diff --git a/docs/subsystems/providers-accounts.md b/docs/subsystems/providers-accounts.md index 9857b8e31..77325fe18 100644 --- a/docs/subsystems/providers-accounts.md +++ b/docs/subsystems/providers-accounts.md @@ -47,6 +47,7 @@ keys and accounts per request is in [Gateway routing and fallback](gateway-routi | 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) | | Sign-in in magpie | `StartSignIn` runs the vendor's own browser OAuth with its client and takes the tokens at a callback on this machine. A browser that can't reach that callback (magpie on a server or in Docker) ends on a page that won't load; its address, pasted (`SubmitSignInCallback`), goes through the same callback handler (`pastedCallback`). ChatGPT's sign-in comes back only to port 1455; when that port can't be opened, the sign-in still starts and waits for the pasted address alone, and says why in `CallbackBlocked` with the port in `CallbackPort`: `reserved` for Windows' WSAEACCES on a port in a range it excludes for Hyper-V, WSL or Docker, `busy` for anything else, such as another program holding it (`callbackBlocked`, #1782). A plugin's browser sign-in (`auto`) whose page names a port on this machine to come back to takes its pasted address too: magpie opens it there on 127.0.0.1, for the plugin's own listener (`pluginCallback`, `loopbackPorts`); Command Code's page posts its key from script, so it offers the API key way instead. A Claude account is signed in by Claude Code itself. Signing in brings back an account removed from magpie (`ShowAccount`). A sign-in started in magpie (`StartSignIn`, `StartPluginSignIn`) reads as done (`SignInStatus`, `WaitSignIn`) only after `finish` has run `ShowAccount` for its account, so the window, which opens the account as soon as it sees done, finds it listed. If providers.json can't be written then, the account stays hidden and the sign-in still ends done. Signing in to a plugin's provider from the command line (`pluginLogin`, with a key or the browser) brings it back too. It also takes off the mark a sign-in its vendor turned away left on the account (`Lapsed`) and shows again the agent's own account removed in magpie (`clearPluginLapse`). The window's plugin sign-in does the same with the browser (`pluginDone`, then `finish`) or with a key (`PluginAPIKey`); a key and the command line share these steps in `PluginSignedIn`. A sign-in leaves through the proxy the account's own requests will use (#1663): `ProxyOfLogin` (the account's, else the subscription's, else the global one) for the account being signed in again, the subscription's for a new one. Every request of the flow goes through `signInFlow.via`, Claude Code's own login gets it as *_PROXY (`netproxy.EnvWith`), and a plugin's sign-in runs its fetch under that proxy (`via` in `host.js`; `plugins_cli.go` for the command line). The window's sign-in box shows it as a "Proxy: …" link (`signInProxyLink`, the app menu, no userinfo shown) with Global, Direct, the subscription's and each account's proxy, or a typed one; picking one starts the sign-in again through it (`SignInOptions.Proxy`), and when it ends the pick is kept as the account's (`keepSignInProxy`: the subscription's own when it is its only account, else the account's entry). Global isn't offered while the subscription has a proxy and other accounts, since nothing could keep it. The browser's own leg goes through the browser's network, not magpie's. Signing out leaves through the same exit: a ChatGPT account's refresh token is revoked through its own proxy, read before the account is forgotten (`forgetSIWCLogin`), and Devin's CLI, asked who is signed in or for its models, runs with the account's proxy (`devinCommand`, `devinProxy`). | [`signin.go`](../../internal/provider/signin.go), [`claude_signin.go`](../../internal/provider/claude_signin.go), [`pluginsignin.go`](../../internal/provider/pluginsignin.go), [`pluginsignin_paste.go`](../../internal/provider/pluginsignin_paste.go), [`proxy.go`](../../internal/provider/proxy.go), [`plugins_cli.go`](../../internal/cli/plugins_cli.go) | | Import from files | `ImportLogins` (ChatGPT, Claude), `ImportGoogleAccounts` (Antigravity) and `ImportFactoryKeys` take other tools' files, from the window (`signin/import`) or `magpie accounts import` (#1453). ChatGPT reads Codex's `auth.json`, CLIProxyAPI's and Cockpit Tools' files, Sub2API's export (`sub2apiEntry`) and codexbar's `~/.codexbar/config.json` (`codexbarEntries`: the `openai_oauth` provider's accounts and `openAI.remoteConnectionAccounts`, the workspace from `openAIAccountId`). Each ChatGPT and Google sign-in is refreshed before it is added, so the tool the file came from is signed out of it; both surfaces say so first, and the command imports nothing without `--yes` or a yes. Claude reads CLIProxyAPI's files and Sub2API's export, whose Claude account says its email as Anthropic does, `email_address`, in `credentials` or `extra`, and keeps its `scope`, `account_uuid` and `org_uuid` as Claude Code's scopes, `accountUuid` and `organizationUuid` (#1975); a file with no email is refused, as Claude Code's own `.credentials.json` is. Claude's are kept as the file has them. A refresh token magpie holds already is `exists`, never refreshed; accounts are matched by email and workspace, or for Claude organization (`sameLogin`). An entry with an access token and no refresh token is refused (`accessOnly`). One file of several that holds no account is a failed row with its place (`ImportedAccount.File`), never skipped. The files are only read. | [`login_import.go`](../../internal/provider/login_import.go), [`google_import.go`](../../internal/provider/google_import.go), [`factory_key.go`](../../internal/provider/factory_key.go), [`accounts_cli.go`](../../internal/cli/accounts_cli.go) | +| Claude setup-token | A Claude account can be added from the long-lived token `claude setup-token` prints (sfss5362 on X), which Claude Code takes in `CLAUDE_CODE_OAUTH_TOKEN` (the window's *Use a setup-token instead…* and *Add an account by setup-token…*, `POST /api/signin/claude-token`). `AddClaudeSetupToken` keeps it in `logins.json` as `{"setupToken":…}`, named `Claude setup-token <6 hex of its hash>` (it tells no email), on beside the others; the same token again is the same account. Such a token has the inference scope only: Claude Code's `auth status` says `oauth_token` with no email or plan, and its `/usage` prints the API cost view, so `/usage` is never run for it and its allowance is unknown (`errClaudeSetupToken`, kept by `passing` as saying nothing about the account) until a reply's rate-limit event tells it. Its config directory (`claudeTokenDir`) holds no `.credentials.json`, which Claude Code could fall back to on a refused token. Claude Code itself is never signed in to it: `addLogin`, `switchLogin`, `putClaudeLogin`, `SetKeepLoginAs`, `NextLogin` and `signInToFirst` pass it over, and the window shows Remove and *magpie only* in place of Use and Make first. Not tried with a real token. | [`claude_setup_token.go`](../../internal/provider/claude_setup_token.go), [`claude_subscription.go`](../../internal/gateway/claude_subscription.go) (`inClaudeDir`), [`providers.go`](../../internal/gui/providers.go) | | Switch accounts only | magpie as a Claude Code (or Codex) account switcher alone, with nothing connected (the owner on X; growaiskills, Rennix7t). In the window, the Agents row of a Claude Code or Codex not connected says the account it is signed in to (`switchEntry` in app.js, from the providers list `prefetchProviders` reads at start, so `/api/state` reads no keychain for it), also when magpie has no models to connect (`switchable`, before the `empty` line). Its menu, headed *Switch accounts only*, lists the agent's saved accounts: a pick goes through `POST /api/login/switch` (`SwitchLogin`), or `provider/keeplogin` with `keepLoginAs` when the agent is kept signed in to an account of the user's choosing, as the account rows do; the button says *Switched* for five seconds and the status line says new sessions use the account, one already open keeps its own until started again. *Only switch {agent}'s sign-in* (`SwitchOnly` above, `provider/switchonly`) is a ticked item there (Codex: with more than one usable account, as under Providers), and the row then says *Not connected · switching accounts only*. *Manage accounts…*, and a pick whose sign-in lapsed, open Providers › the agent. A Codex failing over (#1385) has it in place of the old *ChatGPT accounts* button. Not in the tray panel (it reads no provider list), not on a WSL twin's row, not on a connected agent's. | [`app.js`](../../internal/gui/assets/app.js), [`logins.go`](../../internal/provider/logins.go) | | Used-up switch | When the account Codex or Claude Code is signed in to has used its allowance, the agent is signed in to the next account that is on and has room (#208). For Codex, *Only switch Codex's sign-in* (`SwitchOnly`, `SetSwitchOnly`) keeps magpie's `openai_base_url` failover out of Codex's config, so the switch is all magpie does (#1907); an unreadable providers.json reads as switch-only, so the failover is not written on a guess. For Claude, the same setting keeps the accounts to Claude Code (`Provider.KeptToAgent`): `On()` is false, so the gateway, catalog and groups serve nothing on them, while switching and usage, gated by `leftAlone` on the raw `Off`, go on. No request of a saved Claude account passes magpie then, so one Claude Code wasn't signed in to since has no reading: once the account Claude Code is on is spent, `NextLogin` reads such a spare (`readSpare`, `spareRead` in `claudeWindows`) by Claude Code's own `/usage` in the account's directory, in order and only till one has room; a spare read once is not read again, and one whose read failed waits `claudeUsageWait` (cn_Vincentzyx on X, `TestClaudeSwitchOnlyReadsUnreadSpares`). Codex's spares are read through their saved tokens and had no such gap. | [`codex_switch.go`](../../internal/provider/codex_switch.go) | | Claude Code's proxy | Claude Code on its own subscription asks Anthropic itself, through the proxy its env names. While any Claude account has a proxy of its own (`AccountProxies`), the `env` of Claude Code's `settings.json` names the proxy of the account it is signed in to (#1807): `HTTPS_PROXY` and `HTTP_PROXY` set to that account's own, else the subscription's `Proxy` (`ProxyOfLogin`), and `NO_PROXY` to loopback; none for `direct` or a SOCKS proxy, which Claude Code can't use. It is written on every switch (`switchLogin`, the user's or `SwitchWhenSpent`), when the Claude subscription is saved, and at the gateway's look every `loginSwitchEvery` (a sign-in made in Claude Code itself). Claude Code reads its env at start, so only sessions started after the switch take it. A proxy key the user set (in either case) is theirs: magpie then writes none and takes out none of theirs. What magpie wrote is kept in `claude-proxy-env.json`, and a key is magpie's only while it holds that value. A `settings.json` that doesn't parse is left as it is. Its log lines name the proxy through `netproxy.Redact`, without its user and password (#1886); the env gets it whole. | [`claude_proxy_env.go`](../../internal/provider/claude_proxy_env.go) | diff --git a/internal/gateway/claude_setup_token_test.go b/internal/gateway/claude_setup_token_test.go new file mode 100644 index 000000000..5dd5edf77 --- /dev/null +++ b/internal/gateway/claude_setup_token_test.go @@ -0,0 +1,105 @@ +package gateway + +import ( + "context" + "encoding/json" + "os" + "path/filepath" + "runtime" + "strings" + "testing" + + "github.com/yetone/magpie/internal/provider" + "github.com/yetone/magpie/internal/testenv" +) + +const gwSetupToken = "sk-ant-oat01-gatewaysetuptoken-0123456789abcdefghijklmnop" + +// A Claude account added by a setup-token (sfss5362 on X) is served by the +// real Claude Code, given the token in CLAUDE_CODE_OAUTH_TOKEN for runs in +// that account's own config directory and no other: never on the command +// line, never to Claude Code's own account or another saved one, and never +// the token the shell happens to hold. +func TestClaudeSetupTokenReachesItsOwnRunsOnly(t *testing.T) { + if runtime.GOOS == "windows" { + t.Skip("a shell script stands in for Claude Code") + } + home := t.TempDir() + t.Setenv("HOME", home) + t.Setenv("USERPROFILE", home) + t.Setenv("XDG_CONFIG_HOME", filepath.Join(home, ".config")) + t.Setenv("XDG_CACHE_HOME", filepath.Join(home, ".cache")) + t.Setenv("XDG_DATA_HOME", filepath.Join(home, ".local", "share")) + provider.ForgetAccounts() + t.Cleanup(provider.ForgetAccounts) + + user, err := provider.AddClaudeSetupToken(gwSetupToken) + if err != nil { + t.Fatal(err) + } + provider.ForgetAccounts() + // the directory the gateway is handed for the account, as a turn is + var dir string + for _, p := range provider.All() { + if p.Account != nil && p.Account.Agent == "claude" && p.Account.User == user { + d, _, err := p.Account.Token(context.Background()) + if err != nil { + t.Fatal(err) + } + dir = d + } + } + if dir == "" { + t.Fatalf("no provider serves %q", user) + } + if _, err := os.Stat(filepath.Join(dir, ".credentials.json")); !os.IsNotExist(err) { + t.Fatalf("a sign-in sits in the token account's directory: %v", err) + } + + bin := t.TempDir() + log := filepath.Join(bin, "log") + text := "Current session: 13% used · resets Oct 1 at 3:30pm (UTC)\n" + b, _ := json.Marshal(map[string]any{"type": "result", "is_error": false, "num_turns": 0, "result": text}) + os.WriteFile(filepath.Join(bin, "out"), b, 0o644) + script := "#!/bin/sh\n" + + "{ printf 'args:'; for a in \"$@\"; do printf '[%s]' \"$a\"; done; echo; echo \"dir:$CLAUDE_CONFIG_DIR\"; echo \"token:$CLAUDE_CODE_OAUTH_TOKEN\"; } >> " + log + "\n" + + "cat " + filepath.Join(bin, "out") + "\n" + testenv.Program(t, filepath.Join(bin, "claude"), script) + t.Setenv("PATH", bin+string(os.PathListSeparator)+os.Getenv("PATH")) + t.Setenv("CLAUDE_CODE_OAUTH_TOKEN", "leaked") + + run := func(configDir string) string { + t.Helper() + os.Remove(log) + if _, err := claudeUsage(context.Background(), configDir); err != nil { + t.Fatalf("%q: %v", configDir, err) + } + got, _ := os.ReadFile(log) + return string(got) + } + if got := run(dir); !strings.Contains(got, "token:"+gwSetupToken+"\n") || !strings.Contains(got, "dir:"+dir+"\n") { + t.Fatalf("the token account's run wasn't given its token:\n%s", got) + } else if args, _, _ := strings.Cut(got, "\n"); strings.Contains(args, gwSetupToken) { + t.Fatalf("the token went on the command line: %s", args) + } + for _, other := range []string{"", filepath.Join(filepath.Dir(dir), "0123456789abcdef")} { + if got := run(other); !strings.Contains(got, "token:\n") { + t.Fatalf("a run in %q was given a token:\n%s", other, got) + } + } + + // the bridge's env is built the same way + env := inClaudeDir([]string{"CLAUDE_CODE_OAUTH_TOKEN=leaked", "PATH=/bin"}, dir) + n := 0 + for _, e := range env { + if strings.HasPrefix(e, "CLAUDE_CODE_OAUTH_TOKEN=") { + n++ + if e != "CLAUDE_CODE_OAUTH_TOKEN="+gwSetupToken { + t.Fatalf("bridge env %q", e) + } + } + } + if n != 1 { + t.Fatalf("%d tokens in the bridge's env: %q", n, env) + } +} diff --git a/internal/gateway/claude_subscription.go b/internal/gateway/claude_subscription.go index 2d41c1f84..233d43079 100644 --- a/internal/gateway/claude_subscription.go +++ b/internal/gateway/claude_subscription.go @@ -593,6 +593,9 @@ func (c claudeCLI) env(env []string, configDir string) []string { if configDir != "" { names = append(slices.Clone(names), "CLAUDE_CONFIG_DIR/p") } + if slices.ContainsFunc(env, func(e string) bool { return strings.HasPrefix(e, "CLAUDE_CODE_OAUTH_TOKEN=") }) { + names = append(slices.Clone(names), "CLAUDE_CODE_OAUTH_TOKEN") + } if c.wsl.Root { // asRoot's, for a distro whose user is root names = append(slices.Clone(names), "IS_SANDBOX") @@ -2060,15 +2063,22 @@ func inClaudeDir(env []string, configDir string) []string { if configDir == "" { return env } - out := make([]string, 0, len(env)+1) + out := make([]string, 0, len(env)+2) for _, e := range env { switch k, _, _ := strings.Cut(e, "="); k { - case "CLAUDE_CONFIG_DIR", "CLAUDE_SECURESTORAGE_CONFIG_DIR": + case "CLAUDE_CONFIG_DIR", "CLAUDE_SECURESTORAGE_CONFIG_DIR", "CLAUDE_CODE_OAUTH_TOKEN": continue } out = append(out, e) } - return append(out, "CLAUDE_CONFIG_DIR="+configDir) + out = append(out, "CLAUDE_CONFIG_DIR="+configDir) + // an account added by a setup-token: Claude Code takes the token as + // `claude setup-token` says to, in its environment, for this account's + // directory alone; never on the command line, nor logged + if tok := provider.ClaudeDirToken(configDir); tok != "" { + out = append(out, "CLAUDE_CODE_OAUTH_TOKEN="+tok) + } + return out } func cleanClaudeEnv(env []string) []string { diff --git a/internal/gui/assets/app.js b/internal/gui/assets/app.js index f97c918da..ee047993d 100644 --- a/internal/gui/assets/app.js +++ b/internal/gui/assets/app.js @@ -1614,7 +1614,7 @@ function switchEntry(a) { setTimeout(() => b.classList.remove("done"), 5000 - ago); } b.append(svg(CHEV, 10, 1.6)); - const opts = ls.map((l) => ({ v: "u:" + l.user, name: l.user, literalName: true, note: l.lapsed ? "Sign-in required" : accountPlan({ agent: a.id, plan: l.plan }) })); + const opts = ls.filter((l) => !l.token).map((l) => ({ v: "u:" + l.user, name: l.user, literalName: true, note: l.lapsed ? "Sign-in required" : accountPlan({ agent: a.id, plan: l.plan }) })); const on = cx ? t("magpie only switches {agent}'s sign-in; its requests go straight to OpenAI", ag) : t("magpie serves no requests on these accounts"); // the Only switch setting, where the accounts page offers it if (!cx || ls.filter((l) => !l.lapsed && (l.active || l.on)).length > 1) opts.push({ v: "only", name: t("Only switch {agent}'s sign-in", ag), literalName: true, ticked: !!p.switchOnly, note: on }); @@ -12444,6 +12444,7 @@ async function signedIn(st) { if (!p) status(t("{user} signed in, but magpie can't list it — please report this", { user: who }), "err"); // an account listed already is said to be, not added (#413) else if (st.again) status(t("{user} is already listed — its sign-in was renewed", { user: who }), "ok"); + else if (st.token) status(t("{user} added; requests through magpie use it beside your other accounts", { user: who }), "ok"); else status(st.using ? t("Signed in as {user}", { user: who }) : t("{user} added — switch to it any time", { user: who }), "ok"); state = await api("state"); renderAgents(); @@ -12819,6 +12820,57 @@ function renderCopilotGHE(sub) { return box; } +// a Claude account from a setup-token (claude_setup_token.go) +function startClaudeToken() { + stopSignIn(); + signing = { agent: "claude", state: "token", token: "" }; + renderProviders(); +} + +function renderClaudeToken(sub) { + const box = el("div", "signing claude-token"); + const tt = el("span", "tt"); + box.append(tt); + const flow = signing; + const label = t("Add a Claude account by setup-token"); + tt.append(el("span", "n", label), + el("span", "s", t("Paste the token {cmd} printed. magpie gives it to Claude Code for this account's requests only; Claude Code itself stays signed in as it is.", { cmd: "claude setup-token" })), + el("span", "s", t("A setup-token can't tell its email or allowance: the account is named by the token, and its allowance shows once a reply tells it."))); + const form = el("form", "callback-form"); + const inp = input(flow.token || "", "sk-ant-oat01-…", "password"); + inp.setAttribute("aria-label", label); + const go = el("button", "text primary", t("Add")); + go.type = "submit"; + go.disabled = !inp.value.trim() || !!flow.busy; + const why = el("span", "s why", flow.error || ""); + inp.oninput = () => { flow.token = inp.value; go.disabled = !inp.value.trim(); why.textContent = ""; }; + const submit = async (e) => { + e.preventDefault(); + if (signing !== flow || flow.busy || !inp.value.trim()) return; + flow.busy = true; + go.disabled = true; + try { + const r = await api("signin/claude-token", { token: inp.value }); + if (signing !== flow) return; + await signedIn({ agent: "claude", user: r.user, token: true }); + } catch (err) { + if (signing !== flow) return; + flow.busy = false; + flow.error = err.message; + renderProviders(); + } + }; + form.onsubmit = submit; + go.onclick = submit; + form.append(inp, go); + tt.append(form, why); + const close = el("button", "text", t("Cancel")); + close.onclick = cancelSignIn; + box.append(close); + setTimeout(() => { if (inp.isConnected) inp.focus({ preventScroll: true }); }); + return box; +} + // dropSigningIn: the editor of provider id closing (Cancel, Save, Remove) // leaves no sign-in of its account waiting behind it, to come back with the // editor (#526: 无论我点击底部的移除、取消、保存都没办法); an import being @@ -12894,6 +12946,7 @@ function renderSigning(sub) { return box; } if (signing.state === "ghe") return renderCopilotGHE(sub); + if (signing.state === "token") return renderClaudeToken(sub); if (signing.state === "import" || signing.state === "importing" || signing.state === "imported") return renderLoginImport(sub); if (signing.state === "method" || signing.state === "prompt" || signing.state === "key") return renderPluginAsk(sub); if (signing.state === "failed") { @@ -13067,6 +13120,12 @@ function renderSigning(sub) { const acts = tt.querySelector(".acts") || tt.appendChild(el("span", "acts")); acts.append(imp); } + if (sub.agent === "claude") { + const tok = el("button", "link", t("Use a setup-token instead…")); + tok.onclick = () => startClaudeToken(); + const acts = tt.querySelector(".acts") || tt.appendChild(el("span", "acts")); + acts.append(tok); + } // the one way to put it away (#526): a Close beside Open again did what // this does, two buttons for one thing const x = el("button", "text", t("Cancel")); @@ -13273,7 +13332,7 @@ function renderAccounts(a, p) { row.classList.add("signed-out"); line.append(el("span", "using", t("Sign-in required"))); const again = el("button", "text", t("Sign in again")); - again.onclick = () => startSignIn(a.agent, false, undefined, { user: l.user }); + again.onclick = () => l.token ? startClaudeToken() : startSignIn(a.agent, false, undefined, { user: l.user }); line.append(again); // the one Claude Code is signed in to can't be forgotten (ForgetLogin) if (!l.active) { @@ -13322,6 +13381,10 @@ function renderAccounts(a, p) { line.append(forget); if (l.user === firstUser) line.append(el("span", "using", t("First"))); else if (on) line.append(makeFirst(l)); + } else if (l.token) { + const only = el("span", "using", t("magpie only")); + only.title = t("Added by a setup-token: requests through magpie use it; Claude Code itself can't be signed in to it"); + line.append(forget, only); } else { const use = el("button", "text", on ? t("Make first") : t("Use")); use.title = sub?.own ? t("The gateway uses this account first") : t("Sign {agent} in to this account", { agent: a.agentName }); @@ -13426,6 +13489,7 @@ function renderAccounts(a, p) { imp.title = importSay(a.agent).from; list.append(imp); } + if (a.agent === "claude") list.append(addRow(t("Add an account by setup-token…"), startClaudeToken)); } arrangeAccountRows(list, p); return list; diff --git a/internal/gui/assets/i18n.js b/internal/gui/assets/i18n.js index 3f495987d..8292cc5fe 100644 --- a/internal/gui/assets/i18n.js +++ b/internal/gui/assets/i18n.js @@ -1881,6 +1881,14 @@ const I18N = { "Each key is asked whose account it is, as Droid does with FACTORY_API_KEY.": "逐个查询 Key 所属的账号,与 Droid 处理 FACTORY_API_KEY 时相同。", "Use an API key instead…": "改用 API Key…", "Add an account by API key…": "用 API Key 添加账号…", + "Use a setup-token instead…": "改用 setup-token…", + "Add a Claude account by setup-token": "用 setup-token 添加 Claude 账号", + "Paste the token {cmd} printed. magpie gives it to Claude Code for this account's requests only; Claude Code itself stays signed in as it is.": "粘贴 {cmd} 输出的 token。magpie 只在这个账号的请求里把它交给 Claude Code;Claude Code 本身的登录保持不变。", + "A setup-token can't tell its email or allowance: the account is named by the token, and its allowance shows once a reply tells it.": "setup-token 读不到邮箱和用量:账号以 token 命名,用量要等某次回复带回后才显示。", + "{user} added; requests through magpie use it beside your other accounts": "已添加 {user};经 magpie 的请求会和你的其他账号一起使用它", + "Add an account by setup-token…": "用 setup-token 添加账号…", + "magpie only": "仅 magpie", + "Added by a setup-token: requests through magpie use it; Claude Code itself can't be signed in to it": "由 setup-token 添加:经 magpie 的请求会使用它;Claude Code 本身无法登录到这个账号", "Bring in accounts exported from Antigravity Cockpit, Antigravity Manager or CLIProxyAPI": "导入从 Antigravity Cockpit、Antigravity Manager 或 CLIProxyAPI 导出的账号", "Import accounts from a file…": "从文件导入账号…", "Import {name} accounts": "导入 {name} 账号", @@ -6032,6 +6040,14 @@ const I18N = { "Each key is asked whose account it is, as Droid does with FACTORY_API_KEY.": "逐個查詢 Key 所屬的帳號,與 Droid 處理 FACTORY_API_KEY 時相同。", "Use an API key instead…": "改用 API Key…", "Add an account by API key…": "用 API Key 新增帳號…", + "Use a setup-token instead…": "改用 setup-token…", + "Add a Claude account by setup-token": "用 setup-token 新增 Claude 帳號", + "Paste the token {cmd} printed. magpie gives it to Claude Code for this account's requests only; Claude Code itself stays signed in as it is.": "貼上 {cmd} 輸出的 token。magpie 只在這個帳號的請求裡把它交給 Claude Code;Claude Code 本身的登入保持不變。", + "A setup-token can't tell its email or allowance: the account is named by the token, and its allowance shows once a reply tells it.": "setup-token 讀不到電子郵件和用量:帳號以 token 命名,用量要等某次回覆帶回後才顯示。", + "{user} added; requests through magpie use it beside your other accounts": "已新增 {user};經 magpie 的請求會和你的其他帳號一起使用它", + "Add an account by setup-token…": "用 setup-token 新增帳號…", + "magpie only": "僅 magpie", + "Added by a setup-token: requests through magpie use it; Claude Code itself can't be signed in to it": "由 setup-token 新增:經 magpie 的請求會使用它;Claude Code 本身無法登入到這個帳號", "Bring in accounts exported from Antigravity Cockpit, Antigravity Manager or CLIProxyAPI": "匯入從 Antigravity Cockpit、Antigravity Manager 或 CLIProxyAPI 匯出的帳號", "Import accounts from a file…": "從檔案匯入帳號…", "Import {name} accounts": "匯入 {name} 帳號", @@ -10160,6 +10176,14 @@ const I18N = { "Each key is asked whose account it is, as Droid does with FACTORY_API_KEY.": "Droid が FACTORY_API_KEY で行うように、各キーの所有アカウントを問い合わせます。", "Use an API key instead…": "代わりに APIキーを使う…", "Add an account by API key…": "APIキーでアカウントを追加…", + "Use a setup-token instead…": "代わりに setup-token を使う…", + "Add a Claude account by setup-token": "setup-token で Claude アカウントを追加", + "Paste the token {cmd} printed. magpie gives it to Claude Code for this account's requests only; Claude Code itself stays signed in as it is.": "{cmd} が表示したトークンを貼り付けてください。magpie はこのアカウントのリクエストに限って Claude Code に渡します。Claude Code 自体のサインインはそのままです。", + "A setup-token can't tell its email or allowance: the account is named by the token, and its allowance shows once a reply tells it.": "setup-token ではメールアドレスと使用量を読めません。アカウントはトークンから名付けられ、使用量は応答で伝えられてから表示されます。", + "{user} added; requests through magpie use it beside your other accounts": "{user} を追加しました。magpie 経由のリクエストはほかのアカウントと並べてこれを使います", + "Add an account by setup-token…": "setup-token でアカウントを追加…", + "magpie only": "magpie のみ", + "Added by a setup-token: requests through magpie use it; Claude Code itself can't be signed in to it": "setup-token で追加:magpie 経由のリクエストはこれを使いますが、Claude Code 自体をこのアカウントにサインインさせることはできません", "Bring in accounts exported from Antigravity Cockpit, Antigravity Manager or CLIProxyAPI": "Antigravity Cockpit、Antigravity Manager、CLIProxyAPI からエクスポートしたアカウントを取り込みます", "Import accounts from a file…": "ファイルからアカウントをインポート…", "Import {name} accounts": "{name} アカウントをインポート", @@ -14318,6 +14342,14 @@ const I18N = { "Each key is asked whose account it is, as Droid does with FACTORY_API_KEY.": "Für jeden Schlüssel wird abgefragt, zu welchem Konto er gehört, so wie Droid es mit FACTORY_API_KEY macht.", "Use an API key instead…": "Stattdessen API-Schlüssel verwenden…", "Add an account by API key…": "Konto per API-Schlüssel hinzufügen…", + "Use a setup-token instead…": "Stattdessen ein setup-token verwenden…", + "Add a Claude account by setup-token": "Claude-Konto per setup-token hinzufügen", + "Paste the token {cmd} printed. magpie gives it to Claude Code for this account's requests only; Claude Code itself stays signed in as it is.": "Füge das Token ein, das {cmd} ausgegeben hat. magpie gibt es Claude Code nur für die Anfragen dieses Kontos; Claude Code selbst bleibt angemeldet, wie es ist.", + "A setup-token can't tell its email or allowance: the account is named by the token, and its allowance shows once a reply tells it.": "Ein setup-token verrät weder E-Mail noch Kontingent: Das Konto wird nach dem Token benannt, und sein Kontingent erscheint, sobald eine Antwort es nennt.", + "{user} added; requests through magpie use it beside your other accounts": "{user} hinzugefügt; Anfragen über magpie nutzen es neben deinen anderen Konten", + "Add an account by setup-token…": "Konto per setup-token hinzufügen…", + "magpie only": "Nur magpie", + "Added by a setup-token: requests through magpie use it; Claude Code itself can't be signed in to it": "Per setup-token hinzugefügt: Anfragen über magpie nutzen es; Claude Code selbst kann sich damit nicht anmelden", "Bring in accounts exported from Antigravity Cockpit, Antigravity Manager or CLIProxyAPI": "Konten übernehmen, die aus Antigravity Cockpit, Antigravity Manager oder CLIProxyAPI exportiert wurden", "Import accounts from a file…": "Konten aus Datei importieren…", "Import {name} accounts": "{name}-Konten importieren", diff --git a/internal/gui/core_budget_test.go b/internal/gui/core_budget_test.go index e06f833fa..49ee0e5f7 100644 --- a/internal/gui/core_budget_test.go +++ b/internal/gui/core_budget_test.go @@ -15,8 +15,8 @@ import ( // so a page can't quietly grow back into the core; a change that needs more // raises them and says why in its commit. const ( - appScriptBudget = 1_315_316 // app.js: 1,198,239 after Usage left (P2); 1,218,098 with the 10-15 fixes to pages still in the core; 1,232,466 with the provider editor's Advanced fold and every dialog holding its place, the core's own (10-16); 1,250,533 with the quota refresh kept through redraws, the core's own since the tray panel draws it too, plus 1.5% (#2397); 1,269,083 with Free first's option in the provider editor's ROUTINGS, which the Routing page reads too, plus 1.5%; 1,272,726 with the Providers page drawing its last list at once (#1519), the core's page, and the Routing trace's account names read without Object.entries (#1481), plus 1.5%; a dialog growing out of the row that opened it and folding back into it, the core's own since every page's dialogs open through it (10-20); Codex's and Claude Code's own settings moved from Settings into the agent's row on the Agents page, the core's own since the tray panel and the window both draw them (10-20); 1,314,432 with Settings › Privacy's record of what was masked (its summary, the records view and the local model's controls), which belongs to Settings, the core's own, plus 1.5%; 1,336,481 with a provider's Names & levels saying Provider in model names is Settings' and opening it there (joe), and Settings' Image recognition saying where a custom provider's model is marked (nexnull), both in the core's own pages, with no room added (10-23); 1,337,633 with Settings › Models › Replies' Intent classifier timeout (#2934, reyoung), Settings' own row, drawn by waitRow, which the Image generation timeout's row now shares, with no room added; 1,337,735 with the provider editor's link naming a partner's page by its own host (siteHost) instead of usemagpie.ai's /go link, the core's own editor, with no room added (10-23); 1,338,084 with Check in now saying what the press came to (claimed +credits, already today, not available yet) where it said "refreshed" (#3326), the check-in row the tray panel draws too, the core's own, with no room added (10-23); 1,338,929 with a new partner's tile keeping a small dot until it is opened, in the add sheet, the core's own, with no room added (10-23); 1,343,324 with the sidebar's open-page row marked by one shape that moves on a spring (navTopGo), the window's own shell, which every page sits beside, with no room added (10-23); 1,343,465 with a dialog kept centred while its content comes in, until it is pressed (holdModal, every page's dialogs), the core's own, with no room added (10-24); 1,317,486 with what masking did moved out to Insights › Masking (plugins/redact), the budget lowered to it (10-24); 1,321,336 with Codex's one subagent model, its card's square saying plainly what each choice does and a row with a name in its sheet, where two squares read alike (the owner), the Agents page's, which the tray panel draws too, the core's own, with no room added (10-24); 1,321,424 with Settings › Models' Image generation MCP server row beside Image recognition's (JonahFu on X), the two drawn by one helper (mcpRow), Settings' own, with no room added (10-25); 1,321,994 with a provider of the user's set never to rest for a limit (zoecats), the provider editor's Advanced row, the core's own editor, with no room added (10-25); 1,322,289 with Settings › Privacy's Keep a key's form under Mask secrets (Charles Cao on X), Settings' own row, with no room added (10-25); 1,322,537 with no Codex squares beside its named settings rows (the owner), with no room added (10-25); 1,323,401 with the tray panel drawing its last allowances at once and asking for them beside the state (#3160, #3134), the tray panel's, the core's own, and the 4 bytes 84c50f032 added, with no room added (10-25); 1,326,105 with many releases' notes merged into one list by kind, each line with its version (the owner), in the update sheet and What's new, with no room added (10-25); 1,321,319 with Settings › Observability moved out to its plugin (plugins/otel/page.js) and its Langfuse setup there (an X user), the budget lowered to it (10-26); a quota card whose window is used but names no reset no longer saying "Not used yet" (windy on Discord) raised it to 1,321,347, and back to 1,321,319 with Settings' model pickers sharing one row helper (modelOpt) where six kept their own copy, no raise (10-26); 1,325,845 with every slow page's skeletons getting magpie's bird hopping bar to bar (skelBird, the owner after the Plugins page's README), one bird for the window over whatever page or dialog is loading, the core's own, with no room added (10-26); 1,310,129 with Settings › Network and sharing's gateway rows (its port, bare ids, local network, allowed addresses, web pages) moved out to the gateway plugin (plugins/gateway/settings.js), the budget lowered to it (10-27); 1,310,269 with Test models naming the first model that failed and its error in the status line, where it said only how many (ysm119 on Discord), the provider editor's, the core's own, with no room added (10-27); 1,310,460 with Settings › About's Website row linking usemagpie.ai (the owner), Settings' own row, with no room added (10-27); 1,309,669 with a pool's Stop at the caps and Check usage near a cap ticks under a provider's accounts (plugins#349), the core's own editor, its account rows' Remove and add rows each drawn by one helper (forgetOf, addRow), with no room added (10-28); 1,311,681 with Install another agent on the Agents page naming the agents Plugins has (More in Plugins) and opening Plugins at its Agents (the owner), the Agents page's, the core's own, with no room added (10-28); 1,311,735 with More in Plugins in sight while Install another agent is folded (the owner), with no room added (10-29); 1,313,704 with a window whose WebKit scrolls under wheels it never tells of (macOS 13) remembered once seen, a scroll at rest then waiting 120ms for a second the same way within 80ms before it is put back, kept for a late wheel to give back (waitsBack), and a load landing under the wheel keeping the reader's way (backAfterLoad, issennknight), the window's own scroll guard, with no room added (10-29); back to 1,311,735 with Settings › Models › Web search's rows (renderSearch, renderSearcher, the search APIs' keys) moved out to the search plugin (plugins/search/settings.js), app.js 1,292,527 after it, not lowered further since what is left plus 1.5% is over it (#4133, 10-29); 1,315,316 with the Agents row of a Claude Code or Codex not connected saying the account it is signed in to and switching it to another (Switch accounts only, the owner on X), in place of the failover line's ChatGPT accounts button, the Agents page's, the core's own, its comments cut down, with no room added (10-30) - coreScriptBudget = 1_537_034 // every core script: 1,358,034 after Usage left; 1,380,003 with them; 1,405,937 with the fold; 1,426,102 with 10-16's core work (the GitHub list loading, the move to plugins, Settings › Long conversations), plus 1.5% (#2612); 1,447,368 with loadBack, the window's one state read per return, which every page needs and so is the core's own (1,446,845 before it, 155 bytes under), plus 1.5%; OpenCode Zen's card saying OpenCode tells no key its balance adds ~390 bytes inside it; 1,472,589 with the dialog that grows out of its row and the agents' own settings in their rows, on main's 10-20 core work (the Providers page's last list, the Routing trace's names), plus 1.5% (10-20); 1,506,192 with Settings › Privacy's record of what was masked, plus 1.5%; 1,529,393 with the Intent classifier timeout row (#2934), with no room added; 1,529,495 with the editor's partner link host, with no room added; 1,529,844 with Check in now's press summary (#3326), with no room added; 1,530,689 with the new partner tile's dot, with no room added; 1,535,084 with the sidebar's spring, with no room added; 1,549,478 with the context window card's map (tiles by tokens, the default look, the block grid a switch away) and its text view showing an inline image, in context.js, which the Routing page draws as well as Usage, so the core's own, with no room added (10-24); 1,550,768 with a usage card's refresh opening after its text (#840's card, which the tray panel draws too), the Add key spinner, and a dialog kept centred while its content comes in, with no room added (10-24); 1,524,789 with what masking did moved out to Insights › Masking, lowered to it; 1,528,525 with Codex's one subagent model, with no room added (10-24); 1,528,972 with the Image generation MCP server row (JonahFu on X), with no room added (10-25); 1,529,542 with the limit-rest row (zoecats), with no room added (10-25); 1,529,837 with Keep a key's form (Charles Cao on X), with no room added (10-25); 1,530,050 with no Codex squares beside its named settings rows (the owner), with no room added (10-25); 1,530,631 with a plugin's page growing to its README on the dialog's spring instead of in one jump (the owner), the Plugins page's, in plugins.js, with no room added (10-25); 1,533,445 with the context map counting its tokens on as a live request grows, a tile pointed at keeping its tip, a tool's gathered results saying how many and the small files their folder (the owner, after flohoeller's map on X), in context.js, which the Routing page draws as well as Usage, and the 4 bytes 84c50f032 added to app.js (Settings' Version row) without a raise, with no room added (10-25); 1,534,312 with the tray panel's last allowances drawn at once (#3160, #3134), with no room added (10-25); 1,537,016 with many releases' notes merged into one list by kind (the owner), in app.js, with no room added (10-25); 1,542,244 with a plugin's README loading under magpie's bird bouncing down its lines instead of pulsing bars (the owner), the Plugins page's, in plugins.js, with no room added (10-26); 1,542,418 with a page plugin's sidebar tab coming and going as it is installed, switched on or off, or removed, instead of on the Plugins page's next load (the owner), in plugins.js, with no room added (10-26); 1,537,645 with Settings › Observability moved out to plugins/otel, lowered to it (10-26); 1,537,673 with a used window with no reset not "Not used yet" (windy on Discord), and back to 1,537,645 with Settings' model pickers sharing modelOpt (10-26); 1,541,967 with every slow page's skeletons getting magpie's bird (skelBird, the owner), in app.js, the README's bird sharing its drawing and styles, with no room added (10-26); 1,526,251 with Settings' gateway rows moved out to plugins/gateway/settings.js, lowered to it (10-27); 1,526,391 with Test models naming the first failed model and its error (ysm119 on Discord), in app.js, with no room added (10-27); 1,526,556 with About's Website row (the owner), in app.js, with no room added (10-27); 1,526,500 with a pool's cap ticks (plugins#349), in app.js, with no room added (10-28); 1,527,245 with About's Open-source licenses row and dialog (the owner), in app.js, with no room added (10-28); 1,528,076 with the Partners heading's light (the owner), in app.js, with no room added (10-28); 1,530,449 with Install another agent's More in Plugins row (the owner), in app.js, and Plugins opening at its Agents, in plugins.js, with no room added (10-28); 1,530,807 with layout.js measuring the scrollbar into --bar, which every page's right padding takes off so its sides match (the owner), the window's own shell, with no room added (10-28); 1,530,861 with More in Plugins in sight while Install another agent is folded (the owner), in app.js, with no room added (10-29); 1,532,830 with waitsBack and backAfterLoad (issennknight, macOS 13), the window's own scroll guard, in app.js, with no room added (10-29); the context map's tile wording (a4e929212) and Cindy's Add magpie (628ac36fc) had taken the core over it, and Web search's rows moved out to plugins/search/settings.js brought it back to 1,530,861 (#4133, 10-29); 1,532,459 with a provider editor's account rows on one line each, First or Make first at its right end and the settings that aren't set under ⋯ (the owner), the core's own editor, in app.js, which stays in its budget with its comments cut down, with no room added (10-29); 1,532,602 with a plugin's README waiting for its bird to land on three lines before it goes in, however soon it came (the owner, 10-30), in plugins.js, with no room added; 1,536,357 with Switch accounts only on the Agents row (the owner on X), in app.js, with no room added (10-30); 1,537,034 with a plugin's README read once shown at once, with no bird, when its page opens again and read again behind it, the last 20 kept (the owner), in plugins.js, with no room added (10-30) + appScriptBudget = 1_317_705 // app.js: 1,198,239 after Usage left (P2); 1,218,098 with the 10-15 fixes to pages still in the core; 1,232,466 with the provider editor's Advanced fold and every dialog holding its place, the core's own (10-16); 1,250,533 with the quota refresh kept through redraws, the core's own since the tray panel draws it too, plus 1.5% (#2397); 1,269,083 with Free first's option in the provider editor's ROUTINGS, which the Routing page reads too, plus 1.5%; 1,272,726 with the Providers page drawing its last list at once (#1519), the core's page, and the Routing trace's account names read without Object.entries (#1481), plus 1.5%; a dialog growing out of the row that opened it and folding back into it, the core's own since every page's dialogs open through it (10-20); Codex's and Claude Code's own settings moved from Settings into the agent's row on the Agents page, the core's own since the tray panel and the window both draw them (10-20); 1,314,432 with Settings › Privacy's record of what was masked (its summary, the records view and the local model's controls), which belongs to Settings, the core's own, plus 1.5%; 1,336,481 with a provider's Names & levels saying Provider in model names is Settings' and opening it there (joe), and Settings' Image recognition saying where a custom provider's model is marked (nexnull), both in the core's own pages, with no room added (10-23); 1,337,633 with Settings › Models › Replies' Intent classifier timeout (#2934, reyoung), Settings' own row, drawn by waitRow, which the Image generation timeout's row now shares, with no room added; 1,337,735 with the provider editor's link naming a partner's page by its own host (siteHost) instead of usemagpie.ai's /go link, the core's own editor, with no room added (10-23); 1,338,084 with Check in now saying what the press came to (claimed +credits, already today, not available yet) where it said "refreshed" (#3326), the check-in row the tray panel draws too, the core's own, with no room added (10-23); 1,338,929 with a new partner's tile keeping a small dot until it is opened, in the add sheet, the core's own, with no room added (10-23); 1,343,324 with the sidebar's open-page row marked by one shape that moves on a spring (navTopGo), the window's own shell, which every page sits beside, with no room added (10-23); 1,343,465 with a dialog kept centred while its content comes in, until it is pressed (holdModal, every page's dialogs), the core's own, with no room added (10-24); 1,317,486 with what masking did moved out to Insights › Masking (plugins/redact), the budget lowered to it (10-24); 1,321,336 with Codex's one subagent model, its card's square saying plainly what each choice does and a row with a name in its sheet, where two squares read alike (the owner), the Agents page's, which the tray panel draws too, the core's own, with no room added (10-24); 1,321,424 with Settings › Models' Image generation MCP server row beside Image recognition's (JonahFu on X), the two drawn by one helper (mcpRow), Settings' own, with no room added (10-25); 1,321,994 with a provider of the user's set never to rest for a limit (zoecats), the provider editor's Advanced row, the core's own editor, with no room added (10-25); 1,322,289 with Settings › Privacy's Keep a key's form under Mask secrets (Charles Cao on X), Settings' own row, with no room added (10-25); 1,322,537 with no Codex squares beside its named settings rows (the owner), with no room added (10-25); 1,323,401 with the tray panel drawing its last allowances at once and asking for them beside the state (#3160, #3134), the tray panel's, the core's own, and the 4 bytes 84c50f032 added, with no room added (10-25); 1,326,105 with many releases' notes merged into one list by kind, each line with its version (the owner), in the update sheet and What's new, with no room added (10-25); 1,321,319 with Settings › Observability moved out to its plugin (plugins/otel/page.js) and its Langfuse setup there (an X user), the budget lowered to it (10-26); a quota card whose window is used but names no reset no longer saying "Not used yet" (windy on Discord) raised it to 1,321,347, and back to 1,321,319 with Settings' model pickers sharing one row helper (modelOpt) where six kept their own copy, no raise (10-26); 1,325,845 with every slow page's skeletons getting magpie's bird hopping bar to bar (skelBird, the owner after the Plugins page's README), one bird for the window over whatever page or dialog is loading, the core's own, with no room added (10-26); 1,310,129 with Settings › Network and sharing's gateway rows (its port, bare ids, local network, allowed addresses, web pages) moved out to the gateway plugin (plugins/gateway/settings.js), the budget lowered to it (10-27); 1,310,269 with Test models naming the first model that failed and its error in the status line, where it said only how many (ysm119 on Discord), the provider editor's, the core's own, with no room added (10-27); 1,310,460 with Settings › About's Website row linking usemagpie.ai (the owner), Settings' own row, with no room added (10-27); 1,309,669 with a pool's Stop at the caps and Check usage near a cap ticks under a provider's accounts (plugins#349), the core's own editor, its account rows' Remove and add rows each drawn by one helper (forgetOf, addRow), with no room added (10-28); 1,311,681 with Install another agent on the Agents page naming the agents Plugins has (More in Plugins) and opening Plugins at its Agents (the owner), the Agents page's, the core's own, with no room added (10-28); 1,311,735 with More in Plugins in sight while Install another agent is folded (the owner), with no room added (10-29); 1,313,704 with a window whose WebKit scrolls under wheels it never tells of (macOS 13) remembered once seen, a scroll at rest then waiting 120ms for a second the same way within 80ms before it is put back, kept for a late wheel to give back (waitsBack), and a load landing under the wheel keeping the reader's way (backAfterLoad, issennknight), the window's own scroll guard, with no room added (10-29); back to 1,311,735 with Settings › Models › Web search's rows (renderSearch, renderSearcher, the search APIs' keys) moved out to the search plugin (plugins/search/settings.js), app.js 1,292,527 after it, not lowered further since what is left plus 1.5% is over it (#4133, 10-29); 1,315,316 with the Agents row of a Claude Code or Codex not connected saying the account it is signed in to and switching it to another (Switch accounts only, the owner on X), in place of the failover line's ChatGPT accounts button, the Agents page's, the core's own, its comments cut down, with no room added (10-30); 1,317,705 with a Claude account added from a setup-token (sfss5362 on X): the sign-in's Use a setup-token instead…, its sheet, and its account row's magpie only, the provider editor's account rows, the core's own editor, its comments cut down, with no room added (10-30) + coreScriptBudget = 1_539_423 // every core script: 1,358,034 after Usage left; 1,380,003 with them; 1,405,937 with the fold; 1,426,102 with 10-16's core work (the GitHub list loading, the move to plugins, Settings › Long conversations), plus 1.5% (#2612); 1,447,368 with loadBack, the window's one state read per return, which every page needs and so is the core's own (1,446,845 before it, 155 bytes under), plus 1.5%; OpenCode Zen's card saying OpenCode tells no key its balance adds ~390 bytes inside it; 1,472,589 with the dialog that grows out of its row and the agents' own settings in their rows, on main's 10-20 core work (the Providers page's last list, the Routing trace's names), plus 1.5% (10-20); 1,506,192 with Settings › Privacy's record of what was masked, plus 1.5%; 1,529,393 with the Intent classifier timeout row (#2934), with no room added; 1,529,495 with the editor's partner link host, with no room added; 1,529,844 with Check in now's press summary (#3326), with no room added; 1,530,689 with the new partner tile's dot, with no room added; 1,535,084 with the sidebar's spring, with no room added; 1,549,478 with the context window card's map (tiles by tokens, the default look, the block grid a switch away) and its text view showing an inline image, in context.js, which the Routing page draws as well as Usage, so the core's own, with no room added (10-24); 1,550,768 with a usage card's refresh opening after its text (#840's card, which the tray panel draws too), the Add key spinner, and a dialog kept centred while its content comes in, with no room added (10-24); 1,524,789 with what masking did moved out to Insights › Masking, lowered to it; 1,528,525 with Codex's one subagent model, with no room added (10-24); 1,528,972 with the Image generation MCP server row (JonahFu on X), with no room added (10-25); 1,529,542 with the limit-rest row (zoecats), with no room added (10-25); 1,529,837 with Keep a key's form (Charles Cao on X), with no room added (10-25); 1,530,050 with no Codex squares beside its named settings rows (the owner), with no room added (10-25); 1,530,631 with a plugin's page growing to its README on the dialog's spring instead of in one jump (the owner), the Plugins page's, in plugins.js, with no room added (10-25); 1,533,445 with the context map counting its tokens on as a live request grows, a tile pointed at keeping its tip, a tool's gathered results saying how many and the small files their folder (the owner, after flohoeller's map on X), in context.js, which the Routing page draws as well as Usage, and the 4 bytes 84c50f032 added to app.js (Settings' Version row) without a raise, with no room added (10-25); 1,534,312 with the tray panel's last allowances drawn at once (#3160, #3134), with no room added (10-25); 1,537,016 with many releases' notes merged into one list by kind (the owner), in app.js, with no room added (10-25); 1,542,244 with a plugin's README loading under magpie's bird bouncing down its lines instead of pulsing bars (the owner), the Plugins page's, in plugins.js, with no room added (10-26); 1,542,418 with a page plugin's sidebar tab coming and going as it is installed, switched on or off, or removed, instead of on the Plugins page's next load (the owner), in plugins.js, with no room added (10-26); 1,537,645 with Settings › Observability moved out to plugins/otel, lowered to it (10-26); 1,537,673 with a used window with no reset not "Not used yet" (windy on Discord), and back to 1,537,645 with Settings' model pickers sharing modelOpt (10-26); 1,541,967 with every slow page's skeletons getting magpie's bird (skelBird, the owner), in app.js, the README's bird sharing its drawing and styles, with no room added (10-26); 1,526,251 with Settings' gateway rows moved out to plugins/gateway/settings.js, lowered to it (10-27); 1,526,391 with Test models naming the first failed model and its error (ysm119 on Discord), in app.js, with no room added (10-27); 1,526,556 with About's Website row (the owner), in app.js, with no room added (10-27); 1,526,500 with a pool's cap ticks (plugins#349), in app.js, with no room added (10-28); 1,527,245 with About's Open-source licenses row and dialog (the owner), in app.js, with no room added (10-28); 1,528,076 with the Partners heading's light (the owner), in app.js, with no room added (10-28); 1,530,449 with Install another agent's More in Plugins row (the owner), in app.js, and Plugins opening at its Agents, in plugins.js, with no room added (10-28); 1,530,807 with layout.js measuring the scrollbar into --bar, which every page's right padding takes off so its sides match (the owner), the window's own shell, with no room added (10-28); 1,530,861 with More in Plugins in sight while Install another agent is folded (the owner), in app.js, with no room added (10-29); 1,532,830 with waitsBack and backAfterLoad (issennknight, macOS 13), the window's own scroll guard, in app.js, with no room added (10-29); the context map's tile wording (a4e929212) and Cindy's Add magpie (628ac36fc) had taken the core over it, and Web search's rows moved out to plugins/search/settings.js brought it back to 1,530,861 (#4133, 10-29); 1,532,459 with a provider editor's account rows on one line each, First or Make first at its right end and the settings that aren't set under ⋯ (the owner), the core's own editor, in app.js, which stays in its budget with its comments cut down, with no room added (10-29); 1,532,602 with a plugin's README waiting for its bird to land on three lines before it goes in, however soon it came (the owner, 10-30), in plugins.js, with no room added; 1,536,357 with Switch accounts only on the Agents row (the owner on X), in app.js, with no room added (10-30); 1,537,034 with a plugin's README read once shown at once, with no bird, when its page opens again and read again behind it, the last 20 kept (the owner), in plugins.js, with no room added (10-30); 1,539,423 with a Claude account added from a setup-token (sfss5362 on X), in app.js, with no room added (10-30) ) func TestCoreScriptBudget(t *testing.T) { diff --git a/internal/gui/providers.go b/internal/gui/providers.go index 935b4665a..35346fe59 100644 --- a/internal/gui/providers.go +++ b/internal/gui/providers.go @@ -2319,6 +2319,22 @@ func providerRoutes(mux *http.ServeMux, w Windows) { } rw.WriteHeader(http.StatusNoContent) }) + // A Claude account from a setup-token (`claude setup-token`), which + // Claude Code takes in CLAUDE_CODE_OAUTH_TOKEN: nothing is asked of + // Anthropic, and the token is never echoed back. + mux.HandleFunc("POST /api/signin/claude-token", func(rw http.ResponseWriter, r *http.Request) { + var in struct{ Token string } + if err := json.NewDecoder(io.LimitReader(r.Body, 16<<10)).Decode(&in); err != nil { + fail(rw, err) + return + } + user, err := provider.AddClaudeSetupToken(in.Token) + if err != nil { + fail(rw, err) + return + } + writeJSON(rw, map[string]string{"user": user}) + }) // Accounts brought in from another tool's export (Antigravity's, from // Antigravity Cockpit, Antigravity Manager, CLIProxyAPI; ChatGPT's and // Claude's from CLIProxyAPI or the agents' own files), each file's diff --git a/internal/gui/tests/claude-setup-token.test.cjs b/internal/gui/tests/claude-setup-token.test.cjs new file mode 100644 index 000000000..2052f400e --- /dev/null +++ b/internal/gui/tests/claude-setup-token.test.cjs @@ -0,0 +1,124 @@ +// Run with Node's test runner and Playwright on the module path; see README.md. +// sfss5362 on X: "支持 CLAUDE_CODE_OAUTH_TOKEN 吗". Claude's sign-in offers +// "Use a setup-token instead…", which ends the browser sign-in and asks for +// the token `claude setup-token` printed, said whole in the page's +// language. A refused token says why and stays to be fixed; one taken is +// added. The account it makes is magpie's only: Remove and "magpie only", +// no Use or Make first. +// Chromium and WebKit, English, Chinese (both), Japanese and German, at +// 420px; no backend, the API is faked here. +const assert = require("node:assert/strict"); +const fs = require("node:fs/promises"); +const path = require("node:path"); +const { test } = require("node:test"); +const playwright = require("playwright"); + +const engines = (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"]); +const assets = path.resolve(__dirname, "../assets"); +const TOKEN = "sk-ant-oat01-guitoken-0123456789"; + +for (const engine of engines) for (const lang of ["en", "zh", "zh-TW", "ja", "de"]) { + test(`claude setup-token account (${engine}, ${lang})`, async (t) => { + const browser = await playwright[engine].launch(); + t.after(() => browser.close()); + const page = await browser.newPage({ viewport: { width: 420, height: 720 } }); + page.setDefaultTimeout(5000); + const errors = []; + page.on("pageerror", (e) => errors.push(e.message)); + const tokens = []; + const canceled = []; + await page.route("**/*", async (route) => { + const url = new URL(route.request().url()); + const json = (data, status) => route.fulfill({ json: data, status: status || 200 }); + if (url.pathname === "/boot.js") return route.fulfill({ contentType: "text/javascript", body: `window.bootPrefs = {lang:"${lang}",theme:"dark",web:true};` }); + if (url.pathname === "/wails/runtime.js") return route.fulfill({ contentType: "text/javascript", body: "export const Window = {};" }); + if (url.pathname === "/api/state") return json({ agents: [], profiles: [], settings: { lang, theme: "dark" } }); + if (url.pathname === "/api/providers") return json({ providers: [], presets: [], excluded: [], gateway: {} }); + if (url.pathname === "/api/groups") return json({ groups: [] }); + if (url.pathname === "/api/signin/claude-token") { + const body = route.request().postDataJSON(); + tokens.push(body.token); + if (body.token.startsWith("sk-ant-api")) return json({ error: "this is an Anthropic API key, not a setup-token: add it as an API key provider instead" }, 400); + return json({ user: "Claude setup-token 3204d0" }); + } + if (url.pathname === "/api/signin") return json({ id: "c1", agent: "claude", state: "waiting", url: "https://claude.ai/oauth/authorize?x=1" }); + if (/^\/api\/signin\/c\d+\/cancel$/.test(url.pathname)) { canceled.push(url.pathname.split("/")[3]); return json({}); } + if (/^\/api\/signin\/c\d+$/.test(url.pathname)) return new Promise(() => {}); // stays waiting + if (url.pathname.startsWith("/api/")) return json({}); + const file = path.join(assets, url.pathname === "/" ? "index.html" : url.pathname); + const contentType = { ".html": "text/html", ".js": "text/javascript", ".css": "text/css", ".svg": "image/svg+xml", ".png": "image/png" }[path.extname(file)]; + return route.fulfill({ body: await fs.readFile(file), contentType }); + }); + await page.context().route((url) => url.hostname !== "magpie.test", (route) => route.fulfill({ contentType: "text/html", body: "" })); + await page.goto("http://magpie.test/"); + await page.waitForFunction((l) => state.settings.lang === l, lang); + await page.evaluate(() => { + providers = providers || { providers: [], presets: [], plugins: [] }; + window.signedInWith = []; + window.signedIn = async (st) => { window.signedInWith.push(st); signing = null; }; + window.renderProviders = () => { + const host = document.getElementById("csign") || Object.assign(document.createElement("div"), { id: "csign" }); + host.style.cssText = "position:fixed;inset:0 auto auto 0;width:100%;z-index:1000;"; + host.replaceChildren(signing ? renderSigning(subOf("claude") || { agent: "claude" }) : ""); + document.body.append(host); + }; + startSignIn("claude", true); + }); + const box = page.locator("#csign"); + const said = (s, v) => page.evaluate(([s, v]) => t(s, v), [s, v]); + const translated = async (s, v) => { + const got = await said(s, v); + if (lang !== "en") assert.notEqual(got, s.replace("{cmd}", "claude setup-token"), `${s} isn't in ${lang}`); + return got; + }; + + // the browser sign-in offers the token + await page.waitForFunction(() => signing?.state === "waiting"); + const offer = box.getByRole("button", { name: await translated("Use a setup-token instead…") }); + await offer.click(); + await page.waitForFunction(() => signing?.state === "token"); + assert.deepEqual(canceled, ["c1"]); + const text = await box.innerText(); + assert.ok(text.includes(await translated("Add a Claude account by setup-token")), text); + assert.ok(text.includes(await translated("Paste the token {cmd} printed. magpie gives it to Claude Code for this account's requests only; Claude Code itself stays signed in as it is.", { cmd: "claude setup-token" })), text); + assert.ok(text.includes(await translated("A setup-token can't tell its email or allowance: the account is named by the token, and its allowance shows once a reply tells it.")), text); + const field = box.locator(".claude-token input"); + const add = box.locator('.claude-token button[type="submit"]'); + assert.equal(await field.getAttribute("type"), "password"); + assert.equal(await add.isDisabled(), true); + assert.equal(await box.locator("select").count(), 0); + // inside the sheet at 420px + const w = await box.evaluate((root) => Math.max(...[...root.querySelectorAll("*")].map((e) => e.getBoundingClientRect().right))); + assert.ok(w <= 420, `sheet reaches ${w}px`); + + // a refused token says why and stays + await field.fill("sk-ant-api03-key"); + await add.click(); + await page.waitForFunction(() => document.querySelector("#csign .claude-token .why")?.textContent); + assert.match(await box.locator(".why").textContent(), /API key/); + assert.equal(await page.evaluate(() => signing?.state), "token"); + + // a setup-token is added + await box.locator(".claude-token input").fill(TOKEN); + await box.locator('.claude-token button[type="submit"]').click(); + await page.waitForFunction(() => window.signedInWith.length === 1); + assert.deepEqual(tokens, ["sk-ant-api03-key", TOKEN]); + assert.deepEqual(await page.evaluate(() => window.signedInWith), [{ agent: "claude", user: "Claude setup-token 3204d0", token: true }]); + assert.equal(await box.innerText().then((s) => s.includes(TOKEN)), false); + + // its row is magpie's only + const row = await page.evaluate(() => { + const ls = [{ user: "pro@x.com", active: true, plan: "max" }, { user: "Claude setup-token 3204d0", on: true, token: true }]; + const a = { agent: "claude", agentName: "Claude Code", logins: ls }; + const list = renderAccounts(a, { id: "claude", account: { agent: "claude", user: "pro@x.com" } }); + document.body.append(list); + const rows = [...list.querySelectorAll("*")].filter((e) => e.textContent.includes("Claude setup-token 3204d0") && !e.textContent.includes("pro@x.com") && e.querySelector("button")); + const r = rows[0]; + return r ? { text: r.innerText, buttons: [...r.querySelectorAll("button")].map((b) => b.textContent) } : null; + }).catch((e) => ({ error: e.message })); + assert.ok(row && !row.error, JSON.stringify(row)); + assert.ok(row.text.includes(await translated("magpie only")), row.text); + assert.ok(!row.buttons.includes(await said("Make first")) && !row.buttons.includes(await said("Use")), row.buttons.join(",")); + assert.deepEqual(errors, []); + }); +} diff --git a/internal/provider/claude_auth.go b/internal/provider/claude_auth.go index a3d0dd067..2b3c0abf5 100644 --- a/internal/provider/claude_auth.go +++ b/internal/provider/claude_auth.go @@ -59,6 +59,9 @@ func claudeLoginVersion(l savedLogin) string { if c, ok := parseClaudeCredentials(l.Auth); ok { return c.version() } + if tok := claudeSetupToken(l.Auth); tok != "" { + return claudeTokenVersion(tok) + } return "" } diff --git a/internal/provider/claude_dirs.go b/internal/provider/claude_dirs.go index a487a8f53..64db92ac3 100644 --- a/internal/provider/claude_dirs.go +++ b/internal/provider/claude_dirs.go @@ -155,6 +155,9 @@ func syncSavedClaude(user string) { ls := readLogins() for i := range ls { if ls[i].Agent == "claude" && strings.EqualFold(ls[i].User, user) { + if claudeSetupToken(ls[i].Auth) != "" { + return // Claude Code keeps no sign-in of its own there + } if _, changed, err := syncClaudeDir(&ls[i]); err == nil && changed { _ = writeLogins(ls) } @@ -168,6 +171,11 @@ func syncSavedClaude(user string) { // the account's own proxy. Claude Code's own sign-in isn't touched. func readSavedClaudeUsage(ctx context.Context, user string) ([]QuotaWindow, error) { ws := []QuotaWindow{} + if claudeTokenAccount(user) { + // its /usage shows the API cost view, which would read as no + // allowance at all: unknown, not run + return ws, errClaudeSetupToken + } err := inSavedClaudeDir(user, func(dir string) error { var err error ws, err = readClaudeUsage(ViaLogin(ctx, "claude", user), dir) @@ -195,6 +203,14 @@ func claudeSavedDir(user string) (string, error) { if i < 0 { return "", fmt.Errorf("no saved claude account %q", user) } + if claudeSetupToken(ls[i].Auth) != "" { + // no sign-in to put there: the token goes in Claude Code's + // environment (ClaudeDirToken) + if why := claudeSignedOut(ls[i]); why != "" { + return "", errors.New(why) + } + return claudeTokenDir(user) + } dir := claudeAccountDir(user) has, changed, err := syncClaudeDir(&ls[i]) if err != nil { @@ -373,7 +389,7 @@ func claudeSignedOut(l savedLogin) string { } return l.Lapsed } - if _, ok := parseClaudeCredentials(l.Auth); ok { + if _, ok := parseClaudeCredentials(l.Auth); ok || claudeSetupToken(l.Auth) != "" { return "" } return claudeGoneLapse diff --git a/internal/provider/claude_setup_token.go b/internal/provider/claude_setup_token.go new file mode 100644 index 000000000..b345600bd --- /dev/null +++ b/internal/provider/claude_setup_token.go @@ -0,0 +1,173 @@ +package provider + +// A Claude account added by a setup-token: the long-lived token `claude +// setup-token` prints, which Claude Code takes in CLAUDE_CODE_OAUTH_TOKEN. +// magpie keeps it in logins.json as it keeps a sign-in, and hands it to the +// real Claude Code, in that variable, for runs in the account's own config +// directory only (ClaudeDirToken); it never asks Anthropic anything with it. +// +// What such a token can't do: it has the inference scope only, so Claude +// Code tells no email, plan or organization for it (`auth status` says +// "oauth_token" and no more), and its /usage shows the API cost view, not +// the subscription's windows. The account is named by the token's own +// short hash, and its allowance is unknown (errClaudeSetupToken) until a +// reply's rate-limit headers tell it. Claude Code itself can't be signed in +// to it: there is nothing to put in its keychain or .credentials.json. + +import ( + "crypto/sha256" + "encoding/hex" + "encoding/json" + "errors" + "fmt" + "os" + "path/filepath" + "strings" + "unicode" + + "github.com/yetone/magpie/internal/settings" +) + +// claudeTokenAuth is a setup-token as savedLogin.Auth keeps it. +type claudeTokenAuth struct { + SetupToken string `json:"setupToken"` +} + +// claudeSetupToken is the setup-token a saved Claude login's Auth holds, "" +// for a sign-in. +func claudeSetupToken(auth []byte) string { + if len(auth) == 0 { + return "" + } + var a claudeTokenAuth + if json.Unmarshal(auth, &a) != nil { + return "" + } + return a.SetupToken +} + +// claudeTokenVersion is the credential version of a setup-token +// (claudeLoginVersion): its hash, never the token. +func claudeTokenVersion(token string) string { + sum := sha256.Sum256([]byte(token)) + return "setup-token:" + hex.EncodeToString(sum[:])[:16] +} + +// claudeTokenName is the name a setup-token account gets: Claude tells no +// email for it, so a short hash of the token tells two apart without +// showing any of it. +func claudeTokenName(token string) string { + sum := sha256.Sum256([]byte(token)) + return "Claude setup-token " + hex.EncodeToString(sum[:])[:6] +} + +// errClaudeSetupToken is a setup-token account's allowance: unknown, never +// zero. Its words must not read as a refusal (claudeUsageDenied). +var errClaudeSetupToken = errors.New("unknown: a setup-token can't read the allowance (Claude Code's /usage needs a full sign-in); it shows once a reply tells it") + +// errClaudeTokenSwitch is the answer to signing Claude Code in to a +// setup-token account. +const errClaudeTokenSwitch = "%s was added by a setup-token: magpie's requests use it, but Claude Code itself can't be signed in to it" + +// checkClaudeSetupToken is token trimmed, or why it isn't a setup-token. +func checkClaudeSetupToken(token string) (string, error) { + token = strings.TrimSpace(token) + token = strings.TrimPrefix(token, "CLAUDE_CODE_OAUTH_TOKEN=") + token = strings.Trim(token, `"'`) + switch { + case token == "": + return "", errors.New("paste the token `claude setup-token` printed") + case strings.HasPrefix(token, "sk-ant-api"): + return "", errors.New("this is an Anthropic API key, not a setup-token: add it as an API key provider instead") + case !strings.HasPrefix(token, "sk-ant-oat"): + return "", errors.New("this isn't a setup-token: `claude setup-token` prints one that starts with sk-ant-oat") + case len(token) > 512 || strings.IndexFunc(token, func(r rune) bool { return unicode.IsSpace(r) || r > unicode.MaxASCII }) >= 0: + return "", errors.New("this isn't a setup-token: it has spaces or other characters a token doesn't") + } + return token, nil +} + +// AddClaudeSetupToken adds a Claude account from a setup-token, served by +// Claude Code with the token in CLAUDE_CODE_OAUTH_TOKEN. Claude Code's own +// sign-in is left as it is. It answers the account's name; a token already +// saved answers the account that has it. +func AddClaudeSetupToken(token string) (string, error) { + if settings.AccountDiscoveryOff() { + return "", errAccountDiscoveryOff + } + token, err := checkClaudeSetupToken(token) + if err != nil { + return "", err + } + loginsMu.Lock() + for _, l := range readLogins() { + if l.Agent == "claude" && claudeSetupToken(l.Auth) == token { + loginsMu.Unlock() + return l.User, nil + } + } + loginsMu.Unlock() + auth, err := json.Marshal(claudeTokenAuth{SetupToken: token}) + if err != nil { + return "", err + } + l := savedLogin{Agent: "claude", User: claudeTokenName(token), Auth: auth} + if _, err := addLogin(l); err != nil { + return "", err + } + return l.User, nil +} + +// ClaudeDirToken is the setup-token of the saved Claude account whose +// config directory is dir (claudeAccountDir), "" when it has a sign-in of +// its own or is no saved account's. A run there is given it, and no other. +func ClaudeDirToken(dir string) string { + if dir == "" { + return "" + } + dir = filepath.Clean(dir) + loginsMu.Lock() + defer loginsMu.Unlock() + for _, l := range readLogins() { + if l.Agent != "claude" { + continue + } + if tok := claudeSetupToken(l.Auth); tok != "" && filepath.Clean(claudeAccountDir(l.User)) == dir { + return tok + } + } + return "" +} + +// claudeTokenAccount says the saved Claude account user was added by a +// setup-token. +func claudeTokenAccount(user string) bool { + loginsMu.Lock() + defer loginsMu.Unlock() + for _, l := range readLogins() { + if l.Agent == "claude" && strings.EqualFold(l.User, user) { + return claudeSetupToken(l.Auth) != "" + } + } + return false +} + +// claudeTokenDir makes the config directory a setup-token account runs +// in: no sign-in in it (on a refused token Claude Code would otherwise +// take one it found there; addLogin cleared the directory's keychain item +// with it, forgetClaudeDir), only the onboarding Claude Code asks for +// before its first run. +func claudeTokenDir(user string) (string, error) { + dir := claudeAccountDir(user) + if err := os.MkdirAll(dir, 0o700); err != nil { + return "", err + } + if err := os.Remove(filepath.Join(dir, ".credentials.json")); err != nil && !os.IsNotExist(err) { + return "", fmt.Errorf("a sign-in left in %s: %w", dir, err) + } + profile := filepath.Join(dir, ".claude.json") + if _, err := os.Stat(profile); os.IsNotExist(err) { + _ = writePrivate(profile, []byte("{\n \"hasCompletedOnboarding\": true\n}\n")) + } + return dir, nil +} diff --git a/internal/provider/claude_setup_token_test.go b/internal/provider/claude_setup_token_test.go new file mode 100644 index 000000000..1dad56d55 --- /dev/null +++ b/internal/provider/claude_setup_token_test.go @@ -0,0 +1,171 @@ +package provider + +import ( + "context" + "errors" + "os" + "path/filepath" + "strings" + "sync/atomic" + "testing" + "time" +) + +const testSetupToken = "sk-ant-oat01-setuptoken-abcdefghijklmnopqrstuvwxyz0123456789" + +// sfss5362 on X: "支持 CLAUDE_CODE_OAUTH_TOKEN 吗". A token `claude +// setup-token` printed is added as an account of magpie's own: kept in +// logins.json, named without an email, given to Claude Code for its own +// config directory only, and Claude Code's own sign-in left as it was. +func TestClaudeSetupTokenAccount(t *testing.T) { + home := claudeHome(t) + cred := claudeSignIn(t, home, time.Now().Add(time.Hour)) + writeFile(t, filepath.Join(home, ".claude.json"), map[string]any{"oauthAccount": map[string]any{"emailAddress": "pro@x.com", + "organizationUuid": "org-pro", "organizationName": "pro@x.com's Organization"}}) + forgetAccountCaches() + rememberLogins(true) + before, err := os.ReadFile(cred) + if err != nil { + t.Fatal(err) + } + + user, err := AddClaudeSetupToken(" CLAUDE_CODE_OAUTH_TOKEN=" + testSetupToken + "\n") + if err != nil { + t.Fatal(err) + } + if user == "" || strings.Contains(user, "sk-ant") || strings.Contains(user, testSetupToken[len(testSetupToken)-6:]) { + t.Fatalf("named %q: no name, or a name showing the token", user) + } + if after, _ := os.ReadFile(cred); string(after) != string(before) { + t.Fatal("adding a setup-token wrote Claude Code's own sign-in") + } + // kept as a credential is, in logins.json + if b, _ := os.ReadFile(loginsPath()); !strings.Contains(string(b), testSetupToken) { + t.Fatal("the token isn't kept in logins.json") + } + var got *Login + for _, l := range Logins("claude") { + if l.User == user { + got = &l + } + } + if got == nil { + t.Fatalf("%q isn't listed: %+v", user, Logins("claude")) + } + if got.Active || !got.On || !got.Token || got.Lapsed != "" { + t.Fatalf("setup-token account listed as %+v, want on beside Claude Code's own, not active", *got) + } + // the same token again is the same account + if again, err := AddClaudeSetupToken(testSetupToken); err != nil || again != user { + t.Fatalf("the same token again: %q, %v", again, err) + } + if n := len(Logins("claude")); n != 2 { + t.Fatalf("%d Claude accounts, want 2", n) + } + + // its directory holds no sign-in, and its token is given there alone + dir, err := claudeSavedDir(user) + if err != nil { + t.Fatal(err) + } + if dir != claudeAccountDir(user) { + t.Fatalf("dir %q, want %q", dir, claudeAccountDir(user)) + } + if _, err := os.Stat(filepath.Join(dir, ".credentials.json")); !os.IsNotExist(err) { + t.Fatalf("a sign-in was put in the setup-token account's directory: %v", err) + } + if b, _ := os.ReadFile(filepath.Join(dir, ".claude.json")); !strings.Contains(string(b), "hasCompletedOnboarding") { + t.Fatalf("no onboarding in its .claude.json: %s", b) + } + if tok := ClaudeDirToken(dir); tok != testSetupToken { + t.Fatalf("ClaudeDirToken(own dir) = %q", tok) + } + if tok := ClaudeDirToken(claudeAccountDir("pro@x.com · pro@x.com's Organization")); tok != "" { + t.Fatal("another account's directory was given the token") + } + if tok := ClaudeDirToken(""); tok != "" { + t.Fatal("Claude Code's own run was given the token") + } + + // Claude Code can't be signed in to it + if err := SwitchLogin("claude", user); err == nil || !strings.Contains(err.Error(), "setup-token") { + t.Fatalf("switch onto a setup-token account: %v", err) + } + if after, _ := os.ReadFile(cred); string(after) != string(before) { + t.Fatal("a switch wrote the token into Claude Code's own sign-in") + } + // its version is the token's hash, never the token + if v := ClaudeLoginVersion(user); v == "" || strings.Contains(v, testSetupToken) { + t.Fatalf("version %q", v) + } +} + +// With Claude Code signed out, the first account added is signed in to in +// Claude Code; a setup-token never is. +func TestClaudeSetupTokenSignsClaudeCodeInToNothing(t *testing.T) { + home := claudeHome(t) + user, err := AddClaudeSetupToken(testSetupToken) + if err != nil { + t.Fatal(err) + } + if _, err := os.Stat(filepath.Join(home, ".claude", ".credentials.json")); !os.IsNotExist(err) { + t.Fatalf("Claude Code was signed in to a setup-token: %v", err) + } + ls := Logins("claude") + if len(ls) != 1 || ls[0].User != user || ls[0].Active || !ls[0].On || ls[0].Lapsed != "" { + t.Fatalf("listed as %+v", ls) + } +} + +// A setup-token has the inference scope only: Claude Code's /usage shows +// the API cost view for it. Its allowance is unknown, never none, and +// /usage isn't run for it. +func TestClaudeSetupTokenAllowanceUnknown(t *testing.T) { + claudeHome(t) + var text atomic.Value + text.Store("Total cost: $0.0000\nTotal duration (API): 0s") + runs := fakeClaudeUsage(t, &text, nil) + user, err := AddClaudeSetupToken(testSetupToken) + if err != nil { + t.Fatal(err) + } + ctx := context.Background() + ws, err := readSavedClaudeUsage(ctx, user) + if !errors.Is(err, errClaudeSetupToken) || len(ws) != 0 { + t.Fatalf("read %+v, %v; want unknown", ws, err) + } + if runs.Load() != 0 { + t.Fatal("/usage was run for a setup-token") + } + if claudeUsageDenied.MatchString(err.Error()) { + t.Fatalf("%q reads as a refusal", err) + } + if !passing.MatchString(err.Error()) { + t.Fatalf("%q isn't kept as saying nothing about the account", err) + } + RefreshUsage(ctx, "claude", user) + q := LoginUsage(ctx, "claude")[user] + if q.Error != errClaudeSetupToken.Error() || len(q.Windows) != 0 || runs.Load() != 0 { + t.Fatalf("card %+v after %d runs; want unknown", q, runs.Load()) + } +} + +func TestCheckClaudeSetupToken(t *testing.T) { + for in, ok := range map[string]bool{ + testSetupToken: true, + "'" + testSetupToken + "'": true, + "": false, + "sk-ant-api03-abc": false, + "sk-ant-ort01-refresh": false, + "sk-ant-oat01-a b": false, + `{"claudeAiOauth":{"accessToken":1}}`: false, + } { + tok, err := checkClaudeSetupToken(in) + if (err == nil) != ok { + t.Errorf("%q: %q %v", in, tok, err) + } + if err != nil && strings.Contains(err.Error(), in) && in != "" { + t.Errorf("%q: the error repeats the token: %v", in, err) + } + } +} diff --git a/internal/provider/codex_switch.go b/internal/provider/codex_switch.go index afe4191d2..21bb98f24 100644 --- a/internal/provider/codex_switch.go +++ b/internal/provider/codex_switch.go @@ -219,7 +219,9 @@ func NextLogin(ctx context.Context, agent string) (from, to string, back, ok boo first = &ls[i] } // never one Codex keeps signed in in another folder (switchSavedLogin) - if !l.Active && l.On && l.Lapsed == "" && l.home == "" { + // nor one added by a setup-token, which Claude Code can't be + // signed in to + if !l.Active && l.On && l.Lapsed == "" && l.home == "" && !l.Token { spares = append(spares, l) } } diff --git a/internal/provider/keep_login_as.go b/internal/provider/keep_login_as.go index 23cd20775..e8932448d 100644 --- a/internal/provider/keep_login_as.go +++ b/internal/provider/keep_login_as.go @@ -82,6 +82,9 @@ func SetKeepLoginAs(id, user string) error { if to.Lapsed != "" { return fmt.Errorf("%s has to be signed in to again first", to.User) } + if to.Token { + return fmt.Errorf(errClaudeTokenSwitch, to.User) + } if !p.KeepLogin || p.KeepLoginAs == "" { // the order the gateway goes by now — the one signed in to // first — is kept as the accounts' own, before the sign-in moves @@ -146,7 +149,7 @@ func rankLogins(agent string, order []string) error { // choosing, the one signed in to is the first again. func signInToFirst(agent string) error { for _, l := range Logins(agent) { - if (l.Active || l.On) && !l.Paused && l.Lapsed == "" { + if (l.Active || l.On) && !l.Paused && l.Lapsed == "" && !l.Token { if l.Active { return nil } diff --git a/internal/provider/logins.go b/internal/provider/logins.go index 5d9847387..2bc5983db 100644 --- a/internal/provider/logins.go +++ b/internal/provider/logins.go @@ -58,6 +58,9 @@ type Login struct { // Returns is the account magpie signed the agent out of when it was // spent, and signs it back in to once it has room again (#408). Returns bool `json:"returns,omitempty"` + // Token is a Claude account added by a setup-token: magpie's + // requests use it, Claude Code itself can't be signed in to it. + Token bool `json:"token,omitempty"` // first is the saved Claude account served in the place of Claude // Code's own while it is signed out (claudeStandIn). @@ -1010,6 +1013,7 @@ func Logins(agent string) []Login { } if l.Agent == "claude" { lg.Lapsed = claudeSignedOut(l) + lg.Token = claudeSetupToken(l.Auth) != "" } else { // the one in use too, its sign-in revoked (#1793) lg.Lapsed = revokedLapse(l) @@ -1211,6 +1215,9 @@ func switchSavedLogin(agent, user string) (from string, _ error) { // 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" && claudeSetupToken(target.Auth) != "" { + return "", fmt.Errorf(errClaudeTokenSwitch, target.User) + } 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 @@ -1279,6 +1286,9 @@ func switchSavedLogin(agent, user string) (from string, _ error) { } func putClaudeLogin(l savedLogin) error { + if claudeSetupToken(l.Auth) != "" { + return fmt.Errorf(errClaudeTokenSwitch, l.User) + } c, ok := parseClaudeCredentials(l.Auth) if !ok { return errors.New("the saved Claude Code sign-in is unreadable") @@ -1503,10 +1513,14 @@ func claudeHolders(ls []savedLogin, l savedLogin) (same bool, others []savedLogi return false, nil } c, ok := parseClaudeCredentials(l.Auth) - if !ok { + tok := claudeSetupToken(l.Auth) + if !ok && tok == "" { return false, nil } holds := func(x savedLogin) bool { + if tok != "" { + return claudeSetupToken(x.Auth) == tok + } o, ok := parseClaudeCredentials(x.Auth) return ok && (c.OAuth.AccessToken != "" && o.OAuth.AccessToken == c.OAuth.AccessToken || c.OAuth.RefreshToken != "" && o.OAuth.RefreshToken == c.OAuth.RefreshToken) diff --git a/internal/provider/quota_last.go b/internal/provider/quota_last.go index 408af10ed..8d5a776ab 100644 --- a/internal/provider/quota_last.go +++ b/internal/provider/quota_last.go @@ -42,9 +42,10 @@ func lastQuotasPath() string { return filepath.Join(filepath.Dir(Path()), "quota // passing is an error that says nothing about the account: the vendor // rate limiting, failing or out of reach, or a Claude account's usage not -// read this time (errClaudeNotAsked, errClaudeSaved). A sign-in gone bad +// read this time (errClaudeNotAsked, errClaudeSaved), or one a setup-token +// can't read at all (errClaudeSetupToken). A sign-in gone bad // is not one. -var passing = regexp.MustCompile(`(?i)not read yet|doesn't read a saved account|rate.?limit|too many requests|429|internal server error|bad gateway|service unavailable|gateway timeout|deadline exceeded|timeout|timed out|connection (refused|reset)|no such host|network is unreachable|EOF|asks again|fetch failed|unable to connect|ECONN[A-Z]+|ENOTFOUND|EAI_AGAIN|socket hang up|HTTP 5\d\d`) +var passing = regexp.MustCompile(`(?i)not read yet|a setup-token can't read|doesn't read a saved account|rate.?limit|too many requests|429|internal server error|bad gateway|service unavailable|gateway timeout|deadline exceeded|timeout|timed out|connection (refused|reset)|no such host|network is unreachable|EOF|asks again|fetch failed|unable to connect|ECONN[A-Z]+|ENOTFOUND|EAI_AGAIN|socket hang up|HTTP 5\d\d`) // keyTag names a key's card among the last readings, by what it is (a // plan's windows, a balance) and a digest of the key, never the key: a diff --git a/internal/provider/signin.go b/internal/provider/signin.go index 3180c4130..6a3ddd750 100644 --- a/internal/provider/signin.go +++ b/internal/provider/signin.go @@ -893,6 +893,11 @@ func addLogin(l savedLogin) (using bool, err error) { ls := readLogins() l.User = codexName(ls, l) using = !signedIn || sameLogin(live, l) + if l.Agent == "claude" && claudeSetupToken(l.Auth) != "" { + // Claude Code itself can't be signed in to a setup-token: the + // account is magpie's alone, its own sign-in left as it is + using = false + } if first := claudeStandIn(ls); !signedIn && l.Agent == "claude" && first != "" { // logged out of Claude Code with accounts in magpie: it stays so, // as the user left it (a claude.ai sign-in beside magpie's token diff --git a/internal/provider/subscription_usage.go b/internal/provider/subscription_usage.go index aad1a569c..b638384bc 100644 --- a/internal/provider/subscription_usage.go +++ b/internal/provider/subscription_usage.go @@ -827,6 +827,9 @@ func claudeWindows(ctx context.Context, user string, active bool) ([]QuotaWindow return e.windows(now), nil case active: return []QuotaWindow{}, errClaudeNotAsked + case claudeTokenAccount(user): + // a refresh wouldn't read it either (readSavedClaudeUsage) + return []QuotaWindow{}, errClaudeSetupToken default: return []QuotaWindow{}, errClaudeSaved }