tokenmaxxing 1.121.0 → 1.123.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
@@ -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 wrapper-chain abort, and a failed presence write also go to stdout as the same `informational`/`warning` line.
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 conversation has no prior turn (a `/clear` with no turn since, or a move before the first turn), so it starts with no compaction and no first prompt, and in a stream-json session the relay replays the harness lines the killed child received: `user` lines and the `initialize` and session-state control requests in `REPLAYED_REQUESTS`; every other control request gets an error `control_response` on stdout, because a repeat could run its effect twice, and the `control_response` answers to the killed child's own requests are dropped. A first launch with `--resume <id>` takes the same path when the supervisor holds `sessions/<id>.json` for that id and no project directory holds its transcript. 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.121.0",
3
+ "version": "1.123.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",
@@ -19,7 +19,7 @@ import { saveTermios } from "../lib/tty.ts";
19
19
  import { liveSessionId, loadSessionFlags, pruneStaleSessions, saveSessionFlags, writeRespawnMarker } from "../lib/sessions.ts";
20
20
  import { loadAccounts, loadConfig, readJsonFile, releaseWaitClaim, writeUsage } from "../lib/state.ts";
21
21
  import { gatedFamilies, modelFromFlag, parseStreamLine, scrubCredEnv } from "../lib/usage.ts";
22
- import { RespawnMarkerSchema, type Account, type Config, type ModelInfo, type UsageWindows } from "../lib/types.ts";
22
+ import { JsonTextSchema, RespawnMarkerSchema, type Account, type Config, type ModelInfo, type UsageWindows } from "../lib/types.ts";
23
23
  import { errorMessage, log } from "../lib/log.ts";
24
24
 
25
25
  const SUBCOMMANDS = new Set([
@@ -160,14 +160,29 @@ export function stripPositionals(argv: string[]): string[] {
160
160
  return out;
161
161
  }
162
162
 
163
+ const PROJECT_DIR_MAX = 200;
164
+
163
165
  function projectDirForCwd(): string {
164
- return join(paths.claudeDir, "projects", process.cwd().replace(/[^a-zA-Z0-9]/g, "-"));
166
+ const cwd = process.cwd();
167
+ const name = cwd.replace(/[^a-zA-Z0-9]/g, "-");
168
+ if (name.length <= PROJECT_DIR_MAX) return join(paths.claudeDir, "projects", name);
169
+ let hash = 0;
170
+ for (let i = 0; i < cwd.length; i++) hash = ((hash << 5) - hash + cwd.charCodeAt(i)) | 0;
171
+ return join(paths.claudeDir, "projects", `${name.slice(0, PROJECT_DIR_MAX)}-${Math.abs(hash).toString(36)}`);
165
172
  }
166
173
 
167
174
  function transcriptPath(sessionId: string): string {
168
175
  return join(projectDirForCwd(), `${sessionId}.jsonl`);
169
176
  }
170
177
 
178
+ function findTranscript(sessionId: string): string | null {
179
+ const own = transcriptPath(sessionId);
180
+ if (existsSync(own)) return own;
181
+ const root = join(paths.claudeDir, "projects");
182
+ if (!existsSync(root)) return null;
183
+ return readdirSync(root).map((dir) => join(root, dir, `${sessionId}.jsonl`)).find((p) => existsSync(p)) ?? null;
184
+ }
185
+
171
186
  function latestSessionForCwd(): string | null {
172
187
  const projDir = projectDirForCwd();
173
188
  if (!existsSync(projDir)) return null;
@@ -316,9 +331,23 @@ function relayStdout(source: ReadableStream<Uint8Array>, onLine: (line: string)
316
331
  };
317
332
  }
318
333
 
334
+ const REPLAYED_REQUESTS = new Set(["initialize", "set_max_thinking_tokens", "set_model", "set_permission_mode"]);
335
+
336
+ const RelayLineSchema = z.discriminatedUnion("type", [
337
+ z.looseObject({ type: z.literal("control_response") }),
338
+ z.looseObject({ type: z.literal("control_request"), request_id: z.string(), request: z.looseObject({ subtype: z.string() }) }),
339
+ ]);
340
+
341
+ function controlErrorLine(requestId: string): string {
342
+ return `${JSON.stringify({ type: "control_response", response: { subtype: "error", request_id: requestId, error: "tokenmaxxing restarted Claude Code for an account move, and this request may or may not have run." } })}\n`;
343
+ }
344
+
319
345
  class StdinRelay {
320
346
  private sink: FileSink | null = null;
321
347
  private queue: string[] = [];
348
+ private replayable: string[] = [];
349
+ private dropped: string[] = [];
350
+ private pendingTranscript: string | null = null;
322
351
  private ended = false;
323
352
 
324
353
  constructor() {
@@ -330,8 +359,11 @@ class StdinRelay {
330
359
  });
331
360
  }
332
361
 
333
- attach(sink: FileSink, first: string | null): void {
362
+ attach(sink: FileSink, first: string | null, pendingTranscript: string | null): void {
334
363
  this.sink = sink;
364
+ this.replayable = [];
365
+ this.dropped = [];
366
+ this.pendingTranscript = pendingTranscript;
335
367
  const lines = first === null ? this.queue : [first, ...this.queue];
336
368
  this.queue = [];
337
369
  for (const line of lines) this.forward(line);
@@ -342,6 +374,28 @@ class StdinRelay {
342
374
  this.sink = null;
343
375
  }
344
376
 
377
+ replay(): string[] {
378
+ const dropped = this.dropped;
379
+ this.queue = [...this.replayable, ...this.queue];
380
+ this.replayable = [];
381
+ this.dropped = [];
382
+ return dropped;
383
+ }
384
+
385
+ private keep(line: string): void {
386
+ if (this.pendingTranscript === null) return;
387
+ if (existsSync(this.pendingTranscript)) {
388
+ this.pendingTranscript = null;
389
+ this.replayable = [];
390
+ this.dropped = [];
391
+ return;
392
+ }
393
+ const parsed = RelayLineSchema.safeParse(JsonTextSchema.safeParse(line).data);
394
+ if (!parsed.success) this.replayable.push(line);
395
+ else if (parsed.data.type === "control_request" && REPLAYED_REQUESTS.has(parsed.data.request.subtype)) this.replayable.push(line);
396
+ else if (parsed.data.type === "control_request") this.dropped.push(parsed.data.request_id);
397
+ }
398
+
345
399
  private async pump(): Promise<void> {
346
400
  for await (const line of readLines(Bun.stdin.stream())) this.forward(`${line}\n`);
347
401
  }
@@ -351,6 +405,7 @@ class StdinRelay {
351
405
  try {
352
406
  this.sink.write(line);
353
407
  this.sink.flush();
408
+ this.keep(line);
354
409
  return;
355
410
  } catch (e) {
356
411
  log("supervisor.relay_write_failed", { err: errorMessage(e) });
@@ -449,15 +504,15 @@ export async function runSupervisor(argv: string[]): Promise<number> {
449
504
  }
450
505
  claimSid = sid;
451
506
 
452
- if (resuming && base.length === 0) {
453
- const persisted = loadSessionFlags(sid);
454
- if (persisted) base = stripPositionals(persisted);
455
- }
507
+ const persisted = resuming ? loadSessionFlags(sid) : null;
508
+ if (persisted && base.length === 0) base = stripPositionals(persisted);
509
+ const resume = resuming && (persisted === null || findTranscript(sid) !== null);
456
510
  const persistable = stripPositionals(base);
457
511
  saveSessionFlags(sid, persistable, process.cwd());
458
512
  pruneStaleSessions(Date.now());
459
513
 
460
- let launchArgs = resuming ? ["--resume", sid, ...base] : ["--session-id", sid, ...base];
514
+ let launchArgs = resume ? ["--resume", sid, ...base] : ["--session-id", sid, ...base];
515
+ let pendingTranscript = resume ? null : transcriptPath(sid);
461
516
 
462
517
  mkdirSync(paths.respawnDir, { recursive: true });
463
518
  const marker = join(paths.respawnDir, sid);
@@ -506,7 +561,7 @@ export async function runSupervisor(argv: string[]): Promise<number> {
506
561
  });
507
562
  child = spawned;
508
563
  const drain = tee !== null && spawned.stdout instanceof ReadableStream ? relayStdout(spawned.stdout, tee) : null;
509
- if (relay !== null) relay.attach(spawned.stdin!, firstLine);
564
+ if (relay !== null) relay.attach(spawned.stdin!, firstLine, pendingTranscript);
510
565
  firstLine = null;
511
566
  if (picked) {
512
567
  await recordPresenceOrStop({
@@ -559,8 +614,11 @@ export async function runSupervisor(argv: string[]): Promise<number> {
559
614
  const accounts = loadAccounts(claudePool).accounts;
560
615
  const label = accounts.find((a) => a.id === m.accountId)?.label ?? m.accountId.slice(0, 8);
561
616
  const walledUntil = accounts.find((a) => a.id === seat?.id)?.enforcedUntil ?? 0;
562
- const transcript = transcriptPath(m.sessionId);
563
- const resumable = existsSync(transcript);
617
+ const transcript = findTranscript(m.sessionId);
618
+ const resumable = transcript !== null;
619
+ if (!resumable && relay !== null) {
620
+ for (const id of relay.replay()) process.stdout.write(controlErrorLine(id));
621
+ }
564
622
  let compacted = false;
565
623
  if (m.compact && seat && resumable && walledUntil > Date.now()) {
566
624
  log("supervisor.compact_skipped", { sid: m.sessionId.slice(0, 8), seat: seat.id.slice(0, 8), until: walledUntil });
@@ -585,6 +643,7 @@ export async function runSupervisor(argv: string[]): Promise<number> {
585
643
  saveSessionFlags(m.sessionId, persistable, process.cwd());
586
644
  const prompt = resumable ? resumePrompt({ compacted, origin: m.origin }) : null;
587
645
  firstLine = relay !== null && prompt !== null ? userLine(prompt) : null;
646
+ pendingTranscript = resumable ? null : transcriptPath(m.sessionId);
588
647
  launchArgs = [resumable ? "--resume" : "--session-id", m.sessionId, ...(relay === null && prompt !== null ? [prompt] : []), ...persistable];
589
648
  continue;
590
649
  }