claude-rpc 1.5.2 → 1.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (52) hide show
  1. package/README.md +72 -62
  2. package/SECURITY.md +99 -20
  3. package/package.json +2 -1
  4. package/src/atomic-rename.js +45 -2
  5. package/src/badge.js +3 -4
  6. package/src/card.js +1 -22
  7. package/src/cli-path.js +286 -0
  8. package/src/cli.js +430 -459
  9. package/src/commands.js +245 -0
  10. package/src/community.js +101 -60
  11. package/src/completion.js +196 -0
  12. package/src/config.js +4 -1
  13. package/src/daemon.js +45 -47
  14. package/src/default-config.js +4 -3
  15. package/src/discord-ipc.js +24 -13
  16. package/src/doctor.js +64 -38
  17. package/src/ensure-daemon.js +11 -4
  18. package/src/fmt.js +8 -6
  19. package/src/format.js +8 -13
  20. package/src/gist.js +8 -18
  21. package/src/git.js +4 -1
  22. package/src/help.js +117 -0
  23. package/src/hook.js +27 -32
  24. package/src/insights.js +3 -4
  25. package/src/install.js +100 -79
  26. package/src/leaderboard.js +3 -2
  27. package/src/mcp.js +2 -8
  28. package/src/nudge.js +10 -5
  29. package/src/png.js +135 -0
  30. package/src/pricing.js +25 -3
  31. package/src/privacy.js +22 -7
  32. package/src/profile.js +0 -6
  33. package/src/recap.js +4 -17
  34. package/src/scanner.js +103 -71
  35. package/src/select.js +60 -0
  36. package/src/server/api.js +64 -36
  37. package/src/server/assets/dashboard.client.js +75 -44
  38. package/src/server/assets/dashboard.css +18 -18
  39. package/src/server/assets/dashboard.html +13 -15
  40. package/src/server/assets/wrapped.client.js +26 -11
  41. package/src/server/assets/wrapped.css +2 -2
  42. package/src/server/index.js +43 -32
  43. package/src/server/page.js +6 -3
  44. package/src/server/sse.js +90 -34
  45. package/src/session-card.js +3 -1
  46. package/src/statcards.js +278 -0
  47. package/src/state.js +14 -24
  48. package/src/tui.js +3 -12
  49. package/src/ui.js +7 -5
  50. package/src/verify.js +3 -7
  51. package/src/version.js +1 -1
  52. package/src/week.js +4 -4
package/README.md CHANGED
@@ -64,15 +64,17 @@ Detects Node (installs the npm package) or falls back to the prebuilt Apple-Sili
64
64
  brew install rar-file/claude-rpc/claude-rpc && claude-rpc setup
65
65
  ```
66
66
 
67
- **Windows (no Node required)** — [grab the portable exe from the latest release](https://github.com/rar-file/claude-rpc/releases/latest), then:
67
+ **Windows (no Node required)** — [grab `claude-rpc.exe` from the latest release](https://github.com/rar-file/claude-rpc/releases/latest) (the standalone CLI — no installer), then run it from the folder you saved it to:
68
68
 
69
69
  ```sh
70
- claude-rpc setup
70
+ .\claude-rpc.exe setup
71
71
  ```
72
72
 
73
+ `setup` copies the exe to a fixed per-user location (so the download can go afterwards) and adds that folder to your user PATH, so `claude-rpc <command>` works in any new terminal. Prefer a GUI? The release's `claude-rpc-<version>-x64-setup.exe` (installer, auto-updates) and `claude-rpc-<version>-x64-portable.exe` (no install) are the desktop dashboard app, which runs the same `setup` for you on first launch.
74
+
73
75
  That's the whole pitch.
74
76
 
75
- > `setup` registers a Windows startup entry and wires hooks into Claude Code's `settings.json`, and the daemon reports anonymous totals by default. It ends with one optional y/N — *connect GitHub?* — which publishes a verified public [leaderboard](https://claude-rpc.com/leaderboard) profile only if you say yes (asked once; Enter skips). All of it is reversible (`claude-rpc uninstall`, `community off`, `profile off`) and fully documented in [`SECURITY.md`](SECURITY.md) — read it first if you want to know exactly what runs.
77
+ > `setup` registers a per-user login-autostart entry (a LaunchAgent on macOS, a `systemd --user` unit on Linux, an `HKCU\…\Run` value on Windows) and wires hooks into Claude Code's `settings.json`, and the daemon reports anonymous totals by default. It ends with one optional y/N — *connect GitHub?* — which publishes a verified public [leaderboard](https://claude-rpc.com/leaderboard) profile only if you say yes (asked once; Enter skips). All of it is reversible (`claude-rpc uninstall`, `community off`, `profile off`) and fully documented in [`SECURITY.md`](SECURITY.md) — read it first if you want to know exactly what runs.
76
78
 
77
79
  The Discord *desktop* app must be running. The browser client doesn't expose the local IPC bridge that Rich Presence uses.
78
80
 
@@ -123,7 +125,7 @@ Three local surfaces, all reading the same `~/.claude-rpc/aggregate.json`:
123
125
  <table>
124
126
  <tr>
125
127
  <td align="center" width="50%"><b>web dashboard</b><br/><sub><code>claude-rpc serve</code> · port 47474</sub><br/><br/><img src="docs/dashboard.png" alt="Web dashboard with range selector, activity chart, heatmap, cost panel, languages stack, and leaderboards" /></td>
126
- <td align="center" width="50%"><b>settings gui</b><br/><sub><code>npm run dashboard</code> · Electron</sub><br/><br/><img src="docs/electron.png" alt="Electron config editor with Presence / Discord / Assets / Timing / Daemon / Stats tabs" /></td>
128
+ <td align="center" width="50%"><b>settings gui</b><br/><sub><code>npm run dashboard</code> · Electron</sub><br/><br/><img src="docs/electron.png" alt="Electron config editor with Presence / Discord / Assets / Timing / Daemon / Privacy / Stats tabs" /></td>
127
129
  </tr>
128
130
  </table>
129
131
 
@@ -140,13 +142,18 @@ The web dashboard pushes updates via SSE; the TUI refreshes on a 3-second tick.
140
142
 
141
143
  ### beyond your machine
142
144
 
143
- Shields-style badges and a poster-style summary card you can paste into a README or a Discord message. The fastest path is one command:
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**:
144
146
 
145
147
  ```sh
146
- claude-rpc readme # prints paste-ready README badge markdown
147
- claude-rpc readme --raw | pbcopy # straight to your clipboard
148
+ claude-rpc statcards # menu: card → link / PNG / SVG
149
+ claude-rpc statcards stats --link --md | pbcopy # README markdown, straight to the clipboard
150
+ claude-rpc statcards poster --png # ./claude-poster.png, 2× for Discord / X
151
+ claude-rpc statcards badge --metric streak --svg # ./claude-badge-streak.svg
152
+ claude-rpc statcards list # every card and where it can go
148
153
  ```
149
154
 
155
+ Cards: `stats` (totals + year heatmap), `profile`, `badge`, `heatmap`, `poster`, `session`, `wrapped`. PNGs are drawn by whatever the machine already has (rsvg-convert, or Chrome / Edge / Brave / Chromium headless; Edge ships with Windows), so there is still nothing to install. The link option prints the URL, Markdown and an `<img>` tag, and copies the Markdown.
156
+
150
157
  **Live stats + year heatmap, paste once.** With a public profile (`claude-rpc profile set --handle <you> && claude-rpc profile on`), the community worker serves an always-current stats card with your last 12 months as a heatmap. You don't need `gh` or a gist, and there's nothing to re-run:
151
158
 
152
159
  ```md
@@ -169,28 +176,17 @@ The smaller card and badges are still there:
169
176
 
170
177
  The card shows tokens, sessions, active hours and streak; badge `metric=` is one of `tokens · sessions · hours · streak` (optional `&label=` to retitle). Both refresh themselves as the daemon flushes your profile (~every 30 min). Your profile page at `/u/<you>` has a one-click "copy" for the whole block.
171
178
 
172
- Prefer to render locally? `badge`/`card`/`calendar`/`github-stat` all write SVG, and `--gist` self-hosts a live one:
173
-
174
- ```sh
175
- claude-rpc badge --metric hours --range 7d --out claude-hours.svg
176
- claude-rpc badge --metric streak --out claude-streak.svg
177
- claude-rpc badge --metric hours --gist # publish to a gist (live README badge)
178
- claude-rpc card --range year --out year-on-claude.svg
179
- claude-rpc calendar --metric tokens --out heatmap.svg # year heatmap (hours by default)
180
- claude-rpc calendar --card --out stats.svg # stats + heatmap, offline
181
- ```
179
+ No public profile? Every card except `wrapped` also renders offline from your local stats, as PNG or SVG (`statcards <card> --png` / `--svg`). The older one-card commands (`badge`, `card`, `calendar`, `github-stat`, `session-card`, `readme`) still work, including `--gist`.
182
180
 
183
181
  <div align="center">
184
182
  <img src="site/examples/week-on-claude.svg" width="270" alt="Week-on-claude summary card" />
185
183
  <img src="site/examples/month-on-claude.svg" width="270" alt="Month-on-claude summary card" />
186
184
  <img src="site/examples/year-on-claude.svg" width="270" alt="Year-on-claude summary card — hours, prompts, tokens, lines, cost, daily activity strip" />
187
185
  <br/>
188
- <sub><code>card --range week · month · year</code> (also <code>all</code>) — live at <code>/api/card.svg</code> while the daemon's up</sub>
186
+ <sub><code>statcards poster --range week · month · year</code> (also <code>all</code>) — live at <code>/api/card.svg</code> while <code>claude-rpc serve</code> is running</sub>
189
187
  </div>
190
188
 
191
- `badge --gist` writes the SVG to your own GitHub gist (creates one on first run, updates it after — id remembered in `config.json`). The URL printed back is README-ready and updates every time you re-run the command. Uses `gh` if available, else `GH_TOKEN` with `gist` scope.
192
-
193
- Live equivalents when the daemon is up:
189
+ Live equivalents while `claude-rpc serve` is running (the local dashboard server — the daemon itself serves no HTTP):
194
190
 
195
191
  - `http://127.0.0.1:47474/api/badge.svg?metric=hours&range=7d`
196
192
  - `http://127.0.0.1:47474/api/card.svg?range=year`
@@ -220,7 +216,7 @@ For a complete account of the sensitive things claude-rpc does — startup persi
220
216
 
221
217
  No database, no message bus, no background polling when Claude Code isn't running. State on disk you can `cat` and `jq`. **Zero runtime dependencies** — even the Discord Rich Presence IPC client is hand-rolled (`src/discord-ipc.js`).
222
218
 
223
- 1. **hook** ([`src/hook.js`](src/hook.js)) — Claude Code spawns it on every lifecycle event. Parses the JSON from stdin and mutates the shared state file. The per-tool-call hooks (`PreToolUse`/`PostToolUse`) are wired `async`, so Claude Code never waits on them; the once-per-turn ones take one node start-up (~90ms).
219
+ 1. **hook** ([`src/hook.js`](src/hook.js)) — Claude Code spawns it on every lifecycle event. Parses the JSON from stdin and mutates the shared state file. The per-tool-call hooks (`PreToolUse`/`PostToolUse`) are wired `async`, so Claude Code never waits on them; the once-per-turn ones cost one node start-up each (~60–90ms wall, Node's own boot included).
224
220
  2. **daemon** ([`src/daemon.js`](src/daemon.js)) — long-running. Connects to Discord's local IPC, watches the state file, pushes presence frames every few seconds. Idles at ~55MB. Exponential backoff with jitter on reconnect; `daemon.log` rotates at 5 MB.
225
221
  3. **scanner** ([`src/scanner.js`](src/scanner.js)) — walks `~/.claude/projects/**/*.jsonl` for all-time aggregates (active time, prompts, tools, tokens, streaks, hotspots, lines, languages, cost, bash, web, subagents). Incremental — re-parses only changed files, and runs in a short-lived child process so the daemon never holds the parse memory.
226
222
 
@@ -228,8 +224,9 @@ Persistent state, all human-readable JSON:
228
224
 
229
225
  | Path | What |
230
226
  | ---- | ---- |
231
- | `$TMPDIR/claude-rpc/state.json` | Current session, volatile |
227
+ | `$TMPDIR/claude-rpc/state-<session>.json` | Live per-session state, volatile (`state.json` for events with no session id) |
232
228
  | `~/.claude-rpc/aggregate.json` | All-time aggregates |
229
+ | `~/.claude-rpc/events.jsonl` | Notification / compaction events the hook logs (rotated at 5 MB) |
233
230
  | `~/.claude-rpc/scan-cache.json` | Per-transcript scan cache |
234
231
  | `~/.claude-rpc/private-list.json` | Runtime privacy toggles |
235
232
  | `~/.claude/settings.json` | Hook registrations (managed by `setup`) |
@@ -250,9 +247,9 @@ Per-project, runtime, or auto-detected — whichever fits how you work.
250
247
  Or from the command line, in any project:
251
248
 
252
249
  ```sh
253
- claude-rpc private # add cwd to ~/.claude-rpc/private-list.json
254
- claude-rpc public # remove cwd
255
- claude-rpc privacy # show the resolved visibility for the current dir
250
+ claude-rpc private # hide this folder (adds it to ~/.claude-rpc/private-list.json)
251
+ claude-rpc private off # show it again
252
+ claude-rpc private status # what Discord sees for this folder, and why
256
253
  ```
257
254
 
258
255
  Or globally, in `config.json`:
@@ -299,11 +296,13 @@ Prefer to install from inside Claude Code? There's a [plugin](plugin/) for that:
299
296
  /plugin install claude-rpc@claude-rpc
300
297
  ```
301
298
 
302
- It's a thin bootstrapper — on the first session it just runs `npx claude-rpc@latest setup` for you (the same install as above), then stays out of the way. macOS / Linux / WSL; on Windows use the portable exe. Nothing extra is added to your sessions — the plugin is a single `SessionStart` hook with no model-context cost.
299
+ It's a thin bootstrapper — on the first session it just runs `npx claude-rpc@latest setup` for you (the same install as above), then stays out of the way. macOS / Linux / WSL; on native Windows use `claude-rpc.exe` (see [install](#install)). Nothing extra is added to your sessions — the plugin is a single `SessionStart` hook with no model-context cost.
303
300
 
304
301
  ## commands
305
302
 
306
- `claude-rpc --help` lists them all — and after `setup` you rarely need any.
303
+ `claude-rpc help` lists them all, grouped; `claude-rpc help <command>` (or `<command> --help`) shows one command's options and examples. After `setup` you rarely need any.
304
+
305
+ **Tab completion:** `claude-rpc completion install` turns it on for bash, zsh, fish or PowerShell (setup offers it too). `claude-rpc re<Tab>` → `recap` / `restart`, `claude-rpc scan --<Tab>` → `--force`, and flag values, project names and files complete as well. A typo gets a "did you mean".
307
306
 
308
307
  <details>
309
308
  <summary><b>full command reference</b></summary>
@@ -312,35 +311,46 @@ It's a thin bootstrapper — on the first session it just runs `npx claude-rpc@l
312
311
 
313
312
  | Command | What it does |
314
313
  | ---------------- | ------------ |
315
- | `setup` | Install Claude Code hooks (test-fires one synthetic SessionStart to prove the pipe works) |
316
- | `uninstall` | Remove Claude Code hooks |
317
- | `upgrade-config` | Re-run idempotent migrations on `config.json` |
314
+ | **Get started** | |
315
+ | `setup` | Install Claude Code hooks + login autostart, seed config, start the daemon. `--link <code>` also links this machine to your verified profile (`--wrapped` publishes your year too) |
316
+ | `completion` | Tab completion: `install`, `uninstall`, or print the `bash` / `zsh` / `fish` / `powershell` script |
317
+ | `uninstall` | Remove hooks, login autostart, PATH entry and tab completion (keeps your data) |
318
+ | **Your stats** | |
319
+ | `status` | Interactive TUI: heatmap, hour histogram, leaderboards (`--dump` for plain output) |
320
+ | `today` | Today's stats + when in the day you code |
321
+ | `week` | This week day by day; `--compare` puts it next to last week |
322
+ | `projects [name]`| Every project ranked by active time (`--limit N`), or one project's full record + recent daily rhythm |
323
+ | `usage` | Subscription limits: session + weekly %, the same numbers `/usage` shows |
324
+ | `recap` | Standup summary, yesterday by default (`today\|week\|YYYY-MM-DD`, `--md`, `--json`) |
325
+ | `insights` | 3–5 auto-generated lines about your history |
326
+ | `wrapped` | Your animated year in review; `--publish` puts it on `claude-rpc.com/wrapped/<handle>` |
327
+ | `serve` | The local web dashboard (port 47474) |
328
+ | `export` | The aggregate as JSON, or daily rows as CSV (`--csv` `--out`) |
329
+ | **Share** | |
330
+ | `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
+ | `statusline` | One-line status for tmux/shell prompts (`--template`) |
332
+ | `mcp` | The stats MCP server (stdio); `mcp install` / `mcp uninstall` wire it into Claude Code |
333
+ | **Privacy** | |
334
+ | `private [on\|off\|status]` | Hide this folder from Discord, show it again, or see how it resolves |
335
+ | `pause [30m\|2h\|off\|status]` | Hide the card everywhere for a while (default 1h) |
336
+ | **Online** | |
337
+ | `profile` | Opt-in public leaderboard profile: `status` \| `set` \| `on` \| `off` \| `publish` \| `verify` |
338
+ | `squad` | Private mini-leaderboards with friends: `status` \| `create <name>` \| `join <code>` \| `leave [id]` |
339
+ | `link [code]` | One profile across machines: `link` mints a code on your verified machine, `link <code>` claims it on the new one |
340
+ | `community` | Anonymous community totals, on by default for fresh installs: `status` \| `off` \| `on` \| `report` |
341
+ | **Daemon** | |
318
342
  | `start` / `stop` / `restart` | Lifecycle for the detached daemon |
319
- | `status` | Interactive TUI — heatmap, hour histogram, leaderboards (`--dump` for plain output) |
320
- | `today` / `week` | Focused views (today's stats, weekday breakdown) |
321
- | `usage` | Subscription limits — session + weekly %, the same numbers `/usage` shows |
322
- | `serve` | Open the local web dashboard (port 47474) |
323
- | `preview` | Render every rotation frame against real state |
324
- | `scan` / `rescan`| Incremental / forced re-parse of `~/.claude/projects` |
343
+ | `logs` | Follow the daemon log |
344
+ | **Troubleshoot** | |
345
+ | `doctor` | Diagnostic checklist with one-line fix hints (`--fix` to auto-repair) |
346
+ | `scan` | Re-count your history from `~/.claude/projects` (`--force` re-parses everything) |
325
347
  | `backfill <dir>` | Import transcripts from any folder (backup, other machine) |
326
- | `insights` | Print 3–5 auto-generated lines about your week |
327
- | `recap` | Standup summary — yesterday's work, paste-ready (`today\|week\|date`, `--md`) |
328
- | `badge` | Shields-style SVG (`--metric` `--range` `--out` `--gist`) |
329
- | `card` | Poster-style SVG (`--range year\|month\|week\|all`) |
330
- | `github-stat` | Embeddable profile stat card (`--handle` `--out` `--gist`) |
331
- | `calendar` | Year activity heatmap SVG (`--metric hours\|tokens` `--card` `--out` `--gist`) |
332
- | `session-card` | Recap card for the current session (`--out`) |
333
- | `readme` | Paste-ready README badge markdown for your profile (`--raw` to pipe) |
334
- | `statusline` | One-line status for tmux/shell prompts (`--template`) |
335
- | `mcp install` | Wire the stats MCP server into Claude Code (one command) |
336
- | `mcp` | Run the MCP server (stdio) for Claude Code |
337
- | `wrapped` | Open your animated year-in-review (Claude Wrapped) |
338
- | `private` / `public` / `privacy` | Per-cwd visibility toggles + status |
339
- | `community` | Opt-in community totals — `on` \| `off` \| `status` \| `report` |
340
- | `doctor` | Diagnostic checklist with one-line fix hints |
341
- | `tail` / `logs` | Tail the daemon log |
348
+ | `preview` | Render every rotation frame against real state |
349
+ | `vars` | The full template-variable list as JSON |
350
+ | `upgrade-config` | Re-run idempotent migrations on `config.json` |
342
351
  | `daemon` | Run the daemon in the foreground (debugging) |
343
- | `vars` | Dump the full template-var list as JSON |
352
+
353
+ Older names still work and always will within 1.x: `install` (setup), `dump` (status --dump), `compare` (week --compare), `project <name>` (projects <name>), `rescan` (scan --force), `resume` / `unpause` (pause off), `public` (private off), `privacy` (private status), `tail` / `log` (logs), and `badge`, `card`, `github-stat`, `calendar`, `session-card`, `readme` (statcards).
344
354
 
345
355
  Exit codes: `0` ok · `1` user error · `2` system error · `3` wrong state. `--version` and `--help` work as expected.
346
356
 
@@ -385,9 +395,9 @@ rm -rf ~/.claude-rpc # stats; plus the per-OS config dir if you want it g
385
395
 
386
396
  <br/>
387
397
 
388
- - **Discord doesn't show anything.** Discord *desktop* must be running. The browser client doesn't expose the local IPC bridge. `claude-rpc tail` shows what the daemon is actually doing.
398
+ - **Discord doesn't show anything.** Discord *desktop* must be running. The browser client doesn't expose the local IPC bridge. `claude-rpc logs` shows what the daemon is actually doing.
389
399
  - **Hooks don't fire.** `claude-rpc setup` re-registers them and now test-fires a synthetic `SessionStart` end-to-end, so a broken hook command surfaces immediately. Restart Claude Code afterwards so it re-reads its hook config.
390
- - **Config error.** Bad JSON in `config.json` no longer crashes anything — the daemon logs one line and falls back to baked defaults. `claude-rpc tail` shows the parse error verbatim.
400
+ - **Config error.** Bad JSON in `config.json` no longer crashes anything — the daemon logs one line and falls back to baked defaults. `claude-rpc logs` shows the parse error verbatim.
391
401
  - **Old binary path baked into hooks.** Common after manual exe replacement. `claude-rpc setup` rewrites hook entries to point at the canonical install location.
392
402
 
393
403
  </details>
@@ -401,8 +411,8 @@ per-user [`launchd` LaunchAgent](src/install.js) on macOS and a
401
411
  [`systemd --user` service](src/install.js) on Linux; both start the daemon at
402
412
  login without `sudo` and don't fight a manual `claude-rpc stop`.
403
413
 
404
- **Windows is supported** — grab the portable exe (no Node required), then
405
- `claude-rpc setup`. One caveat documented honestly: `fs.watch` on Windows drops
414
+ **Windows is supported** — grab `claude-rpc.exe` (no Node required), then
415
+ run `claude-rpc.exe setup`. One caveat documented honestly: `fs.watch` on Windows drops
406
416
  events when a writer commits via atomic rename (which the state file, pause file,
407
417
  scanner, and settings GUI all do), so on Windows the **mtime poll is effectively
408
418
  the primary path** and runs an order of magnitude faster (every ~3s vs ~30s
@@ -412,7 +422,7 @@ Autostart is an `HKCU\…\Run` entry launched through a windowless `.vbs` shim (
412
422
  scheduled task, by design — see [`SECURITY.md`](SECURITY.md)).
413
423
 
414
424
  Everything else — the scanner, dashboards, cards, the worker client — is
415
- platform-neutral. CI runs the full suite on Node 18/20/22 and builds the macOS
425
+ platform-neutral. CI runs the full suite on Node 18/20/22/24 and builds the macOS
416
426
  and Windows binaries every release.
417
427
 
418
428
  ## versioning
@@ -428,15 +438,15 @@ not. The worker's HTTP surface is documented in
428
438
  ## development
429
439
 
430
440
  ```sh
431
- npm test # 430+ tests, ~2s
432
- npm run lint # eslint over src + test
441
+ npm test # 550+ tests, a few seconds
442
+ npm run lint # eslint over src + test + vscode-extension
433
443
  npm run start # run daemon in foreground
434
444
  npm run serve # web dashboard against your real data
435
445
  npm run dashboard # Electron settings GUI (dev mode)
436
446
  npm run build:exe # SEA single-file binary for the current OS
437
447
  ```
438
448
 
439
- Tests are `node --test`, zero deps; CI ([release.yml](.github/workflows/release.yml)) runs the suite (+ the Worker's) across Node 18/20/22 and gates the matrix build and npm publish. Where the project's headed (and what it'll deliberately never do): [`ROADMAP.md`](ROADMAP.md).
449
+ Tests are `node --test`, zero deps; CI ([ci.yml](.github/workflows/ci.yml) on every push and PR, [release.yml](.github/workflows/release.yml) on tags) runs the suite (+ the Worker's) across Node 18/20/22/24, and the release run gates the matrix build and npm publish on it. Where the project's headed (and what it'll deliberately never do): [`ROADMAP.md`](ROADMAP.md).
440
450
 
441
451
  ## license
442
452
 
package/SECURITY.md CHANGED
@@ -17,9 +17,10 @@ fetch-and-execute anywhere in `src/`.
17
17
  | Behavior | Where | Scope | Reversible? |
18
18
  | --- | --- | --- | --- |
19
19
  | Startup persistence | `src/install.js` → `addStartupEntry` (Windows Run key, macOS LaunchAgent, Linux `systemd --user`) + `selfHealOnUpdate` (installs it on update); `src/hook.js` → `ensureDaemonRunning` (SessionStart self-heal) | Per-user login autostart (no admin/root/system service) + a detached daemon (re)launched when you start a Claude Code session | Yes — `claude-rpc uninstall` / `removeStartupEntry`; disable every auto-start path with `autostart:false` (or `CLAUDE_RPC_NO_AUTOSTART=1` in the environment for the SessionStart self-heal) |
20
+ | PATH entry (packaged installs only) | `src/cli-path.js` → `ensureCliOnPath` | Windows: appends `<config dir>\bin` to the **user** PATH (HKCU\Environment, original value kind kept). macOS/Linux: one symlink, `~/.local/bin/claude-rpc` (or `/usr/local/bin/claude-rpc` on macOS when only that is on PATH and writable). npm/Homebrew installs are already on PATH and get nothing. | Yes — `claude-rpc uninstall` removes only its own entry/link; `CLAUDE_RPC_NO_PATH=1` skips it |
20
21
  | Hook injection | `src/install.js` → `installHooks` | Only into Claude Code's own `settings.json`, only our own commands | Yes — `uninstallHooks` removes exactly what it added |
21
22
  | Outbound network | `src/community.js`, `src/gist.js`, `src/usage.js`, `src/notify.js`, `default-config.js` | Anonymous counters + (opt-in) profile/gist/webhook + own read-only OAuth-usage poll + GIF assets | Telemetry: `community off`. Profile: `profile off`. Gist/webhook: opt-in only. Usage: `usage.enabled:false`. |
22
- | Local subprocess | `reg.exe`, `wscript`, the daemon itself (`node`/packaged exe — via the Run key and the SessionStart self-heal), `git`, `gh`, `npm`, `claude`, `security`, notifiers | Static or escaped args, no shell interpolation of untrusted input | n/a |
23
+ | Local subprocess | `reg.exe`, `wscript`, the daemon itself (`node`/packaged exe — via the Run key and the SessionStart self-heal) and its short-lived scan worker, `git`, `gh`, `npm`, `claude`, `security`, notifiers | Static or escaped args, no shell interpolation of untrusted input | n/a |
23
24
 
24
25
  No credential access beyond the read-only Claude Code OAuth-token read for usage
25
26
  polling (§3d), no filesystem scanning outside `~/.claude-rpc` and Claude Code
@@ -86,16 +87,33 @@ manage the daemon yourself via `claude-rpc start` / `stop`).
86
87
  **Source:** `src/install.js`, `installHooks` / `uninstallHooks`.
87
88
 
88
89
  `setup` adds command hooks to Claude Code's `settings.json` for nine lifecycle
89
- events: `SessionStart`, `UserPromptSubmit`, `PreToolUse`, `PostToolUse`,
90
- `Stop`, `SubagentStop`, `Notification`, `SessionEnd`, `PreCompact`. Each entry looks like:
90
+ events — `SessionStart`, `UserPromptSubmit`, `PreToolUse`, `PostToolUse`,
91
+ `Stop`, `SubagentStop`, `Notification`, `SessionEnd`, `PreCompact` — plus up to
92
+ three newer ones that are **version-gated**: `PostToolUseFailure` (Claude Code
93
+ 2.0.56+), `PostCompact` (2.1.76+) and `StopFailure` (2.1.78+). Claude Code
94
+ rejects the *whole* hooks block (yours included) when it sees an event name it
95
+ doesn't know, so each of the three is wired only once the installed Claude Code
96
+ version — read from the newest transcript (`detectClaudeCodeVersion`) — is known
97
+ to support it, and is removed again if it isn't. Each entry looks like:
91
98
 
92
99
  ```jsonc
93
- { "matcher": "", "hooks": [{ "type": "command", "command": "\"<exe>\" hook PostToolUse" }] }
100
+ { "matcher": "", "hooks": [{ "type": "command", "command": "\"<exe>\" hook Stop", "_claudeRpc": true }] }
101
+ // the per-tool-call events (PreToolUse, PostToolUse, PostToolUseFailure) also run async:
102
+ { "matcher": "", "hooks": [{ "type": "command", "command": "\"<exe>\" hook PostToolUse", "async": true, "_claudeRpc": true }] }
94
103
  ```
95
104
 
105
+ `<exe>` is the packaged binary. npm and from-source installs write
106
+ `"<absolute node>" "<absolute path to src/hook.js>" <Event>` instead, because
107
+ Claude Code's hook shell may have neither `claude-rpc` nor `node` on its `PATH`.
108
+ `"async": true` makes Claude Code run the per-tool-call hooks in the background
109
+ instead of holding up each tool call; the once-per-turn events stay synchronous
110
+ so status changes land in order. `"_claudeRpc": true` is the ownership marker
111
+ described under **Scope** below.
112
+
96
113
  - **Why:** this *is* the integration. Claude Code's hook system is the
97
114
  supported, documented way for a tool to observe session lifecycle. The hook
98
- reads the event JSON on stdin, updates `~/.claude-rpc/state.json`, and prints
115
+ reads the event JSON on stdin, updates its session's state file in the temp
116
+ dir (`<tmp>/claude-rpc/state-<session>.json`, §5), and prints
99
117
  `{"continue":true}`. It never blocks, rewrites, or vetoes a tool call — see
100
118
  `src/hook.js`, `processHookEvent`.
101
119
  - **What the hook reads:** tool name, file path of the active tool, token usage
@@ -107,9 +125,13 @@ events: `SessionStart`, `UserPromptSubmit`, `PreToolUse`, `PostToolUse`,
107
125
  and `ensureDaemonRunning`. Best-effort, gated by `autostart` (default on). It
108
126
  is the **only** hook event that launches a process; every other event just
109
127
  writes state and acks.
110
- - **Scope:** the installer only ever touches entries whose command matches
111
- `isOurHookCommand` (contains `claude-rpc` or `hook.js`). It will not modify,
112
- reorder, or delete anyone else's hooks.
128
+ - **Scope:** the installer only ever touches hook objects it owns
129
+ (`isOurHook`): ones carrying its `"_claudeRpc": true` marker or — for entries
130
+ written before the marker existed — whose command contains `claude-rpc` or
131
+ the exact absolute path of *this* install's `src/hook.js` (never just any
132
+ `hook.js`). It rewrites its own objects in place, leaves other hooks in the
133
+ same matcher group alone, and will not modify, reorder, or delete anyone
134
+ else's hooks.
113
135
  - **Reverse it:** `claude-rpc uninstall` (or `uninstallHooks`) strips exactly
114
136
  the entries it added and leaves the rest of `settings.json` intact.
115
137
 
@@ -154,8 +176,11 @@ values — only forward deltas since the last accepted report.
154
176
  flow `claude-rpc community on`, which prints the payload schema first.
155
177
  - **Why on by default:** the live badges in the README aggregate these counters.
156
178
  The trade-off is disclosed here, in the README, and at install time.
157
- - **Auditable:** the Worker persists only two running integers and a 30-day
158
- `seen:<instanceId>` dedup marker. The source is in this repo.
179
+ - **Auditable:** for these reports the Worker persists only one
180
+ `total:counters` value (the two running sums, `{sessions, tokens}`), a
181
+ 30-day `seen:<instanceId>` active-install marker (`{ts, version, osFamily}`,
182
+ refreshed at most daily), and rate-limit keys that expire within a minute.
183
+ The source is in this repo.
159
184
 
160
185
  ### 3b. Gist badge publishing — only on explicit command
161
186
 
@@ -258,8 +283,9 @@ language names, 4 model names with share %, and 3 tool names with share %. No
258
283
  file paths, no prompts, no per-day breakdowns. Project names respect the
259
284
  privacy lists and `privacy.patterns` before they ever appear in the preview;
260
285
  anything you see in the confirmation box is everything the server sees. Each
261
- publish overwrites the previous one; records expire worker-side after ~14
262
- months unless re-published.
286
+ publish replaces the previous one *from the same machine*: with linked
287
+ machines, each one publishes its own slice and the page shows their merge.
288
+ Records expire worker-side after ~14 months unless re-published.
263
289
 
264
290
  ### 3d. Subscription usage — your own token, to its issuer, ON by default
265
291
 
@@ -332,11 +358,20 @@ untrusted or remote input into a shell:
332
358
 
333
359
  - `reg.exe add/delete` — the Windows Run key (`src/install.js`).
334
360
  - `wscript.exe` — runs the generated windowless startup shim (`src/install.js`).
361
+ - `powershell.exe -NoProfile -NonInteractive -EncodedCommand …` — packaged
362
+ Windows installs only: adds/removes `<config dir>\bin` in the user PATH
363
+ (`src/cli-path.js`); the script is generated from that fixed path.
335
364
  - `launchctl load/unload` — the macOS LaunchAgent (`src/install.js`); args are
336
365
  the fixed plist path.
337
366
  - `systemctl --user enable/disable/daemon-reload` — the Linux user service
338
367
  (`src/install.js`); args are the fixed unit name.
339
368
  - `chcp.com 65001` — set the console to UTF-8 on Windows TTYs (`src/cli.js`).
369
+ - the claude-rpc runtime itself, as a short-lived **scan worker** — the daemon
370
+ runs each transcript scan in a child process (`"<exe>" scan-worker`, or
371
+ `"<node>" "<absolute src/scan-worker.js>"`) so the parse memory goes back to
372
+ the OS when it exits (`src/scan-worker.js`). Fixed args (plus `--force` for a
373
+ rescan), no shell; it writes `aggregate.json`, prints one JSON summary line,
374
+ and exits. If it can't run, the daemon scans in-process instead.
340
375
  - `git` — read last commit subject / branch for the "just shipped" card
341
376
  (`src/git.js`).
342
377
  - `gh repo view --json isPrivate` — auto-hide GitHub-private repos from the card
@@ -366,11 +401,41 @@ gist `gh` wrapper on Windows) use only trusted args.
366
401
 
367
402
  ## 5. What it stores locally
368
403
 
369
- Under `~/.claude-rpc/` (a.k.a. `%APPDATA%\claude-rpc\` on Windows):
370
- `config.json`, `state.json`, `aggregate.json`, `events.jsonl` (rotated at 5 MB),
371
- `private-list.json`, `community-cursor.json`. The scanner also reads Claude Code
372
- transcript files to build aggregates. None of this leaves your machine except
373
- the minimal telemetry in 3a.
404
+ Three per-user locations (paths are defined in `src/paths.js`):
405
+
406
+ - **Data dir — `~/.claude-rpc/` on every OS** (`DATA_DIR`): `aggregate.json`
407
+ (all-time stats), `scan-cache.json` (per-transcript scan cache),
408
+ `events.jsonl` (Notification / compaction events, rotated to `.1` at 5 MB),
409
+ `private-list.json` (runtime privacy toggles; `CLAUDE_RPC_PRIVATE_LIST`
410
+ overrides the path), `version` (the last version that ran the on-update
411
+ self-heal), `community-cursor.json` (how far the 3a counters have been
412
+ reported) and `nudge-state.json` (which share-a-milestone nudge was last
413
+ shown).
414
+ - **Config dir — per OS** (`USER_CONFIG_DIR`): `$XDG_CONFIG_HOME/claude-rpc/`
415
+ (default `~/.config/claude-rpc/`) on Linux, `~/Library/Application
416
+ Support/claude-rpc/` on macOS, `%APPDATA%\claude-rpc\` on Windows. Holds
417
+ `config.json` (a from-source checkout keeps it next to the source instead)
418
+ and `bin/` — the packaged binary's canonical copy and, on Windows, the
419
+ windowless `claude-rpc-daemon.vbs` startup shim.
420
+ - **Temp dir — `<tmp>/claude-rpc/`** (`os.tmpdir()`, so a reboot clears it by
421
+ design): `state-<session>.json` per live Claude Code session (plus a
422
+ short-lived `.lock`), `state.json` for events that carry no session id,
423
+ `daemon.pid`, `daemon.log` (rotated at 5 MB), `pause.json`
424
+ (`claude-rpc pause`) and `usage.json` (the 3d percentage cache).
425
+
426
+ Beyond these (and any file you name yourself with `--out`), claude-rpc writes
427
+ only what §1 and §2 describe — the login-autostart entry and its own hooks in
428
+ `~/.claude/settings.json` — plus, when `setup` runs from `npx`, the global
429
+ `npm install -g claude-rpc` it promotes itself to (§4), and, if you run
430
+ `mcp install`, the registration `claude mcp add` makes. The scanner reads
431
+ Claude Code's transcript files (`~/.claude/projects/**/*.jsonl`) to build the
432
+ aggregates; it never writes there.
433
+
434
+ None of these files is uploaded. What leaves your machine is exactly what §3
435
+ lists: the anonymous counters (3a, on by default); the public profile, its
436
+ per-day heatmap series, squads and Wrapped (3c — opt-in); gist badges (3b) and
437
+ the status webhook (3f), only when you set them up; and for the usage poll
438
+ (3d) your own Claude Code OAuth token, sent only to `api.anthropic.com`.
374
439
 
375
440
  ## 6. Privacy controls
376
441
 
@@ -380,8 +445,22 @@ per-project `.claude-rpc.json`, a runtime private-list, config glob patterns, an
380
445
  Local dashboards and aggregates are never redacted — privacy is a one-way valve
381
446
  from local state to Discord only.
382
447
 
448
+ ## Supported versions
449
+
450
+ Security fixes land on the latest release line only.
451
+
452
+ | Version | Supported |
453
+ | ------- | --------- |
454
+ | 1.5.x | Yes |
455
+ | < 1.5 | No — upgrade (`npx claude-rpc@latest setup`, `brew upgrade claude-rpc`, or the [latest release](https://github.com/rar-file/claude-rpc/releases/latest)) |
456
+
457
+ The community worker is a single always-current deployment, so a worker fix
458
+ reaches everyone without an upgrade.
459
+
383
460
  ## Reporting a vulnerability
384
461
 
385
- Open an issue at https://github.com/rar-file/claude-rpc/issues, or for anything
386
- sensitive email c.archer.simmons@gmail.com. Please include version
387
- (`claude-rpc --version`), OS, and repro steps.
462
+ Please **don't open a public issue** for a security problem. Report it
463
+ privately through GitHub's private vulnerability reporting:
464
+ https://github.com/rar-file/claude-rpc/security/advisories/new — or, if that
465
+ isn't available to you, email c.archer.simmons@gmail.com. Please include the
466
+ version (`claude-rpc --version`), OS, and repro steps.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "claude-rpc",
3
- "version": "1.5.2",
3
+ "version": "1.6.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",
@@ -32,6 +32,7 @@
32
32
  "dist:mac": "npm run build:exe && npm run prep:dashboard && npm --prefix dashboard run dist:mac",
33
33
  "dist:win": "npm run build:exe && npm run prep:dashboard && npm --prefix dashboard run dist:win",
34
34
  "test": "node ./scripts/run-tests.mjs",
35
+ "release": "node ./scripts/release.mjs",
35
36
  "lint": "eslint src test vscode-extension",
36
37
  "format": "prettier --write \"src/**/*.js\" \"test/**/*.js\"",
37
38
  "format:check": "prettier --check \"src/**/*.js\" \"test/**/*.js\"",
@@ -6,7 +6,12 @@
6
6
  // POSIX rename() is atomic and doesn't contend like this, so this is a
7
7
  // no-op there. The lock is held single-digit milliseconds; a handful of
8
8
  // immediate retries clears it without changing behavior anywhere else.
9
- import { renameSync } from 'node:fs';
9
+ import { createRequire } from 'node:module';
10
+
11
+ // require()d, not imported — on the hook hot path; see hook.js.
12
+ const require = createRequire(import.meta.url);
13
+ const { renameSync, writeFileSync, mkdirSync, existsSync, copyFileSync, unlinkSync } = require('node:fs');
14
+ const { dirname } = require('node:path');
10
15
 
11
16
  const RETRY_CODES = new Set(['EPERM', 'EBUSY', 'EACCES']);
12
17
  const MAX_ATTEMPTS = 5;
@@ -15,7 +20,8 @@ const RETRY_DELAY_MS = 20;
15
20
  // Blocks the calling thread synchronously — the standard dependency-free way
16
21
  // to sleep inside a sync call. Best-effort: if SharedArrayBuffer is ever
17
22
  // unavailable, the retry loop just spins with no delay instead of failing.
18
- function sleepSync(ms) {
23
+ // Shared with state.js's lock-retry loop.
24
+ export function sleepSync(ms) {
19
25
  try {
20
26
  Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
21
27
  } catch {
@@ -44,3 +50,40 @@ export function renameSyncRetry(src, dest, {
44
50
  }
45
51
  throw lastErr;
46
52
  }
53
+
54
+ // Write `data` to `path` via a sibling tmp file + rename, so a reader (the
55
+ // daemon's config watcher, a concurrent CLI) never sees a half-written file.
56
+ // Creates the parent dir. Throws on failure, after removing the tmp file.
57
+ export function writeFileAtomic(path, data) {
58
+ mkdirSync(dirname(path), { recursive: true });
59
+ const tmp = `${path}.${process.pid}.tmp`;
60
+ try {
61
+ writeFileSync(tmp, data);
62
+ renameSyncRetry(tmp, path);
63
+ } catch (e) {
64
+ try { unlinkSync(tmp); } catch { /* never created / already renamed */ }
65
+ throw e;
66
+ }
67
+ }
68
+
69
+ // One-time move of a file from an old location to its new home: does nothing
70
+ // when `dest` already exists or there's nothing at `legacy`. rename() first;
71
+ // tmpdir is often a different filesystem (tmpfs), so EXDEV falls back to
72
+ // copy + unlink. Returns true when it adopted the legacy file. Never throws.
73
+ // `rename` is injectable so the EXDEV fallback is testable.
74
+ export function adoptLegacyFile(dest, legacy, { rename = renameSync } = {}) {
75
+ try {
76
+ if (!legacy || existsSync(dest) || !existsSync(legacy)) return false;
77
+ mkdirSync(dirname(dest), { recursive: true });
78
+ try {
79
+ rename(legacy, dest);
80
+ } catch (e) {
81
+ if (e.code !== 'EXDEV') throw e;
82
+ copyFileSync(legacy, dest);
83
+ try { unlinkSync(legacy); } catch { /* copied; a stale legacy file is harmless */ }
84
+ }
85
+ return true;
86
+ } catch {
87
+ return false;
88
+ }
89
+ }
package/src/badge.js CHANGED
@@ -1,7 +1,7 @@
1
1
  // Shields-style SVG badge generator. Pure function: aggregate + flags → SVG string.
2
2
  // Consumed by `claude-rpc badge` and `GET /api/badge.svg`.
3
3
 
4
- import { dayKey } from './scanner.js';
4
+ import { dayKeyAt } from './scanner.js';
5
5
  import { fmtCost } from './pricing.js';
6
6
  import { fmtNum, fmtHours as fmtHoursLabel } from './fmt.js';
7
7
 
@@ -35,11 +35,10 @@ function pickWindow(byDay, range) {
35
35
  if (!byDay) return [];
36
36
  const days = rangeToDays(range);
37
37
  if (days === null) return Object.entries(byDay); // 'all'
38
- const today = new Date(); today.setHours(0, 0, 0, 0);
38
+ const now = new Date();
39
39
  const out = [];
40
40
  for (let i = 0; i < days; i++) {
41
- const d = new Date(today); d.setDate(d.getDate() - i);
42
- const k = dayKey(d.getTime());
41
+ const k = dayKeyAt(now, i);
43
42
  if (byDay[k]) out.push([k, byDay[k]]);
44
43
  }
45
44
  return out;
package/src/card.js CHANGED
@@ -11,9 +11,8 @@
11
11
  // Output is SVG only (no PNG dep). Modern Discord / GitHub render the SVG
12
12
  // inline; for hard-copy sharing, screenshot or convert via any web tool.
13
13
 
14
- import { dayKey } from './scanner.js';
15
14
  import { fmtCost } from './pricing.js';
16
- import { rangeToDays, rangeLabel, pickWindow } from './badge.js';
15
+ import { rangeLabel, pickWindow } from './badge.js';
17
16
  import { VERSION } from './version.js';
18
17
  import { fmtNum, fmtHours, localDateStamp } from './fmt.js';
19
18
 
@@ -204,26 +203,6 @@ function activityStrip(x, y, w, h, byDay, range) {
204
203
  return `<g>${bars}</g>`;
205
204
  }
206
205
 
207
- // Heatmap-like dot row of the last N days.
208
- function dotRow(x, y, byDay, range) {
209
- const window = pickWindow(byDay, range).reverse();
210
- const sz = 9;
211
- const gap = 2;
212
- let svg = '';
213
- for (let i = 0; i < window.length; i++) {
214
- const [, d] = window[i];
215
- const ms = d.activeMs || 0;
216
- const intensity = ms === 0 ? 0 : Math.min(1, ms / (4 * 3_600_000)); // 4h = full
217
- const fill = intensity === 0
218
- ? PALETTE.paper3
219
- : intensity < 0.34 ? '#f6dccb'
220
- : intensity < 0.67 ? PALETTE.rust3
221
- : PALETTE.rust;
222
- svg += `<rect x="${x + i * (sz + gap)}" y="${y}" width="${sz}" height="${sz}" fill="${fill}" stroke="${PALETTE.ink}" stroke-width="0.5"/>`;
223
- }
224
- return svg;
225
- }
226
-
227
206
  // ── public entry point ─────────────────────────────────────────────────
228
207
 
229
208
  export function renderCard(aggregate, { range = 'year', generatedAt = new Date() } = {}) {