tokenmaxxing 1.66.0 → 1.68.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/DESIGN.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # tokenmaxxing - design
2
2
 
3
- Automatic Claude Code account switching. You run `claude` exactly as always; every session starts on the pooled account with the most session-window headroom per running session, and when the account a session runs on crosses its bar (**90%** of the 5h session window minus the 3-point projection margin, so 87 by default, or **98%** of a weekly window), tokenmaxxing resumes that session on a fresher account at a safe turn boundary. Works across many concurrent sessions at once, each on its own account; a fully depleted pool pauses a session with a countdown and auto-resumes at the soonest reset when it lands within `policy.maxWaitMs` (default 1h; further out, the session stays put rather than parking for hours).
3
+ Automatic Claude Code account switching. You run `claude` exactly as always; every session starts on the pooled account with the most session-window headroom per running session, and when the account a session runs on crosses its bar (**90%** of the 5h session window minus the 3-point projection margin, so 87 by default, or **98%** of a weekly window), tokenmaxxing resumes that session on a fresher account at a safe turn boundary. Works across many concurrent sessions at once, each on its own account; a fully depleted pool queues sessions first come first served onto reset targets (at most four waiters per account, overflow takes the soonest anyway), pauses each one with a countdown, and auto-resumes at its assigned reset when that lands within `policy.maxWaitMs` (default 1h; further out, the session stays put rather than parking for hours).
4
4
 
5
5
  > Scope: **Claude Code first (macOS + Linux, the latter since 2026-07-09).** Codex support landed in 0.13.0 (2026-07-16) with its own parallel state and supervisor; since 1.35.0 both run on one engine. Codex's verified internals live in AGENTS.md's Codex sections.
6
6
  >
@@ -12,7 +12,7 @@ Automatic Claude Code account switching. You run `claude` exactly as always; eve
12
12
 
13
13
  Claude Code namespaces its credential by `CLAUDE_SECURESTORAGE_CONFIG_DIR` (verified in the 2.1.269 binary, `xSe`/`y_`): the variable moves only the credential store (a `.credentials.json` inside that directory on Linux, a keychain item named `Claude Code-credentials-<sha256(dir)[0:8]>` on macOS), while `~/.claude` (settings, transcripts, plugins) and `~/.claude.json` stay shared, so `--resume` works across stores. An empty namespaced store never falls back to the default login. Hooks, the statusline, and MCP servers inherit the variable. That is the whole mechanism: give every pooled account its own store, set the variable per session, and each session runs on its own account with no credential ever moving.
14
14
 
15
- What the variable cannot give you is a change of account for a running process: the store is fixed at spawn. So the supervisor's job is placement and moves: on launch it **picks the seat** (see §5) and spawns claude under that account's store; when the session's Stop hook decides the seat is over its bar, the supervisor **replaces the process at a salvageable moment** - after a turn completes, the conversation is fully written to the transcript JSONL and `claude` is idle at the prompt, so killing it there loses nothing - and relaunches `claude --resume <session-id>` under the target's store. When the whole pool is over its bars it shows an interruptible countdown to the soonest reset first. **Thresholds sit below 100: the headroom is the budget to reach a clean turn boundary before the account actually hits its real limit.** The session window moves at 90 minus the margin (a 5h reset is cheap to sit out), while the weekly windows drain to 98 (weekly allowance is use-it-or-lose-it).
15
+ What the variable cannot give you is a change of account for a running process: the store is fixed at spawn. So the supervisor's job is placement and moves: on launch it **picks the seat** (see §5) and spawns claude under that account's store; when the session's Stop hook decides the seat is over its bar, the supervisor **replaces the process at a salvageable moment** - after a turn completes, the conversation is fully written to the transcript JSONL and `claude` is idle at the prompt, so killing it there loses nothing - and relaunches `claude --resume <session-id>` under the target's store. When the whole pool is over its bars it shows an interruptible countdown to the reset the wait queue assigned (at most four waiters per account, first come first served, overflow on the soonest). **Thresholds sit below 100: the headroom is the budget to reach a clean turn boundary before the account actually hits its real limit.** The session window moves at 90 minus the margin (a 5h reset is cheap to sit out), while the weekly windows drain to 98 (weekly allowance is use-it-or-lose-it).
16
16
 
17
17
  A hook can't do the placement or the relaunch - when `claude` exits, the shell owns the terminal. So tokenmaxxing installs a **supervisor** (aliased to `claude`) that owns the process lifecycle:
18
18
 
@@ -37,13 +37,15 @@ It is a process manager only - spawn with inherited stdio (stdin through a relay
37
37
  - `usage/<uuid8>.json` - the statusline tee per account, written by the sessions running on it.
38
38
  - `live/<session-id>` - PID-validated presence per supervised session, naming its account; placement counts them.
39
39
  - `respawn/<session-id>` - per-session respawn markers (the hook→supervisor signal): the target account, the session to resume, a `waitUntil`, a `compact` flag, and the launch time the marker was written for.
40
+ - `wait-queue.json` - the depleted-pool wait claims (`{sessionId, accountId, at, waitUntil}`), so at most four sessions wait on one account; a session that arrives when every account already has four waiters takes the soonest reset anyway.
40
41
  - `bin/claude` and `bin/codex` - the supervisors, beside the `tokenmaxxing` and `xx` entry points.
41
42
  - `sessions/<sid>.json`, `onboard/`, `setup-tokens.json`, `setup-token/`, `cloud/`, `hub-key`, `update.json`, `spawnrate.json`, `tokenmaxxing.log`, the codex `codex-onboard/`, `codex-respawn/`, and `codex-live/`, and the `grok-*` and `opencode-go-*` state of the status-only pools: the full table is in [State directory layout](docs/content/docs/state-directory.mdx).
42
43
  - Per-account **credential stores** follow the platform's Claude Code store: macOS = a login-keychain item keyed by the store path (never plaintext on disk); Linux = a 0600 `.credentials.json` inside the 0700 store directory (the same plaintext model claude itself uses - its Linux build has no keyring path at all, binary-verified 2.1.205). One `credstore` facade dispatches on a `{kind: keychain|file}` target; call sites never branch on platform. tokenmaxxing writes a store once, at onboarding; Claude Code's own refresh is the only writer afterwards.
43
44
 
44
45
  - A periodic check job (`com.tokenmaxxing.check` launchd agent on macOS, `tokenmaxxing-check.timer` systemd user timer on Linux) running `tokenmaxxing check` once per tick (`policy.checkIntervalMs`, 60s by default): it runs the decision with no seat (nothing moves), folds fresh tees into the index, samples up to three accounts whose last sample attempt is oldest (the direct no-spend usage GET), deletes leftover dead state files at the state root, and on a Bun global install checks npm for a newer version once a day, so the cached figures every placement reads stay fresh.
46
+ - A usage hub service (`com.tokenmaxxing.hub` launchd agent on macOS, `tokenmaxxing-hub.service` systemd user service on Linux) running `tokenmaxxing serve`, so the [usage hub](docs/content/docs/hub.mdx) is up in the background beside the check timer.
45
47
 
46
- The switching path runs no long-lived daemon. The statusline pushes usage. Hooks and the supervisor react. The periodic check job above is the only recurring process. `tokenmaxxing serve`, the optional [usage hub](docs/content/docs/hub.mdx) that answers the CLIProxyAPI management subset for a dashboard from the cached figures, is a foreground server outside the switching path. The `claude` binary, `~/.claude.json`, and Claude Code's default credential store are untouched; inside `~/.claude` only `settings.json` gets the five entries.
48
+ The switching path runs no long-lived daemon. The statusline pushes usage. Hooks and the supervisor react. The periodic check job above is the only recurring process in the switching path. The [usage hub](docs/content/docs/hub.mdx) that answers the CLIProxyAPI management subset for a dashboard from the cached figures runs outside the switching path, as a background service beside the check timer (`tokenmaxxing serve` runs the same server in the foreground). The `claude` binary, `~/.claude.json`, and Claude Code's default credential store are untouched; inside `~/.claude` only `settings.json` gets the five entries.
47
49
 
48
50
  ---
49
51
 
@@ -56,7 +58,7 @@ The Stop hook's stdin has no usage data, but the **statusLine does** (`rate_limi
56
58
  1. Resolve the seat: the pooled account whose store the inherited `CLAUDE_SECURESTORAGE_CONFIG_DIR` names. No seat (a session started outside the supervisor) means nothing to move.
57
59
  2. Read the seat's tee and exit while it is under both bars, as defined in the [switching policy](docs/content/docs/switching.mdx).
58
60
  3. Take the pool lock, re-check, fold every account's tee into the index, select a candidate under the switching policy from the cached figures, and verify that the target's store holds a usable credential (a store Claude Code dead-cleared flags the account for re-auth and the next candidate is tried).
59
- 4. Write `respawn/<session-id>` (atomic temp+rename) naming the target, with `waitUntil` now for a plain move or the soonest reset when the pool is depleted. No credential is written.
61
+ 4. Write `respawn/<session-id>` (atomic temp+rename) naming the target, with `waitUntil` now for a plain move or the assigned reset when the pool is depleted. No credential is written.
60
62
 
61
63
  ### 3.3 Move and depleted-pool pause (supervisor)
62
64
  The supervisor sees `respawn/<sid>`, SIGTERMs its child at the already-committed turn boundary, deletes the marker, resets the terminal, compacts the conversation when the marker asks for it (`compact: true` from the Stop and SessionStart hooks and from the supervisor's own seat watch, `false` from StopFailure: it runs `claude -p --resume <live-id> /compact` under the old seat's store, bounded at five minutes, and a failure only prints why), and (when `waitUntil` is in the future) shows an interruptible countdown to the reset; then it relaunches `claude --resume <live-id>` (`--session-id <live-id>` when that id has no transcript yet, because `--resume` exits with `No conversation found` for it) with `CLAUDE_SECURESTORAGE_CONFIG_DIR` set to the target's store and rewrites the session's presence. The marker file is keyed by the launch id `<sid>`; the live id inside it is the session id the supervised process runs now, which `/clear` and an in-session `/resume` change. A hook adopts a differing stdin id as the live id (`current` in `sessions/<sid>.json`) only when its own process descends, through shell processes alone, from the presence record's pid; any other differing id is a nested session and writes nothing. The resumed process reads that store cold → runs on the target account, same conversation. The `--session-id` path is the exception: the cleared conversation has no prior turn, so it starts empty with no compaction and no first prompt. On the `--resume` path the relaunch submits a first prompt that names the move (and the compaction, when it landed) and asks Claude to continue the task, so the conversation goes on without a keystroke: in a terminal session it is the positional prompt after the session id; in a stream-json session (`--input-format stream-json`, where the binary ignores a positional prompt) the supervisor owns stdin, relays the harness's lines to the child through a pipe, and writes the prompt as the first `user` line of the new process. In a terminal session the supervisor's own notices go to stderr. In a stream-json session (`--output-format stream-json`, read from the effective flags like the relay) there is no terminal and no statusline, so the supervisor writes each notice (the compaction and its failure, the move, the depleted-pool wait with its resume time, the resume) to stdout as a `system` line of subtype `informational` and level `warning`, the shape Claude Code emits for its own print-mode notices, which the harness renders in the conversation while the stream stays parseable; the per-second countdown ticks stay terminal-only, and the supervisor writes only while no child is running. The `SessionStart` hook (every source) re-runs the decision before the first turn and writes the same marker if the seat is already over its bar or the pool is depleted. The supervisor also watches its own seat every ten seconds while the child runs (account record plus tee, the same bars) and writes the marker itself when the seat is at or over a bar, so a move never depends on a hook firing: a harness session between turns whose background workflow burns the window, or a subagent refusal that stamped the wall, is moved within seconds. SIGTERM to the supervisor is forwarded to the child and the supervisor exits after it, so a harness that stops the wrapper (the Agent SDK does) never leaves an orphaned claude on the old seat. A marker whose `launchedAt` does not match the running child is discarded, and after a Ctrl-C on the countdown a later marker whose `waitUntil` falls inside the skipped wait is ignored. A marker that fails to parse is never deleted and never treated as absent: the supervisor stops the child, restores the terminal, and exits naming the marker path. In a stream-json session that fatal, the wrap-depth abort, the wrap-rate abort, and a failed presence write also go to stdout as the same `informational`/`warning` line.
@@ -81,7 +83,7 @@ Each terminal ran the supervisor, so each has its own child `claude`, its own `-
81
83
  ---
82
84
 
83
85
  ## 5. Placement and rotation policy
84
- The [switching policy](docs/content/docs/switching.mdx) is one rule: under both bars, hold; at or over a bar, move to the usable account that ranks first; nothing usable, wait for the soonest reset. The same ranking places a session at launch.
86
+ The [switching policy](docs/content/docs/switching.mdx) is one rule: under both bars, hold; at or over a bar, move to the usable account that ranks first; nothing usable, queue first come first served onto a reset target (at most four waiters per account, overflow takes the soonest anyway) and wait for that reset. The same ranking places a session at launch.
85
87
 
86
88
  - Ranking (decided by consult for #79): greatest remaining headroom to the session bar divided by the number of sessions after placement, `(bar - used) / (sessions + 1)`, then highest pace pressure (remaining percent of the binding gated per-model cap, or of the weekly aggregate for an account with no gated row, over time to its reset), then soonest weekly reset, then lowest weekly usage; unknown usage ranks last. Organization membership is not an input. Codex drops the headroom key, keeps the pace ordering and the weekly tie-breaks, and excludes accounts running in another codex session, because codex has no cross-process refresh lock and two sessions must never share a login.
87
89
  - Selection reads the cached figures only, after folding every account's tee. Each periodic check tick samples up to three accounts whose last sample attempt is oldest, skipping any attempted within `policy.usagePollTtlMs`, over the direct no-spend usage read with the account's stored token, so every account is attempted about once per three ticks per pooled account, or once per `policy.usagePollTtlMs` plus a tick when that is longer, and its cached figure is as fresh as its last successful attempt or its sessions' latest push. The pool lock covers only the reservation and the result write, never the usage GET. The usage endpoint rate limits each account on its own and names the time to come back in the `retry-after` of its HTTP 429; that time is stored as `usageRetryAt`, and no sampler (the tick, `status`, the seat's in-decision sample) reads the account before it. An expired stored access token stays unmeasured until a session on that store refreshes it.
package/README.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # tokenmaxxing
2
2
 
3
- **Automatic Claude Code account switching.** Run `claude` exactly as you always do; each session starts on the pooled account with the most headroom per running session, and when that account nears its usage limit, tokenmaxxing resumes the session on a fresher account at a safe turn boundary - same conversation, compacted on the account it leaves and restarted under another account's credential store with a first prompt that asks Claude to continue. Works across many concurrent sessions, which spread over the pool instead of draining one account together. When the whole pool is at its limit, a session pauses with a countdown and auto-resumes at the soonest reset, when that reset falls within `policy.maxWaitMs` (default 1h - a longer wait stays put rather than parking your terminal for hours).
3
+ **Automatic Claude Code account switching.** Run `claude` exactly as you always do; each session starts on the pooled account with the most headroom per running session, and when that account nears its usage limit, tokenmaxxing resumes the session on a fresher account at a safe turn boundary - same conversation, compacted on the account it leaves and restarted under another account's credential store with a first prompt that asks Claude to continue. Works across many concurrent sessions, which spread over the pool instead of draining one account together. When the whole pool is at its limit, a session queues first come first served for a reset (at most four sessions wait on one account) and pauses with a countdown until its assigned reset, when that reset falls within `policy.maxWaitMs` (default 1h - a longer wait stays put rather than parking your terminal for hours).
4
4
 
5
5
  > **Scope:** Claude Code on macOS and Linux, plus OpenAI's Codex CLI as a second switching pool; grok and opencode-go as status-only pools. It pools **subscription** accounts (Pro/Max), not API keys; the opencode-go pool, which holds Zen API keys, is the one exception.
6
6
 
@@ -52,7 +52,7 @@ programs.tokenmaxxing.package = inputs.tokenmaxxing.packages.${pkgs.system}.defa
52
52
 
53
53
  With either module, run `tokenmaxxing init` afterwards.
54
54
 
55
- `init` verifies and pins the real `claude` binary, opens an isolated `claude` session for your first pooled account (run `/login` there, even if you are already signed in; the login you already have stays for sessions started outside the supervisor), installs the `claude` supervisor and the `xx` entry point, five `settings.json` entries (the tokenmaxxing statusLine, a subagentStatusLine, a Stop hook, a StopFailure hook, a SessionStart hook), and the periodic check timer, and adds the supervisor's bin dir to PATH in your shell rc (idempotent; it must sit ahead of the real `claude` to intercept it). Restart your shell, then add more accounts and go:
55
+ `init` verifies and pins the real `claude` binary, opens an isolated `claude` session for your first pooled account (run `/login` there, even if you are already signed in; the login you already have stays for sessions started outside the supervisor), installs the `claude` supervisor and the `xx` entry point, five `settings.json` entries (the tokenmaxxing statusLine, a subagentStatusLine, a Stop hook, a StopFailure hook, a SessionStart hook), the periodic check timer, and the usage hub service, and adds the supervisor's bin dir to PATH in your shell rc (idempotent; it must sit ahead of the real `claude` to intercept it). Restart your shell, then add more accounts and go:
56
56
 
57
57
  ```sh
58
58
  tokenmaxxing add # logs one in, in isolation, into its own store
@@ -63,7 +63,7 @@ claude # use claude as always; each session gets its own accoun
63
63
 
64
64
  | command | what it does |
65
65
  |---|---|
66
- | `tokenmaxxing init` | verify and pin the real `claude`, log the first account in (isolated) + install supervisor, hooks, PATH line, and check timer |
66
+ | `tokenmaxxing init` | verify and pin the real `claude`, log the first account in (isolated) + install supervisor, hooks, PATH line, check timer, and hub service |
67
67
  | `tokenmaxxing init --codex` | same for codex: log in the first account (isolated), install codex supervisor + Stop hook |
68
68
  | `tokenmaxxing init --grok` / `init --opencode-go` | pool the first grok login or opencode-go key, status-only: no supervisor, no switching |
69
69
  | `tokenmaxxing add [--codex \| --grok \| --opencode-go]` | register an additional account in that pool (isolated login, harvested once into its own store) |
@@ -71,10 +71,10 @@ claude # use claude as always; each session gets its own accoun
71
71
  | `tokenmaxxing status [--cached]` | every pool: accounts with 5h / weekly / per-model usage bars, live session counts, exhausted-until-reset; `--cached` renders the stored figures without sampling |
72
72
  | `tokenmaxxing config` | the config path and the effective values; edit the file in an editor, a bad value fails the next load with the field name |
73
73
  | `tokenmaxxing check` | fold fresh tees, sample up to three stale accounts, and self-update a Bun global install once a day; the periodic timer runs this every tick |
74
- | `tokenmaxxing doctor` | verify the install: PATH order, `claudeBin`, the five settings entries, the timer, the credential identity of every Codex store and of every Claude store whose access token is still fresh (an expiring Claude token is reported as unverifiable, not as a failure), codex hook trust, setup-token age, and shell aliases that shadow `claude` |
74
+ | `tokenmaxxing doctor` | verify the install: PATH order, `claudeBin`, the five settings entries, the timer, the hub service, the credential identity of every Codex store and of every Claude store whose access token is still fresh (an expiring Claude token is reported as unverifiable, not as a failure), codex hook trust, setup-token age, and shell aliases that shadow `claude` |
75
75
  | `tokenmaxxing rename [--codex \| --grok \| --opencode-go] <sel> <label>` / `rm [...] <sel>` | manage a pool (one email can hold both a claude and a codex account); `rm` is refused for an account with a running supervised session |
76
- | `tokenmaxxing serve` | serve the CLIProxyAPI-compatible usage API on `http://localhost:8317` (`hub.port`) so a dashboard such as T3 Code's "Add a CLIProxyAPI hub" shows the quota of every pooled Claude and Codex account; the management key is the contents of `hub-key` in the state directory, minted on the first run. Details in [Usage hub](docs/content/docs/hub.mdx) |
77
- | `tokenmaxxing uninstall [--yes]` | print the targets, then remove the shims, settings entries, codex Stop hook, check timer, and rc PATH line (accounts/stores kept); refused without `--yes` when `HOME` is the login home |
76
+ | `tokenmaxxing serve` | serve the CLIProxyAPI-compatible usage API on `http://localhost:8317` (`hub.port`) so a dashboard such as T3 Code's "Add a CLIProxyAPI hub" shows the quota of every pooled Claude and Codex account; the management key is the contents of `hub-key` in the state directory, minted on the first run, and `init` runs it as a background service beside the check timer. Details in [Usage hub](docs/content/docs/hub.mdx) |
77
+ | `tokenmaxxing uninstall [--yes]` | print the targets, then remove the shims, settings entries, codex Stop hook, check timer, hub service, and rc PATH line (accounts/stores kept); refused without `--yes` when `HOME` is the login home |
78
78
  | `tokenmaxxing setup-token [--print \| rm <label\|uuid>]` | Cursor Cloud only: mint one `claude setup-token` per pooled account (a browser sign-in each) and print the `TOKENMAXXING_TOKENS` secret value; `--print` prints the stored set, `rm` drops one |
79
79
  | `tokenmaxxing cursor init [dir]` | write the Claude relay subagent and `.cursor/environment.json` into a repo |
80
80
  | `tokenmaxxing cloud run [--session <id>] [--max-turns <n>] "<prompt>"` | on a Cursor Cloud VM: run `claude -p` on a setup token, rotate to the next token on a usage limit |
@@ -92,7 +92,7 @@ The bars' headroom is deliberate: it's the budget to reach a clean turn boundary
92
92
  Launches and moves rank usable accounts by session-window headroom per running session, `(bar - used) / (sessions + 1)`, so two fresh accounts alternate and a third session goes to whichever has more headroom left per session; ties break by pace pressure (remaining percent of the binding gated per-model cap, or of the weekly aggregate for an account with no gated row, divided by time to its reset, highest first), then soonest weekly reset, then lowest weekly use. Organization membership is not an input.
93
93
 
94
94
  - Every periodic check tick folds fresh statusline tees into the index and samples up to three accounts whose last sample attempt is oldest, skipping any attempted within `policy.usagePollTtlMs`, with the direct no-spend usage read; a move reads the cached figures, which are as fresh as each account's last successful attempt or its sessions' latest push. An expired stored access token stays unmeasured until a session on that store refreshes it.
95
- - When no account is usable, the session pauses until the soonest reset if that lands within `policy.maxWaitMs`, and otherwise stays put.
95
+ - When no account is usable, the session queues first come first served onto a reset target (at most four waiters per account) and pauses until that reset if it lands within `policy.maxWaitMs`, and otherwise stays put.
96
96
 
97
97
  See [How switching decides](docs/content/docs/switching.mdx) for the policy and the [cache-cost profile](docs/content/docs/switching-profile.mdx) for measurements and their limits.
98
98
 
@@ -113,9 +113,9 @@ See [How switching decides](docs/content/docs/switching.mdx) for the policy and
113
113
  }
114
114
  ```
115
115
 
116
- `thresholds.session` and `thresholds.weekly` are the two bars, one number each (an array `thresholds.session`, the former ladder, fails config loading with a message naming the field); `projectionMargin` is a fixed safety margin subtracted from the session bar only (default 3), so a large turn is less likely to blow past the 5-hour bar between checks; the weekly bar takes no margin because one turn cannot overshoot a week; `switchModels` names the models whose per-model cap triggers a move; `usagePollTtlMs` is how long a usage sample stays fresh, for a seat's own sample and for the accounts each check tick samples; `maxWaitMs` bounds the depleted-pool countdown - a soonest reset further out than this does not pause the session (no respawn marker is written and the session simply keeps hitting its limit until an account recovers); `checkIntervalMs` is the periodic check tick (default 60s), which `init` writes into the timer - re-run `tokenmaxxing init` after changing it so the timer unit picks up the new tick. `claudeBin`, `codexBin`, `grokBin`, and `opencodeBin` pin the real binaries; `init` writes them, and `TOKENMAXXING_CLAUDE_BIN`, `TOKENMAXXING_CODEX_BIN`, `TOKENMAXXING_GROK_BIN`, and `TOKENMAXXING_OPENCODE_BIN` override them for one process, except that `init` pins the binary it resolved into `config.json`.
116
+ `thresholds.session` and `thresholds.weekly` are the two bars, one number each (an array `thresholds.session`, the former ladder, fails config loading with a message naming the field); `projectionMargin` is a fixed safety margin subtracted from the session bar only (default 3), so a large turn is less likely to blow past the 5-hour bar between checks; the weekly bar takes no margin because one turn cannot overshoot a week; `switchModels` names the models whose per-model cap triggers a move; `usagePollTtlMs` is how long a usage sample stays fresh, for a seat's own sample and for the accounts each check tick samples; `maxWaitMs` bounds the depleted-pool countdown - a reset further out than this does not pause the session (no respawn marker is written and the session simply keeps hitting its limit until an account recovers); `checkIntervalMs` is the periodic check tick (default 60s), which `init` writes into the timer - re-run `tokenmaxxing init` after changing it so the timer unit picks up the new tick. `claudeBin`, `codexBin`, `grokBin`, and `opencodeBin` pin the real binaries; `init` writes them, and `TOKENMAXXING_CLAUDE_BIN`, `TOKENMAXXING_CODEX_BIN`, `TOKENMAXXING_GROK_BIN`, and `TOKENMAXXING_OPENCODE_BIN` override them for one process, except that `init` pins the binary it resolved into `config.json`.
117
117
 
118
- State lives in `~/.config/tokenmaxxing/`; outside it the install touches Claude Code's `settings.json`, codex's `hooks.json`, the timer unit, and your shell rc. Each account's credential store is `stores/<uuid8>/`, which Claude Code reads and refreshes as its own: on macOS the credential is a login-keychain item keyed by the store path (never plaintext on disk), on Linux a 0600 `.credentials.json` inside the store (the same plaintext model claude itself uses for `~/.claude/.credentials.json`).
118
+ State lives in `~/.config/tokenmaxxing/`; outside it the install touches Claude Code's `settings.json`, codex's `hooks.json`, the timer and usage hub units, and your shell rc. Each account's credential store is `stores/<uuid8>/`, which Claude Code reads and refreshes as its own: on macOS the credential is a login-keychain item keyed by the store path (never plaintext on disk), on Linux a 0600 `.credentials.json` inside the store (the same plaintext model claude itself uses for `~/.claude/.credentials.json`).
119
119
 
120
120
  ## Codex support
121
121
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "tokenmaxxing",
3
- "version": "1.66.0",
3
+ "version": "1.68.0",
4
4
  "description": "Automatic Claude Code account switching: pool multiple accounts, start each session on its own account, and resume a session on a fresher account when quota fills.",
5
5
  "type": "module",
6
6
  "license": "MIT",
package/src/cli/doctor.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  import { existsSync, readFileSync } from "node:fs";
2
2
  import { verifyRealClaude } from "../lib/claudebin.ts";
3
3
  import { checkSettings, installedBin } from "../lib/settings.ts";
4
- import { checkTimerHealthy, codexStoreHookTrust, findClaudeShadowers, isBinDirAhead, shellRcPath, timerActivationHint } from "../lib/install.ts";
4
+ import { checkTimerHealthy, codexStoreHookTrust, findClaudeShadowers, hubServiceHealthy, isBinDirAhead, shellRcPath, skipImperativeHub, timerActivationHint } from "../lib/install.ts";
5
5
  import { errorMessage } from "../lib/log.ts";
6
6
  import { claudePool, codexPool, paths } from "../lib/paths.ts";
7
7
  import { loadAccounts, loadConfig } from "../lib/state.ts";
@@ -31,6 +31,10 @@ export async function cmdDoctor(): Promise<number> {
31
31
  check(s.stopFailureOk, "StopFailure hook installed in settings.json", "run `tokenmaxxing init`");
32
32
  check(s.sessionStartOk, "SessionStart hook installed in settings.json", "run `tokenmaxxing init`");
33
33
  check(checkTimerHealthy(), "periodic check timer active", timerActivationHint());
34
+ if (existsSync(paths.supervisorLink)) {
35
+ if (skipImperativeHub()) note("usage hub service is owned outside init (TOKENMAXXING_SKIP_HUB set) - not verified here");
36
+ else check(hubServiceHealthy(), "usage hub service active", "run `tokenmaxxing init` (it writes the unit and activates it)");
37
+ }
34
38
 
35
39
  const idx = loadAccounts(claudePool);
36
40
  check(idx.accounts.length > 0, "at least one account in the pool", "run `tokenmaxxing init`");
package/src/cli/serve.ts CHANGED
@@ -7,6 +7,7 @@ import { claude } from "../lib/claude.ts";
7
7
  import { codex, observeCodex } from "../lib/codex.ts";
8
8
  import { CODEX_USAGE_URL } from "../lib/codexusage.ts";
9
9
  import { errorMessage, log } from "../lib/log.ts";
10
+ import { hubDeactivationHint } from "../lib/install.ts";
10
11
  import { paths } from "../lib/paths.ts";
11
12
  import { isExhausted, thresholdBars } from "../lib/picker.ts";
12
13
  import type { Provider } from "../lib/provider.ts";
@@ -198,15 +199,21 @@ export async function cmdServe(args: string[]): Promise<number> {
198
199
  }
199
200
  const cfg = loadConfig();
200
201
  const key = managementKey();
201
- const server = Bun.serve({
202
- hostname: "localhost",
203
- port: cfg.hub.port,
204
- fetch: (req) => handle(req, key),
205
- error: (e) => {
206
- log("hub.error", { err: errorMessage(e) });
207
- return json({ error: "internal error" }, 500);
208
- },
209
- });
202
+ let server: ReturnType<typeof Bun.serve>;
203
+ try {
204
+ server = Bun.serve({
205
+ hostname: "localhost",
206
+ port: cfg.hub.port,
207
+ fetch: (req) => handle(req, key),
208
+ error: (e) => {
209
+ log("hub.error", { err: errorMessage(e) });
210
+ return json({ error: "internal error" }, 500);
211
+ },
212
+ });
213
+ } catch (e) {
214
+ emitError({ message: `cannot bind localhost:${cfg.hub.port}: ${errorMessage(e)} (another \`tokenmaxxing serve\` or the usage hub service may already hold the port - stop it first: ${hubDeactivationHint()})` });
215
+ return 1;
216
+ }
210
217
  console.log(`${c.green("✓")} serving the CLIProxyAPI-compatible usage API at http://localhost:${server.port}/v0/management`);
211
218
  console.log(c.dim(`management key: the contents of ${paths.hubKeyFile}`));
212
219
  log("hub.started", { port: server.port });
@@ -80,7 +80,7 @@ export async function runStopFailureHook(): Promise<number> {
80
80
  );
81
81
  }
82
82
 
83
- const decision = await evaluateAndMaybeSwap(claude, now, canRespawn && enforced != null, enforced);
83
+ const decision = await evaluateAndMaybeSwap(claude, now, canRespawn && enforced != null, enforced, { waiterId: canRespawn ? session?.sid : undefined });
84
84
  if (enforced && session && canRespawn && decision.account && (decision.swapped || decision.waitUntil !== undefined)) {
85
85
  writeRespawnMarker({ session, accountId: decision.account.id, waitUntil: decision.waitUntil ?? now, compact: false });
86
86
  log("stopfailure.marker", { session: session.sid.slice(0, 8), live: session.live.slice(0, 8), account: decision.account.id.slice(0, 8), waitUntil: decision.waitUntil ?? now });
@@ -24,7 +24,7 @@ export async function runBoundaryHook(event: "stop" | "sessionstart"): Promise<n
24
24
  log(`${event}.nested_session`, { stdin: stdin.session_id?.slice(0, 8), supervised: supervised.live.slice(0, 8), source: stdin.source });
25
25
  return 0;
26
26
  }
27
- const decision = await evaluateAndMaybeSwap(claude, Date.now(), session != null);
27
+ const decision = await evaluateAndMaybeSwap(claude, Date.now(), session != null, null, { waiterId: session?.sid });
28
28
  if (session && decision.account && (decision.swapped || decision.waitUntil !== undefined)) {
29
29
  writeRespawnMarker({ session, accountId: decision.account.id, waitUntil: decision.waitUntil ?? Date.now(), compact: true });
30
30
  log(`${event}.${decision.waitUntil !== undefined ? "wait" : "move"}`, { source: stdin.source, account: decision.account.id.slice(0, 8), waitUntil: decision.waitUntil, session: session.sid.slice(0, 8), live: session.live.slice(0, 8) });
@@ -16,7 +16,7 @@ import { teeObservation } from "../lib/sample.ts";
16
16
  import { exitStatus, loopGuardTripped, raceMarkerOrExit, recordPresenceOrStop, runPassthrough } from "../lib/supervise.ts";
17
17
  import { saveTermios } from "../lib/tty.ts";
18
18
  import { liveSessionId, loadSessionFlags, pruneStaleSessions, saveSessionFlags, writeRespawnMarker } from "../lib/sessions.ts";
19
- import { loadAccounts, loadConfig } from "../lib/state.ts";
19
+ import { loadAccounts, loadConfig, releaseWaitClaim } from "../lib/state.ts";
20
20
  import { gatedFamilies, modelFromFlag } from "../lib/usage.ts";
21
21
  import { RespawnMarkerSchema, type Account, type Config, type ModelInfo } from "../lib/types.ts";
22
22
  import { errorMessage, log } from "../lib/log.ts";
@@ -222,7 +222,7 @@ async function moveExhaustedSeat(seat: Account, sid: string, gate: MarkerGate, m
222
222
  const families = gatedFamilies(model, cfg.policy.switchModels);
223
223
  const until = seatBlockedUntil(seat.id, now, families, cfg);
224
224
  if (until == null || until <= gate.overriddenUntil) return false;
225
- const decision = await evaluateAndMaybeSwap(claude, now, true, null, seat.id, families);
225
+ const decision = await evaluateAndMaybeSwap(claude, now, true, null, { seatId: seat.id, sessionFamilies: families, waiterId: sid });
226
226
  log("supervisor.seat_exhausted", { seat: seat.id.slice(0, 8), until, reason: decision.reason, account: decision.account?.id.slice(0, 8), waitUntil: decision.waitUntil });
227
227
  if (decision.account && (decision.swapped || decision.waitUntil !== undefined)) {
228
228
  writeRespawnMarker({ session: { sid, launchedAt: gate.launchedAt, live: liveSessionId(sid) }, accountId: decision.account.id, waitUntil: decision.waitUntil ?? now, compact: true });
@@ -364,10 +364,27 @@ export async function runSupervisor(argv: string[]): Promise<number> {
364
364
 
365
365
  let child: Subprocess | null = null;
366
366
  let terminating = false;
367
+ let claimSid: string | null = null;
368
+ const releaseClaim = async (): Promise<void> => {
369
+ const claimed = claimSid;
370
+ if (claimed == null) return;
371
+ try {
372
+ await withLock(claudePool.lockFile, () => {
373
+ releaseWaitClaim(claimed);
374
+ });
375
+ } catch (e) {
376
+ log("supervisor.claim_release_failed", { err: errorMessage(e) });
377
+ }
378
+ };
367
379
  process.on("SIGTERM", () => {
368
380
  terminating = true;
369
- if (child) child.kill("SIGTERM");
370
- else process.exit(143);
381
+ const released = releaseClaim();
382
+ if (child) {
383
+ child.kill("SIGTERM");
384
+ void released;
385
+ } else {
386
+ released.finally(() => process.exit(143));
387
+ }
371
388
  });
372
389
 
373
390
  if (!info.manage || process.env[UNMANAGED_ENV]) {
@@ -392,6 +409,7 @@ export async function runSupervisor(argv: string[]): Promise<number> {
392
409
  } else {
393
410
  sid = crypto.randomUUID();
394
411
  }
412
+ claimSid = sid;
395
413
 
396
414
  if (resuming && base.length === 0) {
397
415
  const persisted = loadSessionFlags(sid);
@@ -504,6 +522,7 @@ export async function runSupervisor(argv: string[]): Promise<number> {
504
522
  if (m.waitUntil > Date.now()) {
505
523
  if (await countdownWait(label, m.waitUntil, { stream, say })) overriddenUntil = m.waitUntil;
506
524
  } else say(`\n\x1b[36m↻ tokenmaxxing: moving to ${label} - resuming...\x1b[0m\n`, `tokenmaxxing: moving to ${label} and resuming.`);
525
+ await releaseClaim();
507
526
  wanted = m.accountId;
508
527
  saveSessionFlags(m.sessionId, persistable, process.cwd());
509
528
  const prompt = resumable ? resumePrompt(compacted) : null;
@@ -512,6 +531,7 @@ export async function runSupervisor(argv: string[]): Promise<number> {
512
531
  continue;
513
532
  }
514
533
  clearPresence({ dir: paths.presenceDir, id: sid });
534
+ await releaseClaim();
515
535
  log("supervisor.exit", { sid, respawns, code: proc.exitCode, signal: proc.signalCode, terminated: terminating || undefined });
516
536
  return exitStatus(proc);
517
537
  }
@@ -520,6 +540,7 @@ export async function runSupervisor(argv: string[]): Promise<number> {
520
540
  const text = msg.startsWith("tokenmaxxing:") ? msg : `tokenmaxxing: ${msg}`;
521
541
  say(`\n\x1b[31m${text}\x1b[0m\n`, text);
522
542
  log("supervisor.fatal", { err: msg });
543
+ await releaseClaim();
523
544
  return 1;
524
545
  }
525
546
  }
package/src/lib/claude.ts CHANGED
@@ -4,7 +4,7 @@ import { z } from "zod";
4
4
  import { readItem, writeItem, deleteItem, isolatedTarget, readStore, storeTarget, claudeAiOauthOnly } from "./credstore.ts";
5
5
  import { resolveRealClaude, resolveVerifiedClaude } from "./claudebin.ts";
6
6
  import { withClaudeRefreshLock } from "./claudelock.ts";
7
- import { ensurePathInRc, installSupervisor, managedShellRcSkipLines, shellRcPath, timerActivationHint } from "./install.ts";
7
+ import { ensurePathInRc, hubActivationHint, installSupervisor, managedShellRcSkipLines, shellRcPath, timerActivationHint } from "./install.ts";
8
8
  import { withLock } from "./lock.ts";
9
9
  import { errorMessage, log } from "./log.ts";
10
10
  import { claudeTierLabel, describeIdentity, fetchTokenIdentity, isDeadCredential, InvalidGrantError } from "./oauth.ts";
@@ -270,6 +270,8 @@ function install(): void {
270
270
  console.log(`${c.green("✓")} installed ${c.bold("claude")} supervisor + statusLine/Stop/StopFailure/SessionStart hooks`);
271
271
  if (out.timerLoaded) console.log(`${c.green("✓")} periodic check timer active (every ${out.checkIntervalS}s)`);
272
272
  else console.log(c.yellow(`⚠ check timer written but not activated - run: ${timerActivationHint()}`));
273
+ if (out.hubLoaded) console.log(`${c.green("✓")} usage hub service active`);
274
+ else console.log(c.yellow(`⚠ usage hub service written but not activated - run: ${hubActivationHint()}`));
273
275
  if (!out.pathAhead) {
274
276
  console.log();
275
277
  ensurePathAhead();
package/src/lib/decide.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import { withLock } from "./lock.ts";
2
- import { loadAccounts, loadConfig, saveAccounts } from "./state.ts";
3
- import { isExhausted, limitWindows, liveUsed, nextWeeklyReset, pickBest, pickEarliestReset, sessionWindow, thresholdBars, usableAt, weeklyWindow, type PickCtx } from "./picker.ts";
2
+ import { loadAccounts, loadConfig, liveWaitClaims, releaseWaitClaim, replaceWaitClaim, saveAccounts } from "./state.ts";
3
+ import { isExhausted, limitWindows, liveUsed, nextWeeklyReset, pickBest, pickWaitTarget, sessionWindow, thresholdBars, weeklyWindow, type PickCtx } from "./picker.ts";
4
4
  import { familyTokens } from "./usage.ts";
5
5
  import { errorMessage, log } from "./log.ts";
6
6
  import type { Observation, Provider } from "./provider.ts";
@@ -8,6 +8,14 @@ import type { Account, EnforcedLimit } from "./types.ts";
8
8
 
9
9
  export type SwapDecision = { swapped: boolean; account: Account | null; reason: string; waitUntil?: number };
10
10
 
11
+ export type EvalOpts = {
12
+ seatId?: string | null;
13
+ sessionFamilies?: string[];
14
+ waiterId?: string;
15
+ };
16
+
17
+ const MAX_WAITERS_PER_ACCOUNT = 4;
18
+
11
19
  const WEEK_MS = 7 * 24 * 60 * 60 * 1000;
12
20
  const FIVE_HOURS_MS = 5 * 60 * 60 * 1000;
13
21
 
@@ -42,23 +50,30 @@ function enforcedWall(limit: EnforcedLimit, account: Account, now: number): numb
42
50
  return limit.resetsAt ?? cachedReset ?? now + (limit.kind === "session" ? FIVE_HOURS_MS : WEEK_MS);
43
51
  }
44
52
 
45
- export async function evaluateAndMaybeSwap(p: Provider, now = Date.now(), canRespawn = false, enforced: EnforcedLimit | null = null, seatId: string | null = p.liveId(), sessionFamilies?: string[]): Promise<SwapDecision> {
46
- const activeId = seatId;
53
+ export async function evaluateAndMaybeSwap(p: Provider, now = Date.now(), canRespawn = false, enforced: EnforcedLimit | null = null, opts: EvalOpts = {}): Promise<SwapDecision> {
54
+ const activeId = opts.seatId === undefined ? p.liveId() : opts.seatId;
55
+ const waiterId = canRespawn ? opts.waiterId : undefined;
47
56
  const cfg = loadConfig();
48
57
  const bars = thresholdBars(cfg);
49
58
  const stored0 = loadAccounts(p.pool).accounts.find((a) => a.id === activeId);
50
59
  const walled0 = stored0?.enforcedUntil != null && stored0.enforcedUntil > now;
51
- const gated = sessionFamilies ?? p.gatedFamilies(cfg);
60
+ const gated = opts.sessionFamilies ?? p.gatedFamilies(cfg);
52
61
  const observed = stored0 ? await p.observeLive(stored0, cfg, now, { probe: enforced == null && !walled0, perModel: gated == null || gated.length > 0 }) : null;
53
62
  const stored = loadAccounts(p.pool).accounts.find((a) => a.id === activeId);
54
63
 
55
64
  if (!enforced && !isOver(stored, observed, { now, thresholds: bars, currentId: activeId, families: gated, seats: null })) {
65
+ if (waiterId != null && liveWaitClaims(now).some((c) => c.sessionId === waiterId)) {
66
+ await withLock(p.pool.lockFile, () => {
67
+ releaseWaitClaim(waiterId);
68
+ });
69
+ }
56
70
  return { swapped: false, account: null, reason: "under-threshold-or-stale" };
57
71
  }
58
72
 
59
73
  return withLock(p.pool.lockFile, async () => {
74
+ if (waiterId != null) releaseWaitClaim(waiterId);
60
75
  const idx = loadAccounts(p.pool);
61
- const id2 = seatId;
76
+ const id2 = activeId;
62
77
  const active = id2 ? idx.accounts.find((a) => a.id === id2) : undefined;
63
78
 
64
79
  const origin = enforced ? idx.accounts.find((a) => a.id === enforced.account) : undefined;
@@ -91,7 +106,7 @@ export async function evaluateAndMaybeSwap(p: Provider, now = Date.now(), canRes
91
106
  }
92
107
  saveAccounts(p.pool, idx);
93
108
 
94
- const families = sessionFamilies ?? p.gatedFamilies(cfg);
109
+ const families = opts.sessionFamilies ?? p.gatedFamilies(cfg);
95
110
  const walled = active?.enforcedUntil != null && active.enforcedUntil > now;
96
111
  const blindScreen = (enforced != null && (prior || enforced.blind)) || (walled && !enforced2);
97
112
  const screened = blindScreen && families != null ? cfg.policy.switchModels : families;
@@ -142,31 +157,35 @@ export async function evaluateAndMaybeSwap(p: Provider, now = Date.now(), canRes
142
157
  const fresh = loadAccounts(p.pool);
143
158
  const current = seatOf(fresh);
144
159
  const ctx: PickCtx = { now, thresholds: bars, currentId: current?.id ?? null, families: switchFamilies, seats };
145
- const currentAt = current ? usableAt(current, ctx) : Number.POSITIVE_INFINITY;
146
- const other = pickEarliestReset(usable(fresh.accounts), ctx);
147
-
148
- let target: Account | null = null;
149
- let waitUntil = Number.POSITIVE_INFINITY;
150
- if (other && other.availableAt < currentAt) { target = other.account; waitUntil = other.availableAt; }
151
- else if (current) { target = current; waitUntil = currentAt; }
152
- else if (other) { target = other.account; waitUntil = other.availableAt; }
160
+ const waiters = new Map<string, number>();
161
+ for (const claim of liveWaitClaims(now)) {
162
+ if (claim.sessionId === waiterId) continue;
163
+ waiters.set(claim.accountId, (waiters.get(claim.accountId) ?? 0) + 1);
164
+ }
165
+ const target = pickWaitTarget(usable(fresh.accounts), ctx, waiters, MAX_WAITERS_PER_ACCOUNT, now + cfg.policy.maxWaitMs);
153
166
 
154
- if (!target || waitUntil - now > cfg.policy.maxWaitMs) {
167
+ if (!target) {
168
+ const soonest = pickWaitTarget(usable(fresh.accounts), ctx, new Map(), MAX_WAITERS_PER_ACCOUNT, Number.POSITIVE_INFINITY);
169
+ const waitUntil = soonest?.availableAt ?? Number.POSITIVE_INFINITY;
155
170
  log("decide.depleted", { waitUntil: Number.isFinite(waitUntil) ? waitUntil : 0 });
156
171
  return { swapped: false, account: null, reason: "all-depleted", ...(Number.isFinite(waitUntil) ? { waitUntil } : {}) };
157
172
  }
158
173
 
159
- const isCurrent = target.id === (current?.id ?? null);
174
+ const waitUntil = target.availableAt;
175
+ const isCurrent = target.account.id === (current?.id ?? null);
160
176
  if (!isCurrent) {
161
177
  try {
162
- await p.swap(target);
178
+ await p.swap(target.account);
163
179
  } catch (e) {
164
- skipOrThrow(e, target);
180
+ skipOrThrow(e, target.account);
165
181
  continue;
166
182
  }
167
183
  }
168
- log("decide.depleted_wait", { account: target.id.slice(0, 8), waitUntil });
169
- return { swapped: !isCurrent, account: target, reason: "depleted-wait", waitUntil };
184
+ if (waiterId != null) {
185
+ replaceWaitClaim({ sessionId: waiterId, accountId: target.account.id, at: now, waitUntil });
186
+ }
187
+ log("decide.depleted_wait", { account: target.account.id.slice(0, 8), waitUntil });
188
+ return { swapped: !isCurrent, account: target.account, reason: "depleted-wait", waitUntil };
170
189
  }
171
190
  });
172
191
  }
@@ -9,7 +9,7 @@ import { resolveRealClaude } from "./claudebin.ts";
9
9
  import { loadConfig } from "./state.ts";
10
10
  import { ErrnoSchema } from "./types.ts";
11
11
 
12
- export type InstallOutcome = { claudeWrapper: string; installedBin: string; pathAhead: boolean; timerLoaded: boolean; checkIntervalS: number };
12
+ export type InstallOutcome = { claudeWrapper: string; installedBin: string; pathAhead: boolean; timerLoaded: boolean; hubLoaded: boolean; checkIntervalS: number };
13
13
 
14
14
  export function isBinDirAhead(): boolean {
15
15
  const dirs = (process.env.PATH ?? "").split(":");
@@ -39,6 +39,10 @@ export function skipImperativeTimer(): boolean {
39
39
  return envFlag("TOKENMAXXING_SKIP_TIMER");
40
40
  }
41
41
 
42
+ export function skipImperativeHub(): boolean {
43
+ return envFlag("TOKENMAXXING_SKIP_HUB");
44
+ }
45
+
42
46
  function isNixStorePath(path: string): boolean {
43
47
  return path === "/nix/store" || path.startsWith("/nix/store/");
44
48
  }
@@ -103,6 +107,7 @@ export function installSupervisor(): InstallOutcome {
103
107
  installedBin: target,
104
108
  pathAhead: isBinDirAhead(),
105
109
  timerLoaded: installCheckTimer(checkIntervalS),
110
+ hubLoaded: installHubService(),
106
111
  checkIntervalS,
107
112
  };
108
113
  }
@@ -203,9 +208,11 @@ export function uninstallCodexSupervisor(): void {
203
208
  }
204
209
 
205
210
  const LAUNCHD_LABEL = "com.tokenmaxxing.check";
211
+ const LAUNCHD_HUB_LABEL = "com.tokenmaxxing.hub";
212
+ const HUB_UNIT = "tokenmaxxing-hub.service";
206
213
 
207
- function launchdPlist(): string {
208
- return join(paths.launchdAgentsDir, `${LAUNCHD_LABEL}.plist`);
214
+ function launchdPlist(label: string): string {
215
+ return join(paths.launchdAgentsDir, `${label}.plist`);
209
216
  }
210
217
 
211
218
  function launchdDomain(): string | null {
@@ -221,11 +228,19 @@ function run(cmd: string[]): boolean {
221
228
  }
222
229
  }
223
230
 
231
+ function systemdEnv(): string {
232
+ return `Environment="TOKENMAXXING_HOME=${paths.home.replaceAll("%", "%%")}"\n`;
233
+ }
234
+
235
+ function launchdEnv(): string {
236
+ return ` <key>EnvironmentVariables</key><dict><key>TOKENMAXXING_HOME</key><string>${escape(paths.home)}</string></dict>\n`;
237
+ }
238
+
224
239
  function installCheckTimer(intervalS: number): boolean {
225
240
  if (skipImperativeTimer()) return true;
226
241
 
227
242
  if (process.platform === "darwin") {
228
- const plist = launchdPlist();
243
+ const plist = launchdPlist(LAUNCHD_LABEL);
229
244
  writeFileAtomic(
230
245
  plist,
231
246
  `<?xml version="1.0" encoding="UTF-8"?>
@@ -235,7 +250,7 @@ function installCheckTimer(intervalS: number): boolean {
235
250
  <key>Label</key><string>${LAUNCHD_LABEL}</string>
236
251
  <key>ProgramArguments</key><array><string>${escape(installedBin())}</string><string>check</string></array>
237
252
  <key>StartInterval</key><integer>${intervalS}</integer>
238
- <key>StandardOutPath</key><string>/dev/null</string>
253
+ ${launchdEnv()} <key>StandardOutPath</key><string>/dev/null</string>
239
254
  <key>StandardErrorPath</key><string>${escape(join(paths.home, "check.stderr.log"))}</string>
240
255
  </dict>
241
256
  </plist>
@@ -257,7 +272,7 @@ Description=tokenmaxxing account-switch check
257
272
  [Service]
258
273
  Type=oneshot
259
274
  ExecStart=${exec}
260
- `,
275
+ ${systemdEnv()}`,
261
276
  0o644,
262
277
  );
263
278
  writeFileAtomic(
@@ -283,16 +298,23 @@ WantedBy=timers.target
283
298
 
284
299
  export function timerActivationHint(): string {
285
300
  if (process.platform === "darwin") {
286
- return `launchctl bootstrap gui/$(id -u) ${launchdPlist()}`;
301
+ return `launchctl bootstrap gui/$(id -u) ${launchdPlist(LAUNCHD_LABEL)}`;
287
302
  }
288
303
  return "systemctl --user daemon-reload && systemctl --user enable --now tokenmaxxing-check.timer";
289
304
  }
290
305
 
306
+ export function hubActivationHint(): string {
307
+ if (process.platform === "darwin") {
308
+ return `launchctl bootstrap gui/$(id -u) ${launchdPlist(LAUNCHD_HUB_LABEL)}`;
309
+ }
310
+ return `systemctl --user daemon-reload && systemctl --user enable --now ${HUB_UNIT}`;
311
+ }
312
+
291
313
  export function checkTimerHealthy(): boolean {
292
314
  if (skipImperativeTimer()) return true;
293
315
  if (process.platform === "darwin") {
294
316
  const domain = launchdDomain();
295
- return existsSync(launchdPlist()) && domain != null && run(["launchctl", "print", `${domain}/${LAUNCHD_LABEL}`]);
317
+ return existsSync(launchdPlist(LAUNCHD_LABEL)) && domain != null && run(["launchctl", "print", `${domain}/${LAUNCHD_LABEL}`]);
296
318
  }
297
319
  return (
298
320
  existsSync(join(paths.systemdUserDir, "tokenmaxxing-check.timer")) &&
@@ -300,6 +322,15 @@ export function checkTimerHealthy(): boolean {
300
322
  );
301
323
  }
302
324
 
325
+ export function hubServiceHealthy(): boolean {
326
+ if (skipImperativeHub()) return true;
327
+ if (process.platform === "darwin") {
328
+ const domain = launchdDomain();
329
+ return existsSync(launchdPlist(LAUNCHD_HUB_LABEL)) && domain != null && run(["launchctl", "print", `${domain}/${LAUNCHD_HUB_LABEL}`]);
330
+ }
331
+ return existsSync(join(paths.systemdUserDir, HUB_UNIT)) && run(["systemctl", "--user", "is-active", "--quiet", HUB_UNIT]);
332
+ }
333
+
303
334
  export function timerDeactivationHint(): string {
304
335
  if (process.platform === "darwin") {
305
336
  return `launchctl bootout gui/$(id -u)/${LAUNCHD_LABEL}`;
@@ -307,11 +338,18 @@ export function timerDeactivationHint(): string {
307
338
  return "systemctl --user disable --now tokenmaxxing-check.timer";
308
339
  }
309
340
 
310
- function launchdJobLoaded(): "loaded" | "not-loaded" | "unavailable" {
341
+ export function hubDeactivationHint(): string {
342
+ if (process.platform === "darwin") {
343
+ return `launchctl bootout gui/$(id -u)/${LAUNCHD_HUB_LABEL}`;
344
+ }
345
+ return `systemctl --user disable --now ${HUB_UNIT}`;
346
+ }
347
+
348
+ function launchdJobLoaded(label: string): "loaded" | "not-loaded" | "unavailable" {
311
349
  const domain = launchdDomain();
312
350
  if (domain == null) return "unavailable";
313
351
  try {
314
- const { exitCode } = Bun.spawnSync(["launchctl", "print", `${domain}/${LAUNCHD_LABEL}`], { stdout: "ignore", stderr: "ignore", timeout: 10_000 });
352
+ const { exitCode } = Bun.spawnSync(["launchctl", "print", `${domain}/${label}`], { stdout: "ignore", stderr: "ignore", timeout: 10_000 });
315
353
  if (exitCode === 0) return "loaded";
316
354
  return exitCode === 113 ? "not-loaded" : "unavailable";
317
355
  } catch {
@@ -319,9 +357,9 @@ function launchdJobLoaded(): "loaded" | "not-loaded" | "unavailable" {
319
357
  }
320
358
  }
321
359
 
322
- function systemdTimerActive(): "active" | "not-active" | "unavailable" {
360
+ function systemdUnitActive(unit: string): "active" | "not-active" | "unavailable" {
323
361
  try {
324
- const proc = Bun.spawnSync(["systemctl", "--user", "is-active", "tokenmaxxing-check.timer"], { stdout: "pipe", stderr: "ignore", timeout: 10_000 });
362
+ const proc = Bun.spawnSync(["systemctl", "--user", "is-active", unit], { stdout: "pipe", stderr: "ignore", timeout: 10_000 });
325
363
  const state = proc.stdout.toString().trim();
326
364
  if (state === "active" || state === "activating" || state === "reloading") return "active";
327
365
  if (state === "inactive" || state === "failed" || state === "deactivating" || state === "unknown" || state === "maintenance") return "not-active";
@@ -333,16 +371,16 @@ function systemdTimerActive(): "active" | "not-active" | "unavailable" {
333
371
 
334
372
  function removeTimerUnits(): void {
335
373
  if (process.platform === "darwin") {
336
- rmSync(launchdPlist(), { force: true });
374
+ rmSync(launchdPlist(LAUNCHD_LABEL), { force: true });
337
375
  return;
338
376
  }
339
377
  rmSync(join(paths.systemdUserDir, "tokenmaxxing-check.timer"), { force: true });
340
378
  rmSync(join(paths.systemdUserDir, "tokenmaxxing-check.service"), { force: true });
341
379
  }
342
380
 
343
- type TimerOutcome = "removed" | "skipped" | "still-loaded";
381
+ type UnitOutcome = "removed" | "skipped" | "still-loaded";
344
382
 
345
- function uninstallCheckTimer(live: boolean): TimerOutcome {
383
+ function uninstallCheckTimer(live: boolean): UnitOutcome {
346
384
  if (skipImperativeTimer()) return "skipped";
347
385
  if (!live) {
348
386
  removeTimerUnits();
@@ -350,18 +388,94 @@ function uninstallCheckTimer(live: boolean): TimerOutcome {
350
388
  }
351
389
  if (process.platform === "darwin") {
352
390
  const domain = launchdDomain();
353
- const loaded = launchdJobLoaded();
391
+ const loaded = launchdJobLoaded(LAUNCHD_LABEL);
354
392
  const deactivated = loaded === "loaded" && domain != null ? run(["launchctl", "bootout", `${domain}/${LAUNCHD_LABEL}`]) : loaded === "not-loaded";
355
393
  removeTimerUnits();
356
394
  return deactivated ? "removed" : "still-loaded";
357
395
  }
358
- const active = systemdTimerActive();
359
- const deactivated = active === "active" ? run(["systemctl", "--user", "disable", "--now", "tokenmaxxing-check.timer"]) : active === "not-active";
396
+ const active = systemdUnitActive("tokenmaxxing-check.timer");
397
+ const deactivated = active !== "unavailable" && (run(["systemctl", "--user", "disable", "--now", "tokenmaxxing-check.timer"]) || active === "not-active");
360
398
  removeTimerUnits();
361
399
  run(["systemctl", "--user", "daemon-reload"]);
362
400
  return deactivated ? "removed" : "still-loaded";
363
401
  }
364
402
 
403
+ function installHubService(): boolean {
404
+ if (skipImperativeHub()) return true;
405
+
406
+ if (process.platform === "darwin") {
407
+ const plist = launchdPlist(LAUNCHD_HUB_LABEL);
408
+ writeFileAtomic(
409
+ plist,
410
+ `<?xml version="1.0" encoding="UTF-8"?>
411
+ <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
412
+ <plist version="1.0">
413
+ <dict>
414
+ <key>Label</key><string>${LAUNCHD_HUB_LABEL}</string>
415
+ <key>ProgramArguments</key><array><string>${escape(installedBin())}</string><string>serve</string></array>
416
+ <key>KeepAlive</key><dict><key>SuccessfulExit</key><false/></dict>
417
+ <key>RunAtLoad</key><true/>
418
+ ${launchdEnv()} <key>StandardOutPath</key><string>/dev/null</string>
419
+ <key>StandardErrorPath</key><string>${escape(join(paths.home, "hub.stderr.log"))}</string>
420
+ </dict>
421
+ </plist>
422
+ `,
423
+ 0o644,
424
+ );
425
+ const domain = launchdDomain();
426
+ if (domain == null) return false;
427
+ run(["launchctl", "bootout", `${domain}/${LAUNCHD_HUB_LABEL}`]);
428
+ return run(["launchctl", "bootstrap", domain, plist]) || hubServiceHealthy();
429
+ }
430
+
431
+ const exec = `"${installedBin().replaceAll("%", "%%")}" serve`;
432
+ writeFileAtomic(
433
+ join(paths.systemdUserDir, HUB_UNIT),
434
+ `[Unit]
435
+ Description=tokenmaxxing usage hub
436
+ StartLimitIntervalSec=0
437
+
438
+ [Service]
439
+ ExecStart=${exec}
440
+ ${systemdEnv()}Restart=on-failure
441
+ RestartSec=5
442
+
443
+ [Install]
444
+ WantedBy=default.target
445
+ `,
446
+ 0o644,
447
+ );
448
+ return run(["systemctl", "--user", "daemon-reload"]) && run(["systemctl", "--user", "enable", "--now", HUB_UNIT]);
449
+ }
450
+
451
+ function removeHubUnits(): void {
452
+ if (process.platform === "darwin") {
453
+ rmSync(launchdPlist(LAUNCHD_HUB_LABEL), { force: true });
454
+ return;
455
+ }
456
+ rmSync(join(paths.systemdUserDir, HUB_UNIT), { force: true });
457
+ }
458
+
459
+ function uninstallHubService(live: boolean): UnitOutcome {
460
+ if (skipImperativeHub()) return "skipped";
461
+ if (!live) {
462
+ removeHubUnits();
463
+ return "removed";
464
+ }
465
+ if (process.platform === "darwin") {
466
+ const domain = launchdDomain();
467
+ const loaded = launchdJobLoaded(LAUNCHD_HUB_LABEL);
468
+ const deactivated = loaded === "loaded" && domain != null ? run(["launchctl", "bootout", `${domain}/${LAUNCHD_HUB_LABEL}`]) : loaded === "not-loaded";
469
+ removeHubUnits();
470
+ return deactivated ? "removed" : "still-loaded";
471
+ }
472
+ const active = systemdUnitActive(HUB_UNIT);
473
+ const deactivated = active !== "unavailable" && (run(["systemctl", "--user", "disable", "--now", HUB_UNIT]) || active === "not-active");
474
+ removeHubUnits();
475
+ run(["systemctl", "--user", "daemon-reload"]);
476
+ return deactivated ? "removed" : "still-loaded";
477
+ }
478
+
365
479
  export function shellRcPath(): string | null {
366
480
  const override = optionalEnv("TOKENMAXXING_SHELL_RC");
367
481
  if (override != null) return override;
@@ -445,7 +559,7 @@ export function removePathFromRc(rc: string): boolean {
445
559
  return true;
446
560
  }
447
561
 
448
- export type UninstallOutcome = { timer: "removed" | "skipped" | "still-loaded"; pathLineRemoved: boolean };
562
+ export type UninstallOutcome = { timer: UnitOutcome; hub: UnitOutcome; pathLineRemoved: boolean };
449
563
 
450
564
  export function loginHome(): string {
451
565
  const cmd = process.platform === "darwin" ? ["id", "-P"] : ["getent", "passwd", String(process.getuid?.() ?? "")];
@@ -462,13 +576,18 @@ export function onLoginHome(): boolean {
462
576
  export function uninstallTargets(live: boolean): string[] {
463
577
  const timer =
464
578
  process.platform === "darwin"
465
- ? `${launchdPlist()}${live ? ` (and launchctl bootout gui/${process.getuid?.() ?? "?"}/${LAUNCHD_LABEL})` : ""}`
579
+ ? `${launchdPlist(LAUNCHD_LABEL)}${live ? ` (and launchctl bootout gui/${process.getuid?.() ?? "?"}/${LAUNCHD_LABEL})` : ""}`
466
580
  : `${join(paths.systemdUserDir, "tokenmaxxing-check.timer")} and .service${live ? " (and systemctl --user disable --now tokenmaxxing-check.timer)" : ""}`;
581
+ const hub =
582
+ process.platform === "darwin"
583
+ ? `${launchdPlist(LAUNCHD_HUB_LABEL)}${live ? ` (and launchctl bootout gui/${process.getuid?.() ?? "?"}/${LAUNCHD_HUB_LABEL})` : ""}`
584
+ : `${join(paths.systemdUserDir, HUB_UNIT)}${live ? ` (and systemctl --user disable --now ${HUB_UNIT})` : ""}`;
467
585
  const rc = shellRcPath();
468
586
  return [
469
587
  `${paths.claudeSettings}: the hook and statusline entries`,
470
588
  `${codexPaths.hooksJson}: the codex Stop hook entry`,
471
589
  ...(skipImperativeTimer() ? [] : [timer]),
590
+ ...(skipImperativeHub() ? [] : [hub]),
472
591
  paths.supervisorLink,
473
592
  codexSupervisorLink(),
474
593
  join(paths.binDir, "xx"),
@@ -477,14 +596,15 @@ export function uninstallTargets(live: boolean): string[] {
477
596
  ];
478
597
  }
479
598
 
480
- export function uninstallSupervisor(input: { liveTimer: boolean }): UninstallOutcome {
599
+ export function uninstallSupervisor(input: { live: boolean }): UninstallOutcome {
481
600
  uninstallSettings();
482
- const timer = uninstallCheckTimer(input.liveTimer);
601
+ const timer = uninstallCheckTimer(input.live);
602
+ const hub = uninstallHubService(input.live);
483
603
  uninstallCodexSupervisor();
484
604
  for (const f of [paths.supervisorLink, join(paths.binDir, "xx"), installedBin()]) {
485
605
  if (existsSync(f)) rmSync(f, { force: true });
486
606
  }
487
607
  const rc = shellRcPath();
488
608
  const pathLineRemoved = rc != null && removePathFromRc(rc);
489
- return { timer, pathLineRemoved };
609
+ return { timer, hub, pathLineRemoved };
490
610
  }
package/src/lib/paths.ts CHANGED
@@ -48,6 +48,7 @@ export const paths = {
48
48
  export const claudePool = {
49
49
  accountsJson: join(TM_HOME, "accounts.json"),
50
50
  lockFile: join(TM_HOME, "lock"),
51
+ waitQueueJson: join(TM_HOME, "wait-queue.json"),
51
52
  } as const;
52
53
 
53
54
  export const codexPool = {
package/src/lib/picker.ts CHANGED
@@ -135,3 +135,12 @@ export function pickEarliestReset(accounts: Account[], ctx: PickCtx): EarliestRe
135
135
  .filter((x) => Number.isFinite(x.availableAt));
136
136
  return minBy(mapped, (x) => x.availableAt) ?? null;
137
137
  }
138
+
139
+ export function pickWaitTarget(accounts: Account[], ctx: PickCtx, waiters: Map<string, number>, cap: number, deadline: number): EarliestReset | null {
140
+ const mapped = accounts
141
+ .filter((a) => !a.needsReauth)
142
+ .map((a) => ({ account: a, availableAt: usableAt(a, ctx) }))
143
+ .filter((x) => Number.isFinite(x.availableAt) && x.availableAt <= deadline)
144
+ .sort((x, y) => x.availableAt - y.availableAt || (x.account.id === ctx.currentId ? -1 : y.account.id === ctx.currentId ? 1 : 0));
145
+ return mapped.find((x) => (waiters.get(x.account.id) ?? 0) < cap) ?? mapped[0] ?? null;
146
+ }
package/src/lib/state.ts CHANGED
@@ -1,17 +1,19 @@
1
1
  import { closeSync, existsSync, fstatSync, openSync, readFileSync, rmSync, utimesSync } from "node:fs";
2
2
  import { isEqual } from "es-toolkit";
3
3
  import { z } from "zod";
4
- import { optionalEnv, paths, usageJsonFor, type PoolPaths } from "./paths.ts";
4
+ import { claudePool, optionalEnv, paths, usageJsonFor, type PoolPaths } from "./paths.ts";
5
5
  import { writeFileAtomic } from "./atomic.ts";
6
6
  import {
7
7
  AccountsIndexSchema,
8
8
  ConfigSchema,
9
9
  ErrnoSchema,
10
10
  UsageStateSchema,
11
+ WaitQueueSchema,
11
12
  type Account,
12
13
  type AccountsIndex,
13
14
  type Config,
14
15
  type UsageState,
16
+ type WaitClaim,
15
17
  type Window,
16
18
  } from "./types.ts";
17
19
 
@@ -67,6 +69,41 @@ export function saveAccounts(pool: PoolPaths, idx: AccountsIndex): void {
67
69
  writeFileAtomic(pool.accountsJson, JSON.stringify(AccountsIndexSchema.parse(idx), null, 2) + "\n");
68
70
  }
69
71
 
72
+ function loadWaitQueue(): WaitClaim[] {
73
+ if (!existsSync(claudePool.waitQueueJson)) return [];
74
+ let json: unknown;
75
+ try {
76
+ json = JSON.parse(readFileSync(claudePool.waitQueueJson, "utf8"));
77
+ } catch {
78
+ throw new Error(`${claudePool.waitQueueJson} is corrupt (unparsable JSON) - refusing to treat a damaged wait queue as empty; repair or remove the file`);
79
+ }
80
+ const parsed = WaitQueueSchema.safeParse(json);
81
+ if (!parsed.success) {
82
+ throw new Error(`${claudePool.waitQueueJson} does not match the wait-queue schema - refusing to treat a damaged wait queue as empty; repair or remove the file`);
83
+ }
84
+ return parsed.data.claims;
85
+ }
86
+
87
+ function saveWaitQueue(claims: WaitClaim[]): void {
88
+ writeFileAtomic(claudePool.waitQueueJson, JSON.stringify(WaitQueueSchema.parse({ version: 1, claims }), null, 2) + "\n");
89
+ }
90
+
91
+ export function liveWaitClaims(now: number): WaitClaim[] {
92
+ return loadWaitQueue().filter((c) => c.waitUntil > now);
93
+ }
94
+
95
+ export function replaceWaitClaim(claim: WaitClaim): void {
96
+ saveWaitQueue([...liveWaitClaims(Date.now()).filter((c) => c.sessionId !== claim.sessionId), claim]);
97
+ }
98
+
99
+ export function releaseWaitClaim(sessionId: string): void {
100
+ const now = Date.now();
101
+ const raw = loadWaitQueue();
102
+ const next = raw.filter((c) => c.waitUntil > now && c.sessionId !== sessionId);
103
+ if (next.length === raw.length) return;
104
+ saveWaitQueue(next);
105
+ }
106
+
70
107
  export type Harvest = {
71
108
  id: string;
72
109
  email: string | null;
package/src/lib/types.ts CHANGED
@@ -128,6 +128,19 @@ export const ConfigSchema = z
128
128
  });
129
129
  export type Config = z.infer<typeof ConfigSchema>;
130
130
 
131
+ export const WaitClaimSchema = z.object({
132
+ sessionId: z.string(),
133
+ accountId: z.string(),
134
+ at: z.number(),
135
+ waitUntil: z.number(),
136
+ });
137
+ export type WaitClaim = z.infer<typeof WaitClaimSchema>;
138
+
139
+ export const WaitQueueSchema = z.object({
140
+ version: z.literal(1),
141
+ claims: z.array(WaitClaimSchema).default([]),
142
+ });
143
+
131
144
  export const RespawnMarkerSchema = z.object({
132
145
  accountId: z.string(),
133
146
  ts: z.number(),
package/src/main.ts CHANGED
@@ -26,7 +26,7 @@ import { cmdSetupToken } from "./cli/setuptoken.ts";
26
26
  import { cmdCloudRun } from "./cli/cloudrun.ts";
27
27
  import { cmdCursorInit } from "./cli/cursorinit.ts";
28
28
  import { cmdServe } from "./cli/serve.ts";
29
- import { onLoginHome, timerDeactivationHint, uninstallSupervisor, uninstallTargets } from "./lib/install.ts";
29
+ import { hubDeactivationHint, onLoginHome, timerDeactivationHint, uninstallSupervisor, uninstallTargets } from "./lib/install.ts";
30
30
  import { errorMessage } from "./lib/log.ts";
31
31
  import { HOME } from "./lib/paths.ts";
32
32
  import { c, emitError } from "./cli/render.ts";
@@ -185,15 +185,17 @@ async function main(): Promise<number> {
185
185
  emitError({ message: `refused: HOME is the login home (${HOME}) - rerun with ${YES_FLAG} to remove these from the live install` });
186
186
  return 2;
187
187
  }
188
- const out = uninstallSupervisor({ liveTimer: live });
188
+ const out = uninstallSupervisor({ live });
189
189
  const removed = [
190
190
  "supervisor wrapper",
191
191
  "settings entries",
192
192
  ...(out.timer === "removed" ? ["check timer"] : []),
193
+ ...(out.hub === "removed" ? ["usage hub service"] : []),
193
194
  ...(out.pathLineRemoved ? ["rc PATH line"] : []),
194
195
  ];
195
196
  console.log(`removed ${removed.join(", ")}`);
196
197
  if (out.timer === "still-loaded") console.log(c.yellow(`⚠ the check job may still be loaded - run: ${timerDeactivationHint()}`));
198
+ if (out.hub === "still-loaded") console.log(c.yellow(`⚠ the usage hub job may still be loaded - run: ${hubDeactivationHint()}`));
197
199
  if (!out.pathLineRemoved) console.log(c.dim("(no tokenmaxxing PATH line found in the shell rc)"));
198
200
  console.log(`kept: accounts.json, config.json, and every account credential store (claude: stores/ and its keychain items on macOS; codex: codex-stores/; grok: grok-stores/; opencode-go: opencode-go-stores/) - remove accounts with \`xx rm\` to delete their credentials`);
199
201
  return 0;