tokenmaxxing 1.92.0 → 1.93.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/package.json +1 -1
- package/src/lib/claudebin.ts +10 -7
- package/src/lib/proc.ts +13 -0
- package/src/lib/supervise.ts +4 -4
package/DESIGN.md
CHANGED
|
@@ -62,7 +62,7 @@ The Stop hook's stdin has no usage data, but the **statusLine does** (`rate_limi
|
|
|
62
62
|
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.
|
|
63
63
|
|
|
64
64
|
### 3.3 Move and depleted-pool pause (supervisor)
|
|
65
|
-
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 and the old seat's record carries no live `enforcedUntil` (`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; the compaction counts only when a `compact_boundary` row lands in the transcript, because a refused compaction still exits 0, 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). After a Stop move the previous turn had finished, so the prompt asks Claude to end the turn without restating it, and to relaunch any background Bash task, Monitor, or Workflow run that turn waited on, because the move ended it. After any other move the prompt asks Claude to continue the task, says the restart ended every background Bash task, Monitor, and Workflow run the session started, and asks Claude to relaunch what the task still needs; a SessionStart move is in that group because a prompt sent inside the marker poll window can already have started on the old seat. 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
|
|
65
|
+
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 and the old seat's record carries no live `enforcedUntil` (`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; the compaction counts only when a `compact_boundary` row lands in the transcript, because a refused compaction still exits 0, 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). After a Stop move the previous turn had finished, so the prompt asks Claude to end the turn without restating it, and to relaunch any background Bash task, Monitor, or Workflow run that turn waited on, because the move ended it. After any other move the prompt asks Claude to continue the task, says the restart ended every background Bash task, Monitor, and Workflow run the session started, and asks Claude to relaunch what the task still needs; a SessionStart move is in that group because a prompt sent inside the marker poll window can already have started on the old seat. 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 wrapper-chain abort, and a failed presence write also go to stdout as the same `informational`/`warning` line.
|
|
66
66
|
|
|
67
67
|
### 3.4 Placement (supervisor, under the pool lock)
|
|
68
68
|
1. Fold every account's tee into the index.
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "tokenmaxxing",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.93.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/lib/claudebin.ts
CHANGED
|
@@ -6,6 +6,7 @@ import { errorMessage } from "./log.ts";
|
|
|
6
6
|
import { paths } from "./paths.ts";
|
|
7
7
|
import { loadConfig, type BinKey } from "./state.ts";
|
|
8
8
|
import { writeFileAtomic } from "./atomic.ts";
|
|
9
|
+
import { ancestorPids } from "./proc.ts";
|
|
9
10
|
|
|
10
11
|
export const WRAP_DEPTH_ENV = "TOKENMAXXING_WRAP_DEPTH";
|
|
11
12
|
export const MAX_WRAP_DEPTH = 5;
|
|
@@ -17,22 +18,24 @@ export function wrapDepth(env: Record<string, string | undefined> = process.env)
|
|
|
17
18
|
return Number.isFinite(n) && n > 0 ? Math.floor(n) : 0;
|
|
18
19
|
}
|
|
19
20
|
|
|
20
|
-
|
|
21
|
+
const WRAP_RATE_MAX = 60;
|
|
21
22
|
export const WRAP_RATE_WINDOW_MS = 30_000;
|
|
22
|
-
const SpawnRateSchema = z.object({ entries: z.array(z.number()) });
|
|
23
|
+
const SpawnRateSchema = z.object({ entries: z.array(z.object({ at: z.number(), pid: z.number() })) });
|
|
23
24
|
|
|
24
|
-
export function
|
|
25
|
+
export function wrapperChainTripped(now: number): boolean {
|
|
25
26
|
const file = join(paths.home, "spawnrate.json");
|
|
26
|
-
let entries:
|
|
27
|
+
let entries: z.infer<typeof SpawnRateSchema>["entries"] = [];
|
|
27
28
|
try {
|
|
28
29
|
entries = SpawnRateSchema.parse(JSON.parse(readFileSync(file, "utf8"))).entries;
|
|
29
30
|
} catch { }
|
|
30
|
-
entries = entries.filter((
|
|
31
|
-
entries.push(now);
|
|
31
|
+
entries = entries.filter((e) => now - e.at < WRAP_RATE_WINDOW_MS);
|
|
32
|
+
entries.push({ at: now, pid: process.pid });
|
|
32
33
|
try {
|
|
33
34
|
writeFileAtomic(file, JSON.stringify({ entries }));
|
|
34
35
|
} catch { }
|
|
35
|
-
|
|
36
|
+
if (entries.length <= WRAP_RATE_MAX) return false;
|
|
37
|
+
const recent = new Set(entries.map((e) => e.pid));
|
|
38
|
+
return ancestorPids().filter((pid) => recent.has(pid)).length >= MAX_WRAP_DEPTH;
|
|
36
39
|
}
|
|
37
40
|
|
|
38
41
|
export function realpathOrNull(p: string): string | null {
|
package/src/lib/proc.ts
CHANGED
|
@@ -25,6 +25,19 @@ export function spawnedThroughShellsBy(ancestor: number): boolean {
|
|
|
25
25
|
return false;
|
|
26
26
|
}
|
|
27
27
|
|
|
28
|
+
export function ancestorPids(): number[] {
|
|
29
|
+
const res = Bun.spawnSync(["ps", "-A", "-o", "pid=", "-o", "ppid="], { env: { ...process.env, LC_ALL: "C" } });
|
|
30
|
+
if (res.exitCode !== 0) throw new Error(`ps -A exited ${res.exitCode}: ${res.stderr.toString().trim()}`);
|
|
31
|
+
const parent = new Map<number, number>();
|
|
32
|
+
for (const row of res.stdout.toString().split("\n")) {
|
|
33
|
+
const [pid, ppid] = row.split(" ").filter(Boolean).map(Number);
|
|
34
|
+
if (pid !== undefined && ppid !== undefined) parent.set(pid, ppid);
|
|
35
|
+
}
|
|
36
|
+
const out: number[] = [];
|
|
37
|
+
for (let pid = process.ppid; pid > 1; pid = parent.get(pid) ?? 0) out.push(pid);
|
|
38
|
+
return out;
|
|
39
|
+
}
|
|
40
|
+
|
|
28
41
|
export function pidStartTime(pid: number): string | null {
|
|
29
42
|
const res = Bun.spawnSync(["ps", "-p", String(pid), "-o", "lstart="], { env: { ...process.env, LC_ALL: "C" } });
|
|
30
43
|
if (res.exitCode !== 0) return null;
|
package/src/lib/supervise.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import type { Subprocess } from "bun";
|
|
2
|
-
import { LOOP_DIAGNOSIS, MAX_WRAP_DEPTH,
|
|
2
|
+
import { LOOP_DIAGNOSIS, MAX_WRAP_DEPTH, WRAP_RATE_WINDOW_MS, wrapDepth, wrapperChainTripped } from "./claudebin.ts";
|
|
3
3
|
import { errorMessage, log } from "./log.ts";
|
|
4
4
|
import { paths } from "./paths.ts";
|
|
5
5
|
import { writePresence } from "./presence.ts";
|
|
@@ -65,11 +65,11 @@ export function loopGuardTripped(product: WrappedProduct): boolean {
|
|
|
65
65
|
log(`${events}.loop_abort`, { depth });
|
|
66
66
|
return true;
|
|
67
67
|
}
|
|
68
|
-
if (
|
|
68
|
+
if (wrapperChainTripped(Date.now())) {
|
|
69
69
|
console.error(
|
|
70
|
-
`tokenmaxxing: ${LOOP_DIAGNOSIS} ${binary} (
|
|
70
|
+
`tokenmaxxing: ${LOOP_DIAGNOSIS} ${binary} (${MAX_WRAP_DEPTH} nested wrapper entries in ${WRAP_RATE_WINDOW_MS / 1000}s) - ${setting} in ${paths.configJson} does not launch the real ${binary} binary. Fix ${setting}, then run \`tokenmaxxing doctor\`.`,
|
|
71
71
|
);
|
|
72
|
-
log(`${events}.
|
|
72
|
+
log(`${events}.chain_abort`, { nested: MAX_WRAP_DEPTH });
|
|
73
73
|
return true;
|
|
74
74
|
}
|
|
75
75
|
return false;
|