claude-rpc 1.5.2 → 1.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (52) hide show
  1. package/README.md +72 -62
  2. package/SECURITY.md +99 -20
  3. package/package.json +2 -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 +430 -459
  9. package/src/commands.js +245 -0
  10. package/src/community.js +101 -60
  11. package/src/completion.js +196 -0
  12. package/src/config.js +4 -1
  13. package/src/daemon.js +45 -47
  14. package/src/default-config.js +4 -3
  15. package/src/discord-ipc.js +24 -13
  16. package/src/doctor.js +64 -38
  17. package/src/ensure-daemon.js +11 -4
  18. package/src/fmt.js +8 -6
  19. package/src/format.js +8 -13
  20. package/src/gist.js +8 -18
  21. package/src/git.js +4 -1
  22. package/src/help.js +117 -0
  23. package/src/hook.js +27 -32
  24. package/src/insights.js +3 -4
  25. package/src/install.js +100 -79
  26. package/src/leaderboard.js +3 -2
  27. package/src/mcp.js +2 -8
  28. package/src/nudge.js +10 -5
  29. package/src/png.js +135 -0
  30. package/src/pricing.js +25 -3
  31. package/src/privacy.js +22 -7
  32. package/src/profile.js +0 -6
  33. package/src/recap.js +4 -17
  34. package/src/scanner.js +103 -71
  35. package/src/select.js +60 -0
  36. package/src/server/api.js +64 -36
  37. package/src/server/assets/dashboard.client.js +75 -44
  38. package/src/server/assets/dashboard.css +18 -18
  39. package/src/server/assets/dashboard.html +13 -15
  40. package/src/server/assets/wrapped.client.js +26 -11
  41. package/src/server/assets/wrapped.css +2 -2
  42. package/src/server/index.js +43 -32
  43. package/src/server/page.js +6 -3
  44. package/src/server/sse.js +90 -34
  45. package/src/session-card.js +3 -1
  46. package/src/statcards.js +278 -0
  47. package/src/state.js +14 -24
  48. package/src/tui.js +3 -12
  49. package/src/ui.js +7 -5
  50. package/src/verify.js +3 -7
  51. package/src/version.js +1 -1
  52. package/src/week.js +4 -4
package/src/install.js CHANGED
@@ -1,6 +1,8 @@
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,
@@ -61,7 +63,8 @@ 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.
@@ -162,11 +165,9 @@ export function installHooks(exePath, { silent = false, ccVersion = detectClaude
162
165
  const settings = readJson(CLAUDE_SETTINGS, {});
163
166
  const before = JSON.stringify(settings.hooks || {});
164
167
  settings.hooks = settings.hooks || {};
165
- // Three modes, three shapes:
166
- // packaged → `"<exe>" hook <event>` (canonical exe, no node)
167
- // npm → `claude-rpc hook <event>` (bin shim resolves through PATH;
168
- // survives `npm update` and nvm version switches)
169
- // 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>`
170
171
  // Hook commands must resolve under Claude Code's hook shell — `/bin/sh` with a
171
172
  // minimal PATH that, under nvm, has neither `claude-rpc` nor `node` on it (no
172
173
  // system node). So use the ABSOLUTE node (process.execPath) + absolute hook.js
@@ -247,6 +248,12 @@ function daemonLaunch(exePath) {
247
248
  return { exe: process.execPath, args: [DAEMON_SCRIPT] };
248
249
  }
249
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
+
250
257
  function xmlEscape(s) { return String(s).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;'); }
251
258
  function systemctlUser(args) {
252
259
  try { return spawnSync('systemctl', ['--user', ...args], { stdio: 'ignore' }); }
@@ -312,16 +319,21 @@ export function systemdUnit({ exe, args }) {
312
319
  ].join('\n');
313
320
  }
314
321
 
315
- // ── macOS: launchd LaunchAgent (per-user, starts at login) ────────────────────
316
- function addStartupEntryMac(exePath) {
317
- 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) {
318
324
  try {
319
- mkdirSync(dirname(LAUNCHD_PLIST), { recursive: true });
320
- writeFileSync(LAUNCHD_PLIST, plist);
325
+ mkdirSync(dirname(path), { recursive: true });
326
+ writeFileSync(path, content);
327
+ return true;
321
328
  } catch (e) {
322
- step(SYM_WARN, 'startup entry', `couldn't write LaunchAgent (${e.message}) — the session self-heal still starts the daemon`, console.warn);
323
- 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;
324
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;
325
337
  // Load so it's active now and at every login. `load -w` is deprecated but
326
338
  // portable across the macOS versions we target; a failure is non-fatal — the
327
339
  // plist alone starts it next login, and SessionStart self-heal covers the gap.
@@ -338,14 +350,7 @@ function removeStartupEntryMac() {
338
350
 
339
351
  // ── Linux: systemd --user service (starts at login) ───────────────────────────
340
352
  function addStartupEntryLinux(exePath) {
341
- const unit = systemdUnit(daemonLaunch(exePath));
342
- try {
343
- mkdirSync(dirname(SYSTEMD_UNIT), { recursive: true });
344
- writeFileSync(SYSTEMD_UNIT, unit);
345
- } catch (e) {
346
- step(SYM_WARN, 'startup entry', `couldn't write systemd unit (${e.message}) — the session self-heal still starts the daemon`, console.warn);
347
- return;
348
- }
353
+ if (!writeStartupFile(SYSTEMD_UNIT, systemdUnit(daemonLaunch(exePath)), 'systemd unit')) return;
349
354
  // Enable + start now. Non-fatal if there's no systemd --user session (some
350
355
  // containers / minimal WSL): the SessionStart self-heal still brings it up.
351
356
  systemctlUser(['daemon-reload']);
@@ -460,8 +465,10 @@ export function ensureCanonicalExe(currentExe) {
460
465
  try {
461
466
  // Windows won't let you overwrite a currently-executing file. If
462
467
  // canonical is the running daemon, move it aside first — that succeeds
463
- // even while the file handle is open, and Windows will delete the
464
- // 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.
465
472
  if (process.platform === 'win32' && existsSync(CANONICAL_EXE)) {
466
473
  try { renameSync(CANONICAL_EXE, CANONICAL_EXE + '.old-' + Date.now()); }
467
474
  catch { /* not running, no rename needed — copyFileSync below will just overwrite */ }
@@ -519,14 +526,6 @@ export function seedConfig() {
519
526
  return true;
520
527
  }
521
528
 
522
- // Non-destructive merge of any new top-level keys / presence blocks the
523
- // shipped DEFAULT_CONFIG has but the user's existing file doesn't.
524
- //
525
- // Runs every time install/setup or the packaged default launcher fires,
526
- // so an upgraded exe pulls in new shape (e.g. v0.3.6's presence.byStatus)
527
- // without clobbering the user's customizations. Anything the user already
528
- // has — including a pre-existing byStatus, custom rotation array, custom
529
- // appName etc. — is left untouched.
530
529
  // How Claude Code should invoke the MCP server — same three-mode resolution
531
530
  // as the hook commands (packaged exe / npm bin / dev source).
532
531
  export function mcpServerCommand(exePath) {
@@ -556,6 +555,14 @@ export function uninstallMcp({ scope = 'user' } = {}) {
556
555
  return { ok: r.status === 0 };
557
556
  }
558
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.
559
566
  export function migrateConfig({ silent = false } = {}) {
560
567
  if (!existsSync(CONFIG_PATH)) return false;
561
568
  let cfg;
@@ -598,17 +605,15 @@ export function migrateConfig({ silent = false } = {}) {
598
605
  // "Bash · · 0 tokens" on the card. New default uses `{tokensLabel}` which is
599
606
  // empty until tokens > 0, and fillTemplate now collapses adjacent separators.
600
607
  // Migrate only the verbatim old template — leave anything the user customized.
601
- const OLD_WORKING = '{currentToolPretty} · {currentFilePretty} · {tokensFmt} tokens';
602
- const OLD_THINKING = '{modelPretty} · {messagesLabel} · {tokensFmt} tokens';
603
- if (cfg.presence.byStatus?.working?.state === OLD_WORKING &&
604
- DEFAULT_CONFIG.presence?.byStatus?.working?.state) {
605
- cfg.presence.byStatus.working.state = DEFAULT_CONFIG.presence.byStatus.working.state;
606
- added.push('presence.byStatus.working.state');
607
- }
608
- if (cfg.presence.byStatus?.thinking?.state === OLD_THINKING &&
609
- DEFAULT_CONFIG.presence?.byStatus?.thinking?.state) {
610
- cfg.presence.byStatus.thinking.state = DEFAULT_CONFIG.presence.byStatus.thinking.state;
611
- 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
+ }
612
617
  }
613
618
 
614
619
  // v1.4.3: setup's "connect GitHub?" y could die on a server error (the
@@ -736,12 +741,6 @@ function verifyHookPipe(exePath) {
736
741
  return { ok: true, detail: 'SessionStart round-trip succeeded' };
737
742
  }
738
743
 
739
- // `npx claude-rpc setup` runs from npm's throwaway _npx cache, so the
740
- // `claude-rpc` bin the hooks resolve through PATH disappears the moment npx
741
- // exits. Promote to a real global install first, then the rest of setup wires
742
- // hooks to the now-persistent global bin exactly like a normal npm install.
743
- // Best-effort + loud: a failed -g (perms, offline) returns false so the caller
744
- // can stop with the manual command rather than wire a dead hook.
745
744
  // Version of the GLOBALLY-installed claude-rpc, read straight off disk via
746
745
  // `npm root -g` — NOT through PATH. While setup runs under `npx
747
746
  // claude-rpc@latest`, npx prepends its own throwaway cache (the current
@@ -751,10 +750,7 @@ function verifyHookPipe(exePath) {
751
750
  // nothing). Reading the global package.json sidesteps that PATH shadowing.
752
751
  function globalInstalledVersion() {
753
752
  try {
754
- const r = spawnSync('npm', ['root', '-g'], {
755
- encoding: 'utf8', timeout: 4000, windowsHide: true,
756
- shell: process.platform === 'win32', // npm is npm.cmd on Windows
757
- });
753
+ const r = npmSync(['root', '-g'], { timeout: 4000 });
758
754
  const root = (r.stdout || '').trim();
759
755
  if (!root) return null;
760
756
  const pkg = JSON.parse(readFileSync(join(root, 'claude-rpc', 'package.json'), 'utf8'));
@@ -762,6 +758,15 @@ function globalInstalledVersion() {
762
758
  } catch { return null; } // not installed / npm missing / unreadable
763
759
  }
764
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.
765
770
  function promoteNpxToGlobal() {
766
771
  // Already promoted on a previous run AND current? Skip the redundant -g (also
767
772
  // lets setup succeed when a correct global exists but `npm -g` would fail —
@@ -770,11 +775,7 @@ function promoteNpxToGlobal() {
770
775
  noop('global install current');
771
776
  return true;
772
777
  }
773
- const r = spawnSync('npm', ['install', '-g', `claude-rpc@${VERSION}`], {
774
- encoding: 'utf8',
775
- shell: process.platform === 'win32', // npm is npm.cmd on Windows
776
- windowsHide: true, // don't flash a console window
777
- });
778
+ const r = npmSync(['install', '-g', `claude-rpc@${VERSION}`]);
778
779
  if (r.error || r.status !== 0) {
779
780
  // The piped npm chatter only matters when it failed.
780
781
  if (r.stdout) process.stderr.write(r.stdout);
@@ -792,11 +793,7 @@ function promoteNpxToGlobal() {
792
793
  // clue why. Warn loudly up front; never block setup on it (offline is fine).
793
794
  function warnIfStale() {
794
795
  try {
795
- const r = spawnSync('npm', ['view', 'claude-rpc', 'version'], {
796
- encoding: 'utf8', timeout: 4000,
797
- shell: process.platform === 'win32', // npm is npm.cmd on Windows
798
- windowsHide: true, // don't flash a console window
799
- });
796
+ const r = npmSync(['view', 'claude-rpc', 'version'], { timeout: 4000 });
800
797
  const latest = (r.stdout || '').trim();
801
798
  if (!latest || latest === VERSION) return;
802
799
  const num = (v) => v.split('.').map((n) => parseInt(n, 10) || 0);
@@ -854,7 +851,7 @@ export function selfHealOnUpdate({ exePath = null, silent = true } = {}) {
854
851
  return { changed: true, from, rewired, autostart };
855
852
  }
856
853
 
857
- export async function install({ exePath, withStartup = true } = {}) {
854
+ export async function install({ exePath } = {}) {
858
855
  resetRun();
859
856
  console.log('');
860
857
  console.log(` ${c.bold}${c.magenta}◆ claude-rpc setup${c.reset} ${c.dim}v${VERSION}${c.reset}`);
@@ -879,7 +876,9 @@ export async function install({ exePath, withStartup = true } = {}) {
879
876
  phase('config');
880
877
  // Order matters: seed creates the file if missing, then migrate fills in
881
878
  // any blocks new exe versions added (e.g. presence.byStatus from v0.3.6).
882
- 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();
883
882
  migrateConfig();
884
883
 
885
884
  phase('claude code');
@@ -900,34 +899,54 @@ export async function install({ exePath, withStartup = true } = {}) {
900
899
  // The CLI's setup case launches the daemon right after this returns, so its
901
900
  // row lands under this heading; setupOutro() then closes the screen.
902
901
  phase('daemon');
903
- if (withStartup) {
904
- // Cross-platform login autostart: Windows Run-key, macOS LaunchAgent, Linux
905
- // systemd --user. Best-effort — a failure leaves the SessionStart self-heal
906
- // as the (already reliable) fallback, so setup never fails on this.
907
- try { await addStartupEntry(target); }
908
- catch (e) { step(SYM_WARN, 'startup entry', `failed: ${e.message} — session self-heal still covers it`, console.warn); }
909
- }
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 };
910
908
  // Nothing changed: the checklist above stayed silent, so say so in one line.
911
909
  if (!runDirty && probe.ok) {
912
910
  console.log(` ${SYM_OK} ${c.bold}already set up${c.reset} ${c.dim}${noopFacts.join(' · ')}${c.reset}`);
913
911
  }
914
- 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;
915
931
  }
916
932
 
917
933
  // The single closing block of `claude-rpc setup` — what to do now, where the
918
934
  // levers are. Printed by the CLI after the daemon launch so it always lands
919
935
  // last; doctor --fix re-runs install() without it.
920
- 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 }) {
921
939
  if (!changed) return;
922
940
  const point = (label, value, note = '') =>
923
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';
924
943
  console.log('');
925
944
  console.log(` ${SYM_OK} ${c.bold}setup complete${c.reset} — open Claude Code and send a prompt; your card goes live in Discord.`);
926
- point('verify wiring', 'claude-rpc doctor');
945
+ point('verify wiring', `${run} doctor`, cli.newTerminal ? 'in a new terminal' : '');
927
946
  if (IS_PACKAGED) point('start daemon', `"${target}" daemon`, 'also runs automatically at login');
928
- else point('manage daemon', 'claude-rpc start · stop · status');
947
+ else point('manage daemon', `${run} start · stop · status`);
929
948
  point('config', CONFIG_PATH, 'a working Discord app is bundled — set clientId only to use your own');
930
- 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');
931
950
  console.log('');
932
951
  }
933
952
 
@@ -937,6 +956,8 @@ export async function uninstall() {
937
956
  console.log('');
938
957
  uninstallHooks();
939
958
  await removeStartupEntry();
959
+ const { removeCliFromPath } = await import('./cli-path.js');
960
+ if (removeCliFromPath()) step(SYM_OK, 'PATH entry', 'removed');
940
961
  console.log('');
941
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}`);
942
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) {
@@ -42,7 +46,7 @@ export function pickShareNudge(agg, shown = new Set()) {
42
46
  const m = reached(streak, [3, 7, 14, 30, 50, 100, 200, 365]);
43
47
  if (m) out.push({
44
48
  key: `streak:${m}`, weight: 1000 + m,
45
- message: `${m}-day streak — a personal record. Drop a live badge in your README: \`claude-rpc badge --metric streak --gist\``,
49
+ message: `${m}-day streak — a personal record. Drop a live badge in your README: \`claude-rpc statcards badge --metric streak --link\``,
46
50
  });
47
51
  }
48
52
 
@@ -50,7 +54,7 @@ export function pickShareNudge(agg, shown = new Set()) {
50
54
  const s = reached(sessions, [50, 100, 250, 500, 1000, 2500, 5000, 10000]);
51
55
  if (s) out.push({
52
56
  key: `sessions:${s}`, weight: s / 50,
53
- message: `${fmt(s)} Claude Code sessions logged. Show it off: \`claude-rpc card --range all --out claude.svg\` (or --gist for a live one).`,
57
+ message: `${fmt(s)} Claude Code sessions logged. Show it off: \`claude-rpc statcards poster --range all --png\`.`,
54
58
  });
55
59
 
56
60
  const hours = Math.floor((agg.activeMs || 0) / 3_600_000);
@@ -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/png.js ADDED
@@ -0,0 +1,135 @@
1
+ // SVG → PNG with whatever the machine already has, so claude-rpc stays at zero
2
+ // dependencies: rsvg-convert, then a Chromium-family browser in headless mode
3
+ // (Chrome, Edge, Brave, Chromium — Edge ships with every Windows 10/11), then
4
+ // ImageMagick or Inkscape. CLAUDE_RPC_BROWSER points at a browser binary
5
+ // explicitly.
6
+
7
+ import { existsSync, mkdtempSync, writeFileSync, readFileSync, rmSync, statSync, openSync, closeSync } from 'node:fs';
8
+ import { tmpdir } from 'node:os';
9
+ import { join, delimiter } from 'node:path';
10
+ import { pathToFileURL } from 'node:url';
11
+
12
+ const PNG_MAGIC = Buffer.from([0x89, 0x50, 0x4e, 0x47]);
13
+
14
+ // Width/height of the root <svg>, from width/height or the viewBox.
15
+ export function svgSize(svg) {
16
+ const tag = (svg.match(/<svg\b[^>]*>/i) || [''])[0];
17
+ const num = (name) => {
18
+ const m = tag.match(new RegExp(`\\s${name}="([\\d.]+)(px)?"`, 'i'));
19
+ return m ? Number(m[1]) : null;
20
+ };
21
+ let w = num('width');
22
+ let h = num('height');
23
+ if (!w || !h) {
24
+ const vb = tag.match(/viewBox="[\d.-]+[\s,]+[\d.-]+[\s,]+([\d.]+)[\s,]+([\d.]+)"/i);
25
+ if (vb) { w = w || Number(vb[1]); h = h || Number(vb[2]); }
26
+ }
27
+ return { width: Math.ceil(w || 600), height: Math.ceil(h || 300) };
28
+ }
29
+
30
+ function onPath(name, env = process.env, platform = process.platform) {
31
+ const exts = platform === 'win32' ? (env.PATHEXT || '.EXE;.CMD;.BAT').split(';') : [''];
32
+ for (const dir of (env.PATH || env.Path || '').split(delimiter)) {
33
+ if (!dir) continue;
34
+ for (const ext of exts) {
35
+ const p = join(dir, name + ext);
36
+ try { if (statSync(p).isFile()) return p; } catch { /* not here */ }
37
+ }
38
+ }
39
+ return null;
40
+ }
41
+
42
+ function browserCandidates(env = process.env, platform = process.platform) {
43
+ if (platform === 'darwin') {
44
+ return ['Google Chrome', 'Microsoft Edge', 'Brave Browser', 'Chromium']
45
+ .map((app) => `/Applications/${app}.app/Contents/MacOS/${app}`);
46
+ }
47
+ if (platform === 'win32') {
48
+ const roots = [env.ProgramFiles, env['ProgramFiles(x86)'], env.LOCALAPPDATA].filter(Boolean);
49
+ const rel = ['Microsoft\\Edge\\Application\\msedge.exe', 'Google\\Chrome\\Application\\chrome.exe',
50
+ 'BraveSoftware\\Brave-Browser\\Application\\brave.exe'];
51
+ return roots.flatMap((r) => rel.map((p) => join(r, p)));
52
+ }
53
+ return [];
54
+ }
55
+
56
+ // The first available renderer as { kind, bin }, or null.
57
+ export function findRasterizer(env = process.env, platform = process.platform) {
58
+ if (env.CLAUDE_RPC_BROWSER) return existsSync(env.CLAUDE_RPC_BROWSER) ? { kind: 'browser', bin: env.CLAUDE_RPC_BROWSER } : null;
59
+ const rsvg = onPath('rsvg-convert', env, platform);
60
+ if (rsvg) return { kind: 'rsvg', bin: rsvg };
61
+ for (const p of browserCandidates(env, platform)) if (existsSync(p)) return { kind: 'browser', bin: p };
62
+ for (const name of ['google-chrome', 'google-chrome-stable', 'chromium', 'chromium-browser', 'microsoft-edge', 'brave-browser', 'msedge', 'chrome']) {
63
+ const p = onPath(name, env, platform);
64
+ if (p) return { kind: 'browser', bin: p };
65
+ }
66
+ const magick = onPath('magick', env, platform);
67
+ if (magick) return { kind: 'magick', bin: magick };
68
+ const inkscape = onPath('inkscape', env, platform);
69
+ if (inkscape) return { kind: 'inkscape', bin: inkscape };
70
+ return null;
71
+ }
72
+
73
+ // The argv for one renderer. Exported for tests.
74
+ export function rasterArgs(kind, { svgFile, htmlFile, out, width, height, scale, profileDir, root = false }) {
75
+ switch (kind) {
76
+ case 'rsvg': return ['-z', String(scale), '-b', 'none', '-o', out, svgFile];
77
+ case 'magick': return ['-background', 'none', '-density', String(96 * scale), svgFile, out];
78
+ case 'inkscape': return ['--export-type=png', `--export-filename=${out}`, `--export-dpi=${96 * scale}`, svgFile];
79
+ case 'browser': return [
80
+ '--headless=new', '--disable-gpu', '--hide-scrollbars', '--no-first-run', '--no-default-browser-check',
81
+ `--user-data-dir=${profileDir}`, '--default-background-color=00000000',
82
+ `--force-device-scale-factor=${scale}`, `--window-size=${width},${height}`,
83
+ `--screenshot=${out}`, ...(root ? ['--no-sandbox'] : []), pathToFileURL(htmlFile).href,
84
+ ];
85
+ default: throw new Error(`unknown rasterizer ${kind}`);
86
+ }
87
+ }
88
+
89
+ // Render `svg` to a PNG at `out` (2× by default). Throws with a readable
90
+ // message when nothing on the machine can do it.
91
+ export async function svgToPng(svg, out, { scale = 2, env = process.env } = {}) {
92
+ const r = findRasterizer(env);
93
+ if (!r) {
94
+ const e = new Error('no SVG renderer found');
95
+ e.hint = process.platform === 'darwin'
96
+ ? 'install Chrome, or `brew install librsvg` — or use --svg / --link instead'
97
+ : process.platform === 'win32'
98
+ ? 'Microsoft Edge does it — or set CLAUDE_RPC_BROWSER to a Chrome/Edge exe; --svg / --link work without one'
99
+ : 'install librsvg (rsvg-convert) or Chromium — or use --svg / --link instead';
100
+ throw e;
101
+ }
102
+ const { spawnSync } = await import('node:child_process');
103
+ const dir = mkdtempSync(join(tmpdir(), 'claude-rpc-png-'));
104
+ try {
105
+ const { width, height } = svgSize(svg);
106
+ const svgFile = join(dir, 'card.svg');
107
+ const htmlFile = join(dir, 'card.html');
108
+ writeFileSync(svgFile, svg);
109
+ writeFileSync(htmlFile, `<!doctype html><meta charset="utf-8"><style>html,body{margin:0;background:transparent;overflow:hidden}svg{display:block}</style>${svg}`);
110
+ const args = rasterArgs(r.kind, {
111
+ svgFile, htmlFile, out, width, height, scale,
112
+ profileDir: join(dir, 'profile'), root: typeof process.getuid === 'function' && process.getuid() === 0,
113
+ });
114
+ // stdio to a file, not a pipe: Chrome's crashpad helper inherits the pipe
115
+ // and outlives the browser, so spawnSync would wait on it until timeout.
116
+ const errFile = join(dir, 'err.log');
117
+ const fd = openSync(errFile, 'w');
118
+ let res;
119
+ try { res = spawnSync(r.bin, args, { stdio: ['ignore', fd, fd], timeout: 45_000, windowsHide: true }); } finally { closeSync(fd); }
120
+ try { res.stderr = readFileSync(errFile, 'utf8'); } catch { /* keep whatever spawnSync had */ }
121
+ let ok = false;
122
+ try { ok = readFileSync(out).subarray(0, 4).equals(PNG_MAGIC); } catch { /* not written */ }
123
+ if (!ok) {
124
+ const why = (res.error?.message || res.stderr || '').trim().split('\n').slice(-2).join(' ');
125
+ throw new Error(`${basenameOf(r.bin)} could not render the PNG${why ? `: ${why.slice(0, 200)}` : ''}`);
126
+ }
127
+ return { out, via: basenameOf(r.bin), width: width * scale, height: height * scale };
128
+ } finally {
129
+ try { rmSync(dir, { recursive: true, force: true }); } catch { /* temp cleanup is best-effort */ }
130
+ }
131
+ }
132
+
133
+ function basenameOf(p) {
134
+ return String(p).split(/[\\/]/).pop();
135
+ }
package/src/pricing.js CHANGED
@@ -3,20 +3,25 @@
3
3
  // what your Claude Code subscription actually charges. Treat the resulting
4
4
  // `costEstimate` as a usage-weighted rough order of magnitude, not a bill.
5
5
  //
6
- // To customize: edit this file and run `claude-rpc rescan`.
6
+ // To customize: edit this file and run `claude-rpc scan --force`.
7
7
 
8
8
  const PRICING = {
9
9
  // Fable family — Anthropic's frontier tier above Opus. 5.1 cut cache reads 4x.
10
10
  'fable-5': { input: 10.00, output: 50.00, cacheRead: 1.00, cacheWrite: 12.50 },
11
11
  'fable-5-1': { input: 10.00, output: 50.00, cacheRead: 0.25, cacheWrite: 12.50 },
12
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
+
13
17
  // 5.x generation (list prices checked 2026-10-14). Haiku 5.5 uses its
14
18
  // <=100K-token-prompt rates; past 100K it's 5x, which a per-token table
15
19
  // can't express — Claude Code prompts are usually under that.
16
20
  'opus-5': { input: 5.00, output: 25.00, cacheRead: 0.50, cacheWrite: 6.25 },
17
21
  'opus-5-5': { input: 4.00, output: 20.00, cacheRead: 0.20, cacheWrite: 5.00 },
18
22
  'sonnet-5': { input: 2.00, output: 10.00, cacheRead: 0.20, cacheWrite: 2.50 },
19
- 'sonnet-5-5': { input: 2.00, output: 10.00, cacheRead: 0.10, 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 },
20
25
  'haiku-5-5': { input: 0.10, output: 0.50, cacheRead: 0.01, cacheWrite: 0.125 },
21
26
 
22
27
  // Opus 4.x family. 4.0/4.1 launched at $15/$75; the list price dropped to
@@ -39,6 +44,7 @@ const PRICING = {
39
44
  // Generic fallbacks by tier. Opus uses the current-generation rates —
40
45
  // unknown/future opus ids are far more likely to be 4.5+ than 4.1-era.
41
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 },
42
48
  'opus': { input: 5.00, output: 25.00, cacheRead: 0.50, cacheWrite: 6.25 },
43
49
  'sonnet': { input: 3.00, output: 15.00, cacheRead: 0.30, cacheWrite: 3.75 },
44
50
  'haiku': { input: 1.00, output: 5.00, cacheRead: 0.10, cacheWrite: 1.25 },
@@ -46,7 +52,7 @@ const PRICING = {
46
52
 
47
53
  const DEFAULT = PRICING.sonnet;
48
54
 
49
- const TIERS = new Set(['opus', 'sonnet', 'haiku', 'fable']);
55
+ const TIERS = new Set(['opus', 'sonnet', 'haiku', 'fable', 'mythos']);
50
56
 
51
57
  // Map a model id like "claude-opus-4-7-20251101" to a pricing key.
52
58
  //
@@ -57,7 +63,23 @@ const TIERS = new Set(['opus', 'sonnet', 'haiku', 'fable']);
57
63
  // find the first explicit tier token, then read the version digits that
58
64
  // follow. Falls back from `tier-major-minor` → `tier-major` → tier generic
59
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();
60
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) {
61
83
  if (!modelId) return 'sonnet';
62
84
  // Drop a context-window tag like `[1m]` (claude-opus-5-5[1m]) before parsing.
63
85
  const parts = String(modelId).toLowerCase().replace(/\[[^\]]*\]/g, '').split('-');