claude-rpc 1.5.2 → 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 +27 -32
  21. package/src/insights.js +3 -4
  22. package/src/install.js +100 -79
  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 +24 -2
  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,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) {
@@ -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
@@ -10,13 +10,18 @@ const PRICING = {
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('-');
package/src/privacy.js CHANGED
@@ -99,13 +99,20 @@ function readPrivateList() {
99
99
  }
100
100
 
101
101
  function writePrivateList(list) {
102
- if (!existsSync(DATA_DIR)) mkdirSync(DATA_DIR, { recursive: true });
102
+ // The list's own dir (not DATA_DIR), so a CLAUDE_RPC_PRIVATE_LIST override
103
+ // doesn't also create ~/.claude-rpc.
104
+ mkdirSync(dirname(PRIVATE_LIST_PATH), { recursive: true });
103
105
  writeFileSync(PRIVATE_LIST_PATH, JSON.stringify(list, null, 2));
104
106
  }
105
107
 
108
+ // `claude-rpc private`. The GUI-managed visibility map below outranks this
109
+ // list, so a map entry for the cwd (or a parent) saying public / name-only
110
+ // would make the command a silent no-op: pin the cwd hidden in the map too.
106
111
  export function addPrivateCwd(cwd) {
107
- const list = readPrivateList();
108
112
  const abs = resolvePath(cwd);
113
+ const mapped = visibilityForCwd(abs);
114
+ if (mapped && mapped !== 'hidden') setCwdVisibility(abs, 'hidden');
115
+ const list = readPrivateList();
109
116
  if (!list.paths.includes(abs)) {
110
117
  list.paths.push(abs);
111
118
  writePrivateList(list);
@@ -113,9 +120,16 @@ export function addPrivateCwd(cwd) {
113
120
  return list.paths;
114
121
  }
115
122
 
123
+ // `claude-rpc public`. Same precedence in reverse: drop the cwd's own hiding
124
+ // map entry, and if a parent's entry would still hide it, mark it public.
125
+ // An explicit 'public' entry is kept — it also opts out of pattern/gh hiding.
116
126
  export function removePrivateCwd(cwd) {
117
- const list = readPrivateList();
118
127
  const abs = resolvePath(cwd);
128
+ const own = listVisibility()[abs];
129
+ if (own && own !== 'public') setCwdVisibility(abs, null);
130
+ const inherited = visibilityForCwd(abs);
131
+ if (inherited && inherited !== 'public') setCwdVisibility(abs, 'public');
132
+ const list = readPrivateList();
119
133
  list.paths = list.paths.filter((p) => p !== abs);
120
134
  writePrivateList(list);
121
135
  return list.paths;
@@ -279,11 +293,12 @@ export function projectNameIsPrivate(name, config = {}, clean = (s) => s) {
279
293
  return false;
280
294
  }
281
295
 
282
- // Glob-lite. '*' matches any run; otherwise plain text. Case-insensitive.
296
+ // Glob-lite. '*' matches any run; otherwise plain text. Case-insensitive on
297
+ // both sides, for plain and glob patterns alike ("ClientX" ≡ "clientx").
283
298
  function matchesPattern(name, pattern) {
284
- if (pattern === name) return true;
285
- if (!pattern.includes('*')) return false;
286
- const re = new RegExp('^' + pattern.split('*').map(escapeRe).join('.*') + '$', 'i');
299
+ const p = String(pattern);
300
+ if (!p.includes('*')) return p.toLowerCase() === String(name).toLowerCase();
301
+ const re = new RegExp('^' + p.split('*').map(escapeRe).join('.*') + '$', 'i');
287
302
  return re.test(name);
288
303
  }
289
304
  function escapeRe(s) { return s.replace(/[.+?^${}()|[\]\\]/g, '\\$&'); }
package/src/profile.js CHANGED
@@ -6,7 +6,6 @@
6
6
  // Output is pure SVG — GitHub renders it inline in a README <img>.
7
7
 
8
8
  import { fmtCost } from './pricing.js';
9
- import { VERSION } from './version.js';
10
9
  import { fmtNum, fmtHours, localDateStamp } from './fmt.js';
11
10
 
12
11
  const W = 520;
@@ -138,8 +137,3 @@ export function renderProfileCard(aggregate, { handle = '', generatedAt = new Da
138
137
  font-size="11" fill="${PALETTE.inkFaint}">${escapeXml(`best streak ${t.longestStreak}d · ≈${fmtCost(t.cost)} · claude-rpc.com`)}</text>
139
138
  </svg>`;
140
139
  }
141
-
142
- // Top-level convenience matching badge.js / card.js shape.
143
- export function profileCardSvg({ aggregate, handle = '' } = {}) {
144
- return renderProfileCard(aggregate, { handle });
145
- }
package/src/recap.js CHANGED
@@ -11,7 +11,8 @@
11
11
  // today and says so — Monday standups cover Friday.
12
12
  // week — the last 7 local days, ending today
13
13
  // YYYY-MM-DD — one explicit local day
14
- import { dayKey } from './scanner.js';
14
+ import { dayKeyAt } from './scanner.js';
15
+ import { fmtNum as fmtN } from './fmt.js';
15
16
 
16
17
  const WEEKDAYS = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
17
18
  const SHIP_LABELS = [
@@ -22,6 +23,8 @@ const SHIP_LABELS = [
22
23
  ['tag', 'release', 'releases'],
23
24
  ];
24
25
 
26
+ // Not fmt.fmtHours: a recap keeps one decimal past 10h ("23.4h" for a week)
27
+ // and prints an empty day as "0m".
25
28
  function fmtDur(ms) {
26
29
  const m = Math.round((ms || 0) / 60_000);
27
30
  if (m < 1) return '0m';
@@ -29,22 +32,6 @@ function fmtDur(ms) {
29
32
  return `${(m / 60).toFixed(1)}h`;
30
33
  }
31
34
 
32
- function fmtN(n) {
33
- if (!n) return '0';
34
- if (n < 1000) return String(Math.round(n));
35
- if (n < 1e6) return `${(n / 1e3).toFixed(1)}k`;
36
- if (n < 1e9) return `${(n / 1e6).toFixed(2)}M`;
37
- if (n < 1e12) return `${(n / 1e9).toFixed(2)}B`;
38
- return `${(n / 1e12).toFixed(2)}T`;
39
- }
40
-
41
- function dayKeyAt(now, offsetDays) {
42
- const d = new Date(now);
43
- d.setHours(0, 0, 0, 0);
44
- d.setDate(d.getDate() - offsetDays);
45
- return dayKey(d.getTime());
46
- }
47
-
48
35
  // "Tue 2026-07-01" — manual weekday names so output is locale-stable.
49
36
  function prettyDay(key) {
50
37
  const [y, m, d] = String(key).split('-').map(Number);