tokenmaxxing 0.5.0 → 0.6.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 +1 -1
- package/README.md +4 -2
- package/package.json +1 -1
- package/src/cli/add.ts +1 -0
- package/src/cli/render.ts +13 -0
- package/src/cli/status.ts +19 -9
- package/src/cli/switch.ts +67 -23
- package/src/lib/claudebin.ts +8 -3
- package/src/lib/decide.ts +1 -0
- package/src/lib/picker.ts +26 -25
- package/src/lib/state.ts +10 -3
- package/src/lib/types.ts +4 -0
- package/src/lib/usage.ts +16 -6
- package/src/main.ts +1 -1
package/DESIGN.md
CHANGED
|
@@ -78,7 +78,7 @@ Each terminal ran the supervisor, so each has its own child `claude`, its own `-
|
|
|
78
78
|
## 5. Rotation policy
|
|
79
79
|
Trigger at `five_hour >= 95%` OR `seven_day >= 95%`, per org. "Exhausted" is a **timestamped state** (`resets_at`), not a flag - an account is a candidate again after it resets. Optional projected threshold (`95 − EMA(per-turn Δ%)`) so a single large turn can't blow past 100% before the next Stop hook.
|
|
80
80
|
|
|
81
|
-
**Model-aware trigger.** Claude subscriptions also enforce
|
|
81
|
+
**Model-aware trigger.** Claude subscriptions also enforce **per-model weekly caps** - currently only for Sonnet and Fable (there is no Opus-only quota), and Fable's tighter limit binds *before* the aggregate (e.g. 80% week-Fable at only 50% week-all-models). This cap isn't in statusLine stdin, so when the active model is in `policy.switchModels` we read it from `claude -p '/usage'` (free, 0 tokens, TTL-cached) and add `week(<activeModel>) >= threshold` to the trigger. A Fable session switches on the Fable cap; a Sonnet session rides the aggregate.
|
|
82
82
|
|
|
83
83
|
---
|
|
84
84
|
|
package/README.md
CHANGED
|
@@ -48,10 +48,12 @@ claude # use claude as always
|
|
|
48
48
|
Switching triggers at **95%** (configurable) on any of:
|
|
49
49
|
|
|
50
50
|
- **Session** (5-hour) or **week (all models)** - the aggregate windows, fed free/push-based by the statusLine.
|
|
51
|
-
- **Per-model weekly cap** - the capable
|
|
51
|
+
- **Per-model weekly cap** - the most capable model (Fable) has its own tighter weekly limit that binds *before* the aggregate (per-model caps currently exist only for Sonnet and Fable, and Sonnet's is generous). tokenmaxxing reads it from `claude -p '/usage'` (free, 0 tokens, TTL-cached) whenever the active model is one of `policy.switchModels`, so a Fable session switches on the Fable cap while a Sonnet session rides the aggregate.
|
|
52
52
|
|
|
53
53
|
The 5% headroom is deliberate: it's the budget to reach a clean turn boundary and respawn before the wall.
|
|
54
54
|
|
|
55
|
+
The **target** is chosen greedily off each account's cached windows: the usable account (session and week under threshold, or past their reset) whose weekly window **expires soonest** - unused weekly allowance is forfeited at the fixed per-account reset. Cached resets are absolute UTC epochs, so a stale snapshot still resolves correctly: a weekly reset that has passed extrapolates forward in 7-day steps, and a session window past its reset counts as empty. `tokenmaxxing switch` ranks the current account too and does nothing when it already wins, so it is idempotent - running it periodically converges on the right account.
|
|
56
|
+
|
|
55
57
|
## Configuration
|
|
56
58
|
|
|
57
59
|
`~/.config/tokenmaxxing/config.json` (every field optional):
|
|
@@ -61,7 +63,7 @@ The 5% headroom is deliberate: it's the budget to reach a clean turn boundary an
|
|
|
61
63
|
"threshold": 95,
|
|
62
64
|
"policy": {
|
|
63
65
|
"projectionMargin": 0,
|
|
64
|
-
"switchModels": ["fable"
|
|
66
|
+
"switchModels": ["fable"],
|
|
65
67
|
"usagePollTtlMs": 90000
|
|
66
68
|
}
|
|
67
69
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "tokenmaxxing",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.6.0",
|
|
4
4
|
"description": "Automatic Claude Code account switching: pool multiple accounts and hot-swap when quota fills, resuming your session on the fresh account.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"license": "MIT",
|
package/src/cli/add.ts
CHANGED
|
@@ -118,6 +118,7 @@ export async function cmdAdd(): Promise<number> {
|
|
|
118
118
|
needsReauth: false,
|
|
119
119
|
lastUsage: sampled ? { fiveHour: sampled.session, sevenDay: sampled.weekAll } : existing?.lastUsage,
|
|
120
120
|
lastPerModel: sampled && Object.keys(sampled.perModel).length > 0 ? sampled.perModel : existing?.lastPerModel,
|
|
121
|
+
lastUsageAt: sampled ? Date.now() : existing?.lastUsageAt,
|
|
121
122
|
};
|
|
122
123
|
if (existing) Object.assign(existing, fresh);
|
|
123
124
|
else idx.accounts.push(fresh);
|
package/src/cli/render.ts
CHANGED
|
@@ -40,6 +40,19 @@ export function fmtReset(epochMs: number | null | undefined, now = Date.now()):
|
|
|
40
40
|
return `resets in ${m}m`;
|
|
41
41
|
}
|
|
42
42
|
|
|
43
|
+
/** Age of a cached sample, largest unit only: "just now", "3m ago", "2h ago",
|
|
44
|
+
* "5d ago". */
|
|
45
|
+
export function fmtAgo(epochMs: number, now = Date.now()): string {
|
|
46
|
+
const dsec = Math.max(0, Math.round((now - epochMs) / 1000));
|
|
47
|
+
if (dsec < 60) return "just now";
|
|
48
|
+
const d = Math.floor(dsec / 86400);
|
|
49
|
+
const h = Math.floor((dsec % 86400) / 3600);
|
|
50
|
+
const m = Math.floor((dsec % 3600) / 60);
|
|
51
|
+
if (d > 0) return `${d}d ago`;
|
|
52
|
+
if (h > 0) return `${h}h ago`;
|
|
53
|
+
return `${m}m ago`;
|
|
54
|
+
}
|
|
55
|
+
|
|
43
56
|
/** Compact time-until-reset for the statusLine: the largest unit only ("6d",
|
|
44
57
|
* "2h", "45m"), floored to "1m" so a live window never reads as zero, and ""
|
|
45
58
|
* once the reset has passed (the window is simply empty again). Non-empty
|
package/src/cli/status.ts
CHANGED
|
@@ -10,8 +10,8 @@ import { readOAuthAccount } from "../lib/claudejson.ts";
|
|
|
10
10
|
import { probeActiveUsage, probeParkedUsage, type SampleOutcome } from "../lib/sample.ts";
|
|
11
11
|
import { withLock } from "../lib/lock.ts";
|
|
12
12
|
import { paths } from "../lib/paths.ts";
|
|
13
|
-
import { isExhausted } from "../lib/picker.ts";
|
|
14
|
-
import { bar, c, fmtReset } from "./render.ts";
|
|
13
|
+
import { isExhausted, nextWeeklyReset } from "../lib/picker.ts";
|
|
14
|
+
import { bar, c, fmtAgo, fmtReset } from "./render.ts";
|
|
15
15
|
import type { FullUsage } from "../lib/usage.ts";
|
|
16
16
|
import type { UsageWindow } from "../lib/types.ts";
|
|
17
17
|
|
|
@@ -58,6 +58,9 @@ export async function cmdStatus(): Promise<number> {
|
|
|
58
58
|
if (!outcome.ok) return;
|
|
59
59
|
a.lastUsage = { fiveHour: outcome.usage.session, sevenDay: outcome.usage.weekAll };
|
|
60
60
|
if (Object.keys(outcome.usage.perModel).length > 0) a.lastPerModel = outcome.usage.perModel;
|
|
61
|
+
// stamp when the figures were actually measured: the statusLine tee's
|
|
62
|
+
// own write time for the push-fed active account, else the probe time.
|
|
63
|
+
a.lastUsageAt = fromStatusLine && live ? live.ts : Date.now();
|
|
61
64
|
}),
|
|
62
65
|
);
|
|
63
66
|
saveAccounts(idx);
|
|
@@ -66,8 +69,15 @@ export async function cmdStatus(): Promise<number> {
|
|
|
66
69
|
console.log(c.dim(`threshold ${cfg.threshold}% · ${idx.accounts.length} account(s)`));
|
|
67
70
|
console.log();
|
|
68
71
|
|
|
69
|
-
|
|
70
|
-
|
|
72
|
+
// A window whose cached reset has passed is empty again; weekly windows recur
|
|
73
|
+
// on a fixed per-account anchor, so a stale weekly reset extrapolates forward.
|
|
74
|
+
// Fresh samples pass through unchanged (their resets are in the future).
|
|
75
|
+
const row = (name: string, w: UsageWindow, weekly: boolean) => {
|
|
76
|
+
const passed = w.resetsAt != null && w.resetsAt <= now;
|
|
77
|
+
const pct = passed ? 0 : w.usedPercentage;
|
|
78
|
+
const resetsAt = weekly ? nextWeeklyReset(w.resetsAt, now) : passed ? null : w.resetsAt;
|
|
79
|
+
console.log(` ${name.padEnd(5)} ${bar(pct)} ${c.dim(fmtReset(resetsAt, now))}`);
|
|
80
|
+
};
|
|
71
81
|
|
|
72
82
|
for (const a of idx.accounts) {
|
|
73
83
|
const active = a.accountUuid === idx.activeAccountUuid;
|
|
@@ -87,13 +97,13 @@ export async function cmdStatus(): Promise<number> {
|
|
|
87
97
|
|
|
88
98
|
console.log(`${marker} ${c.bold(a.label || a.email)} ${badges.join(" ")}`);
|
|
89
99
|
if (aggregate) {
|
|
90
|
-
row("5h", aggregate.fiveHour);
|
|
91
|
-
row("week", aggregate.sevenDay);
|
|
100
|
+
row("5h", aggregate.fiveHour, false);
|
|
101
|
+
row("week", aggregate.sevenDay, true);
|
|
92
102
|
}
|
|
93
|
-
if (perModel) for (const [name, w] of Object.entries(perModel)) row(name, w);
|
|
103
|
+
if (perModel) for (const [name, w] of Object.entries(perModel)) row(name, w, true);
|
|
94
104
|
if (failed && outcome && !outcome.ok) {
|
|
95
|
-
const
|
|
96
|
-
console.log(` ${c.yellow(
|
|
105
|
+
const cached = aggregate || perModel ? `cached${a.lastUsageAt != null ? ` ${fmtAgo(a.lastUsageAt, now)}` : ""} · ` : "";
|
|
106
|
+
console.log(` ${c.yellow(`${cached}live sample failed`)}: ${c.dim(outcome.reason)}`);
|
|
97
107
|
}
|
|
98
108
|
console.log();
|
|
99
109
|
}
|
package/src/cli/switch.ts
CHANGED
|
@@ -1,16 +1,28 @@
|
|
|
1
|
-
// `tokenmaxxing switch [selector]
|
|
2
|
-
// No selector →
|
|
3
|
-
//
|
|
4
|
-
//
|
|
1
|
+
// `tokenmaxxing switch [selector]`.
|
|
2
|
+
// No selector → greedy: rank EVERY account (current included) by soonest weekly
|
|
3
|
+
// expiry among those with session/week under threshold, off the cached windows.
|
|
4
|
+
// When the current account already wins (or ties - swapping between equals buys
|
|
5
|
+
// nothing), do nothing: the command is idempotent, so running it periodically
|
|
6
|
+
// converges on the right account. With a selector → switch to that one. Runs
|
|
7
|
+
// under the flock. When everything is depleted it stays on / switches to
|
|
8
|
+
// whichever account recovers soonest.
|
|
9
|
+
//
|
|
10
|
+
// The active LABEL can drift from the live login (manual /login is the
|
|
11
|
+
// surviving drift source). A no-op would freeze that drift forever, so when
|
|
12
|
+
// ~/.claude.json names a different account than accounts.json we swap for real
|
|
13
|
+
// instead of trusting the label - performSwap resolves the live credential's
|
|
14
|
+
// true owner, harvesting the drifted login correctly.
|
|
5
15
|
|
|
6
16
|
import { withLock } from "../lib/lock.ts";
|
|
7
17
|
import { paths } from "../lib/paths.ts";
|
|
8
18
|
import { loadAccounts, loadConfig } from "../lib/state.ts";
|
|
19
|
+
import { readOAuthAccount } from "../lib/claudejson.ts";
|
|
9
20
|
import { performSwap, chooseAndSwap } from "../lib/swap.ts";
|
|
10
|
-
import { pickEarliestReset } from "../lib/picker.ts";
|
|
21
|
+
import { isExhausted, pickBest, pickEarliestReset, swapPreference, weeklyExpiry, type PickCtx } from "../lib/picker.ts";
|
|
11
22
|
import { InvalidGrantError } from "../lib/oauth.ts";
|
|
12
23
|
import { findAccount } from "./rename.ts";
|
|
13
24
|
import { c, fmtReset } from "./render.ts";
|
|
25
|
+
import type { Account } from "../lib/types.ts";
|
|
14
26
|
|
|
15
27
|
export async function cmdSwitch(selector?: string): Promise<number> {
|
|
16
28
|
const idx0 = loadAccounts();
|
|
@@ -23,12 +35,10 @@ export async function cmdSwitch(selector?: string): Promise<number> {
|
|
|
23
35
|
|
|
24
36
|
return withLock(paths.lockFile, async () => {
|
|
25
37
|
const idx = loadAccounts();
|
|
38
|
+
const claimed = readOAuthAccount()?.accountUuid ?? null;
|
|
39
|
+
const drifted = claimed != null && claimed !== idx.activeAccountUuid;
|
|
26
40
|
|
|
27
|
-
|
|
28
|
-
const target = findAccount(idx.accounts, selector);
|
|
29
|
-
if (!target) { console.error(c.red(`no account matches "${selector}"`)); return 1; }
|
|
30
|
-
if (target.accountUuid === idx.activeAccountUuid) { console.log(`already on ${c.bold(target.label)}`); return 0; }
|
|
31
|
-
if (target.needsReauth) { console.error(c.red(`${target.label} needs re-auth - \`tokenmaxxing add\``)); return 1; }
|
|
41
|
+
const swapTo = async (target: Account): Promise<number> => {
|
|
32
42
|
try {
|
|
33
43
|
await performSwap(target);
|
|
34
44
|
} catch (e) {
|
|
@@ -37,25 +47,59 @@ export async function cmdSwitch(selector?: string): Promise<number> {
|
|
|
37
47
|
}
|
|
38
48
|
console.log(`${c.green("↻")} switched to ${c.bold(target.label)}`);
|
|
39
49
|
return 0;
|
|
50
|
+
};
|
|
51
|
+
|
|
52
|
+
if (selector) {
|
|
53
|
+
const target = findAccount(idx.accounts, selector);
|
|
54
|
+
if (!target) { console.error(c.red(`no account matches "${selector}"`)); return 1; }
|
|
55
|
+
if (target.accountUuid === idx.activeAccountUuid && !drifted) { console.log(`already on ${c.bold(target.label)}`); return 0; }
|
|
56
|
+
if (target.needsReauth) { console.error(c.red(`${target.label} needs re-auth - \`tokenmaxxing add\``)); return 1; }
|
|
57
|
+
return swapTo(target);
|
|
40
58
|
}
|
|
41
59
|
|
|
42
|
-
// auto:
|
|
43
|
-
const
|
|
44
|
-
|
|
45
|
-
|
|
60
|
+
// auto: greedy over everyone, current included - a no-op when current wins.
|
|
61
|
+
const everyone: PickCtx = { now, threshold: cfg.threshold, currentAccountUuid: null };
|
|
62
|
+
const active = idx.accounts.find((a) => a.accountUuid === idx.activeAccountUuid) ?? null;
|
|
63
|
+
const best = pickBest(idx.accounts, everyone);
|
|
64
|
+
const currentWins =
|
|
65
|
+
best != null && active != null && !active.needsReauth && !isExhausted(active, everyone) &&
|
|
66
|
+
(best.accountUuid === active.accountUuid || swapPreference(now).every((k) => k(active) === k(best)));
|
|
67
|
+
if (currentWins) {
|
|
68
|
+
if (drifted) return swapTo(active);
|
|
69
|
+
const expiry = weeklyExpiry(active, now);
|
|
70
|
+
const why = Number.isFinite(expiry) ? ` (weekly ${fmtReset(expiry, now)})` : "";
|
|
71
|
+
console.log(`already on the best account: ${c.bold(active.label)}${why}`);
|
|
46
72
|
return 0;
|
|
47
73
|
}
|
|
74
|
+
if (best) {
|
|
75
|
+
const landed = await chooseAndSwap({ now, threshold: cfg.threshold });
|
|
76
|
+
if (landed) {
|
|
77
|
+
console.log(`${c.green("↻")} switched to ${c.bold(landed.label)}`);
|
|
78
|
+
return 0;
|
|
79
|
+
}
|
|
80
|
+
}
|
|
48
81
|
|
|
49
|
-
// everything is depleted
|
|
50
|
-
|
|
82
|
+
// No usable target swapped in: everything is depleted, or the remaining
|
|
83
|
+
// candidates' refresh tokens just died (chooseAndSwap marks needs-reauth,
|
|
84
|
+
// hence the reload). Stay on / switch to whichever recovers soonest.
|
|
85
|
+
const fresh = loadAccounts();
|
|
86
|
+
const earliest = pickEarliestReset(fresh.accounts, everyone);
|
|
51
87
|
if (!earliest) { console.error(c.yellow("no switchable account (all need re-auth?)")); return 1; }
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
88
|
+
const reauth = fresh.accounts.filter((a) => a.needsReauth).map((a) => a.label);
|
|
89
|
+
const reauthNote = reauth.length ? ` - re-auth needed: ${reauth.join(", ")}` : "";
|
|
90
|
+
if (earliest.account.accountUuid === fresh.activeAccountUuid && !drifted) {
|
|
91
|
+
// availableAt in the past means the current account is fine and the
|
|
92
|
+
// others are simply unusable - do not claim a limit that is not there.
|
|
93
|
+
const msg = earliest.availableAt <= now
|
|
94
|
+
? `staying on ${c.bold(earliest.account.label)} - no usable switch target${reauthNote}`
|
|
95
|
+
: `all accounts at limit - staying on ${c.bold(earliest.account.label)} (${fmtReset(earliest.availableAt, now)})${reauthNote}`;
|
|
96
|
+
console.log(c.yellow(msg));
|
|
97
|
+
return 0;
|
|
98
|
+
}
|
|
99
|
+
const code = await swapTo(earliest.account);
|
|
100
|
+
if (code === 0 && earliest.availableAt > now) {
|
|
101
|
+
console.log(c.yellow(`all accounts at limit - ${c.bold(earliest.account.label)} recovers soonest (${fmtReset(earliest.availableAt, now)})${reauthNote}`));
|
|
57
102
|
}
|
|
58
|
-
|
|
59
|
-
return 0;
|
|
103
|
+
return code;
|
|
60
104
|
});
|
|
61
105
|
}
|
package/src/lib/claudebin.ts
CHANGED
|
@@ -7,9 +7,14 @@ import { loadConfig } from "./state.ts";
|
|
|
7
7
|
|
|
8
8
|
export function resolveRealClaude(): string {
|
|
9
9
|
const cfg = loadConfig();
|
|
10
|
-
if (cfg.claudeBin
|
|
11
|
-
|
|
12
|
-
|
|
10
|
+
if (cfg.claudeBin) {
|
|
11
|
+
if (existsSync(cfg.claudeBin)) return cfg.claudeBin;
|
|
12
|
+
// A configured-but-vanished binary must not silently degrade to the PATH
|
|
13
|
+
// scan: under a relocated TOKENMAXXING_HOME the scan's binDir guard misses
|
|
14
|
+
// the installed wrapper, which then recurses through the supervisor
|
|
15
|
+
// (observed 2026-07-12 as a forever-hung `/usage` probe).
|
|
16
|
+
throw new Error(`configured claudeBin does not exist: ${cfg.claudeBin} - fix config.json`);
|
|
17
|
+
}
|
|
13
18
|
for (const d of (process.env.PATH ?? "").split(":")) {
|
|
14
19
|
if (!d || d === paths.binDir) continue;
|
|
15
20
|
const cand = join(d, "claude");
|
package/src/lib/decide.ts
CHANGED
|
@@ -116,6 +116,7 @@ export async function evaluateAndMaybeSwap(now = Date.now()): Promise<SwapDecisi
|
|
|
116
116
|
const active = idx.accounts.find((a) => a.accountUuid === idx.activeAccountUuid);
|
|
117
117
|
if (active) {
|
|
118
118
|
active.lastUsage = { fiveHour: u2.fiveHour, sevenDay: u2.sevenDay };
|
|
119
|
+
active.lastUsageAt = u2.ts;
|
|
119
120
|
// Snapshot per-model caps too, so they still show after we switch away.
|
|
120
121
|
if (mu2 && mu2.org === org2) active.lastPerModel = mu2.perModel;
|
|
121
122
|
saveAccounts(idx);
|
package/src/lib/picker.ts
CHANGED
|
@@ -1,10 +1,11 @@
|
|
|
1
|
-
// Choose the
|
|
2
|
-
//
|
|
3
|
-
//
|
|
4
|
-
//
|
|
5
|
-
//
|
|
6
|
-
//
|
|
7
|
-
//
|
|
1
|
+
// Choose the account to switch TO. Greedy policy: among usable accounts (no
|
|
2
|
+
// reauth, no window >= threshold that hasn't reset yet), take the one whose
|
|
3
|
+
// weekly window expires soonest - weekly limits reset at a fixed per-account
|
|
4
|
+
// time and unused allowance is forfeited at reset, so quota nearest its reset
|
|
5
|
+
// is use-it-or-lose-it and should be drained first. Runs entirely off each
|
|
6
|
+
// account's cached windows (absolute UTC epochs, so a stale snapshot still
|
|
7
|
+
// resolves to the correct upcoming reset), which makes the pick deterministic
|
|
8
|
+
// and idempotent: re-running lands on the same account.
|
|
8
9
|
|
|
9
10
|
import { minBy, sortBy } from "es-toolkit";
|
|
10
11
|
import { z } from "zod";
|
|
@@ -13,6 +14,7 @@ import { AccountSchema, type Account } from "./types.ts";
|
|
|
13
14
|
const PickCtxSchema = z.object({
|
|
14
15
|
now: z.number(),
|
|
15
16
|
threshold: z.number(),
|
|
17
|
+
/** account to exclude (hooks switch AWAY from it); null ranks everyone. */
|
|
16
18
|
currentAccountUuid: z.string().nullable(),
|
|
17
19
|
});
|
|
18
20
|
export type PickCtx = z.infer<typeof PickCtxSchema>;
|
|
@@ -28,34 +30,33 @@ export function isExhausted(a: Account, ctx: PickCtx): boolean {
|
|
|
28
30
|
|
|
29
31
|
const WEEK_MS = 7 * 24 * 60 * 60 * 1000;
|
|
30
32
|
|
|
31
|
-
/**
|
|
32
|
-
*
|
|
33
|
-
*
|
|
33
|
+
/** Next occurrence of a weekly reset. The weekly reset is a fixed per-account
|
|
34
|
+
* anchor, so a cached (past) resetsAt extrapolates forward in 7-day steps -
|
|
35
|
+
* an old snapshot still yields the correct upcoming reset. */
|
|
36
|
+
export function nextWeeklyReset(resetsAt: number | null, now: number): number | null {
|
|
37
|
+
if (resetsAt == null || resetsAt > now) return resetsAt;
|
|
38
|
+
return resetsAt + (Math.floor((now - resetsAt) / WEEK_MS) + 1) * WEEK_MS;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** Epoch ms when the account's weekly quota is next forfeited; an account with
|
|
42
|
+
* no sampled reset sorts last. */
|
|
34
43
|
export function weeklyExpiry(a: Account, now: number): number {
|
|
35
|
-
|
|
36
|
-
if (r == null) return Number.POSITIVE_INFINITY;
|
|
37
|
-
if (r > now) return r;
|
|
38
|
-
return r + (Math.floor((now - r) / WEEK_MS) + 1) * WEEK_MS;
|
|
44
|
+
return nextWeeklyReset(a.lastUsage?.sevenDay.resetsAt ?? null, now) ?? Number.POSITIVE_INFINITY;
|
|
39
45
|
}
|
|
40
46
|
|
|
41
|
-
/** The switch preference: soonest weekly expiry first
|
|
42
|
-
* usage
|
|
43
|
-
*
|
|
47
|
+
/** The switch preference: soonest weekly expiry first, tiebreak lowest 7-day
|
|
48
|
+
* usage. Shared with the statusLine pool ordering so the display order IS the
|
|
49
|
+
* swap order. */
|
|
44
50
|
export const swapPreference = (now: number) => [
|
|
45
51
|
(a: Account) => weeklyExpiry(a, now),
|
|
46
52
|
(a: Account) => a.lastUsage?.sevenDay.usedPercentage ?? 0,
|
|
47
|
-
(a: Account) => a.lastUsage?.fiveHour.resetsAt ?? Number.POSITIVE_INFINITY,
|
|
48
53
|
];
|
|
49
54
|
|
|
50
55
|
export function pickBest(accounts: Account[], ctx: PickCtx): Account | null {
|
|
51
|
-
const
|
|
52
|
-
(a) =>
|
|
53
|
-
a.accountUuid !== ctx.currentAccountUuid &&
|
|
54
|
-
!a.needsReauth &&
|
|
55
|
-
!isExhausted(a, ctx),
|
|
56
|
+
const usable = accounts.filter(
|
|
57
|
+
(a) => a.accountUuid !== ctx.currentAccountUuid && !a.needsReauth && !isExhausted(a, ctx),
|
|
56
58
|
);
|
|
57
|
-
|
|
58
|
-
return sortBy(candidates, swapPreference(ctx.now))[0]!;
|
|
59
|
+
return sortBy(usable, swapPreference(ctx.now))[0] ?? null;
|
|
59
60
|
}
|
|
60
61
|
|
|
61
62
|
/** When an account becomes usable again: the latest reset among its over-threshold
|
package/src/lib/state.ts
CHANGED
|
@@ -22,7 +22,9 @@ import {
|
|
|
22
22
|
const DEFAULT_CONFIG: Config = {
|
|
23
23
|
threshold: 95,
|
|
24
24
|
claudeBin: "",
|
|
25
|
-
|
|
25
|
+
// per-model weekly caps exist only for Sonnet and Fable (no Opus-only quota,
|
|
26
|
+
// per the user 2026-07-12), and only Fable's is worth switching on.
|
|
27
|
+
policy: { projectionMargin: 0, switchModels: ["fable"], usagePollTtlMs: 90_000, maxWaitMs: 3_600_000 },
|
|
26
28
|
};
|
|
27
29
|
|
|
28
30
|
/** On-disk shape (all optional); validated via Zod, merged over defaults. */
|
|
@@ -124,10 +126,15 @@ export function saveLastSwapAt(ts: number): void {
|
|
|
124
126
|
writeFileAtomic(paths.lastSwapJson, JSON.stringify(LastSwapSchema.parse({ ts })));
|
|
125
127
|
}
|
|
126
128
|
|
|
127
|
-
/**
|
|
129
|
+
/** An alive feed re-proving unchanged figures still refreshes `ts` this often,
|
|
130
|
+
* so cache-age displays stay honest without a write+fsync per tick. */
|
|
131
|
+
const USAGE_TS_REFRESH_MS = 10 * 60_000;
|
|
132
|
+
|
|
133
|
+
/** Write-on-change: skip the write (and its fsync) when only `ts` would differ,
|
|
134
|
+
* unless the stored `ts` has aged past the refresh window. */
|
|
128
135
|
export function writeUsage(next: UsageState): boolean {
|
|
129
136
|
const prev = loadUsage();
|
|
130
|
-
if (prev && isEqual({ ...prev, ts: 0 }, { ...next, ts: 0 })) return false;
|
|
137
|
+
if (prev && isEqual({ ...prev, ts: 0 }, { ...next, ts: 0 }) && next.ts - prev.ts < USAGE_TS_REFRESH_MS) return false;
|
|
131
138
|
writeFileAtomic(paths.usageJson, JSON.stringify(next));
|
|
132
139
|
return true;
|
|
133
140
|
}
|
package/src/lib/types.ts
CHANGED
|
@@ -84,6 +84,10 @@ export const AccountSchema = z.object({
|
|
|
84
84
|
addedAt: z.string(),
|
|
85
85
|
lastUsage: UsageWindowsSchema.optional(),
|
|
86
86
|
lastPerModel: z.record(z.string(), UsageWindowSchema).optional(),
|
|
87
|
+
/** epoch ms of the sample behind lastUsage/lastPerModel. Their resetsAt
|
|
88
|
+
* values are absolute epochs (UTC-anchored), so even an old snapshot still
|
|
89
|
+
* resolves to correct resets - display it as a dated cache, never discard. */
|
|
90
|
+
lastUsageAt: z.number().optional(),
|
|
87
91
|
needsReauth: z.boolean().optional(),
|
|
88
92
|
subscriptionType: z.string().optional(),
|
|
89
93
|
});
|
package/src/lib/usage.ts
CHANGED
|
@@ -195,6 +195,11 @@ const CRED_ENV_OVERRIDES = [
|
|
|
195
195
|
/** One `claude -p '/usage'` invocation → parsed usage, or null if it produced no
|
|
196
196
|
* limit lines (claude prints only a local-stats footer when its own usage fetch
|
|
197
197
|
* errors/throttles) or failed to run. */
|
|
198
|
+
/** A probe child that wedges (auth prompt, dead endpoint) must never block the
|
|
199
|
+
* Stop/SessionStart hooks or the status flock forever; a healthy `/usage`
|
|
200
|
+
* answers in seconds. */
|
|
201
|
+
const PROBE_KILL_MS = 60_000;
|
|
202
|
+
|
|
198
203
|
async function probeUsageOnce(env: Record<string, string>, now: number): Promise<FullUsage | null> {
|
|
199
204
|
let out: string;
|
|
200
205
|
try {
|
|
@@ -203,12 +208,17 @@ async function probeUsageOnce(env: Record<string, string>, now: number): Promise
|
|
|
203
208
|
stdout: "pipe",
|
|
204
209
|
stderr: "pipe",
|
|
205
210
|
});
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
211
|
+
const killer = setTimeout(() => p.kill(), PROBE_KILL_MS);
|
|
212
|
+
try {
|
|
213
|
+
out = await new Response(p.stdout).text();
|
|
214
|
+
const errText = await new Response(p.stderr).text();
|
|
215
|
+
await p.exited;
|
|
216
|
+
if (p.exitCode !== 0) {
|
|
217
|
+
log("usage.probe_failed", { exit: p.exitCode ?? "signal", stderr: errText.trim().slice(0, 200) });
|
|
218
|
+
return null;
|
|
219
|
+
}
|
|
220
|
+
} finally {
|
|
221
|
+
clearTimeout(killer);
|
|
212
222
|
}
|
|
213
223
|
} catch (e) {
|
|
214
224
|
log("usage.probe_failed", { err: String((e as Error).message ?? e) });
|
package/src/main.ts
CHANGED
|
@@ -24,7 +24,7 @@ function printHelp(): void {
|
|
|
24
24
|
console.log(`${c.bold("tokenmaxxing")} - automatic Claude Code account switching
|
|
25
25
|
|
|
26
26
|
${c.cyan("tokenmaxxing")} show the pool with usage bars (alias of ${c.cyan("status")})
|
|
27
|
-
${c.cyan("tokenmaxxing switch")} [sel] switch
|
|
27
|
+
${c.cyan("tokenmaxxing switch")} [sel] switch to the best (or a specific) account; no-op when already on it
|
|
28
28
|
${c.cyan("tokenmaxxing check")} evaluate once, switch if over threshold (run by the periodic timer)
|
|
29
29
|
${c.cyan("tokenmaxxing init")} import the current account + install supervisor & hooks
|
|
30
30
|
${c.cyan("tokenmaxxing add")} register an additional account (isolated login)
|