claude-rpc 1.6.0 → 1.7.1

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
@@ -15,7 +15,7 @@
15
15
 
16
16
  **Discord Rich Presence for [Claude Code](https://claude.com/claude-code)** — your live model, project, tokens, and lifetime stats, driven by the hooks Claude Code already fires.
17
17
 
18
- **[claude-rpc.com →](https://claude-rpc.com)** — see it in one page.
18
+ **[claude-rpc.com →](https://claude-rpc.com)** — see it in one page. · **[Discord →](https://claude-rpc.com/discord?s=readme)** — help, ideas, show your card.
19
19
 
20
20
  [![community · sessions](https://claude-rpc-totals.claude-rpc.workers.dev/sessions.svg)](#community-totals)   [![community · tokens](https://claude-rpc-totals.claude-rpc.workers.dev/tokens.svg)](#community-totals)
21
21
 
@@ -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/SECURITY.md CHANGED
@@ -137,11 +137,11 @@ described under **Scope** below.
137
137
 
138
138
  ## 3. Outbound network
139
139
 
140
- There are six distinct network behaviors: community totals (3a), gist
140
+ There are seven distinct network behaviors: community totals (3a), gist
141
141
  publishing (3b), squads/web login (3c), subscription-usage polling (3d),
142
- the cosmetic GIF assets (3e), and the opt-in status webhook (3f). Each is
143
- independently optional. The separate desktop dashboard app, if installed,
144
- additionally auto-updates itself (3g).
142
+ the cosmetic GIF assets (3e), the opt-in status webhook (3f), and the
143
+ CLI auto-update check (3h). Each is independently optional. The separate
144
+ desktop dashboard app, if installed, additionally auto-updates itself (3g).
145
145
 
146
146
  ### 3a. Community totals (telemetry) — ON by default for fresh installs
147
147
 
@@ -342,20 +342,36 @@ removing `webhook.url`.
342
342
 
343
343
  ### 3g. Desktop dashboard auto-update — the optional Electron app only
344
344
 
345
- **Source:** `dashboard/main.js` (`initAutoUpdater`, electron-updater). The npm
346
- CLI package never auto-updates. The *separate* desktop dashboard app, if you
345
+ **Source:** `dashboard/main.js` (`initAutoUpdater`, electron-updater). The *separate* desktop dashboard app, if you
347
346
  install it, polls GitHub Releases hourly and downloads + installs updates on
348
347
  quit (`autoDownload` / `autoInstallOnAppQuit`) over HTTPS. The release binaries
349
348
  are currently **unsigned**, so update integrity rests on GitHub Releases + TLS
350
349
  rather than a code signature — a known gap tracked for provenance + published
351
350
  checksums. Avoid it by not installing the dashboard.
352
351
 
352
+ ### 3h. CLI auto-update — ON by default, npm global installs only
353
+
354
+ **Source:** `src/updater.js`, called from the daemon; settings in
355
+ `default-config.js` (`update`). Every ~6 hours the daemon sends one plain
356
+ `GET https://registry.npmjs.org/claude-rpc/latest` (no identifiers, no
357
+ payload) and reads the `version` field. If a newer **same-major** release
358
+ exists and this copy was installed with `npm install -g`, it runs
359
+ `npm install -g claude-rpc@<exact version>` and restarts itself — the same
360
+ package, same npm integrity and provenance checks as a manual install.
361
+ Homebrew, `npx`, the packaged exe and source checkouts are never modified (they
362
+ only log that an update exists). A new major version is never installed
363
+ unattended, a failed install is not retried for 24 hours, and the version
364
+ string is validated as `x.y.z` before it reaches the command line.
365
+ **Turn it off:** `claude-rpc update off` (or `update.auto: false`).
366
+ `claude-rpc update` checks by hand; `claude-rpc update now` installs.
367
+
353
368
  ## 4. Local subprocesses
354
369
 
355
370
  Every binary the package can spawn, with its trigger and argument shape. All
356
371
  arguments are static constants or values we control — none interpolate
357
372
  untrusted or remote input into a shell:
358
373
 
374
+ - `npm install -g claude-rpc@<x.y.z>` — auto-update / `update now` (`src/updater.js`, 3h).
359
375
  - `reg.exe add/delete` — the Windows Run key (`src/install.js`).
360
376
  - `wscript.exe` — runs the generated windowless startup shim (`src/install.js`).
361
377
  - `powershell.exe -NoProfile -NonInteractive -EncodedCommand …` — packaged
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "claude-rpc",
3
- "version": "1.6.0",
3
+ "version": "1.7.1",
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
@@ -2190,6 +2190,47 @@ async function doCommunity(argv) {
2190
2190
  });
2191
2191
  }
2192
2192
 
2193
+ async function doUpdate(argv) {
2194
+ const sub = (argv[0] || 'check').toLowerCase();
2195
+ const { installKind, updateCommand, fetchLatest, isNewer, sameMajor, installVersion, readUpdateState, writeUpdateState } = await import('./updater.js');
2196
+ const kind = installKind();
2197
+ const userCfg = readJson(CONFIG_PATH, {});
2198
+ const auto = loadConfig().update?.auto !== false;
2199
+ if (sub === 'on' || sub === 'off') {
2200
+ userCfg.update = { ...userCfg.update, auto: sub === 'on' };
2201
+ writeUserConfig(userCfg);
2202
+ console.log(` ${c.green}✓${c.reset} auto-update ${sub === 'on' ? 'on' : 'off'}`);
2203
+ return;
2204
+ }
2205
+ if (sub === 'status') {
2206
+ const st = readUpdateState();
2207
+ console.log(` ${c.cyan}·${c.reset} v${VERSION} · installed via ${kind} · auto-update ${auto && kind === 'npm-global' ? 'on' : kind === 'npm-global' ? 'off' : 'n/a'}`);
2208
+ if (st.updatedTo) console.log(` ${c.dim}last auto-update: ${st.updatedFrom} → ${st.updatedTo}${c.reset}`);
2209
+ return;
2210
+ }
2211
+ if (sub !== 'check' && sub !== 'now') {
2212
+ fail(`unknown update subcommand: ${sub}`, { hint: 'try: update [check|now|on|off|status]', code: EX_USER_ERROR });
2213
+ }
2214
+ const latest = await fetchLatest();
2215
+ if (!latest) fail('could not reach the npm registry', { hint: 'check your connection and try again', code: EX_BAD_STATE });
2216
+ if (!isNewer(latest, VERSION)) {
2217
+ console.log(` ${c.green}✓${c.reset} up to date ${c.dim}(v${VERSION})${c.reset}`);
2218
+ return;
2219
+ }
2220
+ console.log(` ${c.yellow}!${c.reset} v${latest} is available ${c.dim}(you have v${VERSION})${c.reset}`);
2221
+ if (kind !== 'npm-global' || sub === 'check') {
2222
+ console.log(` ${c.gray}↳ ${c.reset}${c.cyan}${kind === 'npm-global' ? 'claude-rpc update now' : updateCommand(kind)}${c.reset}`);
2223
+ return;
2224
+ }
2225
+ if (!sameMajor(latest, VERSION)) console.log(` ${c.dim}new major version — check the changelog first${c.reset}`);
2226
+ console.log(` ${c.dim}installing…${c.reset}`);
2227
+ const res = await installVersion(latest);
2228
+ if (!res.ok) fail('install failed', { hint: [res.output.slice(-300) || 'npm exited non-zero', `try: ${updateCommand(kind)}`], code: EX_BAD_STATE });
2229
+ writeUpdateState({ updatedFrom: VERSION, updatedTo: latest, updatedAt: Date.now(), failed: null });
2230
+ console.log(` ${c.green}✓${c.reset} updated to v${latest}`);
2231
+ await restartDaemon();
2232
+ }
2233
+
2193
2234
  function tailLog() {
2194
2235
  if (!existsSync(LOG_PATH)) {
2195
2236
  console.log(` ${c.yellow}!${c.reset} no log yet ${c.dim}${LOG_PATH}${c.reset}`);
@@ -2354,6 +2395,30 @@ async function doCompletion(argv) {
2354
2395
  }
2355
2396
 
2356
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
+
2357
2422
  async function setupCompletionOffer() {
2358
2423
  if (!process.stdin.isTTY || !process.stdout.isTTY || process.env.CLAUDE_RPC_NO_COMPLETION) return;
2359
2424
  const comp = await import('./completion.js');
@@ -2372,6 +2437,12 @@ async function setupCompletionOffer() {
2372
2437
  }
2373
2438
  }
2374
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
+
2375
2446
  async function doStatcards(argv) {
2376
2447
  const { runStatcards } = await import('./statcards.js');
2377
2448
  await runStatcards(argv, {
@@ -2429,6 +2500,7 @@ process.on('unhandledRejection', (e) => {
2429
2500
  case '__complete': await doComplete(args); break;
2430
2501
  case 'completion': await doCompletion(args); break;
2431
2502
  case 'statcards': await doStatcards(args); break;
2503
+ case 'share': await doShare(args); break;
2432
2504
  // `setup` and `install` are aliases as of v0.7: both register hooks AND
2433
2505
  // the login autostart entry (Windows Run key, macOS LaunchAgent, Linux
2434
2506
  // systemd --user unit). Older behavior split them (setup = no startup,
@@ -2513,6 +2585,7 @@ process.on('unhandledRejection', (e) => {
2513
2585
  // Optional GitHub connect — one explicit y/N, asked at most once ever.
2514
2586
  // The --link path above IS a connect, so it never double-asks.
2515
2587
  if (!linkCode) await setupGhConnect();
2588
+ await setupDiscordOffer();
2516
2589
  if (changed) await setupCompletionOffer();
2517
2590
  }
2518
2591
  setupOutro(target, changed, cli);
@@ -2588,6 +2661,7 @@ process.on('unhandledRejection', (e) => {
2588
2661
  case 'public': await doPublic(); break;
2589
2662
  case 'privacy': await doPrivacy(); break;
2590
2663
  case 'community': await doCommunity(args); break;
2664
+ case 'update': await doUpdate(args); break;
2591
2665
  case 'profile': await doProfile(args); break;
2592
2666
  case 'squad': await doSquadCmd(args); break;
2593
2667
  case 'link': await doLink(args); break;
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'],
@@ -103,6 +107,9 @@ export const COMMANDS = [
103
107
  { name: 'community', group: 'online', summary: 'Anonymous community totals', usage: '[status|on|off|report]',
104
108
  subs: [['status', 'Show it'], ['on', 'Opt in'], ['off', 'Opt out'], ['report', 'Send now']] },
105
109
 
110
+ { name: 'update', group: 'daemon', summary: 'Check for a new version (and auto-update)', usage: '[check|now|on|off|status]',
111
+ subs: [['check', 'Look for a newer release'], ['now', 'Install it now'], ['on', 'Auto-update (default)'], ['off', 'Never update unattended'], ['status', 'Show settings']] },
112
+
106
113
  // ── Daemon ──
107
114
  { name: 'start', group: 'daemon', summary: 'Start the Discord daemon' },
108
115
  { name: 'stop', group: 'daemon', summary: 'Stop it' },
package/src/daemon.js CHANGED
@@ -18,7 +18,8 @@ import { desktopNotify, postWebhook, shouldWebhook, shouldNotify, sanitizeLabel
18
18
  import { CONFIG_PATH, STATE_PATH, PID_PATH, LOG_PATH, STATE_DIR, AGGREGATE_PATH, PAUSE_PATH } from './paths.js';
19
19
  import { readUsageCache, pollUsage } from './usage.js';
20
20
  import { pollDecision, pollIntervalMs } from './watch-poll.js';
21
- import { claimSingleInstance } from './ensure-daemon.js';
21
+ import { claimSingleInstance, spawnDaemonDetached } from './ensure-daemon.js';
22
+ import { checkForUpdate } from './updater.js';
22
23
  import { scanInChild } from './scan-worker.js';
23
24
 
24
25
  if (!existsSync(STATE_DIR)) mkdirSync(STATE_DIR, { recursive: true });
@@ -975,6 +976,31 @@ async function runCommunityFlush() {
975
976
  const communityFlushMs = Math.max(60_000, (config.community?.flushIntervalMin || 30) * 60 * 1000);
976
977
  setInterval(runCommunityFlush, communityFlushMs);
977
978
 
979
+ // Auto-update: check the registry, install a newer same-major release (npm
980
+ // global installs only), then hand over to a fresh daemon. The PID file is
981
+ // removed first so the replacement's single-instance claim succeeds while this
982
+ // process is still winding down.
983
+ async function runUpdateCheck() {
984
+ try {
985
+ const r = await checkForUpdate({ current: VERSION, auto: config.update?.auto !== false });
986
+ if (r.installed) {
987
+ log(`auto-update: ${VERSION} → ${r.latest} installed; restarting`);
988
+ try { if (existsSync(PID_PATH)) unlinkSync(PID_PATH); } catch { /* shutdown() retries */ }
989
+ spawnDaemonDetached();
990
+ setTimeout(shutdown, 500);
991
+ } else if (r.error) {
992
+ log(`auto-update: install of ${r.latest} failed: ${String(r.error).slice(-200)}`);
993
+ } else if (r.plan.action === 'notify') {
994
+ log(`auto-update: ${r.latest} available (${r.plan.reason})`);
995
+ }
996
+ } catch (e) {
997
+ log('auto-update check threw:', e.message);
998
+ }
999
+ }
1000
+ const updateEveryMs = Math.max(3_600_000, (config.update?.checkIntervalHours || 6) * 3_600_000);
1001
+ setInterval(runUpdateCheck, updateEveryMs);
1002
+ setTimeout(runUpdateCheck, 5 * 60_000);
1003
+
978
1004
  // Subscription-usage poll (feeds {usageWeeklyPct} & friends + `claude-rpc
979
1005
  // usage`). Only while something is live — no point burning requests against
980
1006
  // an idle account — and backs off to hourly retries after a bad run, since
@@ -146,6 +146,13 @@ export const DEFAULT_CONFIG = {
146
146
  endpoint: "https://claude-rpc-totals.claude-rpc.workers.dev",
147
147
  flushIntervalMin: 30,
148
148
  },
149
+ // Auto-update (npm global installs only; brew/npx/exe/source just get a
150
+ // notice). Same-major releases are installed unattended and the daemon
151
+ // restarts itself. Kill switch: `claude-rpc update off`. SECURITY.md §3h.
152
+ update: {
153
+ auto: true,
154
+ checkIntervalHours: 6,
155
+ },
149
156
  // Subscription usage — the numbers Claude Code's own /usage screen shows
150
157
  // (5h session %, weekly %). The daemon reads Claude Code's OAuth token
151
158
  // LOCALLY and asks api.anthropic.com — the token's issuer — for the
@@ -258,10 +265,10 @@ export const DEFAULT_CONFIG = {
258
265
  buttons: [
259
266
  // The card others see in Discord is the project's main distribution
260
267
  // surface — make the button a real call-to-action, not a bare repo link.
261
- // ?ref=discord lets the landing page attribute installs that originate
262
- // from a presence card. (When the cwd is a github repo the daemon also
268
+ // Lands on /get (install first, then the Discord invite). ?ref=discord
269
+ // lets that page attribute installs that originate from a presence card. (When the cwd is a github repo the daemon also
263
270
  // prepends a "View on GitHub →" button, so both can show.)
264
- { label: "Get claude-rpc →", url: "https://claude-rpc.com/?ref=discord" },
271
+ { label: "Get claude-rpc →", url: "https://claude-rpc.com/get?ref=discord" },
265
272
  ],
266
273
  },
267
274
  statusIcons: {
package/src/install.js CHANGED
@@ -649,6 +649,7 @@ export function migrateConfig({ silent = false } = {}) {
649
649
  const SHIPPED_DEFAULT_BTNS = [
650
650
  { label: 'Claude Code', url: 'https://claude.com/claude-code' },
651
651
  { label: 'Claude Code', url: 'https://github.com/rar-file/claude-rpc' },
652
+ { label: 'Get claude-rpc →', url: 'https://claude-rpc.com/?ref=discord' }, // v0.13–1.6 CTA → /get
652
653
  ];
653
654
  if (NEW_BTN && Array.isArray(cfg.presence?.buttons)) {
654
655
  let changed = false;
@@ -942,6 +943,7 @@ export function setupOutro(target, changed = true, cli = { cmd: 'claude-rpc', ne
942
943
  const run = cli.cmd || 'claude-rpc';
943
944
  console.log('');
944
945
  console.log(` ${SYM_OK} ${c.bold}setup complete${c.reset} — open Claude Code and send a prompt; your card goes live in Discord.`);
946
+ point('community', 'claude-rpc.com/discord?s=cli', 'questions, show your card');
945
947
  point('verify wiring', `${run} doctor`, cli.newTerminal ? 'in a new terminal' : '');
946
948
  if (IS_PACKAGED) point('start daemon', `"${target}" daemon`, 'also runs automatically at login');
947
949
  else point('manage daemon', `${run} start · stop · status`);
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
+ }
package/src/updater.js ADDED
@@ -0,0 +1,141 @@
1
+ // Auto-update for npm global installs.
2
+ //
3
+ // The daemon checks the npm registry every few hours; when a newer release in
4
+ // the SAME major line exists it runs `npm install -g claude-rpc@<exact
5
+ // version>`, then restarts itself. Hooks and config follow on their own — the
6
+ // daemon's self-heal-on-update (daemon.js) re-wires them on first boot of the
7
+ // new version. Everything else (brew, npx, the packaged exe, a source checkout)
8
+ // is never touched: those get a one-line "update available" with the right
9
+ // command. A new MAJOR is never installed unattended.
10
+ //
11
+ // Pure decision functions up top (unit-tested); side effects below.
12
+
13
+ import { readFileSync, writeFileSync, mkdirSync } from 'node:fs';
14
+ import { join, dirname, delimiter } from 'node:path';
15
+ import { STATE_DIR, ROOT, IS_PACKAGED, IS_NPM_INSTALL, IS_NPX } from './paths.js';
16
+
17
+ export const UPDATE_STATE_PATH = join(STATE_DIR, 'update.json');
18
+ export const REGISTRY_URL = 'https://registry.npmjs.org/claude-rpc/latest';
19
+ const RETRY_FAILED_MS = 24 * 3_600_000; // don't hammer a version that failed to install
20
+ const COOLDOWN_MS = 2 * 3_600_000; // a release must be seen this long before it's installed — a yank window
21
+ const INSTALL_TIMEOUT_MS = 180_000;
22
+ const FETCH_TIMEOUT_MS = 8_000;
23
+
24
+ const SEMVER = /^(\d+)\.(\d+)\.(\d+)$/; // no prereleases: only stable tags are ever considered
25
+
26
+ export function parseVersion(v) {
27
+ const m = SEMVER.exec(String(v || '').trim());
28
+ return m ? [Number(m[1]), Number(m[2]), Number(m[3])] : null;
29
+ }
30
+
31
+ export function isNewer(latest, current) {
32
+ const a = parseVersion(latest), b = parseVersion(current);
33
+ if (!a || !b) return false;
34
+ for (let i = 0; i < 3; i++) if (a[i] !== b[i]) return a[i] > b[i];
35
+ return false;
36
+ }
37
+
38
+ export function sameMajor(a, b) {
39
+ const x = parseVersion(a), y = parseVersion(b);
40
+ return !!x && !!y && x[0] === y[0];
41
+ }
42
+
43
+ // How this copy was installed → whether we may update it ourselves and what to
44
+ // tell the user otherwise.
45
+ export function installKind({ packaged = IS_PACKAGED, npm = IS_NPM_INSTALL, npx = IS_NPX, root = ROOT } = {}) {
46
+ if (packaged) return 'packaged';
47
+ if (npx) return 'npx';
48
+ if (/[\\/]Cellar[\\/]/.test(root)) return 'brew';
49
+ if (npm) return 'npm-global';
50
+ return 'dev';
51
+ }
52
+
53
+ export function updateCommand(kind) {
54
+ switch (kind) {
55
+ case 'packaged': return 'download the latest release from https://github.com/rar-file/claude-rpc/releases/latest';
56
+ case 'npx': return 'npx claude-rpc@latest setup';
57
+ case 'brew': return 'brew upgrade claude-rpc';
58
+ case 'dev': return 'git pull';
59
+ default: return 'npm install -g claude-rpc@latest';
60
+ }
61
+ }
62
+
63
+ // → { action: 'none' | 'notify' | 'install', reason }
64
+ export function planUpdate({ current, latest, auto = true, kind, failed = null, seen = null, cooldownMs = COOLDOWN_MS, now = Date.now() }) {
65
+ if (!isNewer(latest, current)) return { action: 'none', reason: 'up to date' };
66
+ if (kind !== 'npm-global') return { action: 'notify', reason: `installed via ${kind}` };
67
+ if (!auto) return { action: 'notify', reason: 'auto-update is off' };
68
+ if (!sameMajor(latest, current)) return { action: 'notify', reason: 'new major version — update manually' };
69
+ if (failed && failed.version === latest && now - failed.at < RETRY_FAILED_MS) {
70
+ return { action: 'notify', reason: 'last install attempt failed — retrying later' };
71
+ }
72
+ if (cooldownMs > 0 && !(seen && seen.version === latest && now - seen.at >= cooldownMs)) {
73
+ return { action: 'notify', reason: 'new release is settling — installing after the cooldown' };
74
+ }
75
+ return { action: 'install', reason: 'newer release available' };
76
+ }
77
+
78
+ export function readUpdateState(path = UPDATE_STATE_PATH) {
79
+ try { return JSON.parse(readFileSync(path, 'utf8')) || {}; } catch { return {}; }
80
+ }
81
+ export function writeUpdateState(patch, path = UPDATE_STATE_PATH) {
82
+ try {
83
+ mkdirSync(STATE_DIR, { recursive: true });
84
+ writeFileSync(path, JSON.stringify({ ...readUpdateState(path), ...patch }));
85
+ } catch { /* best-effort: state is advisory */ }
86
+ }
87
+
88
+ // Latest published version, or null on any failure. Only the version string is
89
+ // read; nothing about this machine is sent (a bare GET to the public registry).
90
+ export async function fetchLatest({ url = REGISTRY_URL, timeoutMs = FETCH_TIMEOUT_MS } = {}) {
91
+ try {
92
+ const res = await fetch(url, { signal: AbortSignal.timeout(timeoutMs), headers: { accept: 'application/json' } });
93
+ if (!res.ok) return null;
94
+ const v = (await res.json())?.version;
95
+ return parseVersion(v) ? v : null;
96
+ } catch { return null; }
97
+ }
98
+
99
+ // Install exactly `version` globally. Resolves { ok, output }. `npm` is a .cmd
100
+ // shim on Windows, which only spawns through a shell.
101
+ export async function installVersion(version) {
102
+ if (!parseVersion(version)) return { ok: false, output: 'bad version' }; // also keeps the shell arg safe
103
+ const { spawn } = await import('node:child_process');
104
+ return new Promise((resolve) => {
105
+ let out = '';
106
+ const win = process.platform === 'win32';
107
+ const child = spawn(win ? 'npm.cmd' : 'npm', ['install', '-g', `claude-rpc@${version}`, '--no-fund', '--no-audit'],
108
+ // Put the running node's own dir first so `npm` is the one that belongs to
109
+ // this node (nvm/fnm/volta installs; a login-launched daemon often has a
110
+ // bare PATH) — i.e. the npm that created the global we're replacing.
111
+ { shell: win, windowsHide: true, stdio: ['ignore', 'pipe', 'pipe'],
112
+ env: { ...process.env, PATH: `${dirname(process.execPath)}${delimiter}${process.env.PATH || ''}` } });
113
+ const timer = setTimeout(() => { try { child.kill(); } catch { /* gone */ } }, INSTALL_TIMEOUT_MS);
114
+ const take = (d) => { out = (out + d).slice(-2000); };
115
+ child.stdout.on('data', take); child.stderr.on('data', take);
116
+ child.on('error', (e) => { clearTimeout(timer); resolve({ ok: false, output: e.message }); });
117
+ child.on('close', (code) => { clearTimeout(timer); resolve({ ok: code === 0, output: out.trim() }); });
118
+ });
119
+ }
120
+
121
+ // One check cycle. Returns { plan, latest, installed }. `install` is injectable
122
+ // for tests; callers restart the daemon when `installed` is true.
123
+ export async function checkForUpdate({ current, auto, kind = installKind(), fetchLatestFn = fetchLatest, install = installVersion, now = Date.now(), cooldownMs = COOLDOWN_MS, statePath = UPDATE_STATE_PATH } = {}) {
124
+ const latest = await fetchLatestFn();
125
+ writeUpdateState({ checkedAt: now, ...(latest ? { latest } : {}) }, statePath);
126
+ if (!latest) return { plan: { action: 'none', reason: 'registry unreachable' }, latest: null, installed: false };
127
+ let state = readUpdateState(statePath);
128
+ if (state.seen?.version !== latest) { // first sighting starts the cooldown clock
129
+ writeUpdateState({ seen: { version: latest, at: now } }, statePath);
130
+ state = readUpdateState(statePath);
131
+ }
132
+ const plan = planUpdate({ current, latest, auto, kind, failed: state.failed || null, seen: state.seen || null, cooldownMs, now });
133
+ if (plan.action !== 'install') return { plan, latest, installed: false };
134
+ const res = await install(latest);
135
+ if (res.ok) {
136
+ writeUpdateState({ updatedFrom: current, updatedTo: latest, updatedAt: now, failed: null }, statePath);
137
+ return { plan, latest, installed: true };
138
+ }
139
+ writeUpdateState({ failed: { version: latest, at: now, output: res.output.slice(-300) } }, statePath);
140
+ return { plan: { action: 'notify', reason: 'install failed' }, latest, installed: false, error: res.output };
141
+ }
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.6.0';
14
+ const BAKED = '1.7.1';
15
15
 
16
16
  function readPkgVersion() {
17
17
  try {