From 15b83901ac86044e08b0f73acbcc962ac95029d6 Mon Sep 17 00:00:00 2001 From: yetone Date: Sat, 31 Oct 2026 17:27:35 +0800 Subject: [PATCH] accounts: switch to the next account with room, or the one with the most left (#4532) StringKe (#4532), comparing magpie with cswap 0.29.0: there was no "switch to the next account", and when every account was past its line the automatic switch stayed on the spent one, where cswap moves to the account with the most room left. - `magpie accounts switch next` (provider.NextInOrder) takes the other accounts that are on in magpie, from the one after the account the agent is on, wrapping round: the first whose allowance is known and has room, else the one with the most room left, and says it is past its line. A saved Claude account not read yet is read first (readSpare), as the automatic switch's spares are. With no reading of any it refuses rather than guess; for any other agent it asks for the account by name. - NextLogin (shared by Codex and Claude Code): when the account the agent is on is spent and every spare is past its line too, it moves to the spare with the most room left (roomLeft: the fullest stopping window's distance below the switch share, or the account's own cap when lower), when that has at least roomMargin (1 point) more than the one it is on, so two all but even accounts don't trade the agent each look. A held, failed or unknown reading is never moved to. One model's own window still counts for nothing, as before. - docs: reference.md (the automatic switch and `next`; its "a Claude account magpie knows nothing of is not moved to" was stale since readSpare), providers-accounts.md's Used-up switch row, the en/zh/ja start pages' command table, `magpie help`. Run (on mote, sandbox HOME through the packages' TestMain): - go test -timeout 45m -count=1 ./internal/provider ./internal/cli: ok (144s, 44s), at this change's tree before the next commit's edits. - TestNextLoginTakesTheMostRoomWhenAllArePast and TestNextInOrder, each over codex and claude with three accounts: green; red with the fallback taken out of NextLogin (the two "most room" cases, both agents) and with NextInOrder not starting after the signed-in account ("the one after it", both agents). The "none has more by the margin" case fails without roomMargin. - Built the nogui binary and ran in a fresh sandbox HOME on mote: `accounts switch claude next --help` (prints the accounts help), `switch claude next` and `switch codex next` with no accounts ("has no other account that is on"), `switch gemini next` (asks for a name), `switch claude nxt` (no such account), `switch claude` (usage). - gofmt -l clean. Cross-OS vet: run at the head of this stack. Not tried: a real switch between real Claude or Codex accounts; the CLI `next` with real saved accounts (the provider tests cover the choice). --- docs/reference.md | 8 +- docs/subsystems/providers-accounts.md | 2 +- internal/cli/accounts_cli.go | 16 ++- internal/cli/main.go | 1 + internal/provider/codex_switch.go | 102 +++++++++++++++++- internal/provider/switch_next_test.go | 146 ++++++++++++++++++++++++++ site/public/docs/ja/start.html | 1 + site/public/docs/start.html | 1 + site/public/docs/zh/start.html | 1 + 9 files changed, 270 insertions(+), 8 deletions(-) create mode 100644 internal/provider/switch_next_test.go diff --git a/docs/reference.md b/docs/reference.md index 3ed4975cc..7dd49575a 100644 --- a/docs/reference.md +++ b/docs/reference.md @@ -1847,7 +1847,13 @@ in to a minute after it starts and every 5 minutes after: once it has used 98% of a window (100% In order), or reached its usage cap, magpie signs the agent in to the next ticked account, in their order, whose allowance is known and under that share. A saved Claude account magpie knows -nothing of yet (see below) is not moved to. Once the account it moved the +nothing of yet (see below) is read first. When every other account is +past that share too, magpie moves the agent to the one with the most room +left, if it has at least a point more than the account it is on; else the +agent stays. `magpie accounts switch claude next` (or `codex next`) does +the same by hand: the next ticked account after the one the agent is on, +in their order and wrapping round, that has room, or the one with the most +room left when none has. Once the account it moved the agent off has every window under 90% again, it signs the agent back in to it. *Keep … signed in to* turns this off: the agent stays on the first account, or on the account you picked, whatever it has left. It changes nothing in the gateway's routing. diff --git a/docs/subsystems/providers-accounts.md b/docs/subsystems/providers-accounts.md index ae55148a5..b133217ab 100644 --- a/docs/subsystems/providers-accounts.md +++ b/docs/subsystems/providers-accounts.md @@ -50,7 +50,7 @@ keys and accounts per request is in [Gateway routing and fallback](gateway-routi | 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. In the tray panel (whose Quick panel shortcut opens it from any app, shuizhuyu on X) it is the *account* line of the agent's opened row (`.ag-who`), drawn from the list kept from the last read (`panelAccounts`, `GET /api/providers?last=1`, no keychain read; a fresh read only when none is kept), so opening the panel reads no sign-in. The menu waits for one fresh `/api/providers` read and opens on what it says; *Manage accounts…* and a lapsed pick open the window's Providers (`window/main?view=providers`). The provider and login actions keep their answer as the last list (`keepProviders`), so a switch made anywhere is in the panel's next line at once (`TestKeptProvidersFollowActions`, `panel-switch-accounts.test.cjs`). 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. Claude Code on its own login is out long before a five-minute look notices (#4443: 4% left to refused in two minutes): while Claude has an account to move to, `KeepOnAnAccountWithRoom` looks at its sign-in every `claudeLookEvery` (a minute) between its full looks when `claudeLookDue`, that is when the account Claude Code is on is near out (`claudeNearOut`, `codexNearShare`; its `/usage` is then due after `claudeNearOutWait` rather than `claudeUsageWait`), or when Claude Code wrote a `rate_limit` refusal ("You've hit your … limit") into one of its sessions since that account's last `/usage` (`scanClaudeLimits`, which reads only what was appended to each `projects/*/*.jsonl` since the last scan). The refusal names no account, so it only makes the `/usage` read due (and the reading stale, `StaleAllowance`); the read decides (`TestClaudeNearOutIsReadEveryMinute`, `TestClaudeRefusalInSessionReadsAtOnce`, `TestKeepOnAnAccountWithRoomLooksAtClaudeNearOut`). | [`codex_switch.go`](../../internal/provider/codex_switch.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). When every one is past its line too, it goes to the one with the most room left (`roomLeft`: the fullest stopping window's distance below the switch share, or the account's own cap when lower), when that has more than the account it is on by `roomMargin` (1 point), so two all but even accounts don't trade it each look; else it stays (StringKe in #4532, after cswap's `best`; `TestNextLoginTakesTheMostRoomWhenAllArePast`). `magpie accounts switch next` (`NextInOrder`) takes the other accounts that are on, from the one after the account the agent is on, wrapping round: the first with room, else the one with the most room left, said to be past its line; with no reading of any, it refuses rather than guess (`TestNextInOrder`). 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. Claude Code on its own login is out long before a five-minute look notices (#4443: 4% left to refused in two minutes): while Claude has an account to move to, `KeepOnAnAccountWithRoom` looks at its sign-in every `claudeLookEvery` (a minute) between its full looks when `claudeLookDue`, that is when the account Claude Code is on is near out (`claudeNearOut`, `codexNearShare`; its `/usage` is then due after `claudeNearOutWait` rather than `claudeUsageWait`), or when Claude Code wrote a `rate_limit` refusal ("You've hit your … limit") into one of its sessions since that account's last `/usage` (`scanClaudeLimits`, which reads only what was appended to each `projects/*/*.jsonl` since the last scan). The refusal names no account, so it only makes the `/usage` read due (and the reading stale, `StaleAllowance`); the read decides (`TestClaudeNearOutIsReadEveryMinute`, `TestClaudeRefusalInSessionReadsAtOnce`, `TestKeepOnAnAccountWithRoomLooksAtClaudeNearOut`). | [`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) | | Routing groups | User-made groups from the Routing view, and auto-found groups of the same model across providers (derived, never stored). The same model is the same id as vendors agree on it (`sameModel`): lowercase, without a vendor's prefix, a version's dot as `-`, a run of spaces, `_` and `-` as one `-` (a relay listing its display name as the id, `GPT-6 Sol`, joins `gpt-6-sol`, Chill on Discord: `TestSameModelDisplayNameAsID`), and without a YYYYMMDD or Ark YYMMDD snapshot date. Every word still counts (`gpt-6`, `gpt-6-mini` and `gpt-6-sol` stay apart), as do a `:variant`, a four-digit release and OpenAI's dashed date (`gpt-4o-2024-08-06`, a pinned snapshot whose group id agents may already name). A provider kept "Only through routing groups" joins them the same way. Members are `provider/model[:effort]`. A group can nest another (`group/`); `SaveGroup` refuses loops. A group given another id (`agent.RenameGroup`: the Routing page, `magpie groups rename`, the TUI) moves every agent field on `group/` to `group/`, spelled as the agent spells it, through the same `renameRefs` a provider's rename uses, then `SyncCatalog`; before, the agents stayed on a group magpie no longer had (lucis0116 on X, `TestRenameGroupMovesTheAgentsOnIt`). A provider's or group's display name needs no move: `store` and `SaveGroup` drop the catalog, and `SyncCatalog` writes the new labels into every agent's list. `Match` takes a glob or `re:` pattern (#766), both matched in any case (`compilePattern`; `(?-i)` inside a `re:` makes case matter). What a pattern matches follows the members named, in the catalog's order, until the user drags it elsewhere (usrname1833 on Discord): `Placed` keeps the whole order, named and matched alike, and the group is read and routed in it (`placedIn`); a model matched since goes last, one no longer matched drops out, a save that sends the named members only leaves the matched where they were (`placedOver`), and a provider's or group's rename carries it (`TestGroupPatternMembersKeepTheirPlace`, `group-member-drag.test.cjs`). A found group follows the providers magpie has: one removed leaves it, while one switched off stays in it (`foundGroups`, `heldOffEntries`; one without a key, such as a plugin not signed in, finds no group), skipped by `membersIn`, left off a found group's card, logos and TUI line with a count of those switched off (XYenon on Discord: `routing-provider-off.test.cjs`, `TestFoundGroupLineLeavesASwitchedOffProviderOut`) and said as switched off in its editor and the TUI's group page, so switching one of two providers off for a while doesn't take the group away from the agents, rules and groups set to it; it is back in its place once on again (#2671: `TestFoundGroupStaysWithAProviderOff`, `TestFoundGroupWithAProviderOff`, `TestReseatKeepsAFoundGroupWithAProviderOff`, `TestFoundGroupMemberOfASwitchedOffProvider`). A found group the user changed (an `auto-…` id stored) is read without the members of providers magpie no longer has (`withoutRemoved`, not written back, so a provider back under its id is back in it), except a manual group's pick, a rule's model, or all of them when none would be left. A switched-off provider's members stay in it, skipped by `membersIn`, and the Routing page says them as switched off (`memberJSON.providerOff`). The user's own groups keep their members. Three templates make a group in one click from the models the user has (`provider.Templates`, `AddTemplate`; the Routing page's cards before a first group and its Templates menu after, `magpie group template [kind] [name]`): `smart` sends a hard turn to the strongest model and an easy one or a compaction to a cheap one, asked by a classifier (the decision API when there is one, else the cheapest priced model that doesn't reason); `thrifty` starts on two cheap models of different providers and sends high reasoning to the strongest; `steady` fails over between the strongest model of up to three providers. A model is weighed by its maker's list price when known, else what its provider charges, else by its id's size words (`sizeOf`); one over `tooDear` (USD 100 a million output tokens) is never picked. A template that can't be made says what is missing (`Need`). It is saved under a name and id no group has (`freeGroupName`, shared with `CopyGroup`), never over one. A group is shared as text (`ShareGroup`, a group row's Copy to share): JSON marked `"magpie": "routing-group"` with a format `version` (`ShareVersion`), holding the group's members as it names them, patterns, routing, rules, classifier and settings. A group holds only `provider/model` ids, never a key, account or address, and the derived matches, found/hidden/off flags and the rules that hold by a folder (a path on the sharer's machine, `Rule.Folders`) stay behind; a pasted one is left out too. `ImportGroup` (the Routing page's Import, `POST /api/groups/import`) reads it with words or a code fence around it, refuses another text, a newer format or none (`ShareError`, said in the reader's language). A member whose provider the importer has is kept; else the same model (`AutoGroupOf`) under the first provider of theirs that serves it (`Instead`); else it is left out and named (`Missing`), with the rules that send to it, its place among the off and fast members, and a classifier gone takes the intent rules and auto effort with it. Nothing is added when no member is left; what is added gets a free name, never replacing a group. A group of patterns only that match nothing now (a plugin's models not listed) has no members: `/api/groups` says them, and an unmakeable template's, as `[]`, never `null`; the Routing page reads the response through `groupsFrom` and draws a group it still can't draw as one row saying so, so one bad group never hides the rest (#1585). | [`group.go`](../../internal/provider/group.go), [`grouptemplate.go`](../../internal/provider/grouptemplate.go), [`group_share.go`](../../internal/provider/group_share.go) | | Allowance | `Quotas` asks every vendor at once: subscription windows (`SubscriptionUsage`), key-bought plans (`PlanQuotas`) and key balances (`KeyBalances`). The Usage page, `magpie quota --json` and `GET /v1/magpie/quotas` read it, each window with its whole-window estimate (`Holds`/`HoldsWhy`, `usage.WithWindowHolds`, which `quotaReport` reaches through the `ReckonHolds` hook since package provider can't import usage, #2333). A single card can be read again on its own (#840). A remote magpie's cards come from what it has kept (`CachedCards`, `GET /v1/magpie/quotas/cards`) and are never read there for this computer except by a card's refresh (`POST /v1/magpie/quotas/refresh`, throttled per card). What it has kept is the Usage page's cards with the readings made behind the requests since laid over them, a later one over an earlier by `readSeq` (`cards_kept.go`): each account's `LoginUsage` reading (the used-up switch, the Codex warm-up, routing's `Allowances`), and each key's `KeyAllowance` windows on its plan or balance card. A Claude account's windows Claude Code told as it answered (`NoteClaudeLimits`, kept in `claudeUsage` with their own `heardSeq`, which drops the account's `LoginUsage` reading) stand on its card over any reading started before them (`withHeardClaude`, #2206), so a magpie only requests reach still tells them. An account or key read that way and never on the page gets a card from that reading, and after a restart, before either is read again, the cards come from `quotas.json`, dated (`AsOf`). A magpie serving only other magpies has nobody on its page (#1313). Each key of a remote-magpie provider also gets a card of its own, under `/~keys`, one section per key (#1547, `remoteKeyCards` in `remote_key_limits.go`): the gateway key's limit as that magpie holds it, read from `GET /v1/magpie/limit` asked with that key alone, so a key never sees another's numbers. It shows a window per cap (tokens, spend) named for the period, used against the cap, with its reset, plus `GatewayKey` (what is left, calls, a cycle of days, used up); a key held to no limit shows `Unlimited`. It is kept for `remoteCardsFor` like the remote's cards and read again by the card's refresh (`?provider=/~keys&user=`). A read that fails keeps the last numbers, dated (`AsOf`); with none the card says why, never zero or no limit. A remote from before `/v1/magpie/limit` (404) says it is too old to tell (`errRemoteNoKeyLimit`). A remote that holds the key to a budget, models or accounts answers its cards 403 `gateway_key_held` (#1981, `errKeyHeld`): the cards kept from before are dropped and only the key's own card shows. Its owner can let the key be told the cards of what it may use (#2216, `magpie gateway-key quotas on`); the remote then answers those, and 403 as before when that is none. A remote's cards are kept by provider and key (`remoteCardsID`), so a changed key never shows what the old one was told, and a read is kept only over one asked before it (`keepRemoteCards`). Cursor, Grok and a Kiro key keep the page's cards only. With Settings → Allowances → *Allowance reads* at *When I ask* (`QuotaReads == "asked"`, #1518: magpie started at login before the proxy app read by itself, direct), only a read the user asked for goes out: the Usage page or the tray panel's Allowances opened (no more than once in 30s, `quotasOpened`, #1588) or refreshed (`?asked=1`), a card's refresh (`RefreshUsage`), `magpie quota`, `magpie accounts`, `magpie quota wait` and the TUI's quotas (`Asked`). Any other read (`quotaReading` → `holdUnasked`) carries `netproxy.Hold`, so its requests fail before they leave, and every reader gives back what it last read, dated, or "not read yet" (`errNotAsked`): routing, the used-up switch, the menu bar and alerts go by that. An account refused for its quota (`StaleAllowance` → `markStaleRead`) or a key refused (`StaleKeyAllowance` → `refused`) is still read, once (`unheld`). Warm-up and check-in are not reads and are unchanged. A plugin's window may carry a prepaid wallet's `balance` in its `unit` and no share (`QuotaWindow.Balance`, #3950): the card and `magpie quota` show the figure (`BalanceText`), and routing reads it through `Allowance.Left`. | [`cards_kept.go`](../../internal/provider/cards_kept.go), [`quotas.go`](../../internal/provider/quotas.go), [`subscription_usage.go`](../../internal/provider/subscription_usage.go), [`planquota.go`](../../internal/provider/planquota.go), [`balance.go`](../../internal/provider/balance.go), [`quota_refresh.go`](../../internal/provider/quota_refresh.go), [`remote_quotas.go`](../../internal/provider/remote_quotas.go), [`remote_key_limits.go`](../../internal/provider/remote_key_limits.go), [`quota_asked.go`](../../internal/provider/quota_asked.go) | diff --git a/internal/cli/accounts_cli.go b/internal/cli/accounts_cli.go index 71e82fc13..3c5091a18 100644 --- a/internal/cli/accounts_cli.go +++ b/internal/cli/accounts_cli.go @@ -21,7 +21,7 @@ import ( ) // accountsCmd: `magpie accounts [agent] [--json]`, `magpie accounts add `, -// `magpie accounts switch|forget `, +// `magpie accounts switch|forget `, `magpie accounts switch next`, // `magpie accounts project `, // `magpie accounts alias [|--clear]` // `magpie accounts switch-only [on|off]` @@ -31,7 +31,7 @@ func accountsCmd(args []string) error { if len(args) > 1 && args[1] == "discovery" { return accountsDiscoveryCmd(args[2:]) } - const usage = "usage: magpie accounts [claude|codex|grok|copilot|gemini|antigravity|zed|factory|mimo|] [--json] | magpie accounts add > | magpie accounts add copilot [--host .ghe.com] | magpie accounts import ... [--yes] | magpie accounts refresh [--json] | magpie accounts checkin [--json] | magpie accounts switch|forget > | magpie accounts switch|forget copilot [@.ghe.com] [--host .ghe.com] | magpie accounts project | magpie accounts alias > [|--clear] | magpie accounts switch-only [on|off]" + const usage = "usage: magpie accounts [claude|codex|grok|copilot|gemini|antigravity|zed|factory|mimo|] [--json] | magpie accounts add > | magpie accounts add copilot [--host .ghe.com] | magpie accounts import ... [--yes] | magpie accounts refresh [--json] | magpie accounts checkin [--json] | magpie accounts switch|forget > | magpie accounts switch next | magpie accounts switch|forget copilot [@.ghe.com] [--host .ghe.com] | magpie accounts project | magpie accounts alias > [|--clear] | magpie accounts switch-only [on|off]" agentID := func(s string) (string, error) { switch strings.ToLower(s) { case "claude", "cc": @@ -190,9 +190,19 @@ func accountsCmd(args []string) error { login, _, _ := strings.Cut(args[3], "@") args[3] = provider.CopilotAccountName(login, h) } - if args[3], err = accountNamed(id, args[3]); err != nil { + over := false + if args[1] == "switch" && strings.EqualFold(args[3], "next") { + // the next account in order with room, or the one with the most + // room left when every one is past its line + if args[3], over, err = provider.NextInOrder(context.Background(), id); err != nil { + return err + } + } else if args[3], err = accountNamed(id, args[3]); err != nil { return err } + if over { + fmt.Println(muted.Render("every other account is past its line; " + args[3] + " has the most room left")) + } if args[1] == "forget" { moved, err := agent.Reseat(func() error { return provider.ForgetLogin(id, args[3]) }) if err != nil { diff --git a/internal/cli/main.go b/internal/cli/main.go index b1a26f64f..50f680be1 100644 --- a/internal/cli/main.go +++ b/internal/cli/main.go @@ -97,6 +97,7 @@ const usage = `magpie — one place to pick every agent's model magpie accounts discovery [on|off] read agents' sign-ins (default on; MAGPIE_NO_ACCOUNTS=1 disables too) magpie accounts import ... [--yes] bring in accounts from other tools' files (Codex's auth.json, Cockpit Tools, CLIProxyAPI, Sub2API); the tool a ChatGPT or Claude file came from is signed out of it magpie accounts switch sign the agent in to another of them + magpie accounts switch next to the next account in order with room, or the one with the most left magpie accounts refresh renew the saved ChatGPT and Claude sign-ins now (the gateway does it every 8 days) magpie accounts checkin WorkBuddy's daily check-in (签到) for each WorkBuddy account, now (Settings can do it daily) magpie accounts project the Google Cloud project a Google account's requests go to diff --git a/internal/provider/codex_switch.go b/internal/provider/codex_switch.go index f744be6a0..492c37508 100644 --- a/internal/provider/codex_switch.go +++ b/internal/provider/codex_switch.go @@ -32,7 +32,9 @@ package provider import ( "context" "encoding/json" + "fmt" "log" + "math" "os" "path/filepath" "slices" @@ -202,8 +204,10 @@ func usedPast(q SubscriptionQuota, share float64, now time.Time) bool { // one it is on: the account magpie moved it off, once that has room again // (back); else, when the one it is on is spent, the first of its other // accounts that are on in magpie, in the order they were saved, whose -// allowance is known and not spent. A saved Claude account not read yet is -// read then (readSpare). ok is false when the agent should stay. +// allowance is known and not spent, or, when every one is past its line +// too, the one with the most room left (roomLeft). A saved Claude account +// not read yet is read then (readSpare). ok is false when the agent should +// stay. func NextLogin(ctx context.Context, agent string) (from, to string, back, ok bool) { if leftAlone(agent) { return "", "", false, false // magpie has no say in its sign-in, or was told to leave it be @@ -282,6 +286,13 @@ func NextLogin(ctx context.Context, agent string) (from, to string, back, ok boo for user, q := range someLoginUsage(ctx, agent, users...) { u[user] = q } + // every spare past its line too: the one with the most room left, when + // it has more than the one it is on by roomMargin, so that the agent + // isn't moved to and fro between two all but even; else it stays + best, most := "", math.Inf(-1) + if !q.Held { + most = roomLeft(q, share, AccountCapsOf(agent, from), now) + roomMargin + } for _, l := range spares { q, known := u[l.User] if agent == "claude" && (!known || unreadSpare(q)) { @@ -290,13 +301,98 @@ func NextLogin(ctx context.Context, agent string) (from, to string, back, ok boo // a time and only till one has room q, known = readSpare(ctx, l) } - if known && q.Error == "" && !q.Held && !usedPast(q, share, now) && !capped(l.User, q) { + if !known || q.Error != "" || q.Held { + continue + } + if !usedPast(q, share, now) && !capped(l.User, q) { return from, l.User, false, true } + if r := roomLeft(q, share, AccountCapsOf(agent, l.User), now); r > most { + best, most = l.User, r + } + } + if best != "" { + return from, best, false, true } return "", "", false, false } +// roomMargin is how much more room (roomLeft) an account past its line +// needs than the one the agent is on, past its line too, to be moved to. +const roomMargin = 1 + +// roomLeft is how far the fullest of q's windows that stop the account for +// every model is below the line it is moved off at: its own usage cap +// (account_caps.go) when that is lower, else share. Below zero when it is +// past the line; a window renewed since it was read, or none, leaves the +// whole line. +func roomLeft(q SubscriptionQuota, share float64, caps WindowCaps, now time.Time) float64 { + room := share + for _, w := range q.Windows { + if w.Aside || w.Model != "" || w.Unlimited || resetPassed(w, now) { + continue + } + line := share + if c, _ := caps.Of(w.Name); c > 0 && float64(c) < line { + line = float64(c) + } + room = min(room, line-w.Used) + } + return room +} + +// NextInOrder is the account `magpie accounts switch next` signs +// agent in to: of its other accounts that are on in magpie, taken in their +// order from the one after the account it is on, the first whose allowance +// is known and has room; when none has, the one with the most room left +// (roomLeft), and over says so. A saved Claude account not read yet is read +// then, as NextLogin's spares are. +func NextInOrder(ctx context.Context, agent string) (to string, over bool, err error) { + if !slices.Contains(loginAgents, agent) { + return "", false, fmt.Errorf("next switches Claude Code's and Codex's accounts; name the %s account to switch to", agent) + } + ls := Logins(agent) + at := slices.IndexFunc(ls, func(l Login) bool { return l.Active }) + var order []Login + for i := range ls { + l := ls[(at+1+i)%len(ls)] + if !l.Active && l.On && l.Lapsed == "" && l.home == "" && !l.Token { + order = append(order, l) + } + } + if len(order) == 0 { + return "", false, fmt.Errorf("%s has no other account that is on in magpie to switch to", agent) + } + users := make([]string, 0, len(order)) + for _, l := range order { + users = append(users, l.User) + } + share, _ := loginSwitching(agent) + u := someLoginUsage(ctx, agent, users...) + now := time.Now() + best, most := "", math.Inf(-1) + for _, l := range order { + q, known := u[l.User] + if agent == "claude" && (!known || unreadSpare(q)) { + q, known = readSpare(ctx, l) + } + if !known || q.Error != "" || q.Held { + continue + } + caps := AccountCapsOf(agent, l.User) + if !usedPast(q, share, now) && !capReached(q, caps, now) { + return l.User, false, nil + } + if r := roomLeft(q, share, caps, now); r > most { + best, most = l.User, r + } + } + if best == "" { + return "", false, fmt.Errorf("magpie has no reading of %s's other accounts' usage: name the one to switch to (magpie accounts switch %s )", agent, agent) + } + return best, true, nil +} + // unreadSpare says q, a saved Claude account's reading, has nothing to go // by: never read (a /usage not run), or a read that failed for a reason // not the account's own. Its /usage is then run (readSpare). diff --git a/internal/provider/switch_next_test.go b/internal/provider/switch_next_test.go new file mode 100644 index 000000000..b4b3f37c1 --- /dev/null +++ b/internal/provider/switch_next_test.go @@ -0,0 +1,146 @@ +package provider + +import ( + "context" + "slices" + "strings" + "testing" + "time" +) + +// threeAccounts signs agent in to three accounts in a sandbox HOME, all on +// in magpie, and answers them as `next` takes them: the two the agent +// isn't on, from the one after the account it is on in their order, +// wrapping round, then that account. +func threeAccounts(t *testing.T, agent string) []string { + t.Helper() + if agent == "codex" { + home := signIn(t) // me@example.com + rememberLogins(true) + codexSignIn(t, home, "work@example.com", "r-work") + rememberLogins(true) + codexSignIn(t, home, "third@example.com", "r-third") + rememberLogins(true) + } else { + claudeThree(t) + } + ls := Logins(agent) + at := slices.IndexFunc(ls, func(l Login) bool { return l.Active }) + if len(ls) != 3 || at < 0 { + t.Fatalf("not three accounts, one signed in: %+v", ls) + } + if at == 2 { + t.Fatalf("the one signed in is the last, so nothing wraps round: %+v", ls) + } + var users []string + for i := range ls { + l := ls[(at+1+i)%3] + if err := SetLoginOn(agent, l.User, true); err != nil { + t.Fatal(err) + } + users = append(users, l.User) + } + return users +} + +func usedAt(agent string, used map[string]float64) func(context.Context, string) map[string]SubscriptionQuota { + at := time.Now().Add(time.Hour) + return func(context.Context, string) map[string]SubscriptionQuota { + out := map[string]SubscriptionQuota{} + for u, v := range used { + out[u] = SubscriptionQuota{Provider: agent, User: u, Windows: []QuotaWindow{ + {Name: "5 hours", Used: v, ResetsAt: &at, Span: 5 * time.Hour}, + {Name: "Fable", Used: 100, Model: "fable", ResetsAt: &at}, // one model's own: never counted + }} + } + return out + } +} + +// StringKe (#4532): when the account the agent is on is spent and every +// other is past its line too, the switch moves to the one with the most +// room left, as cswap does, and stays when none has more than the one it +// is on by roomMargin. Codex shares the switch, so it is held to it too. +func TestNextLoginTakesTheMostRoomWhenAllArePast(t *testing.T) { + for _, agent := range []string{"codex", "claude"} { + t.Run(agent, func(t *testing.T) { + u := threeAccounts(t, agent) + on := u[2] + t.Cleanup(func() { LoginUsageVia(nil) }) + for _, c := range []struct { + name string + used []float64 // u[0], u[1], on + to string + }{ + {"the first has room", []float64{50, 99, 100}, u[0]}, + {"the second has the most room", []float64{99.5, 98.5, 100}, u[1]}, + {"the first has the most room", []float64{98.2, 99.9, 100}, u[0]}, + {"none has more by the margin", []float64{99.5, 99.5, 100}, ""}, + {"the one it is on has the most", []float64{100, 100, 99}, ""}, + } { + LoginUsageVia(usedAt(agent, map[string]float64{u[0]: c.used[0], u[1]: c.used[1], on: c.used[2]})) + from, to, back, ok := NextLogin(context.Background(), agent) + if c.to == "" { + if ok { + t.Errorf("%s: moved %q→%q, want it to stay", c.name, from, to) + } + continue + } + if !ok || back || from != on || to != c.to { + t.Errorf("%s: got %q→%q back=%v ok=%v, want %q→%q", c.name, from, to, back, ok, on, c.to) + } + } + }) + } +} + +// `magpie accounts switch next` takes the accounts in order from +// the one after the account the agent is on, wrapping round: the first +// with room, else the one with the most room left, said to be past its +// line; one off in magpie is never taken. +func TestNextInOrder(t *testing.T) { + for _, agent := range []string{"codex", "claude"} { + t.Run(agent, func(t *testing.T) { + u := threeAccounts(t, agent) + on := u[2] + t.Cleanup(func() { LoginUsageVia(nil) }) + for _, c := range []struct { + name string + used []float64 + off int // 1-based index of an account turned off, 0 none + to string + over bool + }{ + {"the one after it", []float64{10, 10, 10}, 0, u[0], false}, + {"the first spent, the second has room", []float64{99, 10, 10}, 0, u[1], false}, + {"every one past, the second has the most", []float64{99.5, 98.5, 10}, 0, u[1], true}, + {"every one past, the first has the most", []float64{98.5, 100, 10}, 0, u[0], true}, + {"the first off", []float64{10, 10, 10}, 1, u[1], false}, + } { + LoginUsageVia(usedAt(agent, map[string]float64{u[0]: c.used[0], u[1]: c.used[1], on: c.used[2]})) + if c.off > 0 { + if err := SetLoginOn(agent, u[c.off-1], false); err != nil { + t.Fatal(err) + } + } + to, over, err := NextInOrder(context.Background(), agent) + if err != nil || !strings.EqualFold(to, c.to) || over != c.over { + t.Errorf("%s: got %q over=%v err=%v, want %q over=%v", c.name, to, over, err, c.to, c.over) + } + if c.off > 0 { + if err := SetLoginOn(agent, u[c.off-1], true); err != nil { + t.Fatal(err) + } + } + } + // none read: magpie says so rather than guess + LoginUsageVia(func(context.Context, string) map[string]SubscriptionQuota { return map[string]SubscriptionQuota{} }) + if to, _, err := NextInOrder(context.Background(), agent); err == nil { + t.Errorf("no readings: got %q, want an error", to) + } + }) + } + if _, _, err := NextInOrder(context.Background(), "gemini"); err == nil { + t.Error("next for Gemini CLI: want an error") + } +} diff --git a/site/public/docs/ja/start.html b/site/public/docs/ja/start.html index aa2d9c380..bcd09aceb 100644 --- a/site/public/docs/ja/start.html +++ b/site/public/docs/ja/start.html @@ -258,6 +258,7 @@ magpie claude group/opus-anywhere # これを使う

magpie presetsmagpie が知っているベンダー magpie provider add deepseek sk-…プリセットをキー付きで追加 magpie accounts add codexClaude または ChatGPT のサブスクリプションをもう 1 つサインイン + magpie accounts switch claude nextClaude Code(または codex)を、まだ余裕のある次のアカウントに切り替え。どれも上限近くなら、残りが最も多いアカウントへ magpie accounts discovery offエージェントのサインイン(Claude Code と Codex のファイル、キーチェーン)を読み取らない。on で再び読み取る magpie providersプロバイダ一覧:ホスト、キー、モデル、使っているエージェント magpie modelsエージェントが選べるすべてのモデル(provider/model 形式) diff --git a/site/public/docs/start.html b/site/public/docs/start.html index 680ee8a7d..b817ed699 100644 --- a/site/public/docs/start.html +++ b/site/public/docs/start.html @@ -258,6 +258,7 @@ magpie claude group/opus-anywhere # use it magpie presetsThe vendors magpie knows magpie provider add deepseek sk-…Add a preset with its key magpie accounts add codexSign in to one more Claude or ChatGPT subscription + magpie accounts switch claude nextSign Claude Code (or codex) in to the next of your accounts that has room, or the one with the most left when none has magpie accounts discovery offNever read your agents’ sign-ins (Claude Code’s and Codex’s files, the Keychain); on reads them again magpie providersYour providers: host, key, models, who uses them magpie modelsEvery model agents can pick, as provider/model diff --git a/site/public/docs/zh/start.html b/site/public/docs/zh/start.html index 8a319a3ed..c21d561fb 100644 --- a/site/public/docs/zh/start.html +++ b/site/public/docs/zh/start.html @@ -258,6 +258,7 @@ magpie claude group/opus-anywhere # 使用它 magpie presetsmagpie 内置的厂商预设 magpie provider add deepseek sk-…用密钥添加一个预设 magpie accounts add codex再登录一个 Claude 或 ChatGPT 订阅 + magpie accounts switch claude next把 Claude Code(或 codex)切到下一个还有额度的账号;都已过切换线时,切到剩得最多的那个 magpie accounts discovery off不读取智能体的登录信息(Claude Code 和 Codex 的文件、钥匙串);on 重新读取 magpie providers你的供应商:地址、密钥、模型、谁在用 magpie modelsAgent 能选的所有模型,写作 provider/model