claude-rpc 1.5.1 → 1.5.4

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.
Files changed (46) hide show
  1. package/README.md +34 -24
  2. package/SECURITY.md +99 -20
  3. package/package.json +1 -1
  4. package/src/atomic-rename.js +45 -2
  5. package/src/badge.js +3 -4
  6. package/src/card.js +1 -22
  7. package/src/cli-path.js +286 -0
  8. package/src/cli.js +310 -383
  9. package/src/community.js +101 -60
  10. package/src/config.js +4 -1
  11. package/src/daemon.js +45 -47
  12. package/src/default-config.js +4 -3
  13. package/src/discord-ipc.js +24 -13
  14. package/src/doctor.js +63 -37
  15. package/src/ensure-daemon.js +11 -4
  16. package/src/fmt.js +8 -6
  17. package/src/format.js +8 -13
  18. package/src/gist.js +8 -18
  19. package/src/git.js +4 -1
  20. package/src/hook.js +48 -37
  21. package/src/insights.js +3 -4
  22. package/src/install.js +189 -97
  23. package/src/leaderboard.js +3 -2
  24. package/src/mcp.js +2 -8
  25. package/src/nudge.js +8 -3
  26. package/src/pricing.js +37 -4
  27. package/src/privacy.js +22 -7
  28. package/src/profile.js +0 -6
  29. package/src/recap.js +4 -17
  30. package/src/scanner.js +103 -71
  31. package/src/server/api.js +64 -36
  32. package/src/server/assets/dashboard.client.js +75 -44
  33. package/src/server/assets/dashboard.css +18 -18
  34. package/src/server/assets/dashboard.html +13 -15
  35. package/src/server/assets/wrapped.client.js +26 -11
  36. package/src/server/assets/wrapped.css +2 -2
  37. package/src/server/index.js +43 -32
  38. package/src/server/page.js +6 -3
  39. package/src/server/sse.js +90 -34
  40. package/src/session-card.js +3 -1
  41. package/src/state.js +14 -24
  42. package/src/tui.js +3 -12
  43. package/src/ui.js +7 -5
  44. package/src/verify.js +3 -7
  45. package/src/version.js +1 -1
  46. package/src/week.js +4 -4
package/src/cli.js CHANGED
@@ -1,90 +1,52 @@
1
1
  #!/usr/bin/env node
2
- import { spawn, spawnSync } from 'node:child_process';
3
- import { readFileSync, writeFileSync, existsSync, watchFile, unlinkSync, mkdirSync } from 'node:fs';
2
+ // First, before anything probes stdio (ui.js does at load): the dashboard and
3
+ // npm scripts run this file directly, not through bin/claude-rpc.js.
4
+ import './safe-stdio.js';
5
+ import { readFileSync, writeFileSync, existsSync, watchFile, unlinkSync } from 'node:fs';
4
6
  import process from 'node:process';
5
-
6
- // Force the console code page to UTF-8 (65001) on Windows so Unicode box
7
- // drawing, block elements, and other chars render correctly. Default cmd.exe
8
- // code page on Win10 is 437/850, which displays many of our chars as `?`.
9
- // Hook events (no TTY) skip this — they don't print anything user-visible.
10
- if (process.platform === 'win32' && process.stdout.isTTY) {
11
- try { spawnSync('chcp.com', ['65001'], { stdio: 'ignore', windowsHide: true }); } catch { /* chcp absent (Wine, custom shell) — accept whatever code page is set */ }
12
- }
13
- import { DAEMON_SCRIPT, STATE_PATH, LOG_PATH, AGGREGATE_PATH, CONFIG_PATH, IS_PACKAGED, IS_NPX, EXE_PATH } from './paths.js';
14
- import { readActiveState } from './state.js';
15
- import { runHookCli } from './hook.js';
16
- import { parseDuration, setPause, clearPause, pauseUntil } from './pause.js';
17
- import { loadConfig, hasUserConfig } from './config.js';
18
- import { spawnDaemonDetached, daemonAlive } from './ensure-daemon.js';
19
-
20
- // ── Lazy-loaded heavy module graph ───────────────────────────────────────────
21
- // format→scanner→pricing→languages→git→usage (plus install/tui/insights/nudge/
22
- // badge/privacy/leaderboard) is ~60ms of module-load that the fast-exit commands
23
- // (--version, --help, start, stop, restart) never touch. We declare the bindings
24
- // here and fill them via loadStats() only for commands that actually fan out into
25
- // the stats/format/install code, so daemon-control and version stay near-instant.
26
- // (The repo already lazy-imports cold deps like doctor.js/card.js/mcp.js inside
27
- // their handlers — this just extends that to the graph the main switch needs.)
7
+ import { basename, join } from 'node:path';
8
+ import { DAEMON_SCRIPT, STATE_PATH, STATE_DIR, LOG_PATH, AGGREGATE_PATH, CONFIG_PATH, IS_PACKAGED, IS_NPX, EXE_PATH } from './paths.js';
9
+ import { VERSION } from './version.js';
10
+ import { c, fail, tailLines, heat, sparkline, fmtDelta, topPercentile, EX_USER_ERROR, EX_BAD_STATE, EX_SYS_ERROR } from './ui.js';
11
+ import * as lb from './leaderboard.js';
12
+ import { writeFileAtomic } from './atomic-rename.js';
13
+
14
+ // ── Lazy-loaded module graph ─────────────────────────────────────────────────
15
+ // Only the static imports above (all cheap) load up front, so --version,
16
+ // --help, hook, mcp, daemon, serve, tail and pause never pay for subsystems
17
+ // they don't touch. Every other command awaits loadCore() once before dispatch:
18
+ // state/config/daemon-control plus the format→scanner→pricing→usage stats
19
+ // chain the shared helpers below draw on. Modules only one command needs
20
+ // (install, tui, insights, nudge, badge, privacy, pause, week, hook,
21
+ // node:crypto, node:readline, node:child_process) are imported inside that
22
+ // command's handler, like doctor.js/card.js/mcp.js always were.
23
+ let readActiveState, statePathFor, loadConfig, hasUserConfig, spawnDaemonDetached, daemonAlive;
28
24
  let buildVars, fillTemplate, humanProject, humanTool, applyIdle, framePasses, fmtNum, fmtHours;
29
25
  let scan, readAggregate, findLiveSessions, dayKey, weekKey;
30
- let weekGrid;
31
- let runInstall, runUninstall, isInstalled, migrateConfig, installHooks, ensureCanonicalExe, installMcp, uninstallMcp, setupOutro;
32
- let startTui;
33
- let generateInsights;
34
- let maybeNudge, pickTodayMilestone;
35
- let badgeSvg;
36
26
  let fmtCost;
37
- let addPrivateCwd, removePrivateCwd, listPrivateCwds, resolveVisibility;
38
27
  let readUsageCache, fetchUsage, writeUsageCache, fmtResetTime, fmtResetDay;
39
- let lb;
40
-
41
- let statsLoaded = false;
42
- async function loadStats() {
43
- if (statsLoaded) return;
44
- // Load the graph concurrently — these are all leaf-ish modules with no
45
- // ordering dependency, so Promise.all beats a sequential import chain.
46
- const [fmt, scn, wk, inst, tui, ins, ndg, bdg, prc, priv, usg, leaderboard] = await Promise.all([
47
- import('./format.js'), import('./scanner.js'), import('./week.js'),
48
- import('./install.js'), import('./tui.js'), import('./insights.js'),
49
- import('./nudge.js'), import('./badge.js'), import('./pricing.js'),
50
- import('./privacy.js'), import('./usage.js'), import('./leaderboard.js'),
28
+
29
+ async function loadDaemonCtl() {
30
+ ({ spawnDaemonDetached, daemonAlive } = await import('./ensure-daemon.js'));
31
+ }
32
+
33
+ // Idempotent — repeat imports resolve from the module cache.
34
+ async function loadCore() {
35
+ const [st, cfg, fmt, scn, prc, usg] = await Promise.all([
36
+ import('./state.js'), import('./config.js'), import('./format.js'),
37
+ import('./scanner.js'), import('./pricing.js'), import('./usage.js'), loadDaemonCtl(),
51
38
  ]);
39
+ ({ readActiveState, statePathFor } = st);
40
+ ({ loadConfig, hasUserConfig } = cfg);
52
41
  ({ buildVars, fillTemplate, humanProject, humanTool, applyIdle, framePasses, fmtNum, fmtHours } = fmt);
53
42
  ({ scan, readAggregate, findLiveSessions, dayKey, weekKey } = scn);
54
- ({ weekGrid } = wk);
55
- ({ install: runInstall, uninstall: runUninstall, isInstalled, migrateConfig, installHooks, ensureCanonicalExe, installMcp, uninstallMcp, setupOutro } = inst);
56
- ({ startTui } = tui);
57
- ({ generateInsights } = ins);
58
- ({ maybeNudge, pickTodayMilestone } = ndg);
59
- ({ badgeSvg } = bdg);
60
43
  ({ fmtCost } = prc);
61
- ({ addPrivateCwd, removePrivateCwd, listPrivateCwds, resolveVisibility } = priv);
62
44
  ({ readUsageCache, fetchUsage, writeUsageCache, fmtResetTime, fmtResetDay } = usg);
63
- lb = leaderboard;
64
- statsLoaded = true;
65
45
  }
66
- import { VERSION } from './version.js';
67
- import { fail, tailLines, heat, sparkline, fmtDelta, topPercentile, EX_USER_ERROR, EX_BAD_STATE, EX_SYS_ERROR } from './ui.js';
68
- import { randomUUID } from 'node:crypto';
69
- import { createInterface } from 'node:readline';
70
- import { basename, join, dirname } from 'node:path';
71
46
 
72
47
  const cmd = process.argv[2];
48
+ const args = process.argv.slice(3);
73
49
 
74
- // ── ANSI styling (degrades gracefully) ────────────────────────────────────────
75
- const tty = process.stdout.isTTY && !process.env.NO_COLOR;
76
- const c = {
77
- reset: tty ? '\x1b[0m' : '',
78
- dim: tty ? '\x1b[2m' : '',
79
- bold: tty ? '\x1b[1m' : '',
80
- cyan: tty ? '\x1b[36m' : '',
81
- green: tty ? '\x1b[32m' : '',
82
- yellow: tty ? '\x1b[33m' : '',
83
- red: tty ? '\x1b[31m' : '',
84
- magenta: tty ? '\x1b[35m' : '',
85
- blue: tty ? '\x1b[34m' : '',
86
- gray: tty ? '\x1b[90m' : '',
87
- };
88
50
  const ansiRe = /\x1b\[[0-9;]*m/g;
89
51
  const visibleLen = (s) => String(s).replace(ansiRe, '').length;
90
52
 
@@ -93,13 +55,13 @@ function readJson(path, fallback) {
93
55
  try { return JSON.parse(readFileSync(path, 'utf8')); } catch { return fallback; }
94
56
  }
95
57
 
96
- // Persist a mutated config.json. The config dir doesn't exist until `setup`
97
- // runs (npm/npx install no install script), so a bare writeFileSync threw an
98
- // uncaught ENOENT for any config-mutating command run before setup
99
- // (`profile set`, `community on`, `link`, …). mkdirSync first.
58
+ // Persist a mutated config.json. tmp + rename (like verify.updateUserConfig),
59
+ // so the daemon's config watcher never reads a half-written file. The helper
60
+ // also creates the config dir, which doesn't exist until `setup` runs — a
61
+ // config-mutating command run before setup (`profile set`, `community on`,
62
+ // `link`, …) used to throw an uncaught ENOENT.
100
63
  function writeUserConfig(userCfg) {
101
- mkdirSync(dirname(CONFIG_PATH), { recursive: true });
102
- writeFileSync(CONFIG_PATH, JSON.stringify(userCfg, null, 2) + '\n');
64
+ writeFileAtomic(CONFIG_PATH, JSON.stringify(userCfg, null, 2) + '\n');
103
65
  }
104
66
 
105
67
  // Validate a flag's value taken with `argv[++i]`. A value that's missing or
@@ -158,7 +120,7 @@ async function confirmDaemonUp({ timeoutMs = 3000, intervalMs = 100 } = {}) {
158
120
  for (;;) {
159
121
  await new Promise((r) => setTimeout(r, intervalMs));
160
122
  if (daemonAlive()) {
161
- console.log(` ${c.green}✓${c.reset} ${'daemon confirmed'.padEnd(16)}${c.dim}up — connecting to Discord${c.reset}`);
123
+ console.log(` ${c.green}✓${c.reset} ${'daemon is up'.padEnd(16)}${c.dim}connecting to Discord${c.reset}`);
162
124
  return true;
163
125
  }
164
126
  if (Date.now() >= deadline) {
@@ -181,24 +143,28 @@ function stopDaemon({ quiet = false } = {}) {
181
143
  }
182
144
  }
183
145
 
146
+ // Resolves once the replacement daemon has been spawned (true) or couldn't be
147
+ // (false), so callers can confirm it and a following `stop` finds its pid.
184
148
  function restartDaemon() {
185
- if (!stopDaemon({ quiet: true })) { startDaemon(); return; }
186
- // Poll for the old daemon to release the PID file rather than guessing with a
187
- // fixed sleep — under load 600ms wasn't always enough, and startDaemon would
188
- // then see it "still up" and no-op, leaving NO daemon running once the old
189
- // one exited. Give up after ~3s, force-kill the wedged pid, and start anyway.
190
- const deadline = Date.now() + 3000;
191
- const tick = () => {
192
- if (!daemonAlive()) { startDaemon(); return; }
193
- if (Date.now() >= deadline) {
194
- const pid = daemonAlive();
195
- if (pid) { try { process.kill(pid, 'SIGKILL'); } catch { /* already gone */ } }
196
- startDaemon();
197
- return;
198
- }
149
+ return new Promise((resolve) => {
150
+ if (!stopDaemon({ quiet: true })) { resolve(startDaemon()); return; }
151
+ // Poll for the old daemon to release the PID file rather than guessing with a
152
+ // fixed sleep — under load 600ms wasn't always enough, and startDaemon would
153
+ // then see it "still up" and no-op, leaving NO daemon running once the old
154
+ // one exited. Give up after ~3s, force-kill the wedged pid, and start anyway.
155
+ const deadline = Date.now() + 3000;
156
+ const tick = () => {
157
+ if (!daemonAlive()) { resolve(startDaemon()); return; }
158
+ if (Date.now() >= deadline) {
159
+ const pid = daemonAlive();
160
+ if (pid) { try { process.kill(pid, 'SIGKILL'); } catch { /* already gone */ } }
161
+ resolve(startDaemon());
162
+ return;
163
+ }
164
+ setTimeout(tick, 50);
165
+ };
199
166
  setTimeout(tick, 50);
200
- };
201
- setTimeout(tick, 50);
167
+ });
202
168
  }
203
169
 
204
170
  // ── Box drawing — auto-widens to fit longest line ────────────────────────────
@@ -288,7 +254,7 @@ function renderHeatmap(byDay, days = 91) {
288
254
  const cursor = new Date(start);
289
255
  while (cursor <= today) {
290
256
  const k = dayKey(cursor.getTime());
291
- cells.push({ key: k, ms: byDay?.[k]?.activeMs || 0, future: cursor > today });
257
+ cells.push({ key: k, ms: byDay?.[k]?.activeMs || 0 });
292
258
  cursor.setDate(cursor.getDate() + 1);
293
259
  }
294
260
  const cols = Math.ceil(cells.length / 7);
@@ -343,7 +309,7 @@ function renderHeatmap(byDay, days = 91) {
343
309
  let line = ` ${c.dim}${dayLabels[row]}${c.reset} `;
344
310
  for (let col = 0; col < cols; col++) {
345
311
  const cell = cells[col * 7 + row];
346
- if (!cell || cell.future) line += ' ';
312
+ if (!cell) line += ' '; // past today: the walk stops there
347
313
  else line += shade(cell.ms) + ' ';
348
314
  }
349
315
  lines.push(line);
@@ -384,6 +350,21 @@ function lastDays(byDay, n) {
384
350
  return out;
385
351
  }
386
352
 
353
+ // "42m" / "3.5h" / "12h" — compact active-time label for bar-chart rows.
354
+ const hoursLabel = (ms) => {
355
+ const h = ms / 3_600_000;
356
+ return h < 1 ? `${Math.round(h * 60)}m` : (h < 10 ? `${h.toFixed(1)}h` : `${Math.round(h)}h`);
357
+ };
358
+
359
+ // ISO-week key of last week, stepped back from local noon so a DST shift
360
+ // can't land the subtraction in the wrong week.
361
+ function lastWeekKey() {
362
+ const d = new Date();
363
+ d.setHours(12, 0, 0, 0);
364
+ d.setDate(d.getDate() - 7);
365
+ return weekKey(d.getTime());
366
+ }
367
+
387
368
  const dayTokens = (d) => d
388
369
  ? (d.inputTokens || 0) + (d.outputTokens || 0) + (d.cacheReadTokens || 0) + (d.cacheWriteTokens || 0)
389
370
  : 0;
@@ -425,7 +406,8 @@ function todayBoxLines(vars, aggregate) {
425
406
  return lines;
426
407
  }
427
408
 
428
- function showStatus() {
409
+ async function showStatus() {
410
+ const { generateInsights } = await import('./insights.js');
429
411
  const state = readActiveState();
430
412
  const aggregate = readAggregate();
431
413
  const config = loadConfig();
@@ -443,7 +425,9 @@ function showStatus() {
443
425
  pair('status', pid ? `${c.green}● running${c.reset} pid ${pid}` : `${c.red}○ not running${c.reset}`, ''),
444
426
  pair('client', config.clientId || '—'),
445
427
  pair('config', shortPath(CONFIG_PATH), c.gray),
446
- pair('state', shortPath(STATE_PATH), c.gray),
428
+ // The file behind the session shown below (hooks write one per session),
429
+ // or the state dir when no session has written one yet.
430
+ pair('state', shortPath(state.sessionId ? statePathFor(state.sessionId) : STATE_DIR), c.gray),
447
431
  pair('log', shortPath(LOG_PATH), c.gray),
448
432
  ]);
449
433
  console.log('');
@@ -541,11 +525,8 @@ function showStatus() {
541
525
  .slice(0, 6);
542
526
  if (top.length) {
543
527
  const maxMs = top[0][1].activeMs;
544
- const lines = top.map(([name, p]) => {
545
- const h = (p.activeMs / 3_600_000);
546
- const hStr = h < 1 ? `${Math.round(h * 60)}m` : (h < 10 ? `${h.toFixed(1)}h` : `${Math.round(h)}h`);
547
- return `${humanProject(name).slice(0, 20).padEnd(22)} ${bar(p.activeMs, maxMs)} ${c.cyan}${hStr.padStart(5)}${c.reset} ${c.dim}${p.sessions} sess · ${p.userMessages} prompts${c.reset}`;
548
- });
528
+ const lines = top.map(([name, p]) =>
529
+ `${humanProject(name).slice(0, 20).padEnd(22)} ${bar(p.activeMs, maxMs)} ${c.cyan}${hoursLabel(p.activeMs).padStart(5)}${c.reset} ${c.dim}${p.sessions} sess · ${p.userMessages} prompts${c.reset}`);
549
530
  box('top projects by active time', lines, 72);
550
531
  console.log('');
551
532
  }
@@ -607,7 +588,8 @@ function showStatus() {
607
588
  }
608
589
  }
609
590
 
610
- function showToday() {
591
+ async function showToday() {
592
+ const { maybeNudge, pickTodayMilestone } = await import('./nudge.js');
611
593
  const state = readActiveState();
612
594
  const aggregate = readAggregate();
613
595
  const config = loadConfig();
@@ -640,7 +622,8 @@ function showToday() {
640
622
  }
641
623
  }
642
624
 
643
- function showWeek() {
625
+ async function showWeek() {
626
+ const { weekGrid } = await import('./week.js');
644
627
  const state = readActiveState();
645
628
  const aggregate = readAggregate();
646
629
  const config = loadConfig();
@@ -653,11 +636,8 @@ function showWeek() {
653
636
 
654
637
  // Week-over-week context: this week so far vs the whole of last week.
655
638
  // Early in the week "▼" is expected — the vs label keeps that honest.
656
- const prevRef = new Date();
657
- prevRef.setHours(12, 0, 0, 0); // noon — immune to DST midnight edges
658
- prevRef.setDate(prevRef.getDate() - 7);
659
639
  const wkNow = aggregate?.byWeek?.[weekKey(Date.now())];
660
- const wkPrev = aggregate?.byWeek?.[weekKey(prevRef.getTime())];
640
+ const wkPrev = aggregate?.byWeek?.[lastWeekKey()];
661
641
  const dWkActive = fmtDelta(wkNow?.activeMs || 0, wkPrev?.activeMs || 0, { vs: 'vs last week' });
662
642
  const dWkPrompts = fmtDelta(wkNow?.userMessages || 0, wkPrev?.userMessages || 0);
663
643
  const dWkTokens = fmtDelta(dayTokens(wkNow), dayTokens(wkPrev));
@@ -676,11 +656,9 @@ function showWeek() {
676
656
  const { days, maxMs } = weekGrid(aggregate.byDay);
677
657
  const lines = days.map(({ label, ms, isFuture, isToday }) => {
678
658
  if (isFuture) return `${c.dim}${label.padEnd(12)} ${'·'.repeat(22)} —${c.reset}`;
679
- const h = ms / 3_600_000;
680
- const hStr = h < 1 ? `${Math.round(h * 60)}m` : (h < 10 ? `${h.toFixed(1)}h` : `${Math.round(h)}h`);
681
659
  const prefix = isToday ? `${c.bold}` : '';
682
660
  const peak = ms === maxMs && ms > 0 ? ` ${c.bold}${heat(1)}◆${c.reset}` : '';
683
- return `${prefix}${label.padEnd(12)}${c.reset} ${bar(ms, maxMs)} ${c.cyan}${hStr.padStart(5)}${c.reset}${peak}${isToday ? ` ${c.dim}← today${c.reset}` : ''}`;
661
+ return `${prefix}${label.padEnd(12)}${c.reset} ${bar(ms, maxMs)} ${c.cyan}${hoursLabel(ms).padStart(5)}${c.reset}${peak}${isToday ? ` ${c.dim}← today${c.reset}` : ''}`;
684
662
  });
685
663
  box('this week · daily breakdown', lines);
686
664
  console.log('');
@@ -776,11 +754,8 @@ function showCompare() {
776
754
  console.log(`\n No history yet — run ${c.cyan}claude-rpc scan${c.reset} first.\n`);
777
755
  return;
778
756
  }
779
- const prevRef = new Date();
780
- prevRef.setHours(12, 0, 0, 0);
781
- prevRef.setDate(prevRef.getDate() - 7);
782
757
  const nowKey = weekKey(Date.now());
783
- const prevKey = weekKey(prevRef.getTime());
758
+ const prevKey = lastWeekKey();
784
759
  const wk = aggregate.byWeek[nowKey] || {};
785
760
  const pw = aggregate.byWeek[prevKey] || {};
786
761
 
@@ -863,14 +838,7 @@ function statusColor(status) {
863
838
  }
864
839
 
865
840
  function showPreview() {
866
- let state = readActiveState();
867
- const aggregate = readAggregate();
868
- const config = loadConfig();
869
- const live = findLiveSessions({ thresholdMs: 90_000 });
870
- state.liveSessions = live;
871
- state = applyIdle(state, config);
872
- state.usage = readUsageCache();
873
- const vars = buildVars(state, config, aggregate);
841
+ const { vars, config, state } = liveVars();
874
842
  const p = config.presence || {};
875
843
  // Preview the frames the daemon ACTUALLY uses: byStatus (base frame + its
876
844
  // rotation, per status) when present — pickFrames in the daemon prefers it
@@ -935,19 +903,21 @@ function dumpVars() {
935
903
  process.stdout.write(JSON.stringify({ vars: Object.keys(live).sort(), live }));
936
904
  }
937
905
 
906
+ // scan() onProgress callback: a `parsed n/total…` line redrawn at most every 500ms.
907
+ function progressLine() {
908
+ let lastReport = 0;
909
+ return ({ scanned, total }) => {
910
+ if (Date.now() - lastReport > 500) {
911
+ process.stdout.write(`\r ${c.dim}parsed ${scanned}/${total}…${c.reset}`);
912
+ lastReport = Date.now();
913
+ }
914
+ };
915
+ }
916
+
938
917
  function doScan(force = false) {
939
918
  console.log(` ${c.dim}scanning ~/.claude/projects ${force ? '(force re-parse)' : '(incremental)'}…${c.reset}`);
940
919
  const t0 = Date.now();
941
- let lastReport = 0;
942
- const result = scan({
943
- force,
944
- onProgress: ({ scanned, total }) => {
945
- if (Date.now() - lastReport > 500) {
946
- process.stdout.write(`\r ${c.dim}parsed ${scanned}/${total}…${c.reset}`);
947
- lastReport = Date.now();
948
- }
949
- },
950
- });
920
+ const result = scan({ force, onProgress: progressLine() });
951
921
  process.stdout.write('\n');
952
922
  console.log(` ${c.green}✓${c.reset} scan complete ${c.dim}${Date.now() - t0}ms — ${c.reset}${c.cyan}${result.scanned}${c.reset}${c.dim} parsed · ${result.skipped} cached · ${result.removed} removed (${result.total} total)${c.reset}`);
953
923
  if (result.dirs && result.dirs.length > 1) {
@@ -976,20 +946,10 @@ function doBackfill(argv) {
976
946
  }
977
947
  console.log(` ${c.dim}backfilling from ${c.reset}${c.cyan}${path}${c.reset}${c.dim}…${c.reset}`);
978
948
  const t0 = Date.now();
979
- let lastReport = 0;
980
949
  // Pass `extraDirs` rather than `projectsDirs` — this way the default
981
950
  // ~/.claude/projects (+ any auto-discovered alt paths) ALSO gets scanned
982
951
  // and the user's existing cache for those isn't pruned.
983
- const result = scan({
984
- force: false,
985
- extraDirs: [path],
986
- onProgress: ({ scanned, total }) => {
987
- if (Date.now() - lastReport > 500) {
988
- process.stdout.write(`\r ${c.dim}parsed ${scanned}/${total}…${c.reset}`);
989
- lastReport = Date.now();
990
- }
991
- },
992
- });
952
+ const result = scan({ force: false, extraDirs: [path], onProgress: progressLine() });
993
953
  process.stdout.write('\n');
994
954
  console.log(` ${c.green}✓${c.reset} backfill complete ${c.dim}${Date.now() - t0}ms — ${c.reset}${c.cyan}${result.scanned}${c.reset}${c.dim} new/changed · ${result.skipped} cached${c.reset}`);
995
955
  console.log(` ${c.dim}roots: ${result.dirs.join(', ')}${c.reset}`);
@@ -997,7 +957,8 @@ function doBackfill(argv) {
997
957
  console.log(` ${c.dim}aggregate now: ${result.aggregate.sessions} sessions · ${hours}h · ${result.aggregate.userMessages} prompts${c.reset}`);
998
958
  }
999
959
 
1000
- function showInsights() {
960
+ async function showInsights() {
961
+ const { generateInsights } = await import('./insights.js');
1001
962
  const aggregate = readAggregate();
1002
963
  const insights = generateInsights(aggregate, { limit: 6 });
1003
964
  console.log('');
@@ -1035,37 +996,44 @@ async function doRecap(argv) {
1035
996
  }
1036
997
  }
1037
998
 
1038
- function parseBadgeArgs(argv) {
999
+ // Parse `--flag value` / `--flag=value` / boolean `--flag` args onto a copy of
1000
+ // `defaults`. `flags` maps each option key to its spellings — the first is the
1001
+ // name takeValue's error shows; a key whose default is `false` is a boolean
1002
+ // switch. Unknown args are ignored.
1003
+ function parseFlags(argv, defaults, flags) {
1039
1004
  argv = splitEqArgs(argv);
1040
- const out = { metric: 'hours', range: '7d', out: '', gist: false };
1005
+ const out = { ...defaults };
1041
1006
  for (let i = 0; i < argv.length; i++) {
1042
- const a = argv[i];
1043
- if (a === '--metric' || a === '-m') out.metric = takeValue(argv[++i], '--metric');
1044
- else if (a === '--range' || a === '-r') out.range = takeValue(argv[++i], '--range');
1045
- else if (a === '--out' || a === '-o') out.out = takeValue(argv[++i], '--out');
1046
- else if (a === '--label' || a === '-l') out.label = takeValue(argv[++i], '--label');
1047
- else if (a === '--gist') out.gist = true;
1007
+ const key = Object.keys(flags).find((k) => flags[k].includes(argv[i]));
1008
+ if (key) out[key] = defaults[key] === false ? true : takeValue(argv[++i], flags[key][0]);
1048
1009
  }
1049
1010
  return out;
1050
1011
  }
1051
1012
 
1052
- async function doBadge(argv) {
1053
- const opts = parseBadgeArgs(argv);
1013
+ // The aggregate, or a wrong-state exit for the commands that render it.
1014
+ function aggregateOr(what) {
1054
1015
  const aggregate = readAggregate();
1055
- if (!aggregate) {
1056
- fail('no aggregate yet — nothing to render', { hint: 'run `claude-rpc scan` first', code: EX_BAD_STATE });
1057
- }
1016
+ if (!aggregate) fail(`no aggregate yet — nothing to ${what}`, { hint: 'run `claude-rpc scan` first', code: EX_BAD_STATE });
1017
+ return aggregate;
1018
+ }
1019
+
1020
+ // Write a rendered artifact to --out with a one-line receipt (plus any
1021
+ // follow-up lines), or with no --out straight to stdout for piping.
1022
+ function emit(body, out, { note = `${body.length} bytes`, after = [] } = {}) {
1023
+ if (!out) { process.stdout.write(body); return; }
1024
+ writeFileSync(out, body);
1025
+ console.log(` ${c.green}✓${c.reset} wrote ${c.cyan}${out}${c.reset} ${c.dim}(${note})${c.reset}`);
1026
+ for (const line of after) console.log(line);
1027
+ }
1028
+
1029
+ async function doBadge(argv) {
1030
+ const opts = parseFlags(argv, { metric: 'hours', range: '7d', out: '', gist: false },
1031
+ { metric: ['--metric', '-m'], range: ['--range', '-r'], out: ['--out', '-o'], label: ['--label', '-l'], gist: ['--gist'] });
1032
+ const aggregate = aggregateOr('render');
1033
+ const { badgeSvg } = await import('./badge.js');
1058
1034
  const svg = badgeSvg({ aggregate, metric: opts.metric, range: opts.range, label: opts.label });
1059
- if (opts.gist) {
1060
- await publishBadgeToGist(svg, opts);
1061
- return;
1062
- }
1063
- if (opts.out) {
1064
- writeFileSync(opts.out, svg);
1065
- console.log(` ${c.green}✓${c.reset} wrote ${c.cyan}${opts.out}${c.reset} ${c.dim}(${svg.length} bytes)${c.reset}`);
1066
- } else {
1067
- process.stdout.write(svg);
1068
- }
1035
+ if (opts.gist) return publishBadgeToGist(svg, opts);
1036
+ emit(svg, opts.out);
1069
1037
  }
1070
1038
 
1071
1039
  // Publish the rendered badge to a GitHub gist and emit the README-ready
@@ -1127,136 +1095,76 @@ async function publishBadgeToGist(svg, opts, kind = 'badge') {
1127
1095
  // Poster-style SVG card. Bigger sibling of `badge` — shareable summary
1128
1096
  // for a range (year / month / week / all-time). Output is SVG only;
1129
1097
  // screenshot or convert to PNG offline if needed.
1130
- function parseCardArgs(argv) {
1131
- argv = splitEqArgs(argv);
1132
- const out = { range: 'year', out: '' };
1133
- for (let i = 0; i < argv.length; i++) {
1134
- const a = argv[i];
1135
- if (a === '--range' || a === '-r') out.range = takeValue(argv[++i], '--range');
1136
- else if (a === '--out' || a === '-o') out.out = takeValue(argv[++i], '--out');
1137
- }
1138
- return out;
1139
- }
1140
-
1141
1098
  async function doCard(argv) {
1142
- const opts = parseCardArgs(argv);
1143
- const aggregate = readAggregate();
1144
- if (!aggregate) {
1145
- fail('no aggregate yet — nothing to render', { hint: 'run `claude-rpc scan` first', code: EX_BAD_STATE });
1146
- }
1099
+ const opts = parseFlags(argv, { range: 'year', out: '' }, { range: ['--range', '-r'], out: ['--out', '-o'] });
1100
+ const aggregate = aggregateOr('render');
1147
1101
  const { renderCard } = await import('./card.js');
1148
- const svg = renderCard(aggregate, { range: opts.range });
1149
- if (opts.out) {
1150
- writeFileSync(opts.out, svg);
1151
- console.log(` ${c.green}✓${c.reset} wrote ${c.cyan}${opts.out}${c.reset} ${c.dim}(${svg.length} bytes)${c.reset}`);
1152
- console.log(` ${c.dim}tip: open in a browser and save as PNG — or drop it straight into a Discord message; it renders inline${c.reset}`);
1153
- } else {
1154
- process.stdout.write(svg);
1155
- }
1102
+ emit(renderCard(aggregate, { range: opts.range }), opts.out, {
1103
+ after: [` ${c.dim}tip: open in a browser and save as PNG — or drop it straight into a Discord message; it renders inline${c.reset}`],
1104
+ });
1156
1105
  }
1157
1106
 
1158
1107
  // GitHub profile stat card — a compact, embeddable lifetime summary meant
1159
1108
  // for a profile README. `--gist` publishes it to a gist (raw URL stays stable
1160
1109
  // across re-runs) so the README image auto-refreshes when you re-run it.
1161
- function parseGithubStatArgs(argv) {
1162
- argv = splitEqArgs(argv);
1163
- const out = { out: '', gist: false, handle: '' };
1164
- for (let i = 0; i < argv.length; i++) {
1165
- const a = argv[i];
1166
- if (a === '--out' || a === '-o') out.out = takeValue(argv[++i], '--out');
1167
- else if (a === '--handle' || a === '-u') out.handle = takeValue(argv[++i], '--handle');
1168
- else if (a === '--gist') out.gist = true;
1169
- }
1170
- return out;
1171
- }
1172
-
1173
1110
  async function doGithubStat(argv) {
1174
- const opts = parseGithubStatArgs(argv);
1175
- const aggregate = readAggregate();
1176
- if (!aggregate) {
1177
- fail('no aggregate yet — nothing to render', { hint: 'run `claude-rpc scan` first', code: EX_BAD_STATE });
1178
- }
1111
+ const opts = parseFlags(argv, { out: '', gist: false, handle: '' },
1112
+ { out: ['--out', '-o'], handle: ['--handle', '-u'], gist: ['--gist'] });
1113
+ const aggregate = aggregateOr('render');
1179
1114
  const { renderProfileCard } = await import('./profile.js');
1180
1115
  const svg = renderProfileCard(aggregate, { handle: opts.handle });
1181
- if (opts.gist) {
1182
- await publishBadgeToGist(svg, { metric: 'profile', range: 'all-time' }, 'github-stat');
1183
- return;
1184
- }
1185
- if (opts.out) {
1186
- writeFileSync(opts.out, svg);
1187
- console.log(` ${c.green}✓${c.reset} wrote ${c.cyan}${opts.out}${c.reset} ${c.dim}(${svg.length} bytes)${c.reset}`);
1188
- console.log(` ${c.dim}embed in your README: <img src="${opts.out}" alt="Claude Code stats" width="500" />${c.reset}`);
1189
- } else {
1190
- process.stdout.write(svg);
1191
- }
1116
+ if (opts.gist) return publishBadgeToGist(svg, { metric: 'profile', range: 'all-time' }, 'github-stat');
1117
+ emit(svg, opts.out, {
1118
+ after: [` ${c.dim}embed in your README: <img src="${opts.out}" alt="Claude Code stats" width="500" />${c.reset}`],
1119
+ });
1192
1120
  }
1193
1121
 
1194
1122
  // Build the live template-variable table the way the daemon does — current
1195
- // state + idle/stale resolution + aggregate. Shared by statusline/session-card.
1123
+ // state + idle/stale resolution + aggregate. Shared by preview/statusline/
1124
+ // session-card.
1196
1125
  function liveVars() {
1197
- const state = readActiveState();
1198
- state.liveSessions = findLiveSessions({ thresholdMs: 90_000 });
1126
+ const raw = readActiveState();
1127
+ raw.liveSessions = findLiveSessions({ thresholdMs: 90_000 });
1199
1128
  const config = loadConfig();
1200
- const resolved = applyIdle(state, config);
1201
- resolved.usage = readUsageCache();
1202
- return { vars: buildVars(resolved, config, readAggregate()), config };
1129
+ const state = applyIdle(raw, config);
1130
+ state.usage = readUsageCache();
1131
+ return { vars: buildVars(state, config, readAggregate()), config, state };
1203
1132
  }
1204
1133
 
1205
1134
  // statusline — a compact one-line status for tmux / starship / shell prompts
1206
1135
  // and Claude Code's own statusline. `--template "..."` overrides the format.
1207
1136
  function doStatusline(argv) {
1208
- argv = splitEqArgs(argv);
1209
- let tpl = '{statusVerbose} · {project} · {modelPretty}{tokensLabelPad}';
1210
- for (let i = 0; i < argv.length; i++) {
1211
- if (argv[i] === '--template' || argv[i] === '-t') tpl = takeValue(argv[++i], '--template');
1212
- }
1137
+ const { template } = parseFlags(argv, { template: '{statusVerbose} · {project} · {modelPretty}{tokensLabelPad}' },
1138
+ { template: ['--template', '-t'] });
1213
1139
  const { vars } = liveVars();
1214
1140
  vars.tokensLabelPad = vars.tokensLabel ? ` · ${vars.tokensLabel}` : '';
1215
- process.stdout.write(fillTemplate(tpl, vars));
1141
+ process.stdout.write(fillTemplate(template, vars));
1216
1142
  }
1217
1143
 
1218
1144
  // Activity calendar — GitHub-contributions-style year heatmap SVG.
1219
1145
  // --metric hours (default) | tokens; --card wraps it in the stats card.
1220
1146
  async function doCalendar(argv) {
1221
- argv = splitEqArgs(argv);
1222
- const opts = { out: '', gist: false, metric: 'hours', card: false };
1223
- for (let i = 0; i < argv.length; i++) {
1224
- if (argv[i] === '--out' || argv[i] === '-o') opts.out = takeValue(argv[++i], '--out');
1225
- else if (argv[i] === '--gist') opts.gist = true;
1226
- else if (argv[i] === '--card') opts.card = true;
1227
- else if (argv[i] === '--metric') opts.metric = takeValue(argv[++i], '--metric');
1228
- }
1147
+ const opts = parseFlags(argv, { out: '', gist: false, metric: 'hours', card: false },
1148
+ { out: ['--out', '-o'], gist: ['--gist'], card: ['--card'], metric: ['--metric'] });
1229
1149
  if (!['hours', 'tokens'].includes(opts.metric)) {
1230
1150
  fail(`unknown --metric \`${opts.metric}\``, { hint: 'use --metric hours or --metric tokens', code: EX_USER_ERROR });
1231
1151
  }
1232
- const aggregate = readAggregate();
1233
- if (!aggregate) fail('no aggregate yet — nothing to render', { hint: 'run `claude-rpc scan` first', code: EX_BAD_STATE });
1152
+ const aggregate = aggregateOr('render');
1234
1153
  const { renderCalendar, renderCalendarCard } = await import('./calendar.js');
1235
1154
  const svg = opts.card
1236
1155
  ? renderCalendarCard(aggregate, { metric: opts.metric, handle: loadConfig().profile?.handle })
1237
1156
  : renderCalendar(aggregate, { metric: opts.metric });
1238
1157
  const kind = opts.card ? 'stats' : 'calendar';
1239
1158
  if (opts.gist) return publishBadgeToGist(svg, { metric: kind, range: 'year' }, kind);
1240
- if (opts.out) {
1241
- writeFileSync(opts.out, svg);
1242
- console.log(` ${c.green}✓${c.reset} wrote ${c.cyan}${opts.out}${c.reset} ${c.dim}(${svg.length} bytes)${c.reset}`);
1243
- } else process.stdout.write(svg);
1159
+ emit(svg, opts.out);
1244
1160
  }
1245
1161
 
1246
1162
  // Per-session recap card — current/most-recent session as a shareable SVG.
1247
1163
  async function doSessionCard(argv) {
1248
- argv = splitEqArgs(argv);
1249
- const opts = { out: '' };
1250
- for (let i = 0; i < argv.length; i++) {
1251
- if (argv[i] === '--out' || argv[i] === '-o') opts.out = takeValue(argv[++i], '--out');
1252
- }
1164
+ const { out } = parseFlags(argv, { out: '' }, { out: ['--out', '-o'] });
1253
1165
  const { vars } = liveVars();
1254
1166
  const { renderSessionCard } = await import('./session-card.js');
1255
- const svg = renderSessionCard(vars, {});
1256
- if (opts.out) {
1257
- writeFileSync(opts.out, svg);
1258
- console.log(` ${c.green}✓${c.reset} wrote ${c.cyan}${opts.out}${c.reset} ${c.dim}(${svg.length} bytes)${c.reset}`);
1259
- } else process.stdout.write(svg);
1167
+ emit(renderSessionCard(vars, {}), out);
1260
1168
  }
1261
1169
 
1262
1170
  // `claude-rpc readme` — paste-ready markdown for putting your live Claude Code
@@ -1347,9 +1255,12 @@ async function doMcp() {
1347
1255
  runMcpServer();
1348
1256
  }
1349
1257
 
1258
+ const mcpScope = (argv) => argv.includes('--project') ? 'project' : argv.includes('--local') ? 'local' : 'user';
1259
+
1350
1260
  // One-command wiring into Claude Code — runs `claude mcp add` for the user.
1351
- function doMcpInstall(argv) {
1352
- const scope = argv.includes('--project') ? 'project' : argv.includes('--local') ? 'local' : 'user';
1261
+ async function doMcpInstall(argv) {
1262
+ const { installMcp } = await import('./install.js');
1263
+ const scope = mcpScope(argv);
1353
1264
  const res = installMcp({ exePath: EXE_PATH || process.execPath, scope });
1354
1265
  const manual = (r) => `claude mcp add claude-rpc --scope ${scope} -- ${r.command} ${r.args.join(' ')}`;
1355
1266
  if (res.ok) {
@@ -1367,8 +1278,9 @@ function doMcpInstall(argv) {
1367
1278
  }
1368
1279
  }
1369
1280
 
1370
- function doMcpUninstall(argv) {
1371
- const scope = argv.includes('--project') ? 'project' : argv.includes('--local') ? 'local' : 'user';
1281
+ async function doMcpUninstall(argv) {
1282
+ const { uninstallMcp } = await import('./install.js');
1283
+ const scope = mcpScope(argv);
1372
1284
  const res = uninstallMcp({ scope });
1373
1285
  if (res.ok) console.log(` ${c.green}✓${c.reset} removed the claude-rpc MCP server ${c.dim}(scope: ${scope})${c.reset}`);
1374
1286
  else if (res.reason === 'no-claude') fail('the `claude` CLI was not found on your PATH', { code: EX_USER_ERROR });
@@ -1384,25 +1296,30 @@ function doMcpUninstall(argv) {
1384
1296
  // Per-project overrides live in <project>/.claude-rpc.json and take priority
1385
1297
  // over the runtime list. See src/privacy.js for the full resolution chain.
1386
1298
 
1387
- function doPrivate() {
1299
+ async function doPrivate() {
1300
+ const { addPrivateCwd } = await import('./privacy.js');
1388
1301
  const cwd = process.cwd();
1389
1302
  const list = addPrivateCwd(cwd);
1390
1303
  console.log(` ${c.green}✓${c.reset} ${c.cyan}${cwd}${c.reset} marked private`);
1391
1304
  console.log(` ${c.dim}${list.length} ${list.length === 1 ? 'path' : 'paths'} in the private list — the daemon picks it up within ~5 min, or ${c.reset}${c.cyan}claude-rpc restart${c.reset}`);
1392
1305
  }
1393
1306
 
1394
- function doPublic() {
1307
+ async function doPublic() {
1308
+ const { listPrivateCwds, listVisibility, removePrivateCwd } = await import('./privacy.js');
1395
1309
  const cwd = process.cwd();
1396
- const before = listPrivateCwds().length;
1397
- const list = removePrivateCwd(cwd);
1398
- if (list.length === before) {
1310
+ // Either store may have hidden it: the private list or the dashboard's map.
1311
+ const snapshot = () => JSON.stringify([listPrivateCwds(), listVisibility()]);
1312
+ const before = snapshot();
1313
+ removePrivateCwd(cwd);
1314
+ if (snapshot() === before) {
1399
1315
  console.log(` ${c.yellow}!${c.reset} ${c.cyan}${cwd}${c.reset} wasn't in the private list`);
1400
1316
  } else {
1401
1317
  console.log(` ${c.green}✓${c.reset} ${c.cyan}${cwd}${c.reset} removed from the private list`);
1402
1318
  }
1403
1319
  }
1404
1320
 
1405
- function doPrivacy() {
1321
+ async function doPrivacy() {
1322
+ const { resolveVisibility, listPrivateCwds } = await import('./privacy.js');
1406
1323
  const cwd = process.cwd();
1407
1324
  const cfg = loadConfig();
1408
1325
  const { visibility, projectName, reason } = resolveVisibility(cwd, cfg);
@@ -1435,7 +1352,8 @@ function fmtClock(ts) {
1435
1352
  return `${String(d.getHours()).padStart(2, '0')}:${String(d.getMinutes()).padStart(2, '0')}`;
1436
1353
  }
1437
1354
 
1438
- function doPause(argv) {
1355
+ async function doPause(argv) {
1356
+ const { parseDuration, setPause, pauseUntil } = await import('./pause.js');
1439
1357
  const arg = (argv[0] || '').toLowerCase();
1440
1358
  if (arg === 'off' || arg === 'resume') return doResume();
1441
1359
  if (arg === 'status') {
@@ -1454,7 +1372,8 @@ function doPause(argv) {
1454
1372
  console.log(` ${c.dim}the daemon clears the card within seconds — resume early with ${c.reset}${c.cyan}claude-rpc resume${c.reset}`);
1455
1373
  }
1456
1374
 
1457
- function doResume() {
1375
+ async function doResume() {
1376
+ const { pauseUntil, clearPause } = await import('./pause.js');
1458
1377
  const was = pauseUntil();
1459
1378
  clearPause();
1460
1379
  if (was) {
@@ -1472,29 +1391,12 @@ function doResume() {
1472
1391
  // pipes cleanly into jq / a spreadsheet import.
1473
1392
 
1474
1393
  async function doExport(argv) {
1475
- argv = splitEqArgs(argv);
1476
- const csv = argv.includes('--csv');
1477
- let out = '';
1478
- for (let i = 0; i < argv.length; i++) {
1479
- if (argv[i] === '--out' || argv[i] === '-o') out = takeValue(argv[++i], '--out');
1480
- }
1481
- const aggregate = readAggregate();
1482
- if (!aggregate) {
1483
- fail('no aggregate yet — nothing to export', { hint: 'run `claude-rpc scan` first', code: EX_BAD_STATE });
1484
- }
1485
- let payload;
1486
- if (csv) {
1487
- const { aggregateToCsv } = await import('./server/api.js');
1488
- payload = aggregateToCsv(aggregate);
1489
- } else {
1490
- payload = JSON.stringify(aggregate, null, 2) + '\n';
1491
- }
1492
- if (out) {
1493
- writeFileSync(out, payload);
1494
- console.log(` ${c.green}✓${c.reset} wrote ${c.cyan}${out}${c.reset} ${c.dim}(${payload.length} bytes, ${csv ? 'CSV' : 'JSON'})${c.reset}`);
1495
- } else {
1496
- process.stdout.write(payload);
1497
- }
1394
+ const { csv, out } = parseFlags(argv, { csv: false, out: '' }, { csv: ['--csv'], out: ['--out', '-o'] });
1395
+ const aggregate = aggregateOr('export');
1396
+ const payload = csv
1397
+ ? (await import('./server/api.js')).aggregateToCsv(aggregate)
1398
+ : JSON.stringify(aggregate, null, 2) + '\n';
1399
+ emit(payload, out, { note: `${payload.length} bytes, ${csv ? 'CSV' : 'JSON'}` });
1498
1400
  }
1499
1401
 
1500
1402
  // ── Squads — private mini-leaderboards (terminal parity for the web UI) ───
@@ -1522,30 +1424,24 @@ function squadAuth() {
1522
1424
  code: EX_BAD_STATE,
1523
1425
  });
1524
1426
  }
1525
- const netFail = (e) => fail(`couldn't reach the squads service: ${e.message}`, {
1526
- hint: 'check your connection and retry — this never blocks Claude Code',
1527
- code: EX_SYS_ERROR,
1528
- });
1529
- const post = async (path, body) => {
1427
+ const call = async (path, init = {}) => {
1530
1428
  let res;
1531
1429
  try {
1532
- res = await fetch(endpoint + path, {
1533
- method: 'POST',
1534
- headers: { 'Content-Type': 'application/json' },
1535
- body: JSON.stringify({ instanceId, ...body }),
1536
- signal: AbortSignal.timeout(10_000),
1430
+ res = await fetch(endpoint + path, { ...init, signal: AbortSignal.timeout(10_000) });
1431
+ } catch (e) {
1432
+ return fail(`couldn't reach the squads service: ${e.message}`, {
1433
+ hint: 'check your connection and retry — this never blocks Claude Code',
1434
+ code: EX_SYS_ERROR,
1537
1435
  });
1538
- } catch (e) { return netFail(e); }
1539
- return { status: res.status, json: await res.json().catch(() => ({})) };
1540
- };
1541
- const get = async (path) => {
1542
- let res;
1543
- try {
1544
- res = await fetch(endpoint + path, { signal: AbortSignal.timeout(10_000) });
1545
- } catch (e) { return netFail(e); }
1436
+ }
1546
1437
  return { status: res.status, json: await res.json().catch(() => ({})) };
1547
1438
  };
1548
- return { cfg, endpoint, instanceId, post, get };
1439
+ const post = (path, body) => call(path, {
1440
+ method: 'POST',
1441
+ headers: { 'Content-Type': 'application/json' },
1442
+ body: JSON.stringify({ instanceId, ...body }),
1443
+ });
1444
+ return { cfg, endpoint, instanceId, post, get: call };
1549
1445
  }
1550
1446
 
1551
1447
  function squadPageUrl(id) { return `https://claude-rpc.com/squad/${id}`; }
@@ -1735,7 +1631,8 @@ async function doLink(argv) {
1735
1631
  // for the receiving end. As of v0.7 this is on by default for fresh
1736
1632
  // installs and preserved-off for pre-v0.7 upgraders (see migrateConfig).
1737
1633
 
1738
- function prompt(question) {
1634
+ async function prompt(question) {
1635
+ const { createInterface } = await import('node:readline');
1739
1636
  return new Promise((resolve) => {
1740
1637
  const rl = createInterface({ input: process.stdin, output: process.stdout });
1741
1638
  rl.question(question, (answer) => { rl.close(); resolve(answer); });
@@ -1794,13 +1691,18 @@ async function communityOn() {
1794
1691
  return;
1795
1692
  }
1796
1693
  const userCfg = readJson(CONFIG_PATH, {});
1694
+ const { randomUUID } = await import('node:crypto');
1695
+ const priorId = userCfg.community?.instanceId || community.instanceId;
1797
1696
  const next = {
1798
1697
  ...(userCfg.community || {}),
1799
1698
  enabled: true,
1800
- instanceId: userCfg.community?.instanceId || community.instanceId || randomUUID(),
1699
+ instanceId: priorId || randomUUID(),
1801
1700
  };
1802
1701
  userCfg.community = next;
1803
1702
  writeUserConfig(userCfg);
1703
+ // A brand-new id has reported nothing: its first flush sends the history.
1704
+ // A re-enable keeps its cursor (see community.ensureCursor).
1705
+ if (!priorId) (await import('./community.js')).markCursorFresh();
1804
1706
  console.log('');
1805
1707
  console.log(` ${c.green}✓${c.reset} community totals enabled`);
1806
1708
  console.log(` ${c.dim}id: …${next.instanceId.slice(-8)}${c.reset}`);
@@ -1976,7 +1878,7 @@ function profileSet(argv) {
1976
1878
  profileNextStep();
1977
1879
  }
1978
1880
 
1979
- function profileEnable(on) {
1881
+ async function profileEnable(on) {
1980
1882
  const userCfg = readJson(CONFIG_PATH, {});
1981
1883
  const next = { ...(userCfg.profile || {}) };
1982
1884
  if (on && !lb.isValidHandle(next.handle)) {
@@ -1992,8 +1894,9 @@ function profileEnable(on) {
1992
1894
  if (on) {
1993
1895
  const community = { ...(userCfg.community || {}) };
1994
1896
  if (!community.instanceId) {
1995
- community.instanceId = randomUUID();
1897
+ community.instanceId = (await import('node:crypto')).randomUUID();
1996
1898
  userCfg.community = community;
1899
+ (await import('./community.js')).markCursorFresh();
1997
1900
  }
1998
1901
  }
1999
1902
  userCfg.profile = next;
@@ -2201,7 +2104,7 @@ async function setupGhConnect() {
2201
2104
  // privacy filter can't see everything the presence valve can, so the human
2202
2105
  // check is part of the design, not politeness).
2203
2106
  async function doWrappedPublish(argv) {
2204
- await loadStats();
2107
+ await loadCore();
2205
2108
  const cfg = loadConfig();
2206
2109
  const aggregate = readAggregate();
2207
2110
  if (!aggregate) return fail('no aggregate yet', { hint: 'run `claude-rpc scan` first', code: EX_BAD_STATE });
@@ -2214,8 +2117,11 @@ async function doWrappedPublish(argv) {
2214
2117
  const instanceId = cfg.community?.instanceId;
2215
2118
  if (!instanceId) return fail('no instanceId — run `claude-rpc setup`', { code: EX_BAD_STATE });
2216
2119
 
2217
- const yearFlag = argv.indexOf('--year');
2218
- const year = yearFlag !== -1 ? Number(argv[yearFlag + 1]) : new Date().getFullYear();
2120
+ const opts = parseFlags(argv, { year: String(new Date().getFullYear()), yes: false }, { year: ['--year'], yes: ['--yes'] });
2121
+ if (!/^\d{4}$/.test(opts.year)) {
2122
+ return fail(`--year needs a 4-digit year, got \`${opts.year}\``, { hint: 'e.g. --year 2025', code: EX_USER_ERROR });
2123
+ }
2124
+ const year = Number(opts.year);
2219
2125
  const { buildWrappedPayload, publishWrapped } = await import('./community.js');
2220
2126
  const payload = buildWrappedPayload(aggregate, cfg, { instanceId, year });
2221
2127
  const w = payload.wrapped;
@@ -2240,7 +2146,7 @@ async function doWrappedPublish(argv) {
2240
2146
  console.log(` ${c.dim}full payload: the fields above plus lines/cache%/peaks — nothing else.${c.reset}`);
2241
2147
  console.log(` ${c.dim}private-listed and pattern-matched project names are already excluded.${c.reset}\n`);
2242
2148
 
2243
- if (!argv.includes('--yes')) {
2149
+ if (!opts.yes) {
2244
2150
  if (!process.stdout.isTTY) {
2245
2151
  return fail('refusing to publish without confirmation on a non-TTY', {
2246
2152
  hint: 'pass --yes to publish non-interactively', code: EX_USER_ERROR,
@@ -2388,14 +2294,16 @@ function overview() {
2388
2294
 
2389
2295
  function help() {
2390
2296
  const cmds = [
2391
- ['setup', 'Install Claude Code hooks + Windows startup entry (~/.claude/settings.json)'],
2297
+ ['setup', 'Install Claude Code hooks + login autostart (Run key / LaunchAgent / systemd --user)'],
2298
+ ['install', 'Same as setup'],
2392
2299
  ['setup --link <code>', 'One-liner onboarding: install + verify via a claude-rpc.com code (+ --wrapped publishes your year)'],
2393
- ['uninstall', 'Remove Claude Code hooks + Windows startup entry'],
2300
+ ['uninstall', 'Remove Claude Code hooks + the login autostart entry'],
2394
2301
  ['upgrade-config', 'Re-run idempotent migrations on an existing config.json'],
2395
2302
  ['start', 'Start the Discord RPC daemon (detached)'],
2396
2303
  ['stop', 'Stop the daemon'],
2397
2304
  ['restart', 'Stop then start the daemon'],
2398
2305
  ['status', 'Interactive stats TUI; --dump (or piped) prints static text'],
2306
+ ['dump', 'Same as status --dump'],
2399
2307
  ['today', 'Focus view: today\'s stats + 24h activity histogram'],
2400
2308
  ['week', 'Focus view: this week, daily breakdown'],
2401
2309
  ['compare', 'This week vs last week — the full side-by-side diff'],
@@ -2404,6 +2312,7 @@ function help() {
2404
2312
  ['usage', 'Subscription limits — session + weekly % (what /usage shows)'],
2405
2313
  ['serve', 'Open a live web dashboard in your browser'],
2406
2314
  ['preview', 'Show how each rotation frame renders right now'],
2315
+ ['vars', 'Print every template variable and its live value (JSON)'],
2407
2316
  ['scan', 'Incrementally scan ~/.claude/projects for all-time totals'],
2408
2317
  ['rescan', 'Force re-parse every transcript (ignores cache)'],
2409
2318
  ['backfill', 'Import transcripts from any folder (e.g. a backup)'],
@@ -2422,7 +2331,9 @@ function help() {
2422
2331
  ['wrapped', 'Open your animated year-in-review (Claude Wrapped)'],
2423
2332
  ['wrapped --publish', 'Put your Wrapped on the web at claude-rpc.com/wrapped/<handle>'],
2424
2333
  ['pause', 'Snooze the Discord card globally (pause [30m|2h], default 1h)'],
2334
+ ['pause status|off', 'Show whether presence is paused / lift a pause early'],
2425
2335
  ['resume', 'Lift a pause early'],
2336
+ ['unpause', 'Same as resume'],
2426
2337
  ['export', 'Dump the aggregate as JSON, or daily rows as CSV (--csv --out)'],
2427
2338
  ['private', 'Mark the current directory as private (hide from Discord)'],
2428
2339
  ['public', 'Un-mark the current directory'],
@@ -2433,6 +2344,7 @@ function help() {
2433
2344
  ['link', 'Link machines into one profile (mints a code; `link <code>` claims it)'],
2434
2345
  ['doctor', 'Run a diagnostic checklist — common-failure triage (--fix to auto-repair)'],
2435
2346
  ['tail', 'Tail the daemon log file'],
2347
+ ['logs', 'Same as tail (also: log)'],
2436
2348
  ['daemon', 'Run daemon in foreground (debug)'],
2437
2349
  ];
2438
2350
  const colW = cmds.reduce((m, [name]) => Math.max(m, name.length), 0);
@@ -2472,12 +2384,20 @@ process.on('unhandledRejection', (e) => {
2472
2384
  // ESM (dev) and CommonJS (esbuild → SEA bundle) — CJS doesn't allow
2473
2385
  // top-level await.
2474
2386
  (async () => {
2475
- // Fast-exit commands touch none of the lazy stats/format/install graph, so
2476
- // skip the module load and keep them instant. Everything else loads it once
2477
- // up front, which makes every binding available to the handlers below exactly
2478
- // as before. (daemon/serve/wrapped/hook only dynamic-import their own module.)
2479
- const FAST_PATHS = new Set(['--version', '-V', '-v', '--help', '-h', 'help', 'start', 'stop', 'restart', 'hook', 'daemon', 'serve', 'wrapped']);
2480
- if (!FAST_PATHS.has(cmd)) await loadStats();
2387
+ // Force the console code page to UTF-8 (65001) on Windows so Unicode box
2388
+ // drawing, block elements, and other chars render correctly. Default cmd.exe
2389
+ // code page on Win10 is 437/850, which displays many of our chars as `?`.
2390
+ // Hook events (no TTY) skip this — they don't print anything user-visible.
2391
+ if (process.platform === 'win32' && process.stdout.isTTY) {
2392
+ const { spawnSync } = await import('node:child_process');
2393
+ try { spawnSync('chcp.com', ['65001'], { stdio: 'ignore', windowsHide: true }); } catch { /* chcp absent (Wine, custom shell) — accept whatever code page is set */ }
2394
+ }
2395
+ // Fast-exit commands touch none of the core graph (they import their own
2396
+ // module, if any); daemon control needs only ensure-daemon. Everything else
2397
+ // loads the core once up front, so its bindings are set for every handler.
2398
+ const FAST_PATHS = new Set(['--version', '-V', '-v', '--help', '-h', 'help', 'hook', 'mcp', 'daemon', 'serve', 'wrapped', 'scan-worker', 'tail', 'logs', 'log', 'pause', 'resume', 'unpause']);
2399
+ if (['start', 'stop', 'restart'].includes(cmd)) await loadDaemonCtl();
2400
+ else if (!FAST_PATHS.has(cmd)) await loadCore();
2481
2401
  switch (cmd) {
2482
2402
  case '--version':
2483
2403
  case '-V':
@@ -2486,15 +2406,17 @@ process.on('unhandledRejection', (e) => {
2486
2406
  case '-h':
2487
2407
  case 'help': help(); break;
2488
2408
  // `setup` and `install` are aliases as of v0.7: both register hooks AND
2489
- // the Windows startup entry. Older behavior split them (setup = no
2490
- // startup, install = with) but in practice users expect one command
2491
- // to do everything. Non-Windows: addStartupEntry is a no-op + warning.
2409
+ // the login autostart entry (Windows Run key, macOS LaunchAgent, Linux
2410
+ // systemd --user unit). Older behavior split them (setup = no startup,
2411
+ // install = with) but in practice users expect one command to do
2412
+ // everything. Other platforms skip autostart with an info row.
2492
2413
  case 'setup':
2493
2414
  case 'install': {
2494
2415
  // runInstall prints the phased checklist (or a one-line "already set
2495
2416
  // up" on clean re-runs); the daemon row lands after it, then setupOutro
2496
2417
  // closes the screen — only when something actually changed.
2497
- const { target, changed } = await runInstall({ exePath: EXE_PATH || process.execPath });
2418
+ const { install: runInstall, setupOutro } = await import('./install.js');
2419
+ const { target, changed, cli } = await runInstall({ exePath: EXE_PATH || process.execPath });
2498
2420
  // Slimmer first run: bring the daemon up now so the card appears
2499
2421
  // immediately, instead of making the user run a separate `start`.
2500
2422
  // Best-effort — a start hiccup must never make `setup` look failed.
@@ -2511,6 +2433,7 @@ process.on('unhandledRejection', (e) => {
2511
2433
  // pops it as a visible Windows Terminal window whose closure kills
2512
2434
  // the daemon.
2513
2435
  if (!daemonAlive()) {
2436
+ const { spawn, spawnSync } = await import('node:child_process');
2514
2437
  let script = null;
2515
2438
  try {
2516
2439
  const r = spawnSync('npm', ['root', '-g'], {
@@ -2547,13 +2470,11 @@ process.on('unhandledRejection', (e) => {
2547
2470
  // best-effort-loud: a failure explains itself but never rolls back the
2548
2471
  // completed install above.
2549
2472
  {
2550
- const argv = process.argv.slice(3);
2551
- const linkAt = argv.indexOf('--link');
2552
- const linkCode = linkAt !== -1 ? (argv[linkAt + 1] || '').trim() : null;
2473
+ const linkAt = args.indexOf('--link');
2474
+ const linkCode = linkAt !== -1 ? (args[linkAt + 1] || '').trim() : null;
2553
2475
  if (linkCode) {
2554
2476
  console.log('');
2555
- await doLink([linkCode]);
2556
- if (process.exitCode) break; // link failed — its own message + hint already printed
2477
+ await doLink([linkCode]); // a failed link exits via fail() with its own message + hint
2557
2478
  console.log(` ${c.dim}first scan — counting your history…${c.reset}`);
2558
2479
  doScan(false);
2559
2480
  const { flushProfile } = await import('./community.js');
@@ -2561,35 +2482,35 @@ process.on('unhandledRejection', (e) => {
2561
2482
  if (flushed.ok) {
2562
2483
  console.log(` ${c.green}✓${c.reset} profile published — ${c.cyan}${fmtNum(flushed.totals.tokens)}${c.reset} tokens on the board`);
2563
2484
  }
2564
- if (argv.includes('--wrapped')) await doWrappedPublish(['--yes']);
2565
- } else if (argv.includes('--wrapped')) {
2485
+ if (args.includes('--wrapped')) await doWrappedPublish(['--yes']);
2486
+ } else if (args.includes('--wrapped')) {
2566
2487
  console.log(` ${c.yellow}!${c.reset} --wrapped needs a profile — pair it with --link <code>, or run \`claude-rpc wrapped --publish\` after setup`);
2567
2488
  }
2568
2489
  // Optional GitHub connect — one explicit y/N, asked at most once ever.
2569
2490
  // The --link path above IS a connect, so it never double-asks.
2570
2491
  if (!linkCode) await setupGhConnect();
2571
2492
  }
2572
- setupOutro(target, changed);
2493
+ setupOutro(target, changed, cli);
2573
2494
  break;
2574
2495
  }
2575
- case 'uninstall': await runUninstall(); break;
2496
+ case 'uninstall': await (await import('./install.js')).uninstall(); break;
2576
2497
  case 'upgrade-config':
2577
- if (!migrateConfig()) console.log(` ${c.green}✓${c.reset} config already current — nothing to migrate`);
2498
+ if (!(await import('./install.js')).migrateConfig()) console.log(` ${c.green}✓${c.reset} config already current — nothing to migrate`);
2578
2499
  break;
2579
2500
  case 'start': if (startDaemon()) await confirmDaemonUp(); break;
2580
2501
  case 'stop': stopDaemon(); break;
2581
- case 'restart': restartDaemon(); break;
2502
+ case 'restart': if (await restartDaemon()) await confirmDaemonUp(); break;
2582
2503
  case 'status': {
2583
- const dumpFlag = process.argv.slice(3).some((a) => a === '--dump' || a === '-d');
2584
- if (dumpFlag || !process.stdout.isTTY) showStatus();
2585
- else startTui();
2504
+ const dumpFlag = args.some((a) => a === '--dump' || a === '-d');
2505
+ if (dumpFlag || !process.stdout.isTTY) await showStatus();
2506
+ else (await import('./tui.js')).startTui();
2586
2507
  break;
2587
2508
  }
2588
- case 'dump': showStatus(); break;
2589
- case 'today': showToday(); break;
2590
- case 'week': showWeek(); break;
2591
- case 'projects': showProjects(process.argv.slice(3)); break;
2592
- case 'project': showProject(process.argv[3]); break;
2509
+ case 'dump': await showStatus(); break;
2510
+ case 'today': await showToday(); break;
2511
+ case 'week': await showWeek(); break;
2512
+ case 'projects': showProjects(args); break;
2513
+ case 'project': showProject(args[0]); break;
2593
2514
  case 'compare': showCompare(); break;
2594
2515
  case 'usage': await showUsage(); break;
2595
2516
  case 'serve': await import('./server/index.js'); break;
@@ -2597,37 +2518,37 @@ process.on('unhandledRejection', (e) => {
2597
2518
  case 'vars': dumpVars(); break;
2598
2519
  case 'scan': doScan(false); break;
2599
2520
  case 'rescan': doScan(true); break;
2600
- case 'backfill': doBackfill(process.argv.slice(3)); break;
2601
- case 'insights': showInsights(); break;
2602
- case 'recap': await doRecap(process.argv.slice(3)); break;
2603
- case 'badge': await doBadge(process.argv.slice(3)); break;
2604
- case 'card': await doCard(process.argv.slice(3)); break;
2605
- case 'github-stat': await doGithubStat(process.argv.slice(3)); break;
2606
- case 'statusline': doStatusline(process.argv.slice(3)); break;
2607
- case 'calendar': await doCalendar(process.argv.slice(3)); break;
2608
- case 'session-card': await doSessionCard(process.argv.slice(3)); break;
2609
- case 'readme': doReadme(process.argv.slice(3)); break;
2521
+ case 'backfill': doBackfill(args); break;
2522
+ case 'insights': await showInsights(); break;
2523
+ case 'recap': await doRecap(args); break;
2524
+ case 'badge': await doBadge(args); break;
2525
+ case 'card': await doCard(args); break;
2526
+ case 'github-stat': await doGithubStat(args); break;
2527
+ case 'statusline': doStatusline(args); break;
2528
+ case 'calendar': await doCalendar(args); break;
2529
+ case 'session-card': await doSessionCard(args); break;
2530
+ case 'readme': doReadme(args); break;
2610
2531
  case 'mcp': {
2611
- const sub = process.argv[3];
2612
- if (sub === 'install') { doMcpInstall(process.argv.slice(4)); break; }
2613
- if (sub === 'uninstall') { doMcpUninstall(process.argv.slice(4)); break; }
2532
+ const sub = args[0];
2533
+ if (sub === 'install') { await doMcpInstall(args.slice(1)); break; }
2534
+ if (sub === 'uninstall') { await doMcpUninstall(args.slice(1)); break; }
2614
2535
  await doMcp();
2615
2536
  break;
2616
2537
  }
2617
2538
  case 'wrapped':
2618
- if (process.argv.slice(3).includes('--publish')) { await doWrappedPublish(process.argv.slice(3)); break; }
2539
+ if (args.includes('--publish')) { await doWrappedPublish(args); break; }
2619
2540
  process.env.CLAUDE_RPC_OPEN_PATH = '/wrapped'; await import('./server/index.js'); break;
2620
- case 'pause': doPause(process.argv.slice(3)); break;
2541
+ case 'pause': await doPause(args); break;
2621
2542
  case 'resume':
2622
- case 'unpause': doResume(); break;
2623
- case 'export': await doExport(process.argv.slice(3)); break;
2624
- case 'private': doPrivate(); break;
2625
- case 'public': doPublic(); break;
2626
- case 'privacy': doPrivacy(); break;
2627
- case 'community': await doCommunity(process.argv.slice(3)); break;
2628
- case 'profile': await doProfile(process.argv.slice(3)); break;
2629
- case 'squad': await doSquadCmd(process.argv.slice(3)); break;
2630
- case 'link': await doLink(process.argv.slice(3)); break;
2543
+ case 'unpause': await doResume(); break;
2544
+ case 'export': await doExport(args); break;
2545
+ case 'private': await doPrivate(); break;
2546
+ case 'public': await doPublic(); break;
2547
+ case 'privacy': await doPrivacy(); break;
2548
+ case 'community': await doCommunity(args); break;
2549
+ case 'profile': await doProfile(args); break;
2550
+ case 'squad': await doSquadCmd(args); break;
2551
+ case 'link': await doLink(args); break;
2631
2552
  case 'doctor': {
2632
2553
  const { runDoctor, fixPlan } = await import('./doctor.js');
2633
2554
  const fix = process.argv.includes('--fix');
@@ -2647,13 +2568,13 @@ process.on('unhandledRejection', (e) => {
2647
2568
  for (const kind of plan) {
2648
2569
  try {
2649
2570
  if (kind === 'setup') {
2650
- await runInstall({ exePath: EXE_PATH || process.execPath });
2571
+ await (await import('./install.js')).install({ exePath: EXE_PATH || process.execPath });
2651
2572
  console.log(` ${c.green}✓${c.reset} config + hooks repaired`);
2652
2573
  } else if (kind === 'rescan') {
2653
2574
  doScan(true);
2654
2575
  console.log(` ${c.green}✓${c.reset} aggregate rebuilt from transcripts`);
2655
2576
  } else if (kind === 'daemon') {
2656
- restartDaemon();
2577
+ await restartDaemon();
2657
2578
  restarted = true;
2658
2579
  console.log(` ${c.green}✓${c.reset} daemon (re)starting`);
2659
2580
  } else if (kind === 'discord') {
@@ -2665,22 +2586,23 @@ process.on('unhandledRejection', (e) => {
2665
2586
  }
2666
2587
  // A 'setup' rewire only takes effect once the daemon reloads, so ensure a
2667
2588
  // restart even if the daemon wasn't itself flagged.
2668
- if (plan.includes('setup') && !restarted) restartDaemon();
2589
+ if (plan.includes('setup') && !restarted) await restartDaemon();
2669
2590
  console.log(` ${c.dim}run ${c.cyan}claude-rpc doctor${c.reset}${c.dim} again in a few seconds to confirm.${c.reset}`);
2670
- break; // let the restart timer fire before the process drains
2591
+ break;
2671
2592
  }
2672
2593
  case 'tail':
2673
2594
  case 'logs':
2674
2595
  case 'log': tailLog(); break;
2675
- case 'hook': runHookCli(process.argv[3] || 'unknown'); break;
2596
+ case 'hook': (await import('./hook.js')).runHookCli(args[0] || 'unknown'); break;
2676
2597
  case 'daemon': await import('./daemon.js'); break;
2677
2598
  case 'scan-worker': (await import('./scan-worker.js')).runScanWorker(process.argv.includes('--force')); break;
2678
2599
  default: {
2679
2600
  if (packagedDefault) {
2601
+ const { isInstalled, install: runInstall, setupOutro, ensureCanonicalExe, migrateConfig, installHooks } = await import('./install.js');
2680
2602
  if (!isInstalled()) {
2681
- const { target } = await runInstall({ exePath: EXE_PATH || process.execPath });
2603
+ const { target, cli } = await runInstall({ exePath: EXE_PATH || process.execPath });
2682
2604
  startDaemon();
2683
- setupOutro(target);
2605
+ setupOutro(target, true, cli);
2684
2606
  } else {
2685
2607
  // Self-heal an existing install. Two real failure modes this fixes:
2686
2608
  //
@@ -2725,10 +2647,15 @@ process.on('unhandledRejection', (e) => {
2725
2647
  // Version in the hint is deliberate: the #1 cause of "unknown
2726
2648
  // command" in the wild is a stale global install resolving instead of
2727
2649
  // the version the user read the docs for. Make the skew visible.
2650
+ // The update command depends on how this copy was installed.
2651
+ const update = IS_PACKAGED ? 'download the latest release from https://github.com/rar-file/claude-rpc/releases/latest'
2652
+ : IS_NPX ? `npx claude-rpc@latest ${cmd}`
2653
+ : /[\\/]Cellar[\\/]/.test(DAEMON_SCRIPT) ? 'brew upgrade claude-rpc'
2654
+ : 'npm install -g claude-rpc@latest';
2728
2655
  fail(`unknown command: ${cmd}`, {
2729
2656
  hint: [
2730
2657
  'run `claude-rpc --help` for the full command list',
2731
- `this install is v${VERSION} — if the docs mention \`${cmd}\`, update first: npm install -g claude-rpc@latest`,
2658
+ `this install is v${VERSION} — if the docs mention \`${cmd}\`, update first: ${update}`,
2732
2659
  ],
2733
2660
  code: EX_USER_ERROR,
2734
2661
  });