claude-rpc 1.7.0 → 1.7.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -145,6 +145,7 @@ The web dashboard pushes updates via SSE; the TUI refreshes on a 3-second tick.
145
145
  Stat cards and badges for a README, a site or a Discord message, all from one command. Run it bare for a menu: pick a card, then a **live link** (paste once, it refreshes itself), a **PNG** or an **SVG**:
146
146
 
147
147
  ```sh
148
+ claude-rpc share # poster PNG + a ready caption on your clipboard
148
149
  claude-rpc statcards # menu: card → link / PNG / SVG
149
150
  claude-rpc statcards stats --link --md | pbcopy # README markdown, straight to the clipboard
150
151
  claude-rpc statcards poster --png # ./claude-poster.png, 2× for Discord / X
@@ -327,6 +328,7 @@ It's a thin bootstrapper — on the first session it just runs `npx claude-rpc@l
327
328
  | `serve` | The local web dashboard (port 47474) |
328
329
  | `export` | The aggregate as JSON, or daily rows as CSV (`--csv` `--out`) |
329
330
  | **Share** | |
331
+ | `share [week\|month\|year\|all]` | Saves the poster PNG and copies a caption with your numbers and a link (`--no-png`, `--no-copy`, `--png <file>`) |
330
332
  | `statcards [card]` | Cards and badges as a live link, PNG or SVG: `stats` `profile` `badge` `heatmap` `poster` `session` `wrapped` (`--link` `--png [file]` `--svg [file]` `--md` `--html` `--metric` `--range` `--copy`; bare = menu) |
331
333
  | `statusline` | One-line status for tmux/shell prompts (`--template`) |
332
334
  | `mcp` | The stats MCP server (stdio); `mcp install` / `mcp uninstall` wire it into Claude Code |
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "claude-rpc",
3
- "version": "1.7.0",
3
+ "version": "1.7.2",
4
4
  "description": "Discord Rich Presence for Claude Code — live model, project, tokens, and lifetime stats driven by Claude Code's hook system.",
5
5
  "type": "module",
6
6
  "license": "MIT",
package/src/card.js CHANGED
@@ -51,8 +51,9 @@ function rangeTitle(range) {
51
51
  return `${rl} on claude`;
52
52
  }
53
53
 
54
- // Roll up a windowed metric across the active range.
55
- function rollup(aggregate, range) {
54
+ // Roll up a windowed metric across the active range. Exported for share.js's
55
+ // caption, so the text and the poster count the same window.
56
+ export function rollup(aggregate, range) {
56
57
  const window = pickWindow(aggregate?.byDay, range);
57
58
  const out = {
58
59
  activeMs: 0,
package/src/cli.js CHANGED
@@ -2395,6 +2395,30 @@ async function doCompletion(argv) {
2395
2395
  }
2396
2396
 
2397
2397
  // Offer tab completion once during a first setup, on a terminal only.
2398
+ // One y/N at the end of `setup`, asked at most once ever: join the community
2399
+ // Discord. y opens the invite in the browser (the link is printed too, for
2400
+ // headless boxes); n changes nothing. The ?s=cli tag is the join attribution.
2401
+ const DISCORD_JOIN_URL = 'https://claude-rpc.com/discord?s=cli';
2402
+ async function setupDiscordOffer() {
2403
+ if (!process.stdin.isTTY || !process.stdout.isTTY) return;
2404
+ if (readJson(CONFIG_PATH, {}).discordAsked) return;
2405
+ const answer = (await prompt(` join the claude-rpc Discord? ${c.dim}help, card showcase, weekly leaderboard [y/N]${c.reset} `)).trim();
2406
+ // Top-level, not under community: that block's presence is the telemetry
2407
+ // consent marker migrateConfig reads.
2408
+ writeUserConfig({ ...readJson(CONFIG_PATH, {}), discordAsked: true });
2409
+ if (!/^y(es)?$/i.test(answer)) return;
2410
+ try {
2411
+ const { spawn } = await import('node:child_process');
2412
+ const [cmd, args] = process.platform === 'win32' ? ['cmd', ['/c', 'start', '', DISCORD_JOIN_URL]]
2413
+ : process.platform === 'darwin' ? ['open', [DISCORD_JOIN_URL]]
2414
+ : ['xdg-open', [DISCORD_JOIN_URL]];
2415
+ const child = spawn(cmd, args, { detached: true, stdio: 'ignore', windowsHide: true });
2416
+ child.on('error', () => {});
2417
+ child.unref();
2418
+ } catch { /* no opener — the printed link below covers it */ }
2419
+ console.log(` ${c.green}✓${c.reset} ${c.dim}opening${c.reset} ${c.cyan}${DISCORD_JOIN_URL}${c.reset}`);
2420
+ }
2421
+
2398
2422
  async function setupCompletionOffer() {
2399
2423
  if (!process.stdin.isTTY || !process.stdout.isTTY || process.env.CLAUDE_RPC_NO_COMPLETION) return;
2400
2424
  const comp = await import('./completion.js');
@@ -2413,6 +2437,12 @@ async function setupCompletionOffer() {
2413
2437
  }
2414
2438
  }
2415
2439
 
2440
+ async function doShare(argv) {
2441
+ const { runShare } = await import('./share.js');
2442
+ const { copyToClipboard } = await import('./statcards.js');
2443
+ await runShare(argv, { aggregate: () => aggregateOr('render'), copy: copyToClipboard });
2444
+ }
2445
+
2416
2446
  async function doStatcards(argv) {
2417
2447
  const { runStatcards } = await import('./statcards.js');
2418
2448
  await runStatcards(argv, {
@@ -2470,6 +2500,7 @@ process.on('unhandledRejection', (e) => {
2470
2500
  case '__complete': await doComplete(args); break;
2471
2501
  case 'completion': await doCompletion(args); break;
2472
2502
  case 'statcards': await doStatcards(args); break;
2503
+ case 'share': await doShare(args); break;
2473
2504
  // `setup` and `install` are aliases as of v0.7: both register hooks AND
2474
2505
  // the login autostart entry (Windows Run key, macOS LaunchAgent, Linux
2475
2506
  // systemd --user unit). Older behavior split them (setup = no startup,
@@ -2554,6 +2585,7 @@ process.on('unhandledRejection', (e) => {
2554
2585
  // Optional GitHub connect — one explicit y/N, asked at most once ever.
2555
2586
  // The --link path above IS a connect, so it never double-asks.
2556
2587
  if (!linkCode) await setupGhConnect();
2588
+ await setupDiscordOffer();
2557
2589
  if (changed) await setupCompletionOffer();
2558
2590
  }
2559
2591
  setupOutro(target, changed, cli);
package/src/commands.js CHANGED
@@ -67,6 +67,10 @@ export const COMMANDS = [
67
67
  flags: [['--csv', 'Daily rows as CSV'], ['--out', 'Write to a file', 'file']] },
68
68
 
69
69
  // ── Share ──
70
+ { name: 'share', group: 'share', summary: 'Poster PNG + a ready caption on your clipboard', usage: '[week|month|year|all]',
71
+ subs: [['week', 'Last 7 days (default)'], ['month', 'Last 30 days'], ['year', 'Last 12 months'], ['all', 'All time']],
72
+ flags: [['--png', 'Where to save the image', 'file'], ['--no-png', 'Caption only'], ['--no-copy', 'Print, don\'t copy']],
73
+ examples: ['claude-rpc share', 'claude-rpc share month'] },
70
74
  { name: 'statcards', group: 'share', summary: 'Cards and badges as a live link, PNG or SVG', usage: '[card]',
71
75
  subs: [['stats', 'Stats + year heatmap'], ['profile', 'Profile card'], ['badge', 'Small badge'],
72
76
  ['heatmap', 'Year heatmap'], ['poster', 'Poster summary'], ['session', 'This session'],
package/src/doctor.js CHANGED
@@ -7,6 +7,7 @@
7
7
 
8
8
  import { existsSync, readFileSync, statSync, readdirSync } from 'node:fs';
9
9
  import { join } from 'node:path';
10
+ import { hookWord } from './shell-path.js';
10
11
  import {
11
12
  IS_PACKAGED, IS_NPM_INSTALL,
12
13
  CONFIG_PATH, CANONICAL_EXE, USER_CONFIG_DIR, HOOK_SCRIPT,
@@ -113,8 +114,10 @@ export function classifyHookCommand(cmd, {
113
114
  const launcher = m ? (m[1] ?? m[2]) : '';
114
115
  if (launcher && !launcher.includes('/') && !launcher.includes('\\')) return 'legacy';
115
116
  if (launcher && !exists(launcher)) return 'dead';
116
- if (packaged && !c.includes(canonicalExe)) return 'stale';
117
- if (npm && !c.includes(hookScript.replace(/\\/g, '/'))) return 'stale';
117
+ // Windows hooks may carry the 8.3 short form of the path (shell-path.js).
118
+ const wired = (p) => c.includes(p) || c.includes(p.replace(/\\/g, '/')) || c.includes(hookWord(p).replace(/"/g, ''));
119
+ if (packaged && !wired(canonicalExe)) return 'stale';
120
+ if (npm && !wired(hookScript)) return 'stale';
118
121
  return 'ok';
119
122
  }
120
123
 
package/src/install.js CHANGED
@@ -23,6 +23,7 @@ import { DEFAULT_CONFIG } from './default-config.js';
23
23
  import { VERSION } from './version.js';
24
24
  import { c, SYM_OK, SYM_WARN, SYM_FAIL, SYM_INFO, hintLine } from './ui.js';
25
25
  import { inferLegacyVerifyIntent } from './verify.js';
26
+ import { hookWord } from './shell-path.js';
26
27
 
27
28
  const STARTUP_KEY = 'HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Run';
28
29
  const STARTUP_VALUE = 'ClaudeRPC';
@@ -161,6 +162,20 @@ export function isOurHook(h) {
161
162
  return !!h && (h._claudeRpc === true || isOurHookCommand(h.command));
162
163
  }
163
164
 
165
+ // The scripts hooks and autostart launch. Normally this install's own; setup
166
+ // under npx repoints them at the global copy it just installed (see
167
+ // useGlobalInstall) — the _npx cache can be evicted at any time.
168
+ let hookScript = HOOK_SCRIPT;
169
+ let daemonScript = DAEMON_SCRIPT;
170
+
171
+ // The command Claude Code runs for `event`. See shell-path.js for why Windows
172
+ // paths are emitted bare / 8.3 instead of quoted (PowerShell hook shells).
173
+ export function hookCommand(exePath, event, { script = hookScript, node = process.execPath } = {}) {
174
+ return IS_PACKAGED
175
+ ? `${hookWord(exePath)} hook ${event}`
176
+ : `${hookWord(node)} ${hookWord(script)} ${event}`;
177
+ }
178
+
164
179
  export function installHooks(exePath, { silent = false, ccVersion = detectClaudeCodeVersion() } = {}) {
165
180
  const settings = readJson(CLAUDE_SETTINGS, {});
166
181
  const before = JSON.stringify(settings.hooks || {});
@@ -174,10 +189,7 @@ export function installHooks(exePath, { silent = false, ccVersion = detectClaude
174
189
  // for both npm and dev installs; only the packaged exe is self-contained. This
175
190
  // survives `npm update` (HOOK_SCRIPT is stable) and an nvm version switch (nvm
176
191
  // keeps prior versions on disk); re-run setup only if that node is removed.
177
- const node = process.execPath.replace(/\\/g, '/');
178
- const cmdFor = IS_PACKAGED
179
- ? (event) => `"${exePath}" hook ${event}`
180
- : (event) => `"${node}" "${HOOK_SCRIPT.replace(/\\/g, '/')}" ${event}`;
192
+ const cmdFor = (event) => hookCommand(exePath, event);
181
193
 
182
194
  const optional = supportedOptionalEvents(ccVersion);
183
195
  for (const event of Object.keys(OPTIONAL_EVENTS)) {
@@ -245,7 +257,7 @@ const SYSTEMD_UNIT = join(homedir(), '.config', 'systemd', 'user', SYSTEMD_UNIT_
245
257
  // (absolute node, like the hooks — login shells under nvm have no node on PATH).
246
258
  function daemonLaunch(exePath) {
247
259
  if (IS_PACKAGED) return { exe: exePath, args: ['daemon'] };
248
- return { exe: process.execPath, args: [DAEMON_SCRIPT] };
260
+ return { exe: process.execPath, args: [daemonScript] };
249
261
  }
250
262
 
251
263
  // `npm` with the flags every call here needs: npm is npm.cmd on Windows (so a
@@ -709,20 +721,22 @@ export function migrateConfig({ silent = false } = {}) {
709
721
  // command and report success, leaving the user to discover the breakage
710
722
  // the next time they open Claude Code. Returns { ok, detail }.
711
723
  function verifyHookPipe(exePath) {
712
- // Spawn exactly what installHooks wired: the packaged exe, or the absolute
713
- // node + hook.js. Both are absolute, so there's no PATH/PATHEXT/shell
714
- // resolution — it works under the same minimal hook shell Claude Code uses
715
- // (the reason the old `claude-rpc` / bare-`node` forms failed under nvm).
716
- const cmd = IS_PACKAGED ? exePath : process.execPath;
717
- const args = IS_PACKAGED ? ['hook', 'SessionStart'] : [HOOK_SCRIPT, 'SessionStart'];
724
+ // Run the exact command installHooks wired, through a shell Claude Code may
725
+ // use for hooks: sh on POSIX; on Windows, PowerShell — the strictest of its
726
+ // hook shells (a quoted-first command parses there as an expression, #48).
727
+ // Spawning node directly, as this used to, passed while every real hook
728
+ // failed.
729
+ const command = hookCommand(exePath, 'SessionStart');
730
+ const opts = { input: '', encoding: 'utf8', timeout: 8000, windowsHide: true };
718
731
  let result;
719
732
  try {
720
- result = spawnSync(cmd, args, {
721
- input: '',
722
- encoding: 'utf8',
723
- timeout: 3000,
724
- windowsHide: true,
725
- });
733
+ result = process.platform === 'win32'
734
+ ? spawnSync('powershell.exe', ['-NoProfile', '-NonInteractive', '-Command', command], opts)
735
+ : spawnSync('/bin/sh', ['-c', command], opts);
736
+ // No PowerShell on this box (stripped image) — fall back to cmd.
737
+ if (result.error?.code === 'ENOENT' && process.platform === 'win32') {
738
+ result = spawnSync(command, { ...opts, shell: true });
739
+ }
726
740
  } catch (e) {
727
741
  return { ok: false, detail: `spawn failed: ${e.message}` };
728
742
  }
@@ -759,15 +773,27 @@ function globalInstalledVersion() {
759
773
  } catch { return null; } // not installed / npm missing / unreadable
760
774
  }
761
775
 
776
+ // Point hooks + autostart at the global copy promoteNpxToGlobal installed,
777
+ // not this _npx cache tree. The global daemon's selfHealOnUpdate can't fix it
778
+ // later: the version stamp already matches, so it never re-wires (#48).
779
+ function useGlobalInstall() {
780
+ try {
781
+ const root = (npmSync(['root', '-g'], { timeout: 8000 }).stdout || '').trim();
782
+ const dir = root && join(root, 'claude-rpc', 'src');
783
+ if (dir && existsSync(join(dir, 'hook.js')) && existsSync(join(dir, 'daemon.js'))) {
784
+ hookScript = join(dir, 'hook.js');
785
+ daemonScript = join(dir, 'daemon.js');
786
+ }
787
+ } catch { /* npm unavailable — keep this tree; the next setup heals it */ }
788
+ }
789
+
762
790
  // `npx claude-rpc setup` runs from npm's _npx cache, which npm may evict at
763
791
  // any time, so first install the same version globally (`npm install -g`).
764
792
  // Best-effort + loud: a failed -g (perms, offline) returns false so the caller
765
793
  // stops with the manual command. What happens next: the rest of setup still
766
- // runs in THIS process, so installHooks and addStartupEntry wire the cache
767
- // copy's absolute HOOK_SCRIPT / DAEMON_SCRIPT paths; only the daemon launch
768
- // (cli.js `setup`) explicitly runs the global copy. That global daemon's
769
- // selfHealOnUpdate then re-wires hooks + autostart to the global paths — but
770
- // only when the version stamp doesn't already match this version.
794
+ // runs in THIS process; useGlobalInstall then repoints installHooks and
795
+ // addStartupEntry at the global copy, and the daemon launch (cli.js `setup`)
796
+ // runs the global copy explicitly.
771
797
  function promoteNpxToGlobal() {
772
798
  // Already promoted on a previous run AND current? Skip the redundant -g (also
773
799
  // lets setup succeed when a correct global exists but `npm -g` would fail —
@@ -867,6 +893,7 @@ export async function install({ exePath } = {}) {
867
893
  throw err;
868
894
  }
869
895
  step(SYM_OK, 'global install', `claude-rpc@${VERSION}`);
896
+ useGlobalInstall();
870
897
  }
871
898
  const incoming = exePath || process.execPath;
872
899
  // Canonicalize first so hook + startup entries point at a stable location,
package/src/scanner.js CHANGED
@@ -819,8 +819,14 @@ function readCache() {
819
819
  if (!existsSync(SCAN_CACHE_PATH)) return { _v: CACHE_VERSION, files: {} };
820
820
  try {
821
821
  const raw = JSON.parse(readFileSync(SCAN_CACHE_PATH, 'utf8'));
822
- if (!raw || raw._v !== CACHE_VERSION) return { _v: CACHE_VERSION, files: {} };
823
- return raw;
822
+ if (!raw || typeof raw.files !== 'object') return { _v: CACHE_VERSION, files: {} };
823
+ if (raw._v === CACHE_VERSION) return raw;
824
+ // A version bump re-parses everything still on disk, but `_gone` entries
825
+ // (transcripts Claude Code already pruned) can't be re-parsed — carry them
826
+ // over or the bump erases that history for good.
827
+ const files = {};
828
+ for (const [k, v] of Object.entries(raw.files || {})) if (v && v._gone) files[k] = v;
829
+ return { _v: CACHE_VERSION, files };
824
830
  } catch { return { _v: CACHE_VERSION, files: {} }; }
825
831
  }
826
832
 
@@ -1283,7 +1289,7 @@ export function scan({ projectsDir, projectsDirs, onProgress, force = false, ext
1283
1289
  let st;
1284
1290
  try { st = statSync(fp); } catch { continue; }
1285
1291
  const sig = `${st.mtimeMs}:${st.size}`;
1286
- if (!force && cache.files[fp]?._sig === sig) {
1292
+ if (!force && cache.files[fp]?._sig === sig && !cache.files[fp]._gone) {
1287
1293
  skipped += 1;
1288
1294
  continue;
1289
1295
  }
@@ -1300,18 +1306,32 @@ export function scan({ projectsDir, projectsDirs, onProgress, force = false, ext
1300
1306
  // skip corrupt file but keep prior cache entry
1301
1307
  }
1302
1308
  }
1303
- // Remove cache entries for transcripts that disappeared from disk. Only
1304
- // wipe entries whose root is one of the dirs we just scanned — otherwise
1305
- // a one-off backfill against a subset of dirs would nuke cache for
1306
- // unrelated paths.
1309
+ // Transcripts that disappeared from disk are KEPT as `_gone` entries, not
1310
+ // deleted. Claude Code prunes transcripts older than cleanupPeriodDays (30 by
1311
+ // default), and dropping them made every "lifetime" total — and the profile
1312
+ // slice the worker SETs from it — shrink as history aged out. A gone entry is
1313
+ // dropped only when the same transcript is still on disk under another path (a
1314
+ // moved/renamed project dir), which would otherwise count it twice. Only
1315
+ // entries under the dirs we just scanned are touched, so a one-off backfill
1316
+ // against a subset of dirs leaves unrelated paths alone.
1307
1317
  let removed = 0;
1308
1318
  const sep = process.platform === 'win32' ? '\\' : '/';
1309
1319
  const dirPrefixes = dirs.map((d) => d.replace(/[/\\]+$/, '') + sep);
1320
+ // Transcript basenames are the session (or subagent) id, so they survive a move.
1321
+ const baseOf = (p) => p.slice(Math.max(p.lastIndexOf('/'), p.lastIndexOf('\\')) + 1);
1322
+ const liveNames = new Set([...seen].map(baseOf));
1310
1323
  for (const key of Object.keys(cache.files)) {
1311
1324
  if (seen.has(key)) continue;
1312
- if (dirPrefixes.some((p) => key.startsWith(p))) {
1325
+ if (!dirPrefixes.some((p) => key.startsWith(p))) continue;
1326
+ const entry = cache.files[key];
1327
+ if (!entry || liveNames.has(baseOf(key))) {
1313
1328
  delete cache.files[key];
1314
1329
  removed += 1;
1330
+ } else if (!entry._gone) {
1331
+ // Append-parse bookkeeping is useless for a file that no longer exists.
1332
+ const { _parse, _offset, _size, ...kept } = entry;
1333
+ cache.files[key] = { ...kept, _gone: true };
1334
+ removed += 1;
1315
1335
  }
1316
1336
  }
1317
1337
  const changed = scanned > 0 || removed > 0;
package/src/share.js ADDED
@@ -0,0 +1,76 @@
1
+ // `claude-rpc share [week|month|year|all]` — one command to show people what
2
+ // you've been up to: saves the poster PNG for that window and copies a ready
3
+ // caption (your real numbers + a link back) to the clipboard. Nothing is
4
+ // posted anywhere; you paste it wherever you like.
5
+ //
6
+ // claude-rpc share last 7 days → ./claude-share-week.png + caption
7
+ // claude-rpc share month last 30 days
8
+ // claude-rpc share --no-png caption only
9
+ //
10
+ // The link is /get?ref=share so the worker can count what sharing brings in.
11
+
12
+ import { resolve, relative } from 'node:path';
13
+ import { c, fail, EX_USER_ERROR } from './ui.js';
14
+ import { fmtNum, fmtHours } from './fmt.js';
15
+
16
+ export const SHARE_URL = 'https://claude-rpc.com/get?ref=share';
17
+ const RANGES = ['week', 'month', 'year', 'all'];
18
+ const WINDOW = { week: 'last 7 days', month: 'last 30 days', year: 'last 12 months', all: 'all time' };
19
+
20
+ export function parseShareArgs(argv) {
21
+ const o = { range: 'week', png: true, path: null, copy: true };
22
+ for (let i = 0; i < argv.length; i++) {
23
+ const a = argv[i];
24
+ if (a === '--no-png') o.png = false;
25
+ else if (a === '--no-copy') o.copy = false;
26
+ else if (a === '--png' || a === '--out') {
27
+ const n = argv[i + 1];
28
+ if (!n || n.startsWith('-')) return { error: `${a} needs a path` };
29
+ o.path = n; i++;
30
+ } else if (RANGES.includes(a)) o.range = a;
31
+ else return { error: `unknown option ${a}` };
32
+ }
33
+ return o;
34
+ }
35
+
36
+ // The caption: real numbers for the window, skipping any that are zero so a
37
+ // quiet week doesn't read "0 prompts". `r` is card.js rollup() output.
38
+ export function shareCaption(r, { range = 'week', streak = 0 } = {}) {
39
+ const bits = [];
40
+ if (r.activeMs > 0) bits.push(`${fmtHours(r.activeMs)} with Claude Code`);
41
+ if (r.userMessages > 0) bits.push(`${fmtNum(r.userMessages)} prompts`);
42
+ if (r.tokens > 0) bits.push(`${fmtNum(r.tokens)} tokens`);
43
+ if (r.linesAdded > 0) bits.push(`+${fmtNum(r.linesAdded)} lines`);
44
+ if (streak > 1) bits.push(`${streak}-day streak`);
45
+ const head = bits.length ? `My ${WINDOW[range]}: ${bits.join(' · ')}.` : `Tracking my Claude Code sessions.`;
46
+ return `${head}\nLive on my Discord profile with claude-rpc → ${SHARE_URL}`;
47
+ }
48
+
49
+ // ctx: { aggregate(), copy(text) → tool|null }
50
+ export async function runShare(argv, ctx) {
51
+ const o = parseShareArgs(argv);
52
+ if (o.error) return fail(o.error, { hint: 'claude-rpc help share', code: EX_USER_ERROR });
53
+ const aggregate = ctx.aggregate();
54
+ const { rollup, renderCard } = await import('./card.js');
55
+ const caption = shareCaption(rollup(aggregate, o.range), { range: o.range, streak: aggregate?.streak || 0 });
56
+
57
+ console.log('');
58
+ if (o.png) {
59
+ const path = resolve(o.path || `claude-share-${o.range}.png`);
60
+ try {
61
+ const { svgToPng } = await import('./png.js');
62
+ const r = await svgToPng(renderCard(aggregate, { range: o.range }), path);
63
+ console.log(` ${c.green}✓${c.reset} saved ${c.cyan}${relative(process.cwd(), path) || path}${c.reset} ${c.dim}(${r.width}×${r.height}) — drag it into Discord, X or LinkedIn${c.reset}`);
64
+ } catch (e) {
65
+ // No PNG backend is not fatal — the caption is the important half.
66
+ console.log(` ${c.yellow}!${c.reset} ${c.dim}no image: ${e.message}${e.hint ? ` — ${e.hint}` : ''}${c.reset}`);
67
+ }
68
+ }
69
+ console.log('');
70
+ for (const line of caption.split('\n')) console.log(` ${line}`);
71
+ console.log('');
72
+ const tool = o.copy ? await ctx.copy(caption) : null;
73
+ if (tool) console.log(` ${c.magenta}⧉${c.reset} ${c.dim}caption copied — paste it with the image${c.reset}`);
74
+ else if (o.copy) console.log(` ${c.dim}no clipboard tool found — copy the caption above${c.reset}`);
75
+ console.log('');
76
+ }
@@ -0,0 +1,46 @@
1
+ // Paths for hook commands that every hook shell parses the same way.
2
+ //
3
+ // Claude Code runs hook commands through whatever shell the user has: sh /
4
+ // Git Bash, cmd, or PowerShell (issue #48). A line that STARTS with a quoted
5
+ // string is an expression in PowerShell, not a command, so the old
6
+ // `"C:/Program Files/nodejs/node.exe" "…/hook.js" Stop` form failed with
7
+ // "Unexpected token" on every event. PowerShell needs `& "…"`, which sh
8
+ // rejects. The shape all three accept is an unquoted path, so on Windows a
9
+ // path with spaces or shell metacharacters is swapped for its 8.3 short name
10
+ // (C:/PROGRA~1/nodejs/node.exe). Only when that isn't possible (8.3 names
11
+ // disabled on the volume) does it fall back to quoting.
12
+ import { existsSync } from 'node:fs';
13
+ import { spawnSync } from 'node:child_process';
14
+
15
+ // Characters no hook shell treats specially in a bare word.
16
+ const BARE_SAFE = /^[\w:./\\~+-]+$/;
17
+ const shortCache = new Map();
18
+
19
+ // 8.3 short form of an existing Windows path via cmd's %~s modifier, or null.
20
+ // `/c` without `/s` keeps cmd from stripping the quotes around the path.
21
+ export function shortPathWin(p, { spawn = spawnSync, exists = existsSync } = {}) {
22
+ if (shortCache.has(p)) return shortCache.get(p);
23
+ let out = null;
24
+ if (exists(p)) {
25
+ try {
26
+ const r = spawn('cmd.exe', ['/d', '/c', `for %I in ("${p.replace(/\//g, '\\')}") do @echo %~sI`], {
27
+ encoding: 'utf8', timeout: 4000, windowsHide: true, windowsVerbatimArguments: true,
28
+ });
29
+ const line = String(r.stdout || '').trim().split(/\r?\n/).pop();
30
+ if (r.status === 0 && line) out = line.replace(/\\/g, '/');
31
+ } catch { /* cmd unavailable — caller quotes */ }
32
+ }
33
+ shortCache.set(p, out);
34
+ return out;
35
+ }
36
+
37
+ // One argv word of a hook command. POSIX keeps the long-standing quoted form
38
+ // (sh is the only hook shell there). Windows: bare when safe, else the short
39
+ // path, else quoted as a last resort.
40
+ export function hookWord(p, { platform = process.platform, shortPath = shortPathWin } = {}) {
41
+ const fwd = String(p).replace(/\\/g, '/');
42
+ if (platform !== 'win32') return `"${fwd}"`;
43
+ if (BARE_SAFE.test(fwd)) return fwd;
44
+ const short = shortPath(fwd);
45
+ return short && BARE_SAFE.test(short) ? short : `"${fwd}"`;
46
+ }
package/src/version.js CHANGED
@@ -11,7 +11,7 @@ import { readFileSync } from 'node:fs';
11
11
  import { join } from 'node:path';
12
12
  import { ROOT } from './paths.js';
13
13
 
14
- const BAKED = '1.7.0';
14
+ const BAKED = '1.7.2';
15
15
 
16
16
  function readPkgVersion() {
17
17
  try {