From 2ff75161dc78801e6141c31c8730ec948677a542 Mon Sep 17 00:00:00 2001 From: yetone Date: Fri, 30 Oct 2026 21:09:56 +0800 Subject: [PATCH] switch: Claude Code near out or refused for its limit is moved on within a minute (#4443) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit In switch-only mode, Claude Code asks Anthropic directly, so magpie learns the active account is out only from a `claude -p /usage` read. That read was due 5 to 15 minutes (claudeUsageWait) after the last one, and KeepOnAnAccountWithRoom looked at Claude's sign-in only every 5 minutes. Codex already had a 1-minute near-out cadence; Claude had none. mydosu's account read 4% left at 12:16:15, which is under Smart's 98% threshold, so it was rightly not moved then. It burnt through within the 5-minute gap, and Claude Code refused for about 1.5 minutes until a hand switch, while the other account had 100% left. Changed: - While Claude has an account to move to, the loop looks at its sign-in every claudeLookEvery (1 min) between the full looks (claudeLookDue). - Near out (an all-model window at 90% or more, codexNearShare), the active account's /usage is due a minute after the last read instead of at its 5-15 minute wait (claudeWaitOf). - When Claude Code writes its own rate_limit refusal ("You've hit your … limit": error "rate_limit", isApiErrorMessage) into a session in ~/.claude/projects/*/*.jsonl, the next look reads /usage at once and marks the reading stale (StaleAllowance). Only the bytes appended since the last scan are read (at most 1MB per session per scan). The first scan only marks where the sessions end. The refusal is a cue for the read, not a switch by itself: the transcript doesn't say which account was refused. - Cost per minute: Logins("claude") plus leftAlone. With a spare, also a stat of each session file and a read of the appended bytes. /usage runs every minute only while the account is near out and in use, or after a refusal (30s floor still applies). Run: - New tests: TestClaudeNearOutIsReadEveryMinute, TestClaudeRefusalInSessionReadsAtOnce, TestScanClaudeLimits, TestKeepOnAnAccountWithRoomLooksAtClaudeNearOut. Pass under -race -count=3 on mote, with TestClaudeSwitchOnly* and TestClaudeUsage*. - Broken by hand, each red: no near-out wait -> TestClaudeNearOutIsReadEveryMinute ("switched to \"\""); no refusal due -> TestClaudeRefusalInSessionReadsAtOnce; no in-between look in the loop -> TestKeepOnAnAccountWithRoomLooksAtClaudeNearOut (still on pro@x.com at its 1-minute deadline). - Windows (xiaomi-gpu, win-run): the new and Claude tests pass. The whole internal/provider package has 13 reds there, and all 13 fail the same way run alone at origin/main d99e213f5: #2808 (keychain, SavedButSignedOut), #4115 (CodexDaemonEnv, CodexListTag), and #4446, filed now (TestCodexSignInKnown, TestGitOnDisk*). - mote at eaa2eeb29 (this commit on fa427216a): gofmt -l clean; go vet (nogui, GOOS=linux nogui, GOOS=windows); go build for darwin, linux and windows; go test -tags nogui -count=1 -timeout 45m ./... exit 0, every package ok (gateway 672s, agent 268s, provider 173s). - Rebased on 4 commits (gateway, plugin, provider/codex_models; none touch these files), at the pushed tree on mote: go vet (nogui, linux, windows), darwin and windows builds, internal/provider ok (213s) and internal/gateway ok (716s). Not tried: a real Claude account running out, and a real Claude Code session on Windows writing its refusal. The refusal line's format was checked read-only against real local transcripts. No UI added. --- docs/subsystems/providers-accounts.md | 2 +- internal/provider/claude_out_soon.go | 229 +++++++++++++++++++ internal/provider/claude_out_soon_test.go | 256 ++++++++++++++++++++++ internal/provider/codex_switch.go | 49 ++++- internal/provider/subscription_usage.go | 12 +- 5 files changed, 534 insertions(+), 14 deletions(-) create mode 100644 internal/provider/claude_out_soon.go create mode 100644 internal/provider/claude_out_soon_test.go diff --git a/docs/subsystems/providers-accounts.md b/docs/subsystems/providers-accounts.md index 433d31743..d905c948e 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. | [`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). 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). 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/provider/claude_out_soon.go b/internal/provider/claude_out_soon.go new file mode 100644 index 000000000..f31f866fc --- /dev/null +++ b/internal/provider/claude_out_soon.go @@ -0,0 +1,229 @@ +package provider + +// Claude Code on its own login asks Anthropic itself, so magpie learns the +// account it is on is out only from a /usage run, which unasked comes +// claudeUsageWait (5 to 15 minutes) after the last, and the switch looked +// only every loginSwitchEvery. An account burnt from 4% left to its limit +// in two minutes, and Claude Code said "You've hit your 5-hour limit" for +// over a minute while the other account had all of it left (#4443, +// mydosu). So while Claude has an account to move to, its sign-in is +// looked at every claudeLookEvery, and two things make that look read +// /usage at once rather than at its wait: +// +// - the account near out (claudeNearOut): read every claudeNearOutWait; +// - Claude Code having written a rate_limit refusal into one of its +// sessions since the last read (scanClaudeLimits), which is what it +// shows as "You've hit your … limit". Which account it was refused on +// the transcript doesn't say, so it is only the cue for the read; the +// read decides. + +import ( + "bufio" + "bytes" + "encoding/json" + "io" + "os" + "path/filepath" + "strings" + "sync" + "sync/atomic" + "time" +) + +// claudeLookEvery is how often Claude's sign-in is looked at between +// KeepOnAnAccountWithRoom's full looks, while it has an account to move to. +// A var so tests can say. +var claudeLookEvery = time.Minute + +// claudeNearOutWait is how long after a /usage run the next unasked one is +// due while the account Claude Code is on is near out, in place of +// claudeUsageWait. +const claudeNearOutWait = time.Minute + +// claudeNearOut says the windows ws, of the account Claude Code is on, are +// near out: one that stops the account for every model is at +// codexNearShare or past. +func claudeNearOut(ws []QuotaWindow, now time.Time) bool { + return usedPast(SubscriptionQuota{Windows: ws}, codexNearShare, now) +} + +// claudeWaitOf is how long after e's last /usage run the next unasked one +// of the account Claude Code is on is due. +func claudeWaitOf(e claudeUsageEntry, now time.Time) time.Duration { + if e.ws != nil && claudeNearOut(e.windows(now), now) { + return min(e.wait, claudeNearOutWait) + } + return e.wait +} + +// claudeLimitHit is when Claude Code last wrote a rate_limit refusal into +// one of its sessions, as unix nanoseconds (zero: none seen). +var claudeLimitHit atomic.Int64 + +// claudeLimitHitAfter says Claude Code was refused for its limit after t. +func claudeLimitHitAfter(t time.Time) bool { + n := claudeLimitHit.Load() + return n != 0 && time.Unix(0, n).After(t) +} + +// claudeTranscripts is where scanClaudeLimits got to: the sessions written +// to are read on from where the last scan stopped, so each line is read +// once. +var claudeTranscripts struct { + sync.Mutex + started bool + off map[string]int64 +} + +// claudeScanTail is the most of one session read by one scan: a refusal is +// the last line Claude Code writes, and a session that grew more than this +// since is read from its end. +const claudeScanTail = 1 << 20 + +// scanClaudeLimits reads what Claude Code wrote to its sessions (each +// project's *.jsonl) since the last scan and keeps the time of the latest +// rate_limit refusal in claudeLimitHit. The first scan only marks where the +// sessions end: what was refused before magpie looked is the startup +// read's to tell. Its cost is a stat of each session and a read of what +// was added to the ones written to. +func scanClaudeLimits() { + c := &claudeTranscripts + c.Lock() + defer c.Unlock() + projects := filepath.Join(filepath.Dir(claudeCredentialsPath()), "projects") + dirs, _ := os.ReadDir(projects) + off := make(map[string]int64, len(c.off)) + for _, d := range dirs { + root := filepath.Join(projects, d.Name()) + if !d.IsDir() { + if fi, err := os.Stat(root); err != nil || !fi.IsDir() { + continue + } + } + files, _ := os.ReadDir(root) + for _, f := range files { + if f.IsDir() || !strings.HasSuffix(f.Name(), ".jsonl") { + continue + } + fi, err := f.Info() + if err != nil { + continue + } + path := filepath.Join(root, f.Name()) + was, known := c.off[path] + switch { + case !c.started: + off[path] = fi.Size() + case known && was == fi.Size(): + off[path] = was + default: + if !known { + was = 0 // a session begun since the last scan + } + off[path] = scanClaudeSession(path, was, fi.Size()) + } + } + } + c.off, c.started = off, true +} + +// scanClaudeSession reads path from from to size for rate_limit refusals, +// and answers where it got to: the end of its last whole line, so a line +// still being written is read whole next time. +func scanClaudeSession(path string, from, size int64) int64 { + if size < from { + from = 0 // written over + } + start := max(from, size-claudeScanTail) + f, err := os.Open(path) + if err != nil { + return from + } + defer f.Close() + if _, err := f.Seek(start, io.SeekStart); err != nil { + return from + } + r := bufio.NewReader(io.LimitReader(f, size-start)) + pos := start + if start > from { + // started mid-line: what is before the first newline is cut + skipped, err := r.ReadBytes('\n') + pos += int64(len(skipped)) + if err != nil { + return size // all one line not ended, longer than any refusal + } + } + for { + line, err := r.ReadBytes('\n') + if err != nil { + return pos // the rest is a line not yet ended + } + pos += int64(len(line)) + noteClaudeRefusal(line) + } +} + +// claudeRefusal is what marks a line Claude Code writes for a refusal for +// the account's limit ("You've hit your session limit"), cheaply found +// before it is parsed. +var claudeRefusal = []byte(`"rate_limit"`) + +// noteClaudeRefusal keeps the time of line in claudeLimitHit when it is +// Claude Code's own message for a rate_limit refusal. +func noteClaudeRefusal(line []byte) { + if !bytes.Contains(line, claudeRefusal) { + return + } + var m struct { + Error string `json:"error"` + APIError bool `json:"isApiErrorMessage"` + Timestamp string `json:"timestamp"` + } + if json.Unmarshal(line, &m) != nil || m.Error != "rate_limit" || !m.APIError { + return + } + at, err := time.Parse(time.RFC3339Nano, m.Timestamp) + if err != nil { + at = time.Now() + } + for { + was := claudeLimitHit.Load() + if at.UnixNano() <= was || claudeLimitHit.CompareAndSwap(was, at.UnixNano()) { + return + } + } +} + +// claudeLookDue says Claude's sign-in is to be looked at before the next +// full look: it has an account to move to, and the account Claude Code is +// on is near out, or Claude Code was refused for its limit since that +// account's last /usage run. A refusal makes the account's reading stale +// (StaleAllowance), so the look reads it even with allowances read only +// when asked. +func claudeLookDue() bool { + if leftAlone("claude") { + return false + } + var active string + spare := false + for _, l := range Logins("claude") { + switch { + case l.Active: + active = l.User + case l.On && l.Lapsed == "" && l.home == "" && !l.Token: + spare = true + } + } + if active == "" || !spare { + return false + } + scanClaudeLimits() + claudeUsage.Lock() + e := claudeUsage.m[strings.ToLower(active)] + claudeUsage.Unlock() + if claudeLimitHitAfter(e.tried) { + StaleAllowance("claude", active) + return true + } + return e.ws != nil && claudeNearOut(e.windows(time.Now()), time.Now()) +} diff --git a/internal/provider/claude_out_soon_test.go b/internal/provider/claude_out_soon_test.go new file mode 100644 index 000000000..4e0920e06 --- /dev/null +++ b/internal/provider/claude_out_soon_test.go @@ -0,0 +1,256 @@ +package provider + +import ( + "context" + "fmt" + "os" + "path/filepath" + "slices" + "strings" + "sync" + "sync/atomic" + "testing" + "time" +) + +// claudeOutSoon sets up #4443's case: Claude kept to Claude Code +// (switch-only), Claude Code on pro@x.com, max@x.com on with all of its +// allowance left, and /usage answering, for the account Claude Code is on, +// the share set last (set). The account Claude Code is on is read once, at +// first, and doesn't move on. It answers the spare, set, and a func that +// ages every reading by d, as the minutes between two looks do. +func claudeOutSoon(t *testing.T, first string) (spare string, set func(string), age func(d time.Duration)) { + t.Helper() + claudeThree(t) // pro@x.com signed in; team and max saved + var out atomic.Value + out.Store("") + fakeClaudeUsage(t, &out, nil) + claudeUsageWait = func() time.Duration { return 10 * time.Minute } // fakeClaudeUsage puts it back + forget := func() { + lastQuotas.Lock() + lastQuotas.m, lastQuotas.loaded = nil, false + lastQuotas.Unlock() + loginUsageCache.Lock() + loginUsageCache.m = nil + loginUsageCache.Unlock() + claudeLimitHit.Store(0) + claudeTranscripts.Lock() + claudeTranscripts.started, claudeTranscripts.off = false, nil + claudeTranscripts.Unlock() + } + forget() + t.Cleanup(forget) + if err := SetSwitchOnly("claude", true); err != nil { + t.Fatal(err) + } + for _, l := range Logins("claude") { + if strings.HasPrefix(l.User, "max@x.com") { + spare = l.User + if err := SetLoginOn("claude", l.User, true); err != nil { + t.Fatal(err) + } + } + } + if spare == "" { + t.Fatal("no max@x.com") + } + var mu sync.Mutex + active := first + set = func(s string) { + mu.Lock() + active = s + mu.Unlock() + } + UsageClaudeVia(func(_ context.Context, dir string) (string, error) { + mu.Lock() + defer mu.Unlock() + used := "0" // the spare + if dir == "" { + used = active + } + return "Current session: " + used + "% used · resets " + sessionReset(), nil + }) + age = func(d time.Duration) { + loginUsageCache.Lock() + loginUsageCache.m = nil // the minute's cache gone + loginUsageCache.Unlock() + claudeUsage.Lock() + for k, e := range claudeUsage.m { + e.tried, e.at = e.tried.Add(-d), e.at.Add(-d) + claudeUsage.m[k] = e + } + claudeUsage.Unlock() + } + if to, err := SwitchWhenSpent(context.Background(), "claude"); err != nil || to != "" { + t.Fatalf("at %s%%: switched to %q: %v", first, to, err) + } + return spare, set, age +} + +// The account Claude Code is on read near out (#4443: 4% left at +// 12:16:15) is read again a minute later, not at its 5 to 15 minutes' +// wait, and the look a minute later that finds it spent moves Claude Code +// on. +func TestClaudeNearOutIsReadEveryMinute(t *testing.T) { + spare, set, age := claudeOutSoon(t, "96") + if !claudeLookDue() { + t.Fatal("near out, but no look due before the next full one") + } + set("100") + age(claudeLookEvery) + if to, err := SwitchWhenSpent(context.Background(), "claude"); err != nil || to != spare { + t.Fatalf("a minute on, spent: switched to %q: %v, want %q", to, err, spare) + } +} + +// Claude Code refused for its limit ("You've hit your 5-hour limit", +// written to its session) while the reading magpie has says room: the +// next look reads /usage at once, whatever its wait, and moves on. +func TestClaudeRefusalInSessionReadsAtOnce(t *testing.T) { + spare, set, age := claudeOutSoon(t, "50") + session := filepath.Join(filepath.Dir(claudeCredentialsPath()), "projects", "-work", "s1.jsonl") + writeSession(t, session, `{"type":"user","message":{"role":"user","content":"go"},"timestamp":"`+time.Now().UTC().Format(time.RFC3339Nano)+`"}`) + if claudeLookDue() { + t.Fatal("a look due at 50% with no refusal") + } + set("100") + age(2 * time.Minute) + if claudeLookDue() { + t.Fatal("a look due with no refusal written") + } + writeSession(t, session, claudeRefusalLine(time.Now())) + if !claudeLookDue() { + t.Fatal("Claude Code was refused, and no look is due") + } + if to, err := SwitchWhenSpent(context.Background(), "claude"); err != nil || to != spare { + t.Fatalf("after the refusal: switched to %q: %v, want %q", to, err, spare) + } +} + +// What the scan of Claude Code's sessions counts: its own rate_limit +// message, written since the scan before, whole; not one from before +// magpie looked, a half-written line, nor the words in a tool's output. +func TestScanClaudeLimits(t *testing.T) { + claudeHome(t) + reset := func() { + claudeLimitHit.Store(0) + claudeTranscripts.Lock() + claudeTranscripts.started, claudeTranscripts.off = false, nil + claudeTranscripts.Unlock() + } + reset() + t.Cleanup(reset) + projects := filepath.Join(filepath.Dir(claudeCredentialsPath()), "projects") + old := filepath.Join(projects, "-a", "old.jsonl") + at := time.Now().Add(-time.Hour) + writeSession(t, old, claudeRefusalLine(at)) + scanClaudeLimits() + if claudeLimitHitAfter(time.Time{}) { + t.Fatal("a refusal from before the first scan counted") + } + // a tool's output naming it, and a refusal half written + writeSession(t, old, `{"type":"user","message":{"content":[{"type":"tool_result","content":"\"error\":\"rate_limit\""}]},"timestamp":"`+time.Now().UTC().Format(time.RFC3339Nano)+`"}`) + now := time.Now().Add(-time.Second) + line := claudeRefusalLine(now) + appendRaw(t, old, line[:40]) + scanClaudeLimits() + if claudeLimitHitAfter(time.Time{}) { + t.Fatal("a tool's output or a half-written line counted") + } + appendRaw(t, old, line[40:]+"\n") + scanClaudeLimits() + if !claudeLimitHitAfter(now.Add(-time.Millisecond)) || claudeLimitHitAfter(now) { + t.Fatalf("the refusal finished since: hit at %v, want %v", time.Unix(0, claudeLimitHit.Load()), now) + } + // a session begun since the last scan is read from its start + claudeLimitHit.Store(0) + writeSession(t, filepath.Join(projects, "-b", "new.jsonl"), claudeRefusalLine(time.Now())) + scanClaudeLimits() + if !claudeLimitHitAfter(now) { + t.Fatal("a refusal in a new session not counted") + } +} + +// claudeRefusalLine is what Claude Code writes to its session when +// Anthropic refuses the account for its limit, as a real session has it. +func claudeRefusalLine(at time.Time) string { + return fmt.Sprintf(`{"parentUuid":"p","isSidechain":false,"type":"assistant","uuid":"u","timestamp":%q,"message":{"id":"m","container":null,"model":"","role":"assistant","stop_reason":"stop_sequence","stop_sequence":"","type":"message","usage":{"input_tokens":0,"output_tokens":0},"content":[{"type":"text","text":"You've hit your 5-hour limit · resets 5pm (UTC)"}]},"error":"rate_limit","isApiErrorMessage":true,"apiErrorStatus":429}`, + at.UTC().Format(time.RFC3339Nano)) +} + +// writeSession appends line, ended, to the session at path. +func writeSession(t *testing.T, path, line string) { + t.Helper() + if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil { + t.Fatal(err) + } + appendRaw(t, path, line+"\n") +} + +func appendRaw(t *testing.T, path, s string) { + t.Helper() + f, err := os.OpenFile(path, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0o644) + if err != nil { + t.Fatal(err) + } + defer f.Close() + if _, err := f.WriteString(s); err != nil { + t.Fatal(err) + } +} + +// The gateway's loop looks at Claude's sign-in between its five-minute +// looks while the account Claude Code is on is near out, and moves it on +// once a reading says it is spent: the account read at 96% at the first +// look, spent a minute on, is moved off before the next full look. +func TestKeepOnAnAccountWithRoomLooksAtClaudeNearOut(t *testing.T) { + spare, set, age := claudeOutSoon(t, "96") + oldFirst, oldEvery, oldLooked := firstSignInLook, claudeLookEvery, signInsLooked + firstSignInLook, claudeLookEvery = time.Millisecond, 10*time.Millisecond + fulls := make(chan struct{}, 1) + signInsLooked = func(full bool) { + if full { + select { + case fulls <- struct{}{}: + default: + } + } + } + ctx, cancel := context.WithCancel(context.Background()) + done := make(chan struct{}) + go func() { + defer close(done) + KeepOnAnAccountWithRoom(ctx) + }() + t.Cleanup(func() { + cancel() + <-done + firstSignInLook, claudeLookEvery, signInsLooked = oldFirst, oldEvery, oldLooked + }) + // the full look done at 96%, the next is five minutes off + select { + case <-fulls: + case <-time.After(time.Minute): + t.Fatal("no full look") + } + if on := Logins("claude"); slices.ContainsFunc(on, func(l Login) bool { return l.Active && l.User == spare }) { + t.Fatal("moved on at 96%") + } + set("100") + age(claudeNearOutWait) + on := func() string { + for _, l := range Logins("claude") { + if l.Active { + return l.User + } + } + return "" + } + deadline := time.Now().Add(time.Minute) + for on() != spare { + if time.Now().After(deadline) { + t.Fatalf("Claude Code still on %q, want %q", on(), spare) + } + time.Sleep(10 * time.Millisecond) + } +} diff --git a/internal/provider/codex_switch.go b/internal/provider/codex_switch.go index 21bb98f24..f744be6a0 100644 --- a/internal/provider/codex_switch.go +++ b/internal/provider/codex_switch.go @@ -433,11 +433,14 @@ func noteCodexUsedUp(now bool) { } // KeepOnAnAccountWithRoom runs SwitchWhenSpent for Codex and Claude Code a -// minute after it starts and every loginSwitchEvery after that, until ctx -// ends, and keeps Claude Code's proxy that of its account -// (SyncClaudeProxyEnv). +// minute after it starts and every loginSwitchEvery after that (Codex's +// codexLookEvery), until ctx ends, and keeps Claude Code's proxy that of +// its account (SyncClaudeProxyEnv). Between those looks Claude's sign-in is +// looked at every claudeLookEvery when claudeLookDue: Claude Code asks +// Anthropic itself, and an account burnt fast was out minutes before the +// next look (#4443). func KeepOnAnAccountWithRoom(ctx context.Context) { - t := time.NewTimer(time.Minute) + t := time.NewTimer(firstSignInLook) defer t.Stop() live := false defer func() { @@ -445,6 +448,7 @@ func KeepOnAnAccountWithRoom(ctx context.Context) { codexLiveChecks.Add(-1) } }() + var full time.Time // when the next full look is due; zero: now for { select { case <-ctx.Done(): @@ -458,12 +462,17 @@ func KeepOnAnAccountWithRoom(ctx context.Context) { live = true codexLiveChecks.Add(1) } - for _, agent := range switchedAgents { - c, cancel := context.WithTimeout(ctx, time.Minute) - if _, err := SwitchWhenSpent(c, agent); err != nil { - log.Printf("%s: switching to an account with room: %v", agent, err) + claudeDue := claudeLookDue() + if time.Now().Before(full) { + if claudeDue { + lookAtSignIn(ctx, "claude") } - cancel() + signInsLooked(false) + t.Reset(min(time.Until(full), claudeLookEvery)) + continue + } + for _, agent := range switchedAgents { + lookAtSignIn(ctx, agent) } // a sign-in made in Claude Code itself, or a proxy picked since, // takes its account's proxy too (#1807) @@ -473,6 +482,26 @@ func KeepOnAnAccountWithRoom(ctx context.Context) { cancel() // Codex's own sign-in refused for good, or signed in again since noteCodexGoneNow() - t.Reset(codexLookEvery(knownLoginUsage("codex"))) + every := codexLookEvery(knownLoginUsage("codex")) + full = time.Now().Add(every) + signInsLooked(true) + t.Reset(min(every, claudeLookEvery)) + } +} + +// firstSignInLook is when KeepOnAnAccountWithRoom first looks. A var so +// tests can say. +var firstSignInLook = time.Minute + +// signInsLooked is told after each of KeepOnAnAccountWithRoom's looks, +// whether it was a full one. A var so tests can wait on it. +var signInsLooked = func(full bool) {} + +// lookAtSignIn is one look of KeepOnAnAccountWithRoom at agent's sign-in. +func lookAtSignIn(ctx context.Context, agent string) { + c, cancel := context.WithTimeout(ctx, time.Minute) + defer cancel() + if _, err := SwitchWhenSpent(c, agent); err != nil { + log.Printf("%s: switching to an account with room: %v", agent, err) } } diff --git a/internal/provider/subscription_usage.go b/internal/provider/subscription_usage.go index b638384bc..f90f77830 100644 --- a/internal/provider/subscription_usage.go +++ b/internal/provider/subscription_usage.go @@ -779,8 +779,10 @@ func AskUsage() { // claudeWindows is the allowance of the Claude account user, read by // Claude Code's own /usage. The account Claude Code is signed in to -// (active) is read when the user asked since it last was, or when the last -// reading's claudeUsageWait is up and Claude Code was used since. A saved +// (active) is read when the user asked since it last was, when the last +// reading's claudeUsageWait (claudeNearOutWait near out) is up and Claude +// Code was used since, or when Claude Code was refused for its limit +// since. A saved // account is read only when its card is refreshed (savedRefresh), or when // the switch off a spent account has no reading of it (spareRead), by // Claude Code run in the account's own config directory @@ -795,8 +797,12 @@ func claudeWindows(ctx context.Context, user string, active bool) ([]QuotaWindow c.Lock() e, ok := c.m[key] c.Unlock() + // the account Claude Code is on is read sooner near out + // (claudeWaitOf), and at once once Claude Code was refused for its + // limit since (claudeLimitHitAfter, #4443) due := e.tried.IsZero() || claudeAsked.Load() != 0 && asked > e.asked || - active && now.Sub(e.tried) >= e.wait && (e.heard.After(e.tried) || claudeUsedSince(e.tried)) + active && now.Sub(e.tried) >= claudeWaitOf(e, now) && (e.heard.After(e.tried) || claudeUsedSince(e.tried)) || + active && claudeLimitHitAfter(e.tried) // a saved account the switch off a spent one has no reading of // (spareRead): read once, and again only after a wait while its read // keeps failing, never every look