claude-rpc 1.5.0 → 1.5.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
@@ -220,9 +220,9 @@ For a complete account of the sensitive things claude-rpc does — startup persi
220
220
 
221
221
  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
222
 
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. Runs in ~20ms.
224
- 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. Exponential backoff with jitter on reconnect; `daemon.log` rotates at 5 MB.
225
- 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.
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).
224
+ 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
+ 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
226
 
227
227
  Persistent state, all human-readable JSON:
228
228
 
package/SECURITY.md CHANGED
@@ -16,7 +16,7 @@ fetch-and-execute anywhere in `src/`.
16
16
 
17
17
  | Behavior | Where | Scope | Reversible? |
18
18
  | --- | --- | --- | --- |
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` |
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
20
  | 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
21
  | 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
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 |
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "claude-rpc",
3
- "version": "1.5.0",
3
+ "version": "1.5.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/cli.js CHANGED
@@ -2674,6 +2674,7 @@ process.on('unhandledRejection', (e) => {
2674
2674
  case 'log': tailLog(); break;
2675
2675
  case 'hook': runHookCli(process.argv[3] || 'unknown'); break;
2676
2676
  case 'daemon': await import('./daemon.js'); break;
2677
+ case 'scan-worker': (await import('./scan-worker.js')).runScanWorker(process.argv.includes('--force')); break;
2677
2678
  default: {
2678
2679
  if (packagedDefault) {
2679
2680
  if (!isInstalled()) {
package/src/daemon.js CHANGED
@@ -20,6 +20,7 @@ import { CONFIG_PATH, STATE_PATH, PID_PATH, LOG_PATH, STATE_DIR, AGGREGATE_PATH,
20
20
  import { readUsageCache, pollUsage } from './usage.js';
21
21
  import { pollDecision, pollIntervalMs } from './watch-poll.js';
22
22
  import { claimSingleInstance } from './ensure-daemon.js';
23
+ import { scanInChild } from './scan-worker.js';
23
24
 
24
25
  if (!existsSync(STATE_DIR)) mkdirSync(STATE_DIR, { recursive: true });
25
26
 
@@ -779,16 +780,34 @@ function watchFiles() {
779
780
  }, pollIntervalMs());
780
781
  }
781
782
 
783
+ // Scans run in a short-lived child (scan-worker.js) so the parse garbage dies
784
+ // with it instead of pinning the daemon's memory; the child writes
785
+ // aggregate.json and we re-read it. If the child can't run, scan in-process.
786
+ let scanRunning = false;
782
787
  async function runBackgroundScan({ force = false } = {}) {
788
+ if (scanRunning) return; // a slow cold scan can outlast the rescan interval
789
+ scanRunning = true;
783
790
  try {
784
791
  const t0 = Date.now();
785
- const { aggregate: agg, scanned, skipped, removed, total } = scan({ force });
792
+ let res;
793
+ try {
794
+ res = await scanInChild({ force });
795
+ const fresh = readAggregate();
796
+ if (!fresh) throw new Error('scan worker left no aggregate');
797
+ res.aggregate = fresh;
798
+ } catch (e) {
799
+ log('Scan worker failed, scanning in-process:', e.message);
800
+ res = scan({ force });
801
+ }
802
+ const { aggregate: agg, scanned, skipped, removed, total } = res;
786
803
  aggregate = agg;
787
804
  log(`Scan complete: ${scanned} parsed / ${skipped} cached / ${removed} removed / ${total} total in ${Date.now() - t0}ms — allHours=${(agg.activeMs / 3_600_000).toFixed(1)}, sessions=${agg.sessions}, tokens=${(agg.inputTokens + agg.outputTokens)}`);
788
805
  resetTransmit();
789
806
  pushPresence();
790
807
  } catch (e) {
791
808
  log('Scan failed:', e.message);
809
+ } finally {
810
+ scanRunning = false;
792
811
  }
793
812
  }
794
813
 
package/src/hook.js CHANGED
@@ -43,16 +43,26 @@ function parseInput() {
43
43
 
44
44
  // Handle a single hook event. Exported so the bundled exe can dispatch
45
45
  // directly (avoids spawning a child process per hook).
46
- export function processHookEvent(event, input = {}) {
47
- const now = Date.now();
46
+ export function processHookEvent(event, input = {}, at = Date.now()) {
47
+ const now = at;
48
48
  // Each session writes its OWN state file (state-<sessionId>.json) so concurrent
49
49
  // sessions stop clobbering one shared state.json — that thrash made the card
50
50
  // jump between projects, the timer reset, and counters over-count. Subagent
51
51
  // hooks carry the parent's session_id, so their activity rolls up correctly.
52
52
  // No id (legacy payload) → the global state.json, preserving old behavior.
53
53
  const sid = input.session_id || input.sessionId || null;
54
- const update = (fn) => updateState(fn, sid);
55
- const reset = (seed) => resetState(seed, sid);
54
+ // PreToolUse/PostToolUse are wired `async` (ASYNC_EVENTS in install.js) so
55
+ // they never hold up a tool call — which means they can land out of order:
56
+ // a slow PreToolUse after its own PostToolUse, or a PostToolUse after the
57
+ // turn's (synchronous) Stop. `now` is the hook process's START time, i.e.
58
+ // Claude Code's dispatch order, so an event older than the last one applied
59
+ // is `stale`: it may still add to counters but must not overwrite status.
60
+ const update = (fn) => updateState((s) => {
61
+ const stale = now < (s.lastEventAt || 0);
62
+ if (!stale) s.lastEventAt = now;
63
+ return fn(s, stale);
64
+ }, sid);
65
+ const reset = (seed) => resetState({ lastEventAt: now, ...seed }, sid);
56
66
 
57
67
  function setActivity(patch) {
58
68
  update((s) => {
@@ -100,8 +110,10 @@ export function processHookEvent(event, input = {}) {
100
110
  // spawn storms; the daemon's atomic claim reaps any duplicate. Opt out
101
111
  // with `autostart:false` in config.
102
112
  try {
103
- let autostart = true;
104
- try { autostart = loadConfig().autostart !== false; } catch { /* unreadable config — default on */ }
113
+ // CLAUDE_RPC_NO_AUTOSTART=1 is the per-environment opt-out (CI, containers,
114
+ // the test suite) for when editing config.json isn't practical.
115
+ let autostart = process.env.CLAUDE_RPC_NO_AUTOSTART !== '1';
116
+ try { if (autostart) autostart = loadConfig().autostart !== false; } catch { /* unreadable config — default on */ }
105
117
  ensureDaemonRunning({ autostart });
106
118
  } catch { /* presence is best-effort — never break the user's turn */ }
107
119
  break;
@@ -123,21 +135,23 @@ export function processHookEvent(event, input = {}) {
123
135
  const toolName = input.tool_name || input.toolName || 'tool';
124
136
  const toolInput = input.tool_input || input.toolInput || {};
125
137
  const file = toolInput.file_path || toolInput.path || toolInput.notebook_path || null;
126
- update((s) => {
138
+ update((s, stale) => {
127
139
  s.tools += 1;
128
140
  s.toolBreakdown[toolName] = (s.toolBreakdown[toolName] || 0) + 1;
129
- s.currentTool = toolName;
130
- s.currentFile = shortFile(file);
131
- s.toolStartedAt = now;
132
- s.status = 'working';
133
- s.lastActivity = now;
134
- s.claudeClosed = false;
135
141
  if (!s.sessionStart) s.sessionStart = now;
136
- // Remember the running Bash command so the daemon can match custom
137
- // triggers (config.triggers) against it for a brief overlay frame.
138
- if (toolName === 'Bash' && toolInput.command) {
139
- s.lastBashCommand = String(toolInput.command).slice(0, 500);
140
- s.lastBashAt = now;
142
+ if (!stale) {
143
+ s.currentTool = toolName;
144
+ s.currentFile = shortFile(file);
145
+ s.toolStartedAt = now;
146
+ s.status = 'working';
147
+ s.lastActivity = now;
148
+ s.claudeClosed = false;
149
+ // Remember the running Bash command so the daemon can match custom
150
+ // triggers (config.triggers) against it for a brief overlay frame.
151
+ if (toolName === 'Bash' && toolInput.command) {
152
+ s.lastBashCommand = String(toolInput.command).slice(0, 500);
153
+ s.lastBashAt = now;
154
+ }
141
155
  }
142
156
  if (file && (toolName === 'Read' || toolName === 'NotebookEdit')) {
143
157
  s.filesOpened = pushUnique(s.filesOpened, file);
@@ -170,11 +184,13 @@ export function processHookEvent(event, input = {}) {
170
184
  }
171
185
  }
172
186
  }
173
- update((s) => {
174
- s.currentTool = null;
175
- s.toolStartedAt = null;
176
- s.lastActivity = now;
177
- s.claudeClosed = false;
187
+ update((s, stale) => {
188
+ if (!stale) {
189
+ s.currentTool = null;
190
+ s.toolStartedAt = null;
191
+ s.lastActivity = now;
192
+ s.claudeClosed = false;
193
+ }
178
194
  if (!s.sessionStart) s.sessionStart = now;
179
195
  if (file && (toolName === 'Write' || toolName === 'Edit' || toolName === 'NotebookEdit')) {
180
196
  s.filesEdited = pushUnique(s.filesEdited, file);
@@ -267,7 +283,9 @@ export function processHookEvent(event, input = {}) {
267
283
  // ack always goes out.
268
284
  export function runHookCli(event) {
269
285
  try {
270
- processHookEvent(event, parseInput());
286
+ // performance.timeOrigin = when this process was spawned, so dispatch
287
+ // order survives node's (variable) startup time — see `stale` above.
288
+ processHookEvent(event, parseInput(), Math.round(performance.timeOrigin));
271
289
  } catch { /* presence is best-effort; never break the user's turn */ }
272
290
  finally {
273
291
  try { process.stdout.write(JSON.stringify({ continue: true })); } catch { /* stdout closed */ }
package/src/install.js CHANGED
@@ -60,6 +60,13 @@ export const EVENTS = [
60
60
  'Stop', 'SubagentStop', 'Notification', 'SessionEnd', 'PreCompact',
61
61
  ];
62
62
 
63
+ // Wired `"async": true`: Claude Code runs them in the background instead of
64
+ // blocking every tool call on a node cold start (~90ms each, two per call).
65
+ // Presence never feeds anything back to Claude, so nothing waits on them;
66
+ // hook.js orders late arrivals by process start time. The once-per-turn events
67
+ // stay synchronous so status transitions (prompt → Stop) are always ordered.
68
+ export const ASYNC_EVENTS = new Set(['PreToolUse', 'PostToolUse']);
69
+
63
70
  function readJson(p, fb) {
64
71
  try { return JSON.parse(readFileSync(p, 'utf8')); }
65
72
  catch { return fb; }
@@ -109,15 +116,21 @@ export function installHooks(exePath, { silent = false } = {}) {
109
116
  for (const event of EVENTS) {
110
117
  const bucket = settings.hooks[event] = settings.hooks[event] || [];
111
118
  const wanted = cmdFor(event);
119
+ const shape = (h) => {
120
+ const { async: _drop, ...rest } = h;
121
+ return ASYNC_EVENTS.has(event)
122
+ ? { ...rest, type: 'command', command: wanted, async: true, _claudeRpc: true }
123
+ : { ...rest, type: 'command', command: wanted, _claudeRpc: true };
124
+ };
112
125
  const existingEntry = bucket.find((b) =>
113
126
  Array.isArray(b.hooks) && b.hooks.some((h) => isOurHook(h))
114
127
  );
115
128
  if (existingEntry) {
116
129
  existingEntry.hooks = existingEntry.hooks.map((h) =>
117
- isOurHook(h) ? { ...h, command: wanted, _claudeRpc: true } : h
130
+ isOurHook(h) ? shape(h) : h
118
131
  );
119
132
  } else {
120
- bucket.push({ matcher: '', hooks: [{ type: 'command', command: wanted, _claudeRpc: true }] });
133
+ bucket.push({ matcher: '', hooks: [shape({})] });
121
134
  }
122
135
  }
123
136
  if (JSON.stringify(settings.hooks) === before) {
@@ -0,0 +1,50 @@
1
+ // Runs one transcript scan in a SHORT-LIVED child process for the daemon.
2
+ //
3
+ // Parsing transcripts churns through a lot of garbage (a cold scan JSON-parses
4
+ // every line of every transcript, 25MB+ files included). V8 and the allocator
5
+ // keep that memory after a GC, so an in-process scan left the always-on daemon
6
+ // sitting at 150-250MB for a presence card. In a child, all of it goes back to
7
+ // the OS when the child exits; the daemon just re-reads aggregate.json (which
8
+ // scan() writes) and stays near node's baseline.
9
+ //
10
+ // Output contract: one JSON line on stdout, { scanned, skipped, removed, total }.
11
+ import { spawn } from 'node:child_process';
12
+ import { existsSync } from 'node:fs';
13
+ import { scan } from './scanner.js';
14
+ import { IS_PACKAGED, CANONICAL_EXE, ROOT } from './paths.js';
15
+ import { join } from 'node:path';
16
+
17
+ export function runScanWorker(force = false) {
18
+ const { scanned, skipped, removed, total } = scan({ force });
19
+ process.stdout.write(JSON.stringify({ scanned, skipped, removed, total }) + '\n');
20
+ }
21
+
22
+ // Same launch recipe as the daemon itself (ensure-daemon.spawnDaemonDetached):
23
+ // packaged → "<exe>" scan-worker, dev/npm → "<node>" "<abs scan-worker.js>".
24
+ // Resolves with the child's summary; rejects on spawn failure, a non-zero exit,
25
+ // unparseable output or `timeoutMs` — the caller then scans in-process instead.
26
+ export function scanInChild({ force = false, timeoutMs = 10 * 60_000 } = {}) {
27
+ return new Promise((resolve, reject) => {
28
+ const exe = (IS_PACKAGED && existsSync(CANONICAL_EXE)) ? CANONICAL_EXE : process.execPath;
29
+ const args = IS_PACKAGED ? ['scan-worker'] : [join(ROOT, 'src', 'scan-worker.js')];
30
+ if (force) args.push('--force');
31
+ let out = '';
32
+ let child;
33
+ try {
34
+ child = spawn(exe, args, { stdio: ['ignore', 'pipe', 'ignore'], windowsHide: true });
35
+ } catch (e) { reject(e); return; }
36
+ const timer = setTimeout(() => { try { child.kill(); } catch { /* already gone */ } }, timeoutMs);
37
+ child.stdout.on('data', (d) => { out += d; });
38
+ child.on('error', (e) => { clearTimeout(timer); reject(e); });
39
+ child.on('close', (code) => {
40
+ clearTimeout(timer);
41
+ if (code !== 0) { reject(new Error(`scan worker exited ${code}`)); return; }
42
+ try { resolve(JSON.parse(out.trim().split('\n').pop())); } catch (e) { reject(e); }
43
+ });
44
+ });
45
+ }
46
+
47
+ const argv1 = (process.argv[1] || '').replace(/\\/g, '/').toLowerCase();
48
+ if (argv1.endsWith('/src/scan-worker.js')) {
49
+ runScanWorker(process.argv.includes('--force'));
50
+ }
package/src/scanner.js CHANGED
@@ -494,7 +494,9 @@ function parseChunkInto(text, summary, pstate) {
494
494
  // (the cross-chunk bookkeeping for parseChunkInto); anything that breaks the
495
495
  // append assumption (file shrank, entry predates these fields, `_offset`
496
496
  // null) falls back to a from-scratch parse.
497
- export function parseTranscript(filePath, prev = null) {
497
+ const TRANSCRIPT_CHUNK_BYTES = 1024 * 1024;
498
+
499
+ export function parseTranscript(filePath, prev = null, { chunkBytes = TRANSCRIPT_CHUNK_BYTES } = {}) {
498
500
  const st = statSync(filePath);
499
501
  // Append only if this is the SAME file that grew: the current size must be
500
502
  // >= the size at the last parse (mirrors readSessionTokens). The old check,
@@ -511,29 +513,39 @@ export function parseTranscript(filePath, prev = null) {
511
513
  : { recentIds: [], lastRec: null };
512
514
  const startOffset = canAppend ? prev._offset : 0;
513
515
 
514
- let text = '';
515
- const len = st.size - startOffset;
516
- if (len > 0) {
516
+ // Read in fixed chunks rather than the whole file at once: a cold scan walks
517
+ // every transcript (some are 25MB+), and one full-size Buffer + string per
518
+ // file pushed the daemon's RSS past 250MB — memory the allocator then kept.
519
+ // Lines are cut at the last \n BYTE of each chunk; \n is single-byte ASCII
520
+ // and never occurs inside a multi-byte UTF-8 sequence, so no character is
521
+ // ever split. A line longer than a chunk just carries over until it ends.
522
+ let offset = startOffset; // bytes consumed through the last complete line
523
+ let carry = Buffer.alloc(0);
524
+ if (st.size > startOffset) {
517
525
  let fd;
518
526
  try {
519
527
  fd = openSync(filePath, 'r');
520
- const buf = Buffer.allocUnsafe(len);
521
- const n = readSync(fd, buf, 0, len, startOffset);
522
- text = buf.toString('utf8', 0, n);
528
+ const buf = Buffer.allocUnsafe(Math.min(chunkBytes, st.size - startOffset));
529
+ let pos = startOffset;
530
+ while (pos < st.size) {
531
+ const n = readSync(fd, buf, 0, Math.min(buf.length, st.size - pos), pos);
532
+ if (n <= 0) break;
533
+ pos += n;
534
+ const data = carry.length ? Buffer.concat([carry, buf.subarray(0, n)]) : buf.subarray(0, n);
535
+ const nl = data.lastIndexOf(0x0a);
536
+ if (nl !== -1) {
537
+ parseChunkInto(data.toString('utf8', 0, nl + 1), summary, pstate);
538
+ offset += nl + 1;
539
+ }
540
+ carry = Buffer.from(data.subarray(nl + 1)); // copy: `buf` is reused next read
541
+ }
523
542
  } finally {
524
543
  if (fd !== undefined) {
525
544
  try { closeSync(fd); } catch { /* already closed */ }
526
545
  }
527
546
  }
528
547
  }
529
-
530
- // Consume through the last newline; \n is single-byte ASCII so the boundary
531
- // is exact even with multi-byte content in the lines.
532
- const lastNl = text.lastIndexOf('\n');
533
- const complete = lastNl === -1 ? '' : text.slice(0, lastNl + 1);
534
- const remainder = lastNl === -1 ? text : text.slice(lastNl + 1);
535
- parseChunkInto(complete, summary, pstate);
536
- let offset = startOffset + Buffer.byteLength(complete, 'utf8');
548
+ const remainder = carry.toString('utf8');
537
549
  if (remainder.trim()) {
538
550
  if (safeJson(remainder) !== null) {
539
551
  // A complete final line that just isn't newline-terminated (fully
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.5.0';
14
+ const BAKED = '1.5.1';
15
15
 
16
16
  function readPkgVersion() {
17
17
  try {