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/install.js CHANGED
@@ -1,11 +1,13 @@
1
- // One-shot installer logic invoked by the bundled exe.
2
- // Seeds %APPDATA%\claude-rpc\config.json, points Claude Code's hooks at the
3
- // exe, and registers a Windows startup entry so the daemon comes up on login.
1
+ // Installer logic behind `claude-rpc setup` (packaged exe, npm and dev
2
+ // installs alike). Seeds config.json under USER_CONFIG_DIR (or the repo in dev
3
+ // mode), points Claude Code's hooks at this install, and registers a login
4
+ // autostart entry — Windows Run key, macOS LaunchAgent, Linux systemd --user
5
+ // unit — so the daemon comes up on login.
4
6
 
5
7
  import {
6
8
  existsSync, mkdirSync, readFileSync, writeFileSync,
7
9
  copyFileSync, chmodSync, renameSync, statSync,
8
- readdirSync, unlinkSync,
10
+ readdirSync, unlinkSync, openSync, readSync, closeSync,
9
11
  } from 'node:fs';
10
12
  import { dirname, join, resolve } from 'node:path';
11
13
  import { homedir } from 'node:os';
@@ -15,7 +17,7 @@ import {
15
17
  CLAUDE_SETTINGS, CONFIG_PATH, USER_CONFIG_DIR, ROOT,
16
18
  HOOK_SCRIPT, IS_PACKAGED, IS_NPM_INSTALL, IS_NPX,
17
19
  CANONICAL_EXE, CANONICAL_INSTALL_DIR, CANONICAL_EXE_NAME, VERSION_STAMP,
18
- DAEMON_SCRIPT,
20
+ DAEMON_SCRIPT, CLAUDE_PROJECTS,
19
21
  } from './paths.js';
20
22
  import { DEFAULT_CONFIG } from './default-config.js';
21
23
  import { VERSION } from './version.js';
@@ -61,11 +63,77 @@ export const EVENTS = [
61
63
  ];
62
64
 
63
65
  // Wired `"async": true`: Claude Code runs them in the background instead of
64
- // blocking every tool call on a node cold start (~90ms each, two per call).
66
+ // blocking every tool call on a node cold start (~60–90ms wall per event
67
+ // including Node startup, two per call).
65
68
  // Presence never feeds anything back to Claude, so nothing waits on them;
66
69
  // hook.js orders late arrivals by process start time. The once-per-turn events
67
70
  // stay synchronous so status transitions (prompt → Stop) are always ordered.
68
- export const ASYNC_EVENTS = new Set(['PreToolUse', 'PostToolUse']);
71
+ export const ASYNC_EVENTS = new Set(['PreToolUse', 'PostToolUse', 'PostToolUseFailure']);
72
+
73
+ // Hook events newer Claude Code versions added, with the first version that has
74
+ // each. An event name a Claude Code version doesn't know makes it reject the
75
+ // WHOLE hooks block (every hook in settings.json, the user's own too: checked
76
+ // on 2.0.0), so each is wired only once the installed Claude Code is known to
77
+ // support it, and unwired again if it isn't.
78
+ export const OPTIONAL_EVENTS = {
79
+ PostToolUseFailure: '2.0.56', // a failed tool call never fires PostToolUse
80
+ PostCompact: '2.1.76',
81
+ StopFailure: '2.1.78', // a turn that ends on an API error never fires Stop
82
+ };
83
+
84
+ export function versionAtLeast(v, min) {
85
+ const a = String(v || '').split('.').map(Number);
86
+ const b = String(min).split('.').map(Number);
87
+ for (let i = 0; i < 3; i++) {
88
+ if ((a[i] || 0) !== (b[i] || 0)) return (a[i] || 0) > (b[i] || 0);
89
+ }
90
+ return true;
91
+ }
92
+
93
+ // The Claude Code version from the newest transcript (every line carries
94
+ // "version"). Reading it off disk works where `claude --version` doesn't: the
95
+ // daemon's PATH often has no `claude`. Null when there's no transcript yet.
96
+ export function detectClaudeCodeVersion({ projectsDir = CLAUDE_PROJECTS } = {}) {
97
+ let newest = null;
98
+ let newestMtime = -1;
99
+ let projects;
100
+ try { projects = readdirSync(projectsDir); } catch { return null; }
101
+ for (const proj of projects) {
102
+ let files;
103
+ try { files = readdirSync(join(projectsDir, proj)); } catch { continue; }
104
+ for (const f of files) {
105
+ if (!f.endsWith('.jsonl')) continue;
106
+ try {
107
+ const m = statSync(join(projectsDir, proj, f)).mtimeMs;
108
+ if (m > newestMtime) { newestMtime = m; newest = join(projectsDir, proj, f); }
109
+ } catch { /* vanished mid-walk */ }
110
+ }
111
+ }
112
+ if (!newest) return null;
113
+ try {
114
+ const size = statSync(newest).size;
115
+ const len = Math.min(size, 65536);
116
+ const buf = Buffer.alloc(len);
117
+ const fd = openSync(newest, 'r');
118
+ try { readSync(fd, buf, 0, len, size - len); } finally { closeSync(fd); }
119
+ const all = [...buf.toString('utf8').matchAll(/"version":"(\d+\.\d+\.\d+)"/g)];
120
+ return all.length ? all[all.length - 1][1] : null;
121
+ } catch { return null; }
122
+ }
123
+
124
+ export function supportedOptionalEvents(ccVersion) {
125
+ if (!ccVersion) return [];
126
+ return Object.keys(OPTIONAL_EVENTS).filter((e) => versionAtLeast(ccVersion, OPTIONAL_EVENTS[e]));
127
+ }
128
+
129
+ function removeOurHooks(settings, event) {
130
+ const bucket = settings.hooks[event];
131
+ if (!Array.isArray(bucket)) return;
132
+ settings.hooks[event] = bucket
133
+ .map((entry) => ({ ...entry, hooks: (entry.hooks || []).filter((h) => !isOurHook(h)) }))
134
+ .filter((entry) => (entry.hooks || []).length > 0);
135
+ if (settings.hooks[event].length === 0) delete settings.hooks[event];
136
+ }
69
137
 
70
138
  function readJson(p, fb) {
71
139
  try { return JSON.parse(readFileSync(p, 'utf8')); }
@@ -93,15 +161,13 @@ export function isOurHook(h) {
93
161
  return !!h && (h._claudeRpc === true || isOurHookCommand(h.command));
94
162
  }
95
163
 
96
- export function installHooks(exePath, { silent = false } = {}) {
164
+ export function installHooks(exePath, { silent = false, ccVersion = detectClaudeCodeVersion() } = {}) {
97
165
  const settings = readJson(CLAUDE_SETTINGS, {});
98
166
  const before = JSON.stringify(settings.hooks || {});
99
167
  settings.hooks = settings.hooks || {};
100
- // Three modes, three shapes:
101
- // packaged → `"<exe>" hook <event>` (canonical exe, no node)
102
- // npm → `claude-rpc hook <event>` (bin shim resolves through PATH;
103
- // survives `npm update` and nvm version switches)
104
- // dev → `node "<src/hook.js>" <event>` (cloned-source iteration)
168
+ // Two shapes:
169
+ // packaged → `"<exe>" hook <event>` (canonical exe, no node)
170
+ // npm / dev → `"<abs node>" "<abs src/hook.js>" <event>`
105
171
  // Hook commands must resolve under Claude Code's hook shell — `/bin/sh` with a
106
172
  // minimal PATH that, under nvm, has neither `claude-rpc` nor `node` on it (no
107
173
  // system node). So use the ABSOLUTE node (process.execPath) + absolute hook.js
@@ -113,7 +179,12 @@ export function installHooks(exePath, { silent = false } = {}) {
113
179
  ? (event) => `"${exePath}" hook ${event}`
114
180
  : (event) => `"${node}" "${HOOK_SCRIPT.replace(/\\/g, '/')}" ${event}`;
115
181
 
116
- for (const event of EVENTS) {
182
+ const optional = supportedOptionalEvents(ccVersion);
183
+ for (const event of Object.keys(OPTIONAL_EVENTS)) {
184
+ if (!optional.includes(event)) removeOurHooks(settings, event);
185
+ }
186
+ const events = [...EVENTS, ...optional];
187
+ for (const event of events) {
117
188
  const bucket = settings.hooks[event] = settings.hooks[event] || [];
118
189
  const wanted = cmdFor(event);
119
190
  const shape = (h) => {
@@ -134,25 +205,18 @@ export function installHooks(exePath, { silent = false } = {}) {
134
205
  }
135
206
  }
136
207
  if (JSON.stringify(settings.hooks) === before) {
137
- if (!silent) noop(`hooks wired (${EVENTS.length} events)`);
208
+ if (!silent) noop(`hooks wired (${events.length} events)`);
138
209
  return false;
139
210
  }
140
211
  writeJson(CLAUDE_SETTINGS, settings);
141
- if (!silent) dirtyStep(SYM_OK, 'hooks wired', `${EVENTS.length} events → ${CLAUDE_SETTINGS}`);
212
+ if (!silent) dirtyStep(SYM_OK, 'hooks wired', `${events.length} events → ${CLAUDE_SETTINGS}`);
142
213
  return true;
143
214
  }
144
215
 
145
216
  export function uninstallHooks() {
146
217
  const settings = readJson(CLAUDE_SETTINGS, {});
147
218
  if (!settings.hooks) return;
148
- for (const event of EVENTS) {
149
- const bucket = settings.hooks[event];
150
- if (!Array.isArray(bucket)) continue;
151
- settings.hooks[event] = bucket
152
- .map((entry) => ({ ...entry, hooks: (entry.hooks || []).filter((h) => !isOurHook(h)) }))
153
- .filter((entry) => (entry.hooks || []).length > 0);
154
- if (settings.hooks[event].length === 0) delete settings.hooks[event];
155
- }
219
+ for (const event of [...EVENTS, ...Object.keys(OPTIONAL_EVENTS)]) removeOurHooks(settings, event);
156
220
  writeJson(CLAUDE_SETTINGS, settings);
157
221
  step(SYM_OK, 'hooks removed', CLAUDE_SETTINGS);
158
222
  }
@@ -184,6 +248,12 @@ function daemonLaunch(exePath) {
184
248
  return { exe: process.execPath, args: [DAEMON_SCRIPT] };
185
249
  }
186
250
 
251
+ // `npm` with the flags every call here needs: npm is npm.cmd on Windows (so a
252
+ // shell), and windowsHide so it doesn't flash a console window.
253
+ function npmSync(args, opts = {}) {
254
+ return spawnSync('npm', args, { encoding: 'utf8', windowsHide: true, shell: process.platform === 'win32', ...opts });
255
+ }
256
+
187
257
  function xmlEscape(s) { return String(s).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;'); }
188
258
  function systemctlUser(args) {
189
259
  try { return spawnSync('systemctl', ['--user', ...args], { stdio: 'ignore' }); }
@@ -249,16 +319,21 @@ export function systemdUnit({ exe, args }) {
249
319
  ].join('\n');
250
320
  }
251
321
 
252
- // ── macOS: launchd LaunchAgent (per-user, starts at login) ────────────────────
253
- function addStartupEntryMac(exePath) {
254
- const plist = launchdPlist(daemonLaunch(exePath));
322
+ // Write a login-autostart file; false (after a warning row) when it can't be.
323
+ function writeStartupFile(path, content, what) {
255
324
  try {
256
- mkdirSync(dirname(LAUNCHD_PLIST), { recursive: true });
257
- writeFileSync(LAUNCHD_PLIST, plist);
325
+ mkdirSync(dirname(path), { recursive: true });
326
+ writeFileSync(path, content);
327
+ return true;
258
328
  } catch (e) {
259
- step(SYM_WARN, 'startup entry', `couldn't write LaunchAgent (${e.message}) — the session self-heal still starts the daemon`, console.warn);
260
- return;
329
+ step(SYM_WARN, 'startup entry', `couldn't write ${what} (${e.message}) — the session self-heal still starts the daemon`, console.warn);
330
+ return false;
261
331
  }
332
+ }
333
+
334
+ // ── macOS: launchd LaunchAgent (per-user, starts at login) ────────────────────
335
+ function addStartupEntryMac(exePath) {
336
+ if (!writeStartupFile(LAUNCHD_PLIST, launchdPlist(daemonLaunch(exePath)), 'LaunchAgent')) return;
262
337
  // Load so it's active now and at every login. `load -w` is deprecated but
263
338
  // portable across the macOS versions we target; a failure is non-fatal — the
264
339
  // plist alone starts it next login, and SessionStart self-heal covers the gap.
@@ -275,14 +350,7 @@ function removeStartupEntryMac() {
275
350
 
276
351
  // ── Linux: systemd --user service (starts at login) ───────────────────────────
277
352
  function addStartupEntryLinux(exePath) {
278
- const unit = systemdUnit(daemonLaunch(exePath));
279
- try {
280
- mkdirSync(dirname(SYSTEMD_UNIT), { recursive: true });
281
- writeFileSync(SYSTEMD_UNIT, unit);
282
- } catch (e) {
283
- step(SYM_WARN, 'startup entry', `couldn't write systemd unit (${e.message}) — the session self-heal still starts the daemon`, console.warn);
284
- return;
285
- }
353
+ if (!writeStartupFile(SYSTEMD_UNIT, systemdUnit(daemonLaunch(exePath)), 'systemd unit')) return;
286
354
  // Enable + start now. Non-fatal if there's no systemd --user session (some
287
355
  // containers / minimal WSL): the SessionStart self-heal still brings it up.
288
356
  systemctlUser(['daemon-reload']);
@@ -397,8 +465,10 @@ export function ensureCanonicalExe(currentExe) {
397
465
  try {
398
466
  // Windows won't let you overwrite a currently-executing file. If
399
467
  // canonical is the running daemon, move it aside first — that succeeds
400
- // even while the file handle is open, and Windows will delete the
401
- // renamed copy when the process exits.
468
+ // even while the file handle is open. Windows does NOT delete the renamed
469
+ // copy when the process exits; sweepStaleCanonicalBackups after the copy
470
+ // removes every `.old-<ts>` that's no longer locked, so a copy still held
471
+ // by the running daemon goes on the next replacement.
402
472
  if (process.platform === 'win32' && existsSync(CANONICAL_EXE)) {
403
473
  try { renameSync(CANONICAL_EXE, CANONICAL_EXE + '.old-' + Date.now()); }
404
474
  catch { /* not running, no rename needed — copyFileSync below will just overwrite */ }
@@ -456,14 +526,6 @@ export function seedConfig() {
456
526
  return true;
457
527
  }
458
528
 
459
- // Non-destructive merge of any new top-level keys / presence blocks the
460
- // shipped DEFAULT_CONFIG has but the user's existing file doesn't.
461
- //
462
- // Runs every time install/setup or the packaged default launcher fires,
463
- // so an upgraded exe pulls in new shape (e.g. v0.3.6's presence.byStatus)
464
- // without clobbering the user's customizations. Anything the user already
465
- // has — including a pre-existing byStatus, custom rotation array, custom
466
- // appName etc. — is left untouched.
467
529
  // How Claude Code should invoke the MCP server — same three-mode resolution
468
530
  // as the hook commands (packaged exe / npm bin / dev source).
469
531
  export function mcpServerCommand(exePath) {
@@ -493,6 +555,14 @@ export function uninstallMcp({ scope = 'user' } = {}) {
493
555
  return { ok: r.status === 0 };
494
556
  }
495
557
 
558
+ // Non-destructive merge of any new top-level keys / presence blocks the
559
+ // shipped DEFAULT_CONFIG has but the user's existing file doesn't.
560
+ //
561
+ // Runs every time install/setup or the packaged default launcher fires,
562
+ // so an upgraded exe pulls in new shape (e.g. v0.3.6's presence.byStatus)
563
+ // without clobbering the user's customizations. Anything the user already
564
+ // has — including a pre-existing byStatus, custom rotation array, custom
565
+ // appName etc. — is left untouched.
496
566
  export function migrateConfig({ silent = false } = {}) {
497
567
  if (!existsSync(CONFIG_PATH)) return false;
498
568
  let cfg;
@@ -535,17 +605,15 @@ export function migrateConfig({ silent = false } = {}) {
535
605
  // "Bash · · 0 tokens" on the card. New default uses `{tokensLabel}` which is
536
606
  // empty until tokens > 0, and fillTemplate now collapses adjacent separators.
537
607
  // Migrate only the verbatim old template — leave anything the user customized.
538
- const OLD_WORKING = '{currentToolPretty} · {currentFilePretty} · {tokensFmt} tokens';
539
- const OLD_THINKING = '{modelPretty} · {messagesLabel} · {tokensFmt} tokens';
540
- if (cfg.presence.byStatus?.working?.state === OLD_WORKING &&
541
- DEFAULT_CONFIG.presence?.byStatus?.working?.state) {
542
- cfg.presence.byStatus.working.state = DEFAULT_CONFIG.presence.byStatus.working.state;
543
- added.push('presence.byStatus.working.state');
544
- }
545
- if (cfg.presence.byStatus?.thinking?.state === OLD_THINKING &&
546
- DEFAULT_CONFIG.presence?.byStatus?.thinking?.state) {
547
- cfg.presence.byStatus.thinking.state = DEFAULT_CONFIG.presence.byStatus.thinking.state;
548
- added.push('presence.byStatus.thinking.state');
608
+ for (const [status, old] of [
609
+ ['working', '{currentToolPretty} · {currentFilePretty} · {tokensFmt} tokens'],
610
+ ['thinking', '{modelPretty} · {messagesLabel} · {tokensFmt} tokens'],
611
+ ]) {
612
+ const next = DEFAULT_CONFIG.presence?.byStatus?.[status]?.state;
613
+ if (cfg.presence.byStatus?.[status]?.state === old && next) {
614
+ cfg.presence.byStatus[status].state = next;
615
+ added.push(`presence.byStatus.${status}.state`);
616
+ }
549
617
  }
550
618
 
551
619
  // v1.4.3: setup's "connect GitHub?" y could die on a server error (the
@@ -673,12 +741,6 @@ function verifyHookPipe(exePath) {
673
741
  return { ok: true, detail: 'SessionStart round-trip succeeded' };
674
742
  }
675
743
 
676
- // `npx claude-rpc setup` runs from npm's throwaway _npx cache, so the
677
- // `claude-rpc` bin the hooks resolve through PATH disappears the moment npx
678
- // exits. Promote to a real global install first, then the rest of setup wires
679
- // hooks to the now-persistent global bin exactly like a normal npm install.
680
- // Best-effort + loud: a failed -g (perms, offline) returns false so the caller
681
- // can stop with the manual command rather than wire a dead hook.
682
744
  // Version of the GLOBALLY-installed claude-rpc, read straight off disk via
683
745
  // `npm root -g` — NOT through PATH. While setup runs under `npx
684
746
  // claude-rpc@latest`, npx prepends its own throwaway cache (the current
@@ -688,10 +750,7 @@ function verifyHookPipe(exePath) {
688
750
  // nothing). Reading the global package.json sidesteps that PATH shadowing.
689
751
  function globalInstalledVersion() {
690
752
  try {
691
- const r = spawnSync('npm', ['root', '-g'], {
692
- encoding: 'utf8', timeout: 4000, windowsHide: true,
693
- shell: process.platform === 'win32', // npm is npm.cmd on Windows
694
- });
753
+ const r = npmSync(['root', '-g'], { timeout: 4000 });
695
754
  const root = (r.stdout || '').trim();
696
755
  if (!root) return null;
697
756
  const pkg = JSON.parse(readFileSync(join(root, 'claude-rpc', 'package.json'), 'utf8'));
@@ -699,6 +758,15 @@ function globalInstalledVersion() {
699
758
  } catch { return null; } // not installed / npm missing / unreadable
700
759
  }
701
760
 
761
+ // `npx claude-rpc setup` runs from npm's _npx cache, which npm may evict at
762
+ // any time, so first install the same version globally (`npm install -g`).
763
+ // Best-effort + loud: a failed -g (perms, offline) returns false so the caller
764
+ // stops with the manual command. What happens next: the rest of setup still
765
+ // runs in THIS process, so installHooks and addStartupEntry wire the cache
766
+ // copy's absolute HOOK_SCRIPT / DAEMON_SCRIPT paths; only the daemon launch
767
+ // (cli.js `setup`) explicitly runs the global copy. That global daemon's
768
+ // selfHealOnUpdate then re-wires hooks + autostart to the global paths — but
769
+ // only when the version stamp doesn't already match this version.
702
770
  function promoteNpxToGlobal() {
703
771
  // Already promoted on a previous run AND current? Skip the redundant -g (also
704
772
  // lets setup succeed when a correct global exists but `npm -g` would fail —
@@ -707,11 +775,7 @@ function promoteNpxToGlobal() {
707
775
  noop('global install current');
708
776
  return true;
709
777
  }
710
- const r = spawnSync('npm', ['install', '-g', `claude-rpc@${VERSION}`], {
711
- encoding: 'utf8',
712
- shell: process.platform === 'win32', // npm is npm.cmd on Windows
713
- windowsHide: true, // don't flash a console window
714
- });
778
+ const r = npmSync(['install', '-g', `claude-rpc@${VERSION}`]);
715
779
  if (r.error || r.status !== 0) {
716
780
  // The piped npm chatter only matters when it failed.
717
781
  if (r.stdout) process.stderr.write(r.stdout);
@@ -729,11 +793,7 @@ function promoteNpxToGlobal() {
729
793
  // clue why. Warn loudly up front; never block setup on it (offline is fine).
730
794
  function warnIfStale() {
731
795
  try {
732
- const r = spawnSync('npm', ['view', 'claude-rpc', 'version'], {
733
- encoding: 'utf8', timeout: 4000,
734
- shell: process.platform === 'win32', // npm is npm.cmd on Windows
735
- windowsHide: true, // don't flash a console window
736
- });
796
+ const r = npmSync(['view', 'claude-rpc', 'version'], { timeout: 4000 });
737
797
  const latest = (r.stdout || '').trim();
738
798
  if (!latest || latest === VERSION) return;
739
799
  const num = (v) => v.split('.').map((n) => parseInt(n, 10) || 0);
@@ -756,9 +816,17 @@ function warnIfStale() {
756
816
  // version. Best-effort and quiet by default; never throws into the caller.
757
817
  // Returns { changed, from, rewired }.
758
818
  export function selfHealOnUpdate({ exePath = null, silent = true } = {}) {
819
+ // Stamp = our version, plus (line 2) the optional hook events last wired, so
820
+ // a Claude Code update that unlocks a new event re-wires too.
759
821
  let from = null;
760
- try { from = (readFileSync(VERSION_STAMP, 'utf8') || '').trim() || null; } catch { /* first run / unreadable — treat as needing a heal */ }
761
- if (from === VERSION) return { changed: false, from, rewired: false };
822
+ let fromHooks = '';
823
+ try {
824
+ const [v, h] = (readFileSync(VERSION_STAMP, 'utf8') || '').trim().split('\n');
825
+ from = (v || '').trim() || null;
826
+ fromHooks = (h || '').trim();
827
+ } catch { /* first run / unreadable — treat as needing a heal */ }
828
+ const hooksLine = 'hooks:' + supportedOptionalEvents(detectClaudeCodeVersion()).join(',');
829
+ if (from === VERSION && fromHooks === hooksLine) return { changed: false, from, rewired: false };
762
830
  const exe = exePath || ((IS_PACKAGED && existsSync(CANONICAL_EXE)) ? CANONICAL_EXE : process.execPath);
763
831
  let rewired = false;
764
832
  try { rewired = installHooks(exe, { silent }); } catch { /* best-effort — a hook re-wire must never block daemon startup */ }
@@ -778,12 +846,12 @@ export function selfHealOnUpdate({ exePath = null, silent = true } = {}) {
778
846
  } catch { /* best-effort */ }
779
847
  try {
780
848
  mkdirSync(dirname(VERSION_STAMP), { recursive: true });
781
- writeFileSync(VERSION_STAMP, VERSION + '\n');
849
+ writeFileSync(VERSION_STAMP, VERSION + '\n' + hooksLine + '\n');
782
850
  } catch { /* unwritable — we'll just self-heal again next start, which is harmless (idempotent) */ }
783
851
  return { changed: true, from, rewired, autostart };
784
852
  }
785
853
 
786
- export async function install({ exePath, withStartup = true } = {}) {
854
+ export async function install({ exePath } = {}) {
787
855
  resetRun();
788
856
  console.log('');
789
857
  console.log(` ${c.bold}${c.magenta}◆ claude-rpc setup${c.reset} ${c.dim}v${VERSION}${c.reset}`);
@@ -808,7 +876,9 @@ export async function install({ exePath, withStartup = true } = {}) {
808
876
  phase('config');
809
877
  // Order matters: seed creates the file if missing, then migrate fills in
810
878
  // any blocks new exe versions added (e.g. presence.byStatus from v0.3.6).
811
- seedConfig();
879
+ // A freshly seeded config carries a newly minted instanceId: record that it
880
+ // has reported nothing yet, so its first community flush sends the history.
881
+ if (seedConfig()) (await import('./community.js')).markCursorFresh();
812
882
  migrateConfig();
813
883
 
814
884
  phase('claude code');
@@ -829,34 +899,54 @@ export async function install({ exePath, withStartup = true } = {}) {
829
899
  // The CLI's setup case launches the daemon right after this returns, so its
830
900
  // row lands under this heading; setupOutro() then closes the screen.
831
901
  phase('daemon');
832
- if (withStartup) {
833
- // Cross-platform login autostart: Windows Run-key, macOS LaunchAgent, Linux
834
- // systemd --user. Best-effort — a failure leaves the SessionStart self-heal
835
- // as the (already reliable) fallback, so setup never fails on this.
836
- try { await addStartupEntry(target); }
837
- catch (e) { step(SYM_WARN, 'startup entry', `failed: ${e.message} — session self-heal still covers it`, console.warn); }
838
- }
902
+ // Cross-platform login autostart: Windows Run-key, macOS LaunchAgent, Linux
903
+ // systemd --user. Best-effort — a failure leaves the SessionStart self-heal
904
+ // as the (already reliable) fallback, so setup never fails on this.
905
+ try { await addStartupEntry(target); }
906
+ catch (e) { step(SYM_WARN, 'startup entry', `failed: ${e.message} — session self-heal still covers it`, console.warn); }
907
+ const cli = IS_PACKAGED ? await putCliOnPath(target) : { cmd: 'claude-rpc', newTerminal: false };
839
908
  // Nothing changed: the checklist above stayed silent, so say so in one line.
840
909
  if (!runDirty && probe.ok) {
841
910
  console.log(` ${SYM_OK} ${c.bold}already set up${c.reset} ${c.dim}${noopFacts.join(' · ')}${c.reset}`);
842
911
  }
843
- return { target, changed: runDirty };
912
+ return { target, changed: runDirty, cli };
913
+ }
914
+
915
+ // A packaged exe lives in <config dir>/bin, which no shell searches, so the
916
+ // `claude-rpc …` commands setup prints came back "command not found". npm and
917
+ // Homebrew installs are on PATH already. Best-effort: never fails setup, and
918
+ // the returned `cmd` is what actually works in this terminal.
919
+ async function putCliOnPath(target) {
920
+ const { ensureCliOnPath, pathExportHint } = await import('./cli-path.js');
921
+ const cli = ensureCliOnPath({ exe: target });
922
+ if (cli.status === 'added') dirtyStep(SYM_OK, 'on PATH', `${cli.detail} added to your user PATH — open a new terminal to use it`);
923
+ else if (cli.status === 'linked') dirtyStep(SYM_OK, 'on PATH', cli.detail);
924
+ else if (cli.status === 'needs-path') {
925
+ dirtyStep(SYM_WARN, 'on PATH', `${cli.detail}, but ~/.local/bin isn't on your PATH`);
926
+ hintLine(`add it for new terminals: ${pathExportHint()}`);
927
+ } else if (cli.status === 'failed') {
928
+ step(SYM_WARN, 'on PATH', `${cli.detail} — run it as ${cli.cmd}`, console.warn);
929
+ } else noop('on PATH');
930
+ return cli;
844
931
  }
845
932
 
846
933
  // The single closing block of `claude-rpc setup` — what to do now, where the
847
934
  // levers are. Printed by the CLI after the daemon launch so it always lands
848
935
  // last; doctor --fix re-runs install() without it.
849
- export function setupOutro(target, changed = true) {
936
+ // `cli` is install()'s report of how `claude-rpc` resolves; the commands shown
937
+ // use whatever actually works in this terminal.
938
+ export function setupOutro(target, changed = true, cli = { cmd: 'claude-rpc', newTerminal: false }) {
850
939
  if (!changed) return;
851
940
  const point = (label, value, note = '') =>
852
941
  console.log(` ${c.dim}→${c.reset} ${c.dim}${label.padEnd(14)}${c.reset} ${c.cyan}${value}${c.reset}${note ? ` ${c.dim}${note}${c.reset}` : ''}`);
942
+ const run = cli.cmd || 'claude-rpc';
853
943
  console.log('');
854
944
  console.log(` ${SYM_OK} ${c.bold}setup complete${c.reset} — open Claude Code and send a prompt; your card goes live in Discord.`);
855
- point('verify wiring', 'claude-rpc doctor');
945
+ point('verify wiring', `${run} doctor`, cli.newTerminal ? 'in a new terminal' : '');
856
946
  if (IS_PACKAGED) point('start daemon', `"${target}" daemon`, 'also runs automatically at login');
857
- else point('manage daemon', 'claude-rpc start · stop · status');
947
+ else point('manage daemon', `${run} start · stop · status`);
858
948
  point('config', CONFIG_PATH, 'a working Discord app is bundled — set clientId only to use your own');
859
- point('other machine?', 'claude-rpc link', 'run it there, claim the code here — one leaderboard profile');
949
+ point('other machine?', `${run} link`, 'run it there, claim the code here — one leaderboard profile');
860
950
  console.log('');
861
951
  }
862
952
 
@@ -866,6 +956,8 @@ export async function uninstall() {
866
956
  console.log('');
867
957
  uninstallHooks();
868
958
  await removeStartupEntry();
959
+ const { removeCliFromPath } = await import('./cli-path.js');
960
+ if (removeCliFromPath()) step(SYM_OK, 'PATH entry', 'removed');
869
961
  console.log('');
870
962
  console.log(` ${SYM_OK} ${c.bold}uninstalled${c.reset} — config at ${c.cyan}${USER_CONFIG_DIR}${c.reset} ${c.dim}left intact; delete it manually if you want.${c.reset}`);
871
963
  console.log('');
@@ -50,8 +50,9 @@ export function normalizeGithubUser(input) {
50
50
  }
51
51
 
52
52
  // The public identity fields a profile contributes to the board. Deliberately
53
- // tiny — identity only; usage stats are sent as server-validated deltas
54
- // separately, never trusted as a client-asserted total.
53
+ // tiny — identity only. Usage stats travel next to them in the /profile
54
+ // payload as absolute lifetime totals (community.buildProfilePayload), which
55
+ // the worker clamps to plausibility ceilings — client-asserted, not deltas.
55
56
  export function profileFields(profileCfg = {}) {
56
57
  return {
57
58
  handle: profileCfg.handle || null,
package/src/mcp.js CHANGED
@@ -10,16 +10,10 @@
10
10
  import { readAggregate, dayKey } from './scanner.js';
11
11
  import { buildRecap, renderRecapMarkdown } from './recap.js';
12
12
  import { VERSION } from './version.js';
13
+ import { fmtNum as fmtN } from './fmt.js';
13
14
 
15
+ // Not fmt.fmtHours: this keeps one decimal past 10h ("123.4h" lifetime totals).
14
16
  function fmtH(ms) { const h = (ms || 0) / 3_600_000; return h < 1 ? `${Math.round(h * 60)}m` : `${h.toFixed(1)}h`; }
15
- function fmtN(n) {
16
- if (!n) return '0';
17
- if (n < 1000) return String(Math.round(n));
18
- if (n < 1e6) return `${(n / 1e3).toFixed(1)}k`;
19
- if (n < 1e9) return `${(n / 1e6).toFixed(2)}M`;
20
- if (n < 1e12) return `${(n / 1e9).toFixed(2)}B`;
21
- return `${(n / 1e12).toFixed(2)}T`;
22
- }
23
17
 
24
18
  // ── Tool handlers — pure(aggregate) → string. Exported for tests. ──────────
25
19
  export const TOOLS = {
package/src/nudge.js CHANGED
@@ -12,9 +12,13 @@
12
12
 
13
13
  import { readFileSync, writeFileSync, mkdirSync } from 'node:fs';
14
14
  import { join, dirname } from 'node:path';
15
- import { STATE_DIR } from './paths.js';
15
+ import { DATA_DIR, STATE_DIR } from './paths.js';
16
+ import { adoptLegacyFile } from './atomic-rename.js';
16
17
 
17
- const NUDGE_STATE = join(STATE_DIR, 'nudge-state.json');
18
+ // Persistent, so a reboot doesn't re-show every nudge. Through v1.5.2 it lived
19
+ // in os.tmpdir(); readShownKeys moves that file here once.
20
+ export const NUDGE_STATE = join(DATA_DIR, 'nudge-state.json');
21
+ export const LEGACY_NUDGE_STATE = join(STATE_DIR, 'nudge-state.json');
18
22
 
19
23
  // Largest milestone in `list` that `value` has reached, or null.
20
24
  function reached(value, list) {
@@ -93,7 +97,8 @@ export function pickTodayMilestone(agg, todayTokens = 0) {
93
97
 
94
98
  // Set of every nudge key already shown. Older state files stored a single
95
99
  // `key`; fold it in so upgrading doesn't re-show the last nudge.
96
- function readShownKeys(path = NUDGE_STATE) {
100
+ export function readShownKeys(path = NUDGE_STATE, legacyPath = path === NUDGE_STATE ? LEGACY_NUDGE_STATE : null) {
101
+ adoptLegacyFile(path, legacyPath);
97
102
  try {
98
103
  const raw = JSON.parse(readFileSync(path, 'utf8'));
99
104
  const keys = Array.isArray(raw.shown) ? raw.shown : [];
package/src/pricing.js CHANGED
@@ -6,8 +6,23 @@
6
6
  // To customize: edit this file and run `claude-rpc rescan`.
7
7
 
8
8
  const PRICING = {
9
- // Fable family — Anthropic's frontier tier above Opus.
10
- 'fable-5': { input: 10.00, output: 50.00, cacheRead: 1.00, cacheWrite: 12.50 },
9
+ // Fable family — Anthropic's frontier tier above Opus. 5.1 cut cache reads 4x.
10
+ 'fable-5': { input: 10.00, output: 50.00, cacheRead: 1.00, cacheWrite: 12.50 },
11
+ 'fable-5-1': { input: 10.00, output: 50.00, cacheRead: 0.25, cacheWrite: 12.50 },
12
+
13
+ // Mythos (Project Glasswing only): Fable-tier capabilities and prices.
14
+ 'mythos-5': { input: 10.00, output: 50.00, cacheRead: 1.00, cacheWrite: 12.50 },
15
+ 'mythos-5-1': { input: 10.00, output: 50.00, cacheRead: 0.25, cacheWrite: 12.50 },
16
+
17
+ // 5.x generation (list prices checked 2026-10-14). Haiku 5.5 uses its
18
+ // <=100K-token-prompt rates; past 100K it's 5x, which a per-token table
19
+ // can't express — Claude Code prompts are usually under that.
20
+ 'opus-5': { input: 5.00, output: 25.00, cacheRead: 0.50, cacheWrite: 6.25 },
21
+ 'opus-5-5': { input: 4.00, output: 20.00, cacheRead: 0.20, cacheWrite: 5.00 },
22
+ 'sonnet-5': { input: 2.00, output: 10.00, cacheRead: 0.20, cacheWrite: 2.50 },
23
+ 'sonnet-5-5': { input: 2.00, output: 10.00, cacheRead: 0.20, cacheWrite: 2.50 },
24
+ 'haiku-5': { input: 0.10, output: 0.50, cacheRead: 0.01, cacheWrite: 0.125 },
25
+ 'haiku-5-5': { input: 0.10, output: 0.50, cacheRead: 0.01, cacheWrite: 0.125 },
11
26
 
12
27
  // Opus 4.x family. 4.0/4.1 launched at $15/$75; the list price dropped to
13
28
  // $5/$25 with Opus 4.5 and has held through 4.8.
@@ -29,6 +44,7 @@ const PRICING = {
29
44
  // Generic fallbacks by tier. Opus uses the current-generation rates —
30
45
  // unknown/future opus ids are far more likely to be 4.5+ than 4.1-era.
31
46
  'fable': { input: 10.00, output: 50.00, cacheRead: 1.00, cacheWrite: 12.50 },
47
+ 'mythos': { input: 10.00, output: 50.00, cacheRead: 1.00, cacheWrite: 12.50 },
32
48
  'opus': { input: 5.00, output: 25.00, cacheRead: 0.50, cacheWrite: 6.25 },
33
49
  'sonnet': { input: 3.00, output: 15.00, cacheRead: 0.30, cacheWrite: 3.75 },
34
50
  'haiku': { input: 1.00, output: 5.00, cacheRead: 0.10, cacheWrite: 1.25 },
@@ -36,7 +52,7 @@ const PRICING = {
36
52
 
37
53
  const DEFAULT = PRICING.sonnet;
38
54
 
39
- const TIERS = new Set(['opus', 'sonnet', 'haiku', 'fable']);
55
+ const TIERS = new Set(['opus', 'sonnet', 'haiku', 'fable', 'mythos']);
40
56
 
41
57
  // Map a model id like "claude-opus-4-7-20251101" to a pricing key.
42
58
  //
@@ -47,9 +63,26 @@ const TIERS = new Set(['opus', 'sonnet', 'haiku', 'fable']);
47
63
  // find the first explicit tier token, then read the version digits that
48
64
  // follow. Falls back from `tier-major-minor` → `tier-major` → tier generic
49
65
  // → sonnet, in that order.
66
+ //
67
+ // Memoized per id string: the scanner calls this (directly and via costFor)
68
+ // for every assistant turn of every transcript, but a corpus only ever holds a
69
+ // handful of distinct model ids. PRICING is never mutated, so the cache can't
70
+ // go stale; the size cap just bounds a pathological transcript.
71
+ const keyCache = new Map();
50
72
  export function pricingKeyFor(modelId) {
73
+ if (typeof modelId !== 'string') return resolvePricingKey(modelId);
74
+ let k = keyCache.get(modelId);
75
+ if (k === undefined) {
76
+ if (keyCache.size >= 256) keyCache.clear();
77
+ keyCache.set(modelId, (k = resolvePricingKey(modelId)));
78
+ }
79
+ return k;
80
+ }
81
+
82
+ function resolvePricingKey(modelId) {
51
83
  if (!modelId) return 'sonnet';
52
- const parts = String(modelId).toLowerCase().split('-');
84
+ // Drop a context-window tag like `[1m]` (claude-opus-5-5[1m]) before parsing.
85
+ const parts = String(modelId).toLowerCase().replace(/\[[^\]]*\]/g, '').split('-');
53
86
 
54
87
  let tier = null;
55
88
  let tierIdx = -1;