claude-rpc 1.9.0 → 1.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -205,7 +205,7 @@ claude-rpc community on # explicit consent flow (upgraders / re-enable
205
205
  claude-rpc community report # one-shot manual flush (testing)
206
206
  ```
207
207
 
208
- Each report sends only: a `sessionsDelta`, a `tokensDelta`, the claude-rpc version, OS family (`linux`/`darwin`/`win32`), and the anonymous UUID v4. No prompts, paths, models, repos, costs, usernames, or hostnames — the Worker's [`validateReport`](worker/src/index.js) is the schema of record. The full Worker source is in this repo so the privacy claim is auditable. Every worker route — path, params, response — is documented in [`docs/WORKER-API.md`](docs/WORKER-API.md).
208
+ Each report sends only: a `sessionsDelta`, a `tokensDelta`, the claude-rpc version, OS family (`linux`/`darwin`/`win32`), how it was installed (npm / npx / brew / exe), how its last auto-update went, the names of claude-rpc commands you used in the last 7 days, and the anonymous UUID v4. No prompts, paths, models, repos, costs, usernames, or hostnames — the Worker's [`validateReport`](worker/src/index.js) is the schema of record. The full Worker source is in this repo so the privacy claim is auditable. Every worker route — path, params, response — is documented in [`docs/WORKER-API.md`](docs/WORKER-API.md).
209
209
 
210
210
  For a complete account of the sensitive things claude-rpc does — startup persistence, hook injection, every outbound request, and the exact telemetry payload — see [`SECURITY.md`](SECURITY.md). It's also the reference for supply-chain scanner findings (Socket.dev et al.): the flagged persistence and hook-injection behaviors are inherent to the tool and documented there.
211
211
 
@@ -338,7 +338,6 @@ It's a thin bootstrapper — on the first session it just runs `npx claude-rpc@l
338
338
  | `pause [30m\|2h\|off\|status]` | Hide the card everywhere for a while (default 1h) |
339
339
  | **Online** | |
340
340
  | `profile` | Opt-in public leaderboard profile: `status` \| `set` \| `on` \| `off` \| `publish` \| `verify` |
341
- | `squad` | Private mini-leaderboards with friends: `status` \| `create <name>` \| `join <code>` \| `leave [id]` |
342
341
  | `link [code]` | One profile across machines: `link` mints a code on your verified machine, `link <code>` claims it on the new one |
343
342
  | `community` | Anonymous community totals, on by default for fresh installs: `status` \| `off` \| `on` \| `report` |
344
343
  | **Daemon** | |
package/SECURITY.md CHANGED
@@ -138,7 +138,7 @@ described under **Scope** below.
138
138
  ## 3. Outbound network
139
139
 
140
140
  There are seven distinct network behaviors: community totals (3a), gist
141
- publishing (3b), squads/web login (3c), subscription-usage polling (3d),
141
+ publishing (3b), web login & the public profile (3c), subscription-usage polling (3d),
142
142
  the cosmetic GIF assets (3e), the opt-in status webhook (3f), and the
143
143
  CLI auto-update check (3h). Each is independently optional. The separate
144
144
  desktop dashboard app, if installed, additionally auto-updates itself (3g).
@@ -159,12 +159,23 @@ The **complete** payload (see `buildPayload`, enforced by the Worker's
159
159
  "instanceId": "<random UUID v4>",
160
160
  "sessionsDelta": 3,
161
161
  "tokensDelta": 142000,
162
- "version": "0.7.3",
162
+ "version": "1.10.0",
163
163
  "osFamily": "win32",
164
+ "install": "packaged",
165
+ "upd": "ok",
166
+ "feat": ["settings", "status", "tui"],
164
167
  "ts": 1716500000000
165
168
  }
166
169
  ```
167
170
 
171
+ The last three (1.10+, `usageFacts` in `src/community.js`, allowlisted by the
172
+ Worker's `usageFields`) say how this copy was installed (`npm-global` / `npx` /
173
+ `brew` / `packaged` / `dev`), how its last auto-update went (`ok` / `off` /
174
+ `manual` / `perm` / `failed` / `pending` / `unknown`), and the **names** of
175
+ claude-rpc commands used on this machine in the last 7 days. Never arguments,
176
+ counts, or timestamps. The local record is `feature-usage.json` in the state
177
+ directory (command name → last-used time).
178
+
168
179
  What is **not** sent, ever: prompts, responses, file paths, file contents,
169
180
  project/repo names, models, cost figures, usernames, hostnames, IP (beyond what
170
181
  any HTTP request inherently exposes to Cloudflare's edge), or absolute counter
@@ -178,7 +189,7 @@ values — only forward deltas since the last accepted report.
178
189
  The trade-off is disclosed here, in the README, and at install time.
179
190
  - **Auditable:** for these reports the Worker persists only one
180
191
  `total:counters` value (the two running sums, `{sessions, tokens}`), a
181
- 30-day `seen:<instanceId>` active-install marker (`{ts, version, osFamily}`,
192
+ 30-day `seen:<instanceId>` active-install marker (`{ts, version, osFamily, install, upd, feat}`,
182
193
  refreshed at most daily), and rate-limit keys that expire within a minute.
183
194
  The source is in this repo.
184
195
 
@@ -190,13 +201,9 @@ Publishes a badge SVG to *your own* GitHub gist via the `gh` CLI or a
190
201
  `gist.github.com`. Never runs unattended, never on install, never from the
191
202
  daemon.
192
203
 
193
- ### 3c. Squads & web login — opt-in, profile-derived
204
+ ### 3c. Web login & public profile — opt-in
194
205
 
195
- **Source:** `worker/src/index.js` (+ `worker/src/auth.js`), `src/cli.js`
196
- (`squad` command), `site/squad.html`. Squads are private mini-leaderboards
197
- that regroup stats you **already publish** via the opt-in profile — joining
198
- one sends nothing new from your machine; the worker derives weekly standings
199
- from the same clamped lifetime totals the public board uses.
206
+ **Source:** `worker/src/index.js` (+ `worker/src/auth.js`), `site/link.html`.
200
207
 
201
208
  "Log in with GitHub" on the website is plain OAuth (no scopes — public
202
209
  identity only; we never see email or repos). Sessions are stateless signed
@@ -204,9 +211,7 @@ tokens holding **only your public GitHub login**, stored in your browser's
204
211
  localStorage and expiring after 7 days. The browser never receives an
205
212
  `instanceId` — that remains the CLI's local credential; the worker resolves
206
213
  GitHub login → profile via the link your own gist verification created.
207
- Worker-side storage adds: `gh:<login>` → profile link, `squad:*` membership
208
- records, and weekly baseline snapshots (auto-expiring). Leaving your last
209
- squad deletes its record.
214
+ Worker-side storage adds: `gh:<login>` → profile link.
210
215
 
211
216
  When the opt-in public profile is enabled (`profile on` + a handle), the daemon
212
217
  also POSTs to `<endpoint>/profile` on the same 30-minute timer. Unlike the
@@ -469,7 +474,7 @@ aggregates; it never writes there.
469
474
 
470
475
  None of these files is uploaded. What leaves your machine is exactly what §3
471
476
  lists: the anonymous counters (3a, on by default); the public profile, its
472
- per-day heatmap series, squads and Wrapped (3c — opt-in); gist badges (3b) and
477
+ per-day heatmap series and Wrapped (3c — opt-in); gist badges (3b) and
473
478
  the status webhook (3f), only when you set them up; and for the usage poll
474
479
  (3d) your own Claude Code OAuth token, sent only to `api.anthropic.com`.
475
480
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "claude-rpc",
3
- "version": "1.9.0",
3
+ "version": "1.10.0",
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/cli.js CHANGED
@@ -10,6 +10,7 @@ import { VERSION } from './version.js';
10
10
  import { c, fail, tailLines, heat, sparkline, fmtDelta, topPercentile, EX_USER_ERROR, EX_BAD_STATE, EX_SYS_ERROR } from './ui.js';
11
11
  import * as lb from './leaderboard.js';
12
12
  import { writeFileAtomic } from './atomic-rename.js';
13
+ import { stampFeature } from './feature-usage.js';
13
14
 
14
15
  // ── Lazy-loaded module graph ─────────────────────────────────────────────────
15
16
  // Only the static imports above (all cheap) load up front, so --version,
@@ -1406,16 +1407,22 @@ async function doExport(argv) {
1406
1407
  emit(payload, out, { note: `${payload.length} bytes, ${csv ? 'CSV' : 'JSON'}` });
1407
1408
  }
1408
1409
 
1409
- // ── Squads — private mini-leaderboards (terminal parity for the web UI) ───
1410
+ // ── Link (one profile across machines) ───────────────────────────────────
1410
1411
  //
1411
- // `claude-rpc squad create <name>` → invite code + link
1412
- // `claude-rpc squad join <code>`
1413
- // `claude-rpc squad` / `squad status` → standings for every squad you're in
1414
- // `claude-rpc squad leave [id]`
1415
- // The web flow (claude-rpc.com + GitHub login) drives the same worker
1416
- // endpoints; the CLI authenticates with the community instanceId it already has.
1417
-
1418
- function squadAuth() {
1412
+ // Two-sided by design — one verb owns the whole story:
1413
+ // claude-rpc link on your MAIN (verified) machine → mints a
1414
+ // one-time code, no browser needed
1415
+ // claude-rpc link <code> on the NEW machine → claims it, merging this
1416
+ // install into the same leaderboard identity
1417
+ // The browser fallback lives at claude-rpc.com/link (log in with
1418
+ // GitHub → same code) for when the other machine isn't handy. Claiming
1419
+ // verifies the profile (✓).
1420
+
1421
+ const LINK_PAGE = 'https://claude-rpc.com/link';
1422
+
1423
+ // Authenticated worker calls for this machine: the community instanceId is
1424
+ // the credential (the browser path uses a GitHub session instead).
1425
+ function identityAuth() {
1419
1426
  const cfg = loadConfig();
1420
1427
  const endpoint = (cfg.community?.endpoint || '').replace(/\/+$/, '');
1421
1428
  const instanceId = cfg.community?.instanceId;
@@ -1426,7 +1433,7 @@ function squadAuth() {
1426
1433
  });
1427
1434
  }
1428
1435
  if (!instanceId) {
1429
- fail('squads need an identity', {
1436
+ fail('linking needs an identity', {
1430
1437
  hint: 'run `claude-rpc profile set --handle <name> && claude-rpc profile on` first',
1431
1438
  code: EX_BAD_STATE,
1432
1439
  });
@@ -1436,7 +1443,7 @@ function squadAuth() {
1436
1443
  try {
1437
1444
  res = await fetch(endpoint + path, { ...init, signal: AbortSignal.timeout(10_000) });
1438
1445
  } catch (e) {
1439
- return fail(`couldn't reach the squads service: ${e.message}`, {
1446
+ return fail(`couldn't reach claude-rpc.com: ${e.message}`, {
1440
1447
  hint: 'check your connection and retry — this never blocks Claude Code',
1441
1448
  code: EX_SYS_ERROR,
1442
1449
  });
@@ -1451,111 +1458,6 @@ function squadAuth() {
1451
1458
  return { cfg, endpoint, instanceId, post, get: call };
1452
1459
  }
1453
1460
 
1454
- function squadPageUrl(id) { return `https://claude-rpc.com/squad/${id}`; }
1455
-
1456
- function printSquadInvite(squad) {
1457
- console.log('');
1458
- console.log(` ${c.green}✓${c.reset} squad ${c.bold}${squad.name}${c.reset}`);
1459
- console.log(` ${c.dim}invite code:${c.reset} ${c.cyan}${squad.code}${c.reset}`);
1460
- console.log(` ${c.dim}standings: ${c.reset} ${c.cyan}${squadPageUrl(squad.id)}${c.reset}`);
1461
- console.log('');
1462
- console.log(` ${c.dim}send your crew this:${c.reset}`);
1463
- console.log(` join my Claude Code squad "${squad.name}" — npx claude-rpc@latest setup, then:`);
1464
- console.log(` ${c.cyan}claude-rpc squad join ${squad.code}${c.reset} ${c.dim}(or join in the browser: ${squadPageUrl(squad.id)})${c.reset}`);
1465
- console.log('');
1466
- }
1467
-
1468
- async function squadStatus({ post, get }) {
1469
- const mine = await post('/squads/mine', {});
1470
- if (!mine.json?.squads) return fail(`could not load squads: ${mine.json?.error || mine.status}`, { code: EX_SYS_ERROR });
1471
- if (!mine.json.squads.length) {
1472
- console.log('');
1473
- console.log(` ${c.dim}no squads yet — start one:${c.reset} ${c.cyan}claude-rpc squad create "the night shift"${c.reset}`);
1474
- console.log('');
1475
- return;
1476
- }
1477
- for (const s of mine.json.squads) {
1478
- const r = await get(`/squad?id=${encodeURIComponent(s.id)}`);
1479
- const standings = r.json?.standings || [];
1480
- const lines = standings.map((row) => {
1481
- const who = `${row.displayName || '@' + row.handle}${row.verified ? ' ✓' : ''}${row.owner ? ` ${c.dim}(owner)${c.reset}` : ''}`;
1482
- return `${c.bold}#${row.rank}${c.reset} ${who.padEnd(28)} ${c.cyan}${fmtNum(row.weekTokens)}${c.reset} ${c.dim}this week${c.reset} · ${fmtNum(row.tokens)} ${c.dim}lifetime${c.reset}`;
1483
- });
1484
- lines.push('');
1485
- lines.push(`${c.dim}week ${r.json?.squad?.week || ''} · invite ${c.reset}${c.cyan}${s.code}${c.reset}${c.dim} · ${squadPageUrl(s.id)}${c.reset}`);
1486
- box(`${s.name} (${s.members})`, lines, 70);
1487
- console.log('');
1488
- }
1489
- }
1490
-
1491
- async function doSquadCmd(argv) {
1492
- const sub = (argv[0] || 'status').toLowerCase();
1493
- const ctx = squadAuth();
1494
- if (sub === 'status' || sub === '') return squadStatus(ctx);
1495
- if (sub === 'create') {
1496
- const name = argv.slice(1).join(' ').trim();
1497
- if (!name) {
1498
- return fail('usage: claude-rpc squad create <name>',
1499
- { hint: 'example: claude-rpc squad create "the night shift"', code: EX_USER_ERROR });
1500
- }
1501
- const r = await ctx.post('/squad/create', { name });
1502
- if (r.status !== 200) return fail(`create failed: ${r.json?.error || r.status}`, { code: EX_SYS_ERROR });
1503
- return printSquadInvite(r.json.squad);
1504
- }
1505
- if (sub === 'join') {
1506
- const code = (argv[1] || '').trim();
1507
- if (!code) {
1508
- return fail('usage: claude-rpc squad join SQ-XXXXXX',
1509
- { hint: 'the invite code comes from whoever created the squad (`claude-rpc squad create`)', code: EX_USER_ERROR });
1510
- }
1511
- const r = await ctx.post('/squad/join', { code });
1512
- if (r.status !== 200) {
1513
- return fail(`join failed: ${r.json?.error || r.status}`,
1514
- { hint: 'double-check the invite code with whoever created the squad', code: EX_SYS_ERROR });
1515
- }
1516
- const s = r.json.squad;
1517
- console.log(` ${c.green}✓${c.reset} ${s.alreadyMember ? 'already in' : 'joined'} ${c.bold}${s.name}${c.reset} ${c.dim}(${s.members} member${s.members === 1 ? '' : 's'})${c.reset}`);
1518
- console.log(` ${c.dim}standings: ${squadPageUrl(s.id)} — or run ${c.reset}${c.cyan}claude-rpc squad${c.reset}`);
1519
- return;
1520
- }
1521
- if (sub === 'leave') {
1522
- const mine = await ctx.post('/squads/mine', {});
1523
- const squads = mine.json?.squads || [];
1524
- if (!squads.length) return fail('you are not in any squads', { code: EX_BAD_STATE });
1525
- let target = null;
1526
- const wanted = (argv[1] || '').toLowerCase();
1527
- if (wanted) target = squads.find((s) => s.id === wanted || s.name.toLowerCase() === wanted);
1528
- else if (squads.length === 1) target = squads[0];
1529
- if (!target) {
1530
- return fail(squads.length > 1 && !wanted ? 'you are in several squads — name one' : `no squad matching "${argv[1]}"`, {
1531
- hint: `claude-rpc squad leave <id|name> — yours: ${squads.map((s) => `${s.name} (${s.id})`).join(', ')}`,
1532
- code: EX_USER_ERROR,
1533
- });
1534
- }
1535
- const r = await ctx.post('/squad/leave', { squadId: target.id });
1536
- if (r.status !== 200) return fail(`leave failed: ${r.json?.error || r.status}`, { code: EX_SYS_ERROR });
1537
- console.log(` ${c.green}✓${c.reset} left ${c.bold}${target.name}${c.reset}${r.json.dissolved ? ` ${c.dim}(last member — squad dissolved)${c.reset}` : ''}`);
1538
- return;
1539
- }
1540
- fail(`unknown squad subcommand: ${sub}`, {
1541
- hint: 'try: squad [status|create <name>|join <code>|leave [id]]',
1542
- code: EX_USER_ERROR,
1543
- });
1544
- }
1545
-
1546
- // ── Link (one profile across machines) ───────────────────────────────────
1547
- //
1548
- // Two-sided by design — one verb owns the whole story:
1549
- // claude-rpc link on your MAIN (verified) machine → mints a
1550
- // one-time code, no browser needed
1551
- // claude-rpc link <code> on the NEW machine → claims it, merging this
1552
- // install into the same leaderboard identity
1553
- // The browser fallback lives at claude-rpc.com/link (log in with
1554
- // GitHub → same code) for when the other machine isn't handy. Claiming
1555
- // verifies the profile (✓) and unlocks managing squads from the browser.
1556
-
1557
- const LINK_PAGE = 'https://claude-rpc.com/link';
1558
-
1559
1461
  // Mint side: this machine asks the worker for a code. The worker only obliges
1560
1462
  // when this install's canonical profile is verified — the ✓ a claim grants
1561
1463
  // has to root in an already-proven identity.
@@ -1583,7 +1485,7 @@ async function linkMint(ctx) {
1583
1485
  }
1584
1486
 
1585
1487
  async function doLink(argv) {
1586
- const ctx = squadAuth();
1488
+ const ctx = identityAuth();
1587
1489
  const code = (argv[0] || '').trim();
1588
1490
  if (!code) return linkMint(ctx);
1589
1491
  // Make sure the profile row exists server-side before claiming — same
@@ -1613,7 +1515,7 @@ async function doLink(argv) {
1613
1515
  ...(prevProfile.enabled === undefined ? { enabled: true } : {}),
1614
1516
  };
1615
1517
  writeUserConfig(userCfg);
1616
- console.log(` ${c.green}✓${c.reset} linked as ${c.cyan}@${r.json.githubUser}${c.reset} — profile verified, squads unlocked in the browser`);
1518
+ console.log(` ${c.green}✓${c.reset} linked as ${c.cyan}@${r.json.githubUser}${c.reset} — profile verified`);
1617
1519
  if (r.json.created) {
1618
1520
  console.log(` ${c.green}✓${c.reset} board profile created — handle ${c.cyan}@${r.json.handle}${c.reset} ${c.dim}(rename any time: claude-rpc profile set --handle <you>)${c.reset}`);
1619
1521
  }
@@ -2590,6 +2492,10 @@ process.on('unhandledRejection', (e) => {
2590
2492
  }
2591
2493
  if (['start', 'stop', 'restart'].includes(cmd)) await loadDaemonCtl();
2592
2494
  else if (!FAST_PATHS.has(cmd)) await loadCore();
2495
+ // Coarse "used in the last 7 days" stamp for the anonymous report (see
2496
+ // feature-usage.js). Command name only; unlisted commands are ignored.
2497
+ if (cmd) stampFeature(cmd);
2498
+ if (process.env.CLAUDE_RPC_DESKTOP === '1') stampFeature('desktop');
2593
2499
  switch (cmd) {
2594
2500
  case '--version':
2595
2501
  case '-V':
@@ -2712,7 +2618,7 @@ process.on('unhandledRejection', (e) => {
2712
2618
  case 'status': {
2713
2619
  const dumpFlag = args.some((a) => a === '--dump' || a === '-d');
2714
2620
  if (dumpFlag || !process.stdout.isTTY) await showStatus();
2715
- else (await import('./tui.js')).startTui();
2621
+ else { stampFeature('tui'); (await import('./tui.js')).startTui(); }
2716
2622
  break;
2717
2623
  }
2718
2624
  case 'dump': await showStatus(); break;
@@ -2771,7 +2677,6 @@ process.on('unhandledRejection', (e) => {
2771
2677
  case 'community': await doCommunity(args); break;
2772
2678
  case 'update': await doUpdate(args); break;
2773
2679
  case 'profile': await doProfile(args); break;
2774
- case 'squad': await doSquadCmd(args); break;
2775
2680
  case 'link': await doLink(args); break;
2776
2681
  case 'doctor': {
2777
2682
  const { runDoctor, fixPlan } = await import('./doctor.js');
package/src/commands.js CHANGED
@@ -102,8 +102,6 @@ export const COMMANDS = [
102
102
  subs: [['status', 'Show it'], ['set', 'Change handle / name / github'], ['on', 'Go public'], ['off', 'Go private'],
103
103
  ['publish', 'Push your numbers now'], ['verify', 'Prove the GitHub account is yours']],
104
104
  flags: [['--handle', 'With set: your handle', 'any'], ['--name', 'With set: display name', 'any'], ['--github', 'With set: GitHub login', 'any']] },
105
- { name: 'squad', group: 'online', summary: 'Private leaderboards with friends', usage: '[status|create|join|leave]',
106
- subs: [['status', 'Your squads'], ['create', 'Start one'], ['join', 'Join with a code'], ['leave', 'Leave one']] },
107
105
  { name: 'link', group: 'online', summary: 'Join machines into one profile', usage: '[code]' },
108
106
  { name: 'community', group: 'online', summary: 'Anonymous community totals', usage: '[status|on|off|report]',
109
107
  subs: [['status', 'Show it'], ['on', 'Opt in'], ['off', 'Opt out'], ['report', 'Send now']] },
package/src/community.js CHANGED
@@ -15,7 +15,8 @@
15
15
  // 2. Never sends anything beyond the documented payloads. Each build*Payload
16
16
  // function is the complete schema for its endpoint, mirrored by the
17
17
  // worker's validators. The anonymous /report carries only counter
18
- // deltas, version and OS family. The opt-in /profile adds the chosen
18
+ // deltas, version, OS family, install kind, last auto-update outcome
19
+ // and the names of commands used in the last 7 days. The opt-in /profile adds the chosen
19
20
  // identity, lifetime totals and a per-day token/active-time series.
20
21
  // /wrapped (sent only by `wrapped --publish`, after showing the user the
21
22
  // payload) adds that year's stats, including privacy-filtered project
@@ -37,6 +38,8 @@ import { cleanProjectName, dayKey } from './scanner.js';
37
38
  import { HEATMAP_DAYS } from './heatmap.js';
38
39
  import { humanModel } from './format.js';
39
40
  import { adoptLegacyFile, writeFileAtomic } from './atomic-rename.js';
41
+ import { recentFeatures, updateOutcome } from './feature-usage.js';
42
+ import { installKind, readUpdateState } from './updater.js';
40
43
 
41
44
  // How much of this install's lifetime has already been reported. It must
42
45
  // survive reboots: the worker adds every delta blindly, so a lost cursor
@@ -126,7 +129,7 @@ const MAX_REPORT_TOKENS = 5_000_000_000;
126
129
  // Pure: given an aggregate and a cursor, produce the next payload. The
127
130
  // worker's validateReport must accept this shape; if you add a field
128
131
  // here, add it there too.
129
- export function buildPayload(aggregate, cursor, { instanceId, now = Date.now() }) {
132
+ export function buildPayload(aggregate, cursor, { instanceId, now = Date.now(), usage = usageFacts(now) }) {
130
133
  const sessions = aggregate?.sessions || 0;
131
134
  const tokens = totalTokens(aggregate);
132
135
  return {
@@ -135,10 +138,19 @@ export function buildPayload(aggregate, cursor, { instanceId, now = Date.now() }
135
138
  tokensDelta: Math.min(MAX_REPORT_TOKENS, Math.max(0, tokens - (cursor.tokens || 0))),
136
139
  version: VERSION,
137
140
  osFamily: osFamily(),
141
+ ...usage,
138
142
  ts: now,
139
143
  };
140
144
  }
141
145
 
146
+ // How this copy is installed, how its last auto-update went, and which
147
+ // commands were used in the last 7 days (names only — feature-usage.js).
148
+ export function usageFacts(now = Date.now()) {
149
+ try {
150
+ return { install: installKind(), upd: updateOutcome(readUpdateState()), feat: recentFeatures({ now }) };
151
+ } catch { return {}; }
152
+ }
153
+
142
154
  function totalTokens(aggregate) {
143
155
  return (aggregate?.inputTokens || 0)
144
156
  + (aggregate?.outputTokens || 0)
@@ -0,0 +1,78 @@
1
+ // Coarse, local feature-usage stamps for the anonymous community report.
2
+ //
3
+ // Each user-facing command records "last used at" in STATE_DIR (no args, no
4
+ // paths, no counts). The daemon's /report then sends the NAMES of commands
5
+ // used in the last 7 days (`feat`), alongside how this copy was installed and
6
+ // how its last auto-update went. That's the whole signal: it tells the author
7
+ // which features anyone actually uses, and why updates do or don't land.
8
+ // Turned off with everything else by `claude-rpc community off`.
9
+
10
+ import { readFileSync, mkdirSync } from 'node:fs';
11
+ import { join } from 'node:path';
12
+ import { STATE_DIR } from './paths.js';
13
+ import { writeFileAtomic } from './atomic-rename.js';
14
+
15
+ export const FEATURE_USAGE_PATH = join(STATE_DIR, 'feature-usage.json');
16
+ export const FEATURE_WINDOW_MS = 7 * 86_400_000;
17
+ const RESTAMP_MS = 3_600_000; // statusline/mcp run constantly; one write an hour is plenty
18
+
19
+ // Command → reported feature name. Anything not listed is never recorded.
20
+ const ALIASES = { log: 'tail', logs: 'tail', unpause: 'resume', install: 'setup', 'upgrade-config': 'setup' };
21
+ export const FEATURES = new Set([
22
+ 'tui', 'desktop', 'setup', 'uninstall', 'start', 'stop', 'restart', 'status', 'dump', 'today', 'week',
23
+ 'projects', 'project', 'compare', 'usage', 'serve', 'settings', 'preview', 'vars', 'scan', 'rescan',
24
+ 'backfill', 'insights', 'recap', 'badge', 'card', 'github-stat', 'statusline', 'calendar',
25
+ 'session-card', 'readme', 'mcp', 'wrapped', 'share', 'statcards', 'completion', 'pause', 'resume',
26
+ 'export', 'private', 'public', 'privacy', 'community', 'update', 'profile', 'link', 'doctor', 'tail',
27
+ ]);
28
+
29
+ export function featureName(cmd) {
30
+ const name = ALIASES[cmd] || cmd;
31
+ return FEATURES.has(name) ? name : null;
32
+ }
33
+
34
+ function read(path) {
35
+ try { const j = JSON.parse(readFileSync(path, 'utf8')); return j && typeof j === 'object' ? j : {}; } catch { return {}; }
36
+ }
37
+
38
+ // Best-effort; never throws.
39
+ export function stampFeature(cmd, { now = Date.now(), path = FEATURE_USAGE_PATH } = {}) {
40
+ const name = featureName(cmd);
41
+ if (!name) return;
42
+ try {
43
+ const cur = read(path);
44
+ if (Number.isFinite(cur[name]) && now - cur[name] < RESTAMP_MS) return;
45
+ cur[name] = now;
46
+ mkdirSync(STATE_DIR, { recursive: true });
47
+ writeFileAtomic(path, JSON.stringify(cur));
48
+ } catch { /* advisory only */ }
49
+ }
50
+
51
+ // Sorted names used within the window.
52
+ export function recentFeatures({ now = Date.now(), path = FEATURE_USAGE_PATH, windowMs = FEATURE_WINDOW_MS } = {}) {
53
+ const cur = read(path);
54
+ return Object.keys(cur).filter((k) => FEATURES.has(k) && Number.isFinite(cur[k]) && now - cur[k] < windowMs).sort();
55
+ }
56
+
57
+ // Pure: update.json → a short outcome code for the report.
58
+ // ok last check found nothing newer / last install succeeded
59
+ // off auto-update disabled
60
+ // manual this install kind can't self-update (brew, npx, dev, packaged off-canonical)
61
+ // perm install folder not writable
62
+ // failed last install attempt failed
63
+ // pending newer release seen, inside the cooldown
64
+ // unknown never checked (pre-1.7 state, or the daemon hasn't run a check yet)
65
+ export function updateOutcome(state) {
66
+ const p = state?.lastPlan;
67
+ if (!p) return 'unknown';
68
+ if (state.failed?.version && state.failed.version === p.latest && state.updatedTo !== p.latest) return 'failed';
69
+ const r = String(p.reason || '');
70
+ if (p.action === 'none') return r === 'registry unreachable' ? 'unknown' : 'ok';
71
+ if (p.action === 'install') return 'ok';
72
+ if (/install failed|last install attempt failed/.test(r)) return 'failed';
73
+ if (/auto-update is off/.test(r)) return 'off';
74
+ if (/admin rights|not writable/.test(r)) return 'perm';
75
+ if (/settling|cooldown/.test(r)) return 'pending';
76
+ if (/installed via|new major/.test(r)) return 'manual';
77
+ return 'unknown';
78
+ }
package/src/install.js CHANGED
@@ -455,6 +455,14 @@ function sweepStaleCanonicalBackups() {
455
455
  // Copy the running binary into CANONICAL_EXE if it's not already there.
456
456
  // Returns the path that hook entries should point at — canonical on success,
457
457
  // the original path as a fallback. Only meaningful in packaged mode.
458
+ // Pure: is a (the on-disk canonical exe's version) newer than b?
459
+ export function canonicalIsNewer(a, b) {
460
+ const p = (v) => String(v).split('.').map(Number);
461
+ const x = p(a), y = p(b);
462
+ for (let i = 0; i < 3; i++) if (x[i] !== y[i]) return x[i] > y[i];
463
+ return false;
464
+ }
465
+
458
466
  export function ensureCanonicalExe(currentExe) {
459
467
  if (!IS_PACKAGED) return currentExe;
460
468
  if (samePath(currentExe, CANONICAL_EXE)) return CANONICAL_EXE;
@@ -474,6 +482,17 @@ export function ensureCanonicalExe(currentExe) {
474
482
  } catch { /* stat failed — fall through to copy attempt */ }
475
483
  }
476
484
 
485
+ // The canonical exe self-updates (updater.js installPackaged), so it can be
486
+ // NEWER than the copy running setup — e.g. the desktop app re-running setup
487
+ // with its older bundled CLI. Never downgrade it.
488
+ if (existsSync(CANONICAL_EXE)) {
489
+ const m = /(\d+\.\d+\.\d+)/.exec(String(spawnSync(CANONICAL_EXE, ['--version'], { timeout: 15_000, windowsHide: true, encoding: 'utf8' }).stdout || ''));
490
+ if (m && canonicalIsNewer(m[1], VERSION)) {
491
+ noop(`exe already v${m[1]}`);
492
+ return CANONICAL_EXE;
493
+ }
494
+ }
495
+
477
496
  try {
478
497
  // Windows won't let you overwrite a currently-executing file. If
479
498
  // canonical is the running daemon, move it aside first — that succeeds
package/src/updater.js CHANGED
@@ -8,17 +8,26 @@
8
8
  // is never touched: those get a one-line "update available" with the right
9
9
  // command. A new MAJOR is never installed unattended.
10
10
  //
11
+ // The packaged binary (claude-rpc.exe / the macOS arm64 binary — what the
12
+ // desktop app and the standalone download install as the canonical exe) also
13
+ // self-updates since 1.10: it downloads the release asset from GitHub, checks
14
+ // it against the release's SHA256SUMS, test-runs it, and swaps it in place. A
15
+ // release without SHA256SUMS (anything before 1.10) is never installed.
16
+ //
11
17
  // Pure decision functions up top (unit-tested); side effects below.
12
18
 
13
- import { readFileSync, writeFileSync, mkdirSync, accessSync, constants as fsConstants } from 'node:fs';
19
+ import { readFileSync, writeFileSync, mkdirSync, accessSync, renameSync, chmodSync, unlinkSync, existsSync, constants as fsConstants } from 'node:fs';
14
20
  import { join, dirname, delimiter } from 'node:path';
15
- import { STATE_DIR, ROOT, IS_PACKAGED, IS_NPM_INSTALL, IS_NPX } from './paths.js';
21
+ import { createHash } from 'node:crypto';
22
+ import { STATE_DIR, ROOT, IS_PACKAGED, IS_NPM_INSTALL, IS_NPX, CANONICAL_EXE } from './paths.js';
16
23
 
17
24
  export const UPDATE_STATE_PATH = join(STATE_DIR, 'update.json');
18
25
  export const REGISTRY_URL = 'https://registry.npmjs.org/claude-rpc/latest';
19
26
  const RETRY_FAILED_MS = 24 * 3_600_000; // don't hammer a version that failed to install
20
27
  const COOLDOWN_MS = 2 * 3_600_000; // a release must be seen this long before it's installed — a yank window
21
28
  const INSTALL_TIMEOUT_MS = 180_000;
29
+ export const RELEASE_BASE = 'https://github.com/rar-file/claude-rpc/releases/download';
30
+ const MAX_ASSET_BYTES = 250 * 1024 * 1024;
22
31
  const FETCH_TIMEOUT_MS = 8_000;
23
32
 
24
33
  const SEMVER = /^(\d+)\.(\d+)\.(\d+)$/; // no prereleases: only stable tags are ever considered
@@ -60,14 +69,31 @@ export function updateCommand(kind) {
60
69
  }
61
70
  }
62
71
 
72
+ // The release asset a packaged build of this platform updates from, or null
73
+ // when no prebuilt binary is published for it (those only get a notice).
74
+ export function packagedAsset(platform = process.platform, arch = process.arch) {
75
+ if (platform === 'win32' && arch === 'x64') return 'claude-rpc.exe';
76
+ if (platform === 'darwin' && arch === 'arm64') return 'claude-rpc';
77
+ return null;
78
+ }
79
+
80
+ // Can this packaged process replace itself? Only when it IS the canonical exe
81
+ // (the copy hooks + autostart launch) and a binary exists for this platform.
82
+ export function packagedSelfUpdatable({ packaged = IS_PACKAGED, execPath = process.execPath, canonical = CANONICAL_EXE, asset = packagedAsset() } = {}) {
83
+ if (!packaged || !asset) return false;
84
+ const norm = (x) => (process.platform === 'win32' ? String(x).toLowerCase() : String(x));
85
+ return norm(execPath) === norm(canonical);
86
+ }
87
+
63
88
  // → { action: 'none' | 'notify' | 'install', reason }
64
- export function planUpdate({ current, latest, auto = true, kind, writable = true, failed = null, seen = null, cooldownMs = COOLDOWN_MS, now = Date.now() }) {
89
+ export function planUpdate({ current, latest, auto = true, kind, writable = true, failed = null, seen = null, cooldownMs = COOLDOWN_MS, now = Date.now(), packagedOk = false }) {
65
90
  if (!isNewer(latest, current)) return { action: 'none', reason: 'up to date' };
66
- if (kind !== 'npm-global') return { action: 'notify', reason: `installed via ${kind}` };
91
+ const selfUpdating = kind === 'npm-global' || (kind === 'packaged' && packagedOk);
92
+ if (!selfUpdating) return { action: 'notify', reason: `installed via ${kind}` };
67
93
  if (!auto) return { action: 'notify', reason: 'auto-update is off' };
68
94
  // A root-owned global (system node, `sudo npm i -g`) fails with EACCES every
69
95
  // single attempt — say so once instead of failing silently every day.
70
- if (!writable) return { action: 'notify', reason: 'the global npm folder needs admin rights — update manually' };
96
+ if (!writable) return { action: 'notify', reason: kind === 'packaged' ? 'the install folder is not writable — update manually' : 'the global npm folder needs admin rights — update manually' };
71
97
  if (!sameMajor(latest, current)) return { action: 'notify', reason: 'new major version — update manually' };
72
98
  if (failed && failed.version === latest && now - failed.at < RETRY_FAILED_MS) {
73
99
  return { action: 'notify', reason: 'last install attempt failed — retrying later' };
@@ -121,6 +147,67 @@ export async function installVersion(version) {
121
147
  });
122
148
  }
123
149
 
150
+ // Pure: the hex digest SHA256SUMS lists for `name` (sha256sum format:
151
+ // "<hex> <name>" or "<hex> *<name>"), or null.
152
+ export function checksumFor(sums, name) {
153
+ for (const line of String(sums || '').split(/\r?\n/)) {
154
+ const m = /^([0-9a-f]{64})\s+\*?(.+?)\s*$/i.exec(line);
155
+ if (m && m[2] === name) return m[1].toLowerCase();
156
+ }
157
+ return null;
158
+ }
159
+
160
+ async function fetchBuffer(url, { timeoutMs, maxBytes }) {
161
+ const res = await fetch(url, { signal: AbortSignal.timeout(timeoutMs), redirect: 'follow' });
162
+ if (!res.ok) throw new Error(`HTTP ${res.status} for ${url.split('/').slice(-2).join('/')}`);
163
+ const len = Number(res.headers.get('content-length') || 0);
164
+ if (len > maxBytes) throw new Error('download too large');
165
+ const buf = Buffer.from(await res.arrayBuffer());
166
+ if (buf.length > maxBytes) throw new Error('download too large');
167
+ return buf;
168
+ }
169
+
170
+ // Replace the packaged canonical exe with release `version`. Resolves
171
+ // { ok, output }. Nothing is swapped unless the download matches SHA256SUMS
172
+ // AND the new binary answers `--version` with exactly `version`. Windows can't
173
+ // overwrite a running exe but can rename it, so the running copy is moved to
174
+ // .old-<ts> (setup's sweepStaleCanonicalBackups removes it later).
175
+ export async function installPackaged(version, { exe = CANONICAL_EXE, asset = packagedAsset(), base = RELEASE_BASE, fetchFn = fetchBuffer, runVersion = runExeVersion } = {}) {
176
+ if (!parseVersion(version)) return { ok: false, output: 'bad version' };
177
+ if (!asset) return { ok: false, output: 'no prebuilt binary for this platform' };
178
+ const tmp = `${exe}.new`;
179
+ try {
180
+ const sums = (await fetchFn(`${base}/v${version}/SHA256SUMS`, { timeoutMs: 15_000, maxBytes: 64 * 1024 })).toString('utf8');
181
+ const want = checksumFor(sums, asset);
182
+ if (!want) return { ok: false, output: `SHA256SUMS for v${version} has no entry for ${asset}` };
183
+ const bin = await fetchFn(`${base}/v${version}/${asset}`, { timeoutMs: INSTALL_TIMEOUT_MS, maxBytes: MAX_ASSET_BYTES });
184
+ const got = createHash('sha256').update(bin).digest('hex');
185
+ if (got !== want) return { ok: false, output: `checksum mismatch for ${asset} (got ${got.slice(0, 12)}…, want ${want.slice(0, 12)}…)` };
186
+ writeFileSync(tmp, bin);
187
+ if (process.platform !== 'win32') chmodSync(tmp, 0o755);
188
+ const said = await runVersion(tmp);
189
+ if (said !== version) throw new Error(`downloaded binary reports ${said || 'nothing'}, expected ${version}`);
190
+ if (process.platform === 'win32' && existsSync(exe)) renameSync(exe, `${exe}.old-${Date.now()}`);
191
+ renameSync(tmp, exe);
192
+ return { ok: true, output: `replaced ${exe}` };
193
+ } catch (e) {
194
+ try { unlinkSync(tmp); } catch { /* never written */ }
195
+ return { ok: false, output: String(e?.message || e) };
196
+ }
197
+ }
198
+
199
+ // `<exe> --version` → "1.2.3" or null.
200
+ export async function runExeVersion(exe) {
201
+ const { execFile } = await import('node:child_process');
202
+ return new Promise((resolve) => {
203
+ execFile(exe, ['--version'], { timeout: 20_000, windowsHide: true }, (err, stdout) => {
204
+ if (err) return resolve(null);
205
+ const m = /(\d+\.\d+\.\d+)/.exec(String(stdout));
206
+ resolve(m ? m[1] : null);
207
+ });
208
+ });
209
+ }
210
+
124
211
  // Can this process replace its own package? (npm writes the new copy into the
125
212
  // folder that holds ours: …/lib/node_modules on POSIX, %AppData%\npm\node_modules.)
126
213
  export function installDirWritable(root = ROOT) {
@@ -138,7 +225,7 @@ export function installedVersion(root = ROOT) {
138
225
  // One check cycle. Returns { plan, latest, installed }. `install`, `verify`
139
226
  // and `writable` are injectable for tests; callers restart the daemon when
140
227
  // `installed` is true.
141
- export async function checkForUpdate({ current, auto, kind = installKind(), fetchLatestFn = fetchLatest, install = installVersion, verify = (v) => installedVersion() === v, writable = installDirWritable, now = Date.now(), cooldownMs = COOLDOWN_MS, statePath = UPDATE_STATE_PATH } = {}) {
228
+ export async function checkForUpdate({ current, auto, kind = installKind(), packagedOk = kind === 'packaged' && packagedSelfUpdatable(), fetchLatestFn = fetchLatest, install = kind === 'packaged' ? installPackaged : installVersion, verify = kind === 'packaged' ? () => true : (v) => installedVersion() === v, writable = kind === 'packaged' ? () => installDirWritable(CANONICAL_EXE) : installDirWritable, now = Date.now(), cooldownMs = COOLDOWN_MS, statePath = UPDATE_STATE_PATH } = {}) {
142
229
  const latest = await fetchLatestFn();
143
230
  writeUpdateState({ checkedAt: now, ...(latest ? { latest } : {}) }, statePath);
144
231
  if (!latest) return { plan: { action: 'none', reason: 'registry unreachable' }, latest: null, installed: false };
@@ -147,7 +234,8 @@ export async function checkForUpdate({ current, auto, kind = installKind(), fetc
147
234
  writeUpdateState({ seen: { version: latest, at: now } }, statePath);
148
235
  state = readUpdateState(statePath);
149
236
  }
150
- const plan = planUpdate({ current, latest, auto, kind, writable: kind === 'npm-global' ? writable() : true, failed: state.failed || null, seen: state.seen || null, cooldownMs, now });
237
+ const selfUpdating = kind === 'npm-global' || (kind === 'packaged' && packagedOk);
238
+ const plan = planUpdate({ current, latest, auto, kind, packagedOk, writable: selfUpdating ? writable() : true, failed: state.failed || null, seen: state.seen || null, cooldownMs, now });
151
239
  writeUpdateState({ lastPlan: { action: plan.action, reason: plan.reason, latest, at: now } }, statePath);
152
240
  if (plan.action !== 'install') return { plan, latest, installed: false };
153
241
  const res = await install(latest);
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.9.0';
14
+ const BAKED = '1.10.0';
15
15
 
16
16
  function readPkgVersion() {
17
17
  try {