tokenmaxxing 1.89.0 → 1.91.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 +3 -3
- package/README.md +2 -2
- package/package.json +1 -1
- package/src/cli/status.ts +5 -1
- package/src/lib/claude.ts +17 -7
- package/src/lib/grokusage.ts +1 -1
- package/src/lib/picker.ts +1 -1
- package/src/lib/provider.ts +1 -1
- package/src/lib/sample.ts +82 -18
package/DESIGN.md
CHANGED
|
@@ -53,7 +53,7 @@ The switching path runs no long-lived daemon. The statusline pushes usage. Hooks
|
|
|
53
53
|
## 3. How a move happens
|
|
54
54
|
|
|
55
55
|
### 3.1 Usage feed (free, push-based)
|
|
56
|
-
The Stop hook's stdin has no usage data, but the **statusLine does** (`rate_limits.{five_hour,seven_day}.{used_percentage,resets_at}`, after every turn, 300ms debounce, zero cost). tokenmaxxing's statusLine tees that to `usage/<uuid8>.json` for the session's seat, read from the inherited `CLAUDE_SECURESTORAGE_CONFIG_DIR` (write-on-change, O(ms)), and renders its own native line (it replaced the earlier pass-through delegation on 2026-07-11: install takes the statusLine slot outright, so a pre-existing custom statusline command is overwritten). A session with no pooled seat writes no tee. The seat is sampled when its tee is older than `policy.usagePollTtlMs`, and for the per-model rows when the active model is a gated family: the direct no-spend usage read with the seat's stored token. The compact child still sets `TOKENMAXXING_PROBE=1` so the hook entries return at once. The sample takes one attempt per interval; a failed sample doubles the interval up to 30 minutes, and a success resets it.
|
|
56
|
+
The Stop hook's stdin has no usage data, but the **statusLine does** (`rate_limits.{five_hour,seven_day}.{used_percentage,resets_at}`, after every turn, 300ms debounce, zero cost). tokenmaxxing's statusLine tees that to `usage/<uuid8>.json` for the session's seat, read from the inherited `CLAUDE_SECURESTORAGE_CONFIG_DIR` (write-on-change, O(ms)), and renders its own native line (it replaced the earlier pass-through delegation on 2026-07-11: install takes the statusLine slot outright, so a pre-existing custom statusline command is overwritten). A session with no pooled seat writes no tee. The seat is sampled when its tee is older than `policy.usagePollTtlMs`, and for the per-model rows when the active model is a gated family, at most once per the account's sample interval (§5): the direct no-spend usage read with the seat's stored token. The compact child still sets `TOKENMAXXING_PROBE=1` so the hook entries return at once. The sample takes one attempt per interval; a failed sample doubles the interval up to 30 minutes, and a success resets it. A sample that finds the stored access token expired has Claude Code refresh it first (§5).
|
|
57
57
|
|
|
58
58
|
### 3.2 Detect + decide + signal (Stop hook, per turn)
|
|
59
59
|
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.
|
|
@@ -87,7 +87,7 @@ Each terminal ran the supervisor, so each has its own child `claude`, its own `-
|
|
|
87
87
|
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.
|
|
88
88
|
|
|
89
89
|
- 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.
|
|
90
|
-
- 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
|
|
90
|
+
- 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 the account's sample interval, over the direct no-spend usage read with the account's stored token. The interval is 15 minutes times the unused fraction of the bar closest to being reached, never under `policy.usagePollTtlMs`, and 15 minutes for an account at or over an aggregate bar. The windows are the session and weekly aggregates plus the `policy.switchModels` caps that are still under their bar, and an account with no stored aggregate gets `policy.usagePollTtlMs`. Every account is attempted about once per three ticks per pooled account, or once per its sample interval 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. No sampler sends a read with an expired stored access token, because the endpoint answers it with 401 and, after a few, with the same 429. A sample that finds the token expired first runs `claude -p /usage --no-session-persistence --safe-mode` with the account's store set and a throwaway `CLAUDE_CONFIG_DIR`, so Claude Code refreshes the token under its own lock, and then reads with the new token; the child's output is not read. A refresh that leaves the token expired fails the sample with no read, and one that clears the store flags the account `needsReauth`.
|
|
91
91
|
- The depleted pause happens at the bar, not at 100; Codex has no pause and rides its account until the server refuses it, because a running sibling cannot adopt another account without restarting.
|
|
92
92
|
- Neither pool has a post-swap cooldown or a manual `switch`: a move is a respawn of one session under a fixed store, so nothing another session reads is invalidated by it, and placement at launch replaces the manual pick.
|
|
93
93
|
|
|
@@ -135,7 +135,7 @@ TypeScript on Bun, shipped as source: one multi-call entry (`src/main.ts`, `#!/u
|
|
|
135
135
|
|
|
136
136
|
### 2026-09-12 (per-account stores, 1.37.0)
|
|
137
137
|
|
|
138
|
-
Hermetic run on Linux under a throwaway `HOME` and `TOKENMAXXING_HOME`, a stub `claude` that records its environment, and a synthetic three-account version 2 pool with equal headroom on two accounts and the third over its session bar. Usage comes from a stub usage endpoint named by `TOKENMAXXING_OAUTH_USAGE_URL` that answers per access token.
|
|
138
|
+
Hermetic run on Linux under a throwaway `HOME` and `TOKENMAXXING_HOME`, a stub `claude` that records its environment, and a synthetic three-account version 2 pool with equal headroom on two accounts and the third over its session bar. Usage comes from a stub usage endpoint named by `TOKENMAXXING_OAUTH_USAGE_URL` that answers per access token. No `/usage` output is parsed.
|
|
139
139
|
|
|
140
140
|
1. **Placement - ✅.** The first supervised launch spawned the stub with `CLAUDE_SECURESTORAGE_CONFIG_DIR=stores/<first account>` and wrote its presence; the second launch, with equal headroom, landed on the other account.
|
|
141
141
|
2. **Plain move - ✅.** A 95% session tee for the second session's account made its Stop hook write the marker; the supervisor relaunched `--resume <sid>` under the first account's store within a second and rewrote the presence file.
|
package/README.md
CHANGED
|
@@ -90,7 +90,7 @@ The bars' headroom is deliberate: it's the budget to reach a clean turn boundary
|
|
|
90
90
|
|
|
91
91
|
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.
|
|
92
92
|
|
|
93
|
-
- 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
|
|
93
|
+
- 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 the account's sample interval (15 minutes for an empty account, shrinking to `policy.usagePollTtlMs` as it nears a bar, and 15 minutes again at or over an aggregate bar), 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. A sample that finds the stored access token expired has Claude Code refresh it first (`claude -p /usage` under that store) and reads with the new token.
|
|
94
94
|
- 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.
|
|
95
95
|
|
|
96
96
|
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.
|
|
@@ -112,7 +112,7 @@ See [How switching decides](docs/content/docs/switching.mdx) for the policy and
|
|
|
112
112
|
}
|
|
113
113
|
```
|
|
114
114
|
|
|
115
|
-
`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
|
|
115
|
+
`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 the shortest sample interval, the one an account near a bar gets, for a seat's own sample, for `status`, 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`, `opencodeBin`, and `piBin` pin the real binaries; `init` writes them, and `TOKENMAXXING_CLAUDE_BIN`, `TOKENMAXXING_CODEX_BIN`, `TOKENMAXXING_GROK_BIN`, `TOKENMAXXING_OPENCODE_BIN`, and `TOKENMAXXING_PI_BIN` override them for one process, except that `init` pins the binary it resolved into `config.json`.
|
|
116
116
|
|
|
117
117
|
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`).
|
|
118
118
|
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "tokenmaxxing",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.91.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/status.ts
CHANGED
|
@@ -27,7 +27,7 @@ type StatusAccount = {
|
|
|
27
27
|
usage: UsageReport | null;
|
|
28
28
|
usageAt: number | null;
|
|
29
29
|
limitsAt: number | null;
|
|
30
|
-
sample: SampleReport
|
|
30
|
+
sample: SampleReport;
|
|
31
31
|
};
|
|
32
32
|
|
|
33
33
|
type PoolReport = {
|
|
@@ -109,6 +109,10 @@ async function collect(p: Provider, cfg: Config, now: number, cached: boolean):
|
|
|
109
109
|
stored.usageRetryAt = a.usageRetryAt;
|
|
110
110
|
dirty = true;
|
|
111
111
|
}
|
|
112
|
+
if ((a.lastProbeAt ?? 0) > (stored.lastProbeAt ?? 0)) {
|
|
113
|
+
stored.lastProbeAt = a.lastProbeAt;
|
|
114
|
+
dirty = true;
|
|
115
|
+
}
|
|
112
116
|
if (a.lastUsageAt != null && (stored.lastUsageAt == null || a.lastUsageAt > stored.lastUsageAt)) {
|
|
113
117
|
landWindows(stored, p.mergeWindows(a.windows, stored.windows), a.lastUsageAt, bars);
|
|
114
118
|
if (a.email != null) stored.email = a.email;
|
package/src/lib/claude.ts
CHANGED
|
@@ -13,7 +13,7 @@ import { landWindows, pickBest, pickEarliestReset, thresholdBars, type PickCtx }
|
|
|
13
13
|
import { deletePiStore } from "./piauth.ts";
|
|
14
14
|
import { livingPresences } from "./presence.ts";
|
|
15
15
|
import { StoreUnusableError, type Observation, type Provider, type SampleReport } from "./provider.ts";
|
|
16
|
-
import { foldTee, sampleAccountUsage, teeObservation, usageBlockedUntil } from "./sample.ts";
|
|
16
|
+
import { foldTee, readyToSample, runSample, sampleAccountUsage, sampleDue, sampleIntervalMs, teeObservation, usageBlockedUntil } from "./sample.ts";
|
|
17
17
|
import { clearUsageSnapshot, liveWaitClaims, loadAccounts, loadConfig, loadUsageSnapshot, pinBinOverride, readJsonFile, saveAccounts, type Harvest } from "./state.ts";
|
|
18
18
|
import { saveTermios, restoreTermios } from "./tty.ts";
|
|
19
19
|
import { fetchUsageDirect, gatedFamilies, mergeWindows, modelFromFlag, scrubCredentialEnv, windowsOf } from "./usage.ts";
|
|
@@ -33,11 +33,10 @@ function presence(): Map<string, number> {
|
|
|
33
33
|
const PROBE_BACKOFF_CAP_MS = 30 * 60 * 1000;
|
|
34
34
|
|
|
35
35
|
async function observeLive(account: Account, cfg: Config, now: number, opts: { probe: boolean; perModel: boolean }): Promise<Observation | null> {
|
|
36
|
-
const
|
|
37
|
-
const interval = Math.min(ttl * 2 ** (account.probeFails ?? 0), PROBE_BACKOFF_CAP_MS);
|
|
36
|
+
const interval = Math.min(sampleIntervalMs(account, cfg, now) * 2 ** (account.probeFails ?? 0), PROBE_BACKOFF_CAP_MS);
|
|
38
37
|
const probeAttempted = account.lastProbeAt != null && now - account.lastProbeAt <= interval;
|
|
39
38
|
const snap = loadUsageSnapshot(account.id);
|
|
40
|
-
const fresh = snap != null && now - snap.at <=
|
|
39
|
+
const fresh = snap != null && now - snap.at <= cfg.policy.usagePollTtlMs;
|
|
41
40
|
if (opts.probe && !probeAttempted && usageBlockedUntil(account, now) == null && (!fresh || opts.perModel)) {
|
|
42
41
|
const startedAt = Date.now();
|
|
43
42
|
const outcome = await sampleAccountUsage(account);
|
|
@@ -64,9 +63,10 @@ async function observeLive(account: Account, cfg: Config, now: number, opts: { p
|
|
|
64
63
|
return teeObservation(current);
|
|
65
64
|
}
|
|
66
65
|
|
|
67
|
-
async function samplePool(accounts: Account[]): Promise<Map<string, SampleReport>> {
|
|
66
|
+
async function samplePool(accounts: Account[], _liveId: string | null, now: number): Promise<Map<string, SampleReport>> {
|
|
68
67
|
const reports = new Map<string, SampleReport>();
|
|
69
|
-
const
|
|
68
|
+
const cfg = loadConfig();
|
|
69
|
+
const bars = thresholdBars(cfg);
|
|
70
70
|
await Promise.all(
|
|
71
71
|
accounts.map(async (a) => {
|
|
72
72
|
const tee = loadUsageSnapshot(a.id);
|
|
@@ -76,7 +76,17 @@ async function samplePool(accounts: Account[]): Promise<Map<string, SampleReport
|
|
|
76
76
|
reports.set(a.id, { ok: true, source: "statusline" });
|
|
77
77
|
return;
|
|
78
78
|
}
|
|
79
|
-
const
|
|
79
|
+
const ready = await readyToSample(a, now);
|
|
80
|
+
if (!ready.ok) {
|
|
81
|
+
reports.set(a.id, { ok: false, reason: ready.reason });
|
|
82
|
+
return;
|
|
83
|
+
}
|
|
84
|
+
if (!sampleDue(a, cfg, now)) {
|
|
85
|
+
reports.set(a.id, { ok: true, source: "cached" });
|
|
86
|
+
return;
|
|
87
|
+
}
|
|
88
|
+
a.lastProbeAt = now;
|
|
89
|
+
const outcome = await runSample(a, ready);
|
|
80
90
|
if (!outcome.ok) {
|
|
81
91
|
if (outcome.retryAt != null) a.usageRetryAt = outcome.retryAt;
|
|
82
92
|
reports.set(a.id, { ok: false, reason: outcome.reason });
|
package/src/lib/grokusage.ts
CHANGED
|
@@ -20,7 +20,7 @@ const CreditsPeriodSchema = z.looseObject({
|
|
|
20
20
|
|
|
21
21
|
const CreditsConfigSchema = z.looseObject({
|
|
22
22
|
currentPeriod: CreditsPeriodSchema,
|
|
23
|
-
creditUsagePercent: z.number(),
|
|
23
|
+
creditUsagePercent: z.number().default(0),
|
|
24
24
|
});
|
|
25
25
|
|
|
26
26
|
const CreditsBillingSchema = z.looseObject({
|
package/src/lib/picker.ts
CHANGED
|
@@ -49,7 +49,7 @@ export function liveUsed(w: Window, now: number): number {
|
|
|
49
49
|
return w.usedPercentage;
|
|
50
50
|
}
|
|
51
51
|
|
|
52
|
-
function barFor(w: Window, thresholds: Thresholds): number {
|
|
52
|
+
export function barFor(w: Window, thresholds: Thresholds): number {
|
|
53
53
|
return isSessionWindow(w) ? thresholds.session : thresholds.weekly;
|
|
54
54
|
}
|
|
55
55
|
|
package/src/lib/provider.ts
CHANGED
|
@@ -4,7 +4,7 @@ import type { Account, Config, Window } from "./types.ts";
|
|
|
4
4
|
|
|
5
5
|
export type Observation = { windows: Window[]; at: number };
|
|
6
6
|
|
|
7
|
-
export type SampleReport = { ok: true; source: "statusline" | "probe" } | { ok: false; reason: string };
|
|
7
|
+
export type SampleReport = { ok: true; source: "statusline" | "probe" | "cached" } | { ok: false; reason: string };
|
|
8
8
|
|
|
9
9
|
export type SwapFailure = "dead-grant" | "skip" | "fatal";
|
|
10
10
|
|
package/src/lib/sample.ts
CHANGED
|
@@ -1,18 +1,42 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { mkdtempSync, rmSync } from "node:fs";
|
|
2
|
+
import { tmpdir } from "node:os";
|
|
3
|
+
import { join } from "node:path";
|
|
4
|
+
import { CLAUDE_BIN, MAX_WRAP_DEPTH, resolveRealBin, WRAP_DEPTH_ENV } from "./claudebin.ts";
|
|
5
|
+
import { deleteItem, readStore, storeTarget } from "./credstore.ts";
|
|
2
6
|
import { withLock } from "./lock.ts";
|
|
3
7
|
import { errorMessage, log } from "./log.ts";
|
|
4
8
|
import { claudeTierLabel, isDeadCredential } from "./oauth.ts";
|
|
5
|
-
import { claudePool, paths } from "./paths.ts";
|
|
6
|
-
import { landWindows, thresholdBars } from "./picker.ts";
|
|
9
|
+
import { claudePool, paths, storeDirFor } from "./paths.ts";
|
|
10
|
+
import { barFor, gatedWindows, landWindows, liveUsed, thresholdBars } from "./picker.ts";
|
|
7
11
|
import { seatCounts } from "./presence.ts";
|
|
8
12
|
import type { Observation } from "./provider.ts";
|
|
9
13
|
import { loadAccounts, loadUsageSnapshot, saveAccounts } from "./state.ts";
|
|
10
|
-
import { fetchUsageDirect, mergeWindows, windowsOf } from "./usage.ts";
|
|
11
|
-
import type { Account, Config, Thresholds, UsageWindows } from "./types.ts";
|
|
14
|
+
import { fetchUsageDirect, mergeWindows, scrubCredentialEnv, windowsOf } from "./usage.ts";
|
|
15
|
+
import type { Account, Config, Thresholds, UsageWindows, Window } from "./types.ts";
|
|
12
16
|
|
|
13
17
|
export type SampleOutcome = { ok: true; usage: UsageWindows; via: "get" } | { ok: false; reason: string; retryAt?: number };
|
|
14
18
|
|
|
15
|
-
type PreparedSample = { ok: true; token: string } | { ok: false; reason: string };
|
|
19
|
+
type PreparedSample = { ok: true; token: string; expiresAt: number } | { ok: false; reason: string };
|
|
20
|
+
|
|
21
|
+
const SAMPLE_INTERVAL_MAX_MS = 15 * 60 * 1000;
|
|
22
|
+
|
|
23
|
+
export function sampleIntervalMs(account: Account, cfg: Config, now: number): number {
|
|
24
|
+
const floor = cfg.policy.usagePollTtlMs;
|
|
25
|
+
const bars = thresholdBars(cfg);
|
|
26
|
+
const aggregates = account.windows.filter((w) => w.name == null);
|
|
27
|
+
if (aggregates.length === 0) return floor;
|
|
28
|
+
const blocked = (w: Window) => liveUsed(w, now) >= barFor(w, bars);
|
|
29
|
+
if (aggregates.some(blocked)) return Math.max(floor, SAMPLE_INTERVAL_MAX_MS);
|
|
30
|
+
const open = [...aggregates, ...gatedWindows(account, cfg.policy.switchModels).filter((w) => !blocked(w))];
|
|
31
|
+
const spare = Math.min(...open.map((w) => 1 - liveUsed(w, now) / barFor(w, bars)));
|
|
32
|
+
return Math.max(floor, SAMPLE_INTERVAL_MAX_MS * spare);
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
const sampledAt = (a: Account) => Math.max(a.lastUsageAt ?? 0, a.lastProbeAt ?? 0);
|
|
36
|
+
|
|
37
|
+
export function sampleDue(account: Account, cfg: Config, now: number): boolean {
|
|
38
|
+
return now - sampledAt(account) > sampleIntervalMs(account, cfg, now);
|
|
39
|
+
}
|
|
16
40
|
|
|
17
41
|
export function teeObservation(account: Account): Observation | null {
|
|
18
42
|
const stored = account.lastUsageAt != null ? { windows: account.windows, at: account.lastUsageAt } : null;
|
|
@@ -45,7 +69,7 @@ export async function prepareSample(account: Account): Promise<PreparedSample> {
|
|
|
45
69
|
}
|
|
46
70
|
if (!account.oauthAccount) return { ok: false, reason: "account record has no oauthAccount - run `tokenmaxxing auth`" };
|
|
47
71
|
account.tier = claudeTierLabel(creds) ?? account.tier;
|
|
48
|
-
return { ok: true, token: creds.accessToken };
|
|
72
|
+
return { ok: true, token: creds.accessToken, expiresAt: creds.expiresAt };
|
|
49
73
|
}
|
|
50
74
|
|
|
51
75
|
export function usageBlockedUntil(account: Account, now: number): number | null {
|
|
@@ -56,19 +80,60 @@ function rateLimitedReason(retryAt: number, now: number): string {
|
|
|
56
80
|
return `the usage endpoint rate limited this account, next read in ${Math.ceil((retryAt - now) / 60_000)}m`;
|
|
57
81
|
}
|
|
58
82
|
|
|
59
|
-
|
|
83
|
+
const REFRESH_KILL_MS = 60_000;
|
|
84
|
+
|
|
85
|
+
async function refreshStore(account: Account): Promise<number | null> {
|
|
86
|
+
const home = mkdtempSync(join(tmpdir(), "tokenmaxxing-refresh-"));
|
|
87
|
+
const env = scrubCredentialEnv({ ...process.env, TOKENMAXXING_PROBE: "1", [WRAP_DEPTH_ENV]: String(MAX_WRAP_DEPTH) });
|
|
88
|
+
env.CLAUDE_CONFIG_DIR = home;
|
|
89
|
+
env.CLAUDE_SECURESTORAGE_CONFIG_DIR = storeDirFor(account.id);
|
|
90
|
+
try {
|
|
91
|
+
const p = Bun.spawn([resolveRealBin(CLAUDE_BIN), "-p", "/usage", "--no-session-persistence", "--safe-mode"], {
|
|
92
|
+
env,
|
|
93
|
+
cwd: home,
|
|
94
|
+
stdin: "ignore",
|
|
95
|
+
stdout: "ignore",
|
|
96
|
+
stderr: "ignore",
|
|
97
|
+
timeout: REFRESH_KILL_MS,
|
|
98
|
+
killSignal: "SIGKILL",
|
|
99
|
+
});
|
|
100
|
+
await p.exited;
|
|
101
|
+
return p.exitCode;
|
|
102
|
+
} finally {
|
|
103
|
+
rmSync(home, { recursive: true, force: true });
|
|
104
|
+
await withLock(claudePool.lockFile, async () => {
|
|
105
|
+
if (loadAccounts(claudePool).accounts.some((a) => a.id === account.id)) return;
|
|
106
|
+
await deleteItem(storeTarget(account.id));
|
|
107
|
+
rmSync(storeDirFor(account.id), { recursive: true, force: true });
|
|
108
|
+
rmSync(`${storeDirFor(account.id)}.lock`, { recursive: true, force: true });
|
|
109
|
+
});
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
export async function runSample(account: Account, prepared: { token: string; expiresAt: number }): Promise<SampleOutcome> {
|
|
114
|
+
let token = prepared.token;
|
|
115
|
+
if (prepared.expiresAt <= Date.now()) {
|
|
116
|
+
const exit = await refreshStore(account);
|
|
117
|
+
const refreshed = await prepareSample(account);
|
|
118
|
+
if (!refreshed.ok) return refreshed;
|
|
119
|
+
if (refreshed.expiresAt <= Date.now()) return { ok: false, reason: `the stored access token expired and claude did not refresh it (exit ${exit ?? "killed"})` };
|
|
120
|
+
token = refreshed.token;
|
|
121
|
+
}
|
|
60
122
|
const read = await fetchUsageDirect(token);
|
|
61
123
|
if (read.ok) return { ok: true, usage: read.usage, via: "get" };
|
|
62
124
|
if (read.retryAt == null) return { ok: false, reason: "usage read failed (see log)" };
|
|
63
125
|
return { ok: false, reason: rateLimitedReason(read.retryAt, Date.now()), retryAt: read.retryAt };
|
|
64
126
|
}
|
|
65
127
|
|
|
66
|
-
export async function
|
|
67
|
-
const now = Date.now();
|
|
128
|
+
export async function readyToSample(account: Account, now: number): Promise<PreparedSample> {
|
|
68
129
|
const blockedUntil = usageBlockedUntil(account, now);
|
|
69
130
|
if (blockedUntil != null) return { ok: false, reason: rateLimitedReason(blockedUntil, now) };
|
|
70
|
-
|
|
71
|
-
|
|
131
|
+
return prepareSample(account);
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
export async function sampleAccountUsage(account: Account): Promise<SampleOutcome> {
|
|
135
|
+
const ready = await readyToSample(account, Date.now());
|
|
136
|
+
return ready.ok ? runSample(account, ready) : ready;
|
|
72
137
|
}
|
|
73
138
|
|
|
74
139
|
const SAMPLE_BATCH = 3;
|
|
@@ -80,17 +145,16 @@ export async function sampleOldest(cfg: Config): Promise<void> {
|
|
|
80
145
|
const idx = loadAccounts(claudePool);
|
|
81
146
|
let dirty = false;
|
|
82
147
|
for (const a of idx.accounts) dirty = foldTee(a, thresholdBars(cfg)) || dirty;
|
|
83
|
-
const sampledAt = (a: Account) => Math.max(a.lastUsageAt ?? 0, a.lastProbeAt ?? 0);
|
|
84
148
|
const seats = seatCounts(paths.presenceDir);
|
|
85
149
|
const stale = idx.accounts
|
|
86
|
-
.filter((a) => a.needsReauth !== true &&
|
|
150
|
+
.filter((a) => a.needsReauth !== true && sampleDue(a, cfg, now))
|
|
87
151
|
.sort((a, b) => Number(seats.has(b.id)) - Number(seats.has(a.id)) || sampledAt(a) - sampledAt(b))
|
|
88
152
|
.slice(0, SAMPLE_BATCH);
|
|
89
153
|
if (stale.length === 0) {
|
|
90
154
|
if (dirty) saveAccounts(claudePool, idx);
|
|
91
155
|
return [];
|
|
92
156
|
}
|
|
93
|
-
const batch: { account: Account; token: string }[] = [];
|
|
157
|
+
const batch: { account: Account; prepared: { token: string; expiresAt: number } }[] = [];
|
|
94
158
|
for (const target of stale) {
|
|
95
159
|
target.lastProbeAt = now;
|
|
96
160
|
const prepared = await prepareSample(target);
|
|
@@ -101,15 +165,15 @@ export async function sampleOldest(cfg: Config): Promise<void> {
|
|
|
101
165
|
continue;
|
|
102
166
|
}
|
|
103
167
|
target.storeFails = 0;
|
|
104
|
-
if (usageBlockedUntil(target, now) == null) batch.push({ account: target,
|
|
168
|
+
if (usageBlockedUntil(target, now) == null) batch.push({ account: target, prepared });
|
|
105
169
|
}
|
|
106
170
|
saveAccounts(claudePool, idx);
|
|
107
171
|
return batch;
|
|
108
172
|
});
|
|
109
173
|
await Promise.all(
|
|
110
|
-
reserved.map(async ({ account,
|
|
174
|
+
reserved.map(async ({ account, prepared }) => {
|
|
111
175
|
const startedAt = Date.now();
|
|
112
|
-
const outcome = await runSample(account,
|
|
176
|
+
const outcome = await runSample(account, prepared);
|
|
113
177
|
await withLock(claudePool.lockFile, () => {
|
|
114
178
|
const idx = loadAccounts(claudePool);
|
|
115
179
|
const stored = idx.accounts.find((a) => a.id === account.id);
|