claude-rpc 1.5.1 → 1.5.4

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 (46) hide show
  1. package/README.md +34 -24
  2. package/SECURITY.md +99 -20
  3. package/package.json +1 -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 +310 -383
  9. package/src/community.js +101 -60
  10. package/src/config.js +4 -1
  11. package/src/daemon.js +45 -47
  12. package/src/default-config.js +4 -3
  13. package/src/discord-ipc.js +24 -13
  14. package/src/doctor.js +63 -37
  15. package/src/ensure-daemon.js +11 -4
  16. package/src/fmt.js +8 -6
  17. package/src/format.js +8 -13
  18. package/src/gist.js +8 -18
  19. package/src/git.js +4 -1
  20. package/src/hook.js +48 -37
  21. package/src/insights.js +3 -4
  22. package/src/install.js +189 -97
  23. package/src/leaderboard.js +3 -2
  24. package/src/mcp.js +2 -8
  25. package/src/nudge.js +8 -3
  26. package/src/pricing.js +37 -4
  27. package/src/privacy.js +22 -7
  28. package/src/profile.js +0 -6
  29. package/src/recap.js +4 -17
  30. package/src/scanner.js +103 -71
  31. package/src/server/api.js +64 -36
  32. package/src/server/assets/dashboard.client.js +75 -44
  33. package/src/server/assets/dashboard.css +18 -18
  34. package/src/server/assets/dashboard.html +13 -15
  35. package/src/server/assets/wrapped.client.js +26 -11
  36. package/src/server/assets/wrapped.css +2 -2
  37. package/src/server/index.js +43 -32
  38. package/src/server/page.js +6 -3
  39. package/src/server/sse.js +90 -34
  40. package/src/session-card.js +3 -1
  41. package/src/state.js +14 -24
  42. package/src/tui.js +3 -12
  43. package/src/ui.js +7 -5
  44. package/src/verify.js +3 -7
  45. package/src/version.js +1 -1
  46. package/src/week.js +4 -4
package/src/doctor.js CHANGED
@@ -6,20 +6,23 @@
6
6
  // run repeatedly. Exit code 0 when everything passes, 1 when any check fails.
7
7
 
8
8
  import { existsSync, readFileSync, statSync, readdirSync } from 'node:fs';
9
- import { join, basename } from 'node:path';
9
+ import { join } from 'node:path';
10
10
  import {
11
- IS_PACKAGED, IS_NPM_INSTALL, IS_INSTALLED,
11
+ IS_PACKAGED, IS_NPM_INSTALL,
12
12
  CONFIG_PATH, CANONICAL_EXE, USER_CONFIG_DIR, HOOK_SCRIPT,
13
13
  STATE_PATH, PID_PATH, LOG_PATH,
14
- AGGREGATE_PATH, SCAN_CACHE_PATH,
14
+ AGGREGATE_PATH,
15
15
  CLAUDE_HOME, CLAUDE_PROJECTS, CLAUDE_SETTINGS,
16
16
  } from './paths.js';
17
17
  import { findLiveSessions } from './scanner.js';
18
+ import { listSessionStates, readActiveState } from './state.js';
19
+ import { isAlive } from './ensure-daemon.js';
18
20
  import { detectGithubUrl } from './git.js';
19
21
  import { resolveVisibility, listPrivateCwds, detectGithubPrivate } from './privacy.js';
20
22
  import { readClaudeCredentials, readUsageCache } from './usage.js';
21
23
  import { EVENTS as HOOK_EVENTS, isOurHook } from './install.js';
22
24
  import { c, check as uiCheck } from './ui.js';
25
+ import { findOnPath, pathExportHint } from './cli-path.js';
23
26
 
24
27
  const counters = { pass: 0, fail: 0, warn: 0 };
25
28
 
@@ -69,18 +72,9 @@ function checkNodeVersion() {
69
72
  }
70
73
 
71
74
  function checkMode() {
72
- let mode, detail;
73
- if (IS_PACKAGED) {
74
- mode = 'pass';
75
- detail = `packaged exe at ${process.execPath}`;
76
- } else if (IS_NPM_INSTALL) {
77
- mode = 'pass';
78
- detail = 'npm install (global or local node_modules)';
79
- } else {
80
- mode = 'pass';
81
- detail = 'dev source (cloned repo, no node_modules wrapper)';
82
- }
83
- check('execution mode', mode, detail);
75
+ check('execution mode', 'pass', IS_PACKAGED ? `packaged exe at ${process.execPath}`
76
+ : IS_NPM_INSTALL ? 'npm install (global or local node_modules)'
77
+ : 'dev source (cloned repo, no node_modules wrapper)');
84
78
  }
85
79
 
86
80
  // Pure classifiers — extracted so doctor's decision logic is unit-testable
@@ -283,8 +277,18 @@ function checkCanonicalExe() {
283
277
  }
284
278
  }
285
279
 
286
- function isAlive(pid) {
287
- try { process.kill(pid, 0); return true; } catch { return false; }
280
+ // Every command setup, doctor and the docs print is `claude-rpc …`, which only
281
+ // works when the shell can find it. Packaged installs live in <config dir>/bin,
282
+ // off PATH; setup puts them on it (see cli-path.js).
283
+ function checkCliOnPath() {
284
+ if (!IS_PACKAGED) return;
285
+ const found = findOnPath('claude-rpc');
286
+ if (found) { check('claude-rpc on PATH', 'pass', found); return; }
287
+ check('claude-rpc on PATH', 'warn', `not found — this terminal can run it as "${CANONICAL_EXE}"`,
288
+ process.platform === 'win32'
289
+ ? 'run `setup` again to add it to your user PATH (or `doctor --fix`), then open a new terminal'
290
+ : `run \`setup\` again (or \`doctor --fix\`) to link ~/.local/bin/claude-rpc; if ~/.local/bin isn't on PATH: ${pathExportHint()}`,
291
+ 'setup');
288
292
  }
289
293
 
290
294
  function checkDaemon() {
@@ -353,23 +357,47 @@ function checkDaemonLog() {
353
357
  }
354
358
  }
355
359
 
360
+ // Hook-written session state. Real sessions write per-session
361
+ // state-<sid>.json files (the global state.json only backs hook payloads
362
+ // without a session id), so judge the session the card would show. An old
363
+ // last hook event is only a problem while Claude Code is visibly active —
364
+ // that's hooks not firing; otherwise it's just an idle machine.
365
+ export const STATE_FRESH_MS = 5 * 60_000;
366
+
367
+ export function classifySessionState({ sessionCount, legacyExists, active, liveTranscripts, now = Date.now() }) {
368
+ if (!sessionCount && !legacyExists) {
369
+ return { label: 'session state', status: 'warn', detail: 'none yet', hint: 'created by the first hook event of a Claude Code session' };
370
+ }
371
+ const ageMs = active?.lastActivity ? now - active.lastActivity : Infinity;
372
+ const ageLabel = ageMs === Infinity ? 'never' : `${(ageMs / 60_000).toFixed(1)} min ago`;
373
+ const files = sessionCount ? `${sessionCount} session${sessionCount === 1 ? '' : 's'}` : 'legacy state.json only';
374
+ const detail = `${files} · status=${active?.status} · last hook event ${ageLabel}`;
375
+ if (ageMs <= STATE_FRESH_MS) return { label: 'session state fresh', status: 'pass', detail };
376
+ if (liveTranscripts) {
377
+ return {
378
+ label: 'session state fresh', status: 'warn', detail,
379
+ hint: 'claude code is writing a transcript but no hook has updated the state — run `claude-rpc setup` to re-wire the hooks',
380
+ fixKind: 'setup',
381
+ };
382
+ }
383
+ return { label: 'session state', status: 'info', detail: `${detail} · no session active` };
384
+ }
385
+
356
386
  function checkState() {
357
- if (!existsSync(STATE_PATH)) {
358
- check('state.json', 'warn', 'not present', 'created by the first hook event');
359
- return;
360
- }
361
- let state;
362
- try { state = JSON.parse(readFileSync(STATE_PATH, 'utf8')); }
363
- catch (e) {
364
- check('state.json', 'fail', `parse error: ${e.message}`,
365
- `delete ${STATE_PATH} and let the next hook event recreate it`);
366
- return;
387
+ try {
388
+ const sessions = listSessionStates();
389
+ let liveTranscripts = false;
390
+ try { liveTranscripts = findLiveSessions({ thresholdMs: 90_000 }).length > 0; } catch { /* unknown → treat as idle */ }
391
+ const r = classifySessionState({
392
+ sessionCount: sessions.length,
393
+ legacyExists: existsSync(STATE_PATH),
394
+ active: readActiveState(),
395
+ liveTranscripts,
396
+ });
397
+ check(r.label, r.status, r.detail, r.hint, r.fixKind);
398
+ } catch (e) {
399
+ check('session state', 'warn', `lookup failed: ${e.message}`);
367
400
  }
368
- const ageMin = state.lastActivity
369
- ? (Date.now() - state.lastActivity) / 60_000
370
- : Infinity;
371
- const ageLabel = ageMin === Infinity ? 'never' : `${ageMin.toFixed(1)} min ago`;
372
- check('state.json fresh', 'pass', `status=${state.status} · last activity ${ageLabel}`);
373
401
  }
374
402
 
375
403
  function checkAggregate() {
@@ -402,11 +430,8 @@ function checkPrivacy(cfg) {
402
430
  : visibility === 'name-only' ? 'warn'
403
431
  : 'pass';
404
432
  check('current directory visibility', status, detail);
405
- if (listed.length) {
406
- check('private-list entries', 'pass', `${listed.length} ${listed.length === 1 ? 'path' : 'paths'} marked private`);
407
- } else {
408
- check('private-list entries', 'pass', 'none');
409
- }
433
+ check('private-list entries', 'pass',
434
+ listed.length ? `${listed.length} ${listed.length === 1 ? 'path' : 'paths'} marked private` : 'none');
410
435
  // Private-repo guard. The "View on GitHub →" button URL is read from
411
436
  // .git/config (no gh needed), but auto-hiding a PRIVATE repo needs the gh
412
437
  // CLI. On a github repo here where the button would show (public verdict,
@@ -489,6 +514,7 @@ export function runDoctor() {
489
514
  checkNodeVersion();
490
515
  checkMode();
491
516
  checkCanonicalExe();
517
+ checkCliOnPath();
492
518
 
493
519
  section('Config');
494
520
  checkDataDir();
@@ -11,13 +11,16 @@
11
11
  // entry, several SessionStart hooks from concurrent sessions — exactly one
12
12
  // daemon survives.
13
13
 
14
- import { spawn } from 'node:child_process';
15
- import {
16
- openSync, closeSync, writeFileSync, readFileSync, unlinkSync, existsSync, statSync, mkdirSync,
17
- } from 'node:fs';
14
+ import { createRequire } from 'node:module';
18
15
  import { join } from 'node:path';
19
16
  import { PID_PATH, STATE_DIR, DAEMON_SCRIPT, CANONICAL_EXE, IS_PACKAGED } from './paths.js';
20
17
 
18
+ // require()d, not imported — on the hook hot path; see hook.js.
19
+ const require = createRequire(import.meta.url);
20
+ const {
21
+ openSync, closeSync, writeFileSync, readFileSync, unlinkSync, existsSync, statSync, mkdirSync,
22
+ } = require('node:fs');
23
+
21
24
  // mtime of this marker = last time any launcher attempted a spawn. A short
22
25
  // cooldown stops concurrent SessionStart hooks (several sessions opening at
23
26
  // once) and any startup crash-loop from spawning a swarm of throwaway daemons —
@@ -58,6 +61,10 @@ export function spawnDaemonDetached() {
58
61
  const exe = (IS_PACKAGED && existsSync(CANONICAL_EXE)) ? CANONICAL_EXE : process.execPath;
59
62
  const args = IS_PACKAGED ? ['daemon'] : [DAEMON_SCRIPT];
60
63
  try {
64
+ // Required here, not imported: node:child_process (plus dgram and the
65
+ // spawn bindings it pulls in) costs the hook a few ms on every event,
66
+ // although it only spawns when the daemon is down.
67
+ const { spawn } = require('node:child_process');
61
68
  const child = spawn(exe, args, { detached: true, stdio: 'ignore', windowsHide: true });
62
69
  // An async spawn failure (ENOENT on the exe) emits 'error'; with no listener
63
70
  // Node rethrows it as an unhandled exception that can take down the launcher.
package/src/fmt.js CHANGED
@@ -1,11 +1,13 @@
1
1
  // Canonical number/duration formatters shared across the card, badge, profile,
2
- // insights and the live presence engine (format.js re-exports these). Single
3
- // source of truth so tier-boundary rounding behaves identically everywhere —
4
- // the copies had drifted (sub-1000 rounding, a missing Billion tier).
2
+ // insights, recap, the MCP tools and the live presence engine (format.js
3
+ // re-exports these), so tier-boundary rounding behaves identically everywhere —
4
+ // the copies had drifted (sub-1000 rounding, a missing Billion tier, 999_999
5
+ // printing "1000.0k").
5
6
  //
6
- // NOTE: worker/src/badge.js keeps a byte-for-byte copy of fmtNum — the worker
7
- // deploys dependency-free and can't import across the package boundary. Keep
8
- // the two in sync; test/format.test.js pins fmtNum's tier behavior.
7
+ // NOTE: worker/src/badge.js still keeps byte-for-byte copies of fmtNum and
8
+ // fmtHours. It could import this file the way worker/src/index.js already
9
+ // imports src/heatmap.js (this one has no imports either); until it does, keep
10
+ // them in sync — test/format.test.js pins fmtNum's tier behavior.
9
11
 
10
12
  // Compact integer: 999 → "999", 1_500 → "1.5k", 1_500_000 → "1.50M", up to "T".
11
13
  // The unit is chosen from the ROUNDED value, so 999_999 → "1.00M" (not the old
package/src/format.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import { basename, dirname, extname } from 'node:path';
2
- import { dayKey, weekKey, DATE_SUFFIX_RE, cleanProjectName } from './scanner.js';
2
+ import { dayKey, weekKey, cleanProjectName } from './scanner.js';
3
3
  import { fmtCost, ratesFor } from './pricing.js';
4
4
  import { languageOf } from './languages.js';
5
5
  import { detectGitBranch, detectGitRepo } from './git.js';
@@ -72,12 +72,13 @@ function plural(n, sing, plur) {
72
72
  // two so a trailing date stamp ("…-5-20260301") can't be read as a minor.
73
73
  function humanModel(id) {
74
74
  if (!id || typeof id !== 'string') return 'Claude';
75
- const m = id.match(/(opus|sonnet|haiku|fable)[^\d]*(\d{1,2})(?!\d)(?:[-.](\d{1,2})(?!\d))?/i);
75
+ const m = id.match(/(opus|sonnet|haiku|fable|mythos)[^\d]*(\d{1,2})(?!\d)(?:[-.](\d{1,2})(?!\d))?/i);
76
76
  if (m) {
77
77
  const name = `${m[1][0].toUpperCase()}${m[1].slice(1).toLowerCase()}`;
78
78
  return m[3] ? `${name} ${m[2]}.${m[3]}` : `${name} ${m[2]}`;
79
79
  }
80
80
  if (/fable/i.test(id)) return 'Fable';
81
+ if (/mythos/i.test(id)) return 'Mythos';
81
82
  if (/opus/i.test(id)) return 'Opus';
82
83
  if (/sonnet/i.test(id)) return 'Sonnet';
83
84
  if (/haiku/i.test(id)) return 'Haiku';
@@ -237,11 +238,9 @@ export function buildVars(state, config, aggregate) {
237
238
 
238
239
  const sessionActive = state.sessionStart && state.status !== 'stale' ? 1 : 0;
239
240
 
240
- // Today's per-day bucket (from aggregate.byDay) — falls back to zeros.
241
- const today = agg.byDay?.[dayKey(Date.now())] || {
242
- activeMs: 0, userMessages: 0, toolCalls: 0,
243
- inputTokens: 0, outputTokens: 0, cacheReadTokens: 0, cacheWriteTokens: 0, sessions: 0,
244
- };
241
+ // Today's per-day bucket (from aggregate.byDay). Missing → an empty bucket;
242
+ // every field read below already defaults to 0.
243
+ const today = agg.byDay?.[dayKey(Date.now())] || {};
245
244
  const todayReal = (today.inputTokens || 0) + (today.outputTokens || 0);
246
245
  const todayCache = (today.cacheReadTokens || 0) + (today.cacheWriteTokens || 0);
247
246
  // {todayTokens} / {todayTokensFmt} = grand total today (in + out + cache).
@@ -249,11 +248,8 @@ export function buildVars(state, config, aggregate) {
249
248
 
250
249
  const bestDay = agg.bestDay || null;
251
250
 
252
- // This week's bucket.
253
- const thisWeek = agg.byWeek?.[weekKey(Date.now())] || {
254
- activeMs: 0, userMessages: 0, toolCalls: 0,
255
- inputTokens: 0, outputTokens: 0, cacheReadTokens: 0, cacheWriteTokens: 0, sessions: 0,
256
- };
251
+ // This week's bucket (same empty-bucket fallback).
252
+ const thisWeek = agg.byWeek?.[weekKey(Date.now())] || {};
257
253
  const weekTokensSum = (thisWeek.inputTokens || 0) + (thisWeek.outputTokens || 0)
258
254
  + (thisWeek.cacheReadTokens || 0) + (thisWeek.cacheWriteTokens || 0);
259
255
 
@@ -305,7 +301,6 @@ export function buildVars(state, config, aggregate) {
305
301
  : '';
306
302
 
307
303
  // Peak weekday by active time — byWeekday holds one blankDay bucket per 0–6.
308
- const WEEKDAY_NAMES = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
309
304
  let peakWd = null;
310
305
  for (const [wd, b] of Object.entries(agg.byWeekday || {})) {
311
306
  if ((b.activeMs || 0) > 0 && (!peakWd || b.activeMs > peakWd.activeMs)) {
package/src/gist.js CHANGED
@@ -166,6 +166,10 @@ export async function publishGistFile({
166
166
  token = process.env.GH_TOKEN || process.env.GITHUB_TOKEN,
167
167
  }) {
168
168
  if (!svg || typeof svg !== 'string') throw new Error('publishGistFile: svg must be a non-empty string');
169
+ // Same result shape from either backend: EDIT keeps the caller's gist
170
+ // identity, CREATE adopts the new gist's (plus its html URL).
171
+ const edited = () => ({ id: gistId, owner: owner || '', filename, rawUrl: rawGistUrl({ owner: owner || '', id: gistId, filename }) });
172
+ const created = (g) => ({ id: g.id, owner: g.owner, filename, htmlUrl: g.htmlUrl, rawUrl: rawGistUrl({ owner: g.owner, id: g.id, filename }) });
169
173
  if (hasGh()) {
170
174
  const dir = mkdtempSync(join(tmpdir(), 'claude-rpc-gist-'));
171
175
  const path = join(dir, filename);
@@ -173,16 +177,9 @@ export async function publishGistFile({
173
177
  try {
174
178
  if (gistId) {
175
179
  ghEdit(gistId, path);
176
- return { id: gistId, owner: owner || '', filename, rawUrl: rawGistUrl({ owner: owner || '', id: gistId, filename }) };
180
+ return edited();
177
181
  }
178
- const created = ghCreate(path, description, isPublic);
179
- return {
180
- id: created.id,
181
- owner: created.owner,
182
- filename,
183
- htmlUrl: created.htmlUrl,
184
- rawUrl: rawGistUrl({ owner: created.owner, id: created.id, filename }),
185
- };
182
+ return created(ghCreate(path, description, isPublic));
186
183
  } finally {
187
184
  rmSync(dir, { recursive: true, force: true });
188
185
  }
@@ -192,14 +189,7 @@ export async function publishGistFile({
192
189
  }
193
190
  if (gistId) {
194
191
  await restEdit({ svg, filename, gistId, token });
195
- return { id: gistId, owner: owner || '', filename, rawUrl: rawGistUrl({ owner: owner || '', id: gistId, filename }) };
192
+ return edited();
196
193
  }
197
- const created = await restCreate({ svg, filename, description, isPublic, token });
198
- return {
199
- id: created.id,
200
- owner: created.owner,
201
- filename,
202
- htmlUrl: created.htmlUrl,
203
- rawUrl: rawGistUrl({ owner: created.owner, id: created.id, filename }),
204
- };
194
+ return created(await restCreate({ svg, filename, description, isPublic, token }));
205
195
  }
package/src/git.js CHANGED
@@ -7,9 +7,12 @@
7
7
  // The detached-HEAD case (HEAD contains a raw SHA, not `ref: refs/heads/...`)
8
8
  // returns an empty branch — template `requires` will hide the branch frame.
9
9
 
10
- import { readFileSync, statSync } from 'node:fs';
10
+ import { createRequire } from 'node:module';
11
11
  import { basename, join, isAbsolute } from 'node:path';
12
12
 
13
+ // require()d, not imported — on the hook hot path; see hook.js.
14
+ const { readFileSync, statSync } = createRequire(import.meta.url)('node:fs');
15
+
13
16
  const TTL_MS = 5 * 60 * 1000;
14
17
  const cache = new Map(); // cwd → { ts, github, branch, repo }
15
18
 
package/src/hook.js CHANGED
@@ -1,50 +1,41 @@
1
1
  #!/usr/bin/env node
2
2
  import './safe-stdio.js';
3
- import { readFileSync, appendFileSync, existsSync, mkdirSync, statSync, renameSync } from 'node:fs';
3
+ import { createRequire } from 'node:module';
4
4
  import { dirname } from 'node:path';
5
5
  import { updateState, resetState, pushUnique, shortFile } from './state.js';
6
6
  import { detectLastCommitSubject, detectGitBranch } from './git.js';
7
7
  import { EVENTS_LOG_PATH } from './paths.js';
8
8
  import { loadConfig } from './config.js';
9
9
  import { ensureDaemonRunning } from './ensure-daemon.js';
10
- // Ship classification lives in ships.js (shared with the scanner); re-exported
11
- // here so existing importers/tests keep working.
10
+ // Ship classification lives in ships.js (shared with the scanner).
12
11
  import { classifyShip } from './ships.js';
13
- export { classifyShip };
12
+
13
+ // require()d, not imported: a builtin's ESM facade reads every export, and
14
+ // fs's lazy getters then load fs/promises and the fs streams on every hook
15
+ // event. The same goes for the rest of the hook's module graph.
16
+ const fs = createRequire(import.meta.url)('node:fs');
17
+ const { readFileSync, appendFileSync, existsSync, mkdirSync, statSync, renameSync } = fs;
14
18
 
15
19
  const EVENTS_LOG_ROTATE_BYTES = 5 * 1024 * 1024;
16
20
 
17
21
  function appendEvent(entry) {
18
22
  try {
19
23
  mkdirSync(dirname(EVENTS_LOG_PATH), { recursive: true });
20
- if (existsSync(EVENTS_LOG_PATH)) {
21
- const st = statSync(EVENTS_LOG_PATH);
22
- if (st.size > EVENTS_LOG_ROTATE_BYTES) {
23
- renameSync(EVENTS_LOG_PATH, EVENTS_LOG_PATH + '.1');
24
- }
24
+ if (existsSync(EVENTS_LOG_PATH) && statSync(EVENTS_LOG_PATH).size > EVENTS_LOG_ROTATE_BYTES) {
25
+ renameSync(EVENTS_LOG_PATH, EVENTS_LOG_PATH + '.1');
25
26
  }
26
27
  appendFileSync(EVENTS_LOG_PATH, JSON.stringify(entry) + '\n');
27
28
  } catch { /* best-effort log: hooks must never fail because of an unwritable events.jsonl */ }
28
29
  }
29
30
 
30
- function readStdin() {
31
- try {
32
- return readFileSync(0, 'utf8');
33
- } catch {
34
- return '';
35
- }
36
- }
37
-
31
+ // The JSON event payload on stdin. Unreadable, empty, or malformed → {}.
38
32
  function parseInput() {
39
- const raw = readStdin();
40
- if (!raw.trim()) return {};
41
- try { return JSON.parse(raw); } catch { return {}; }
33
+ try { return JSON.parse(readFileSync(0, 'utf8')); } catch { return {}; }
42
34
  }
43
35
 
44
36
  // Handle a single hook event. Exported so the bundled exe can dispatch
45
37
  // directly (avoids spawning a child process per hook).
46
- export function processHookEvent(event, input = {}, at = Date.now()) {
47
- const now = at;
38
+ export function processHookEvent(event, input = {}, now = Date.now()) {
48
39
  // Each session writes its OWN state file (state-<sessionId>.json) so concurrent
49
40
  // sessions stop clobbering one shared state.json — that thrash made the card
50
41
  // jump between projects, the timer reset, and counters over-count. Subagent
@@ -101,9 +92,10 @@ export function processHookEvent(event, input = {}, at = Date.now()) {
101
92
  status: 'idle',
102
93
  });
103
94
  // Self-heal the daemon. A reboot, crash, OS sleep, or closed terminal can
104
- // leave nothing running, so the card silently never appears — and on
105
- // macOS/Linux there's no login-autostart entry at all (only Windows wires
106
- // a Run key). Every Claude Code session begins with this hook, so make it
95
+ // leave nothing running, so the card silently never appears — and the
96
+ // login-autostart entry (Run key / LaunchAgent / systemd --user) can be
97
+ // missing, unloaded or unsupported (no systemd --user session, other
98
+ // platforms). Every Claude Code session begins with this hook, so make it
107
99
  // (best-effort) guarantee the daemon is up: presence is then assured
108
100
  // exactly when you're using Claude, on every platform. ensureDaemonRunning
109
101
  // is a no-op when a daemon is already alive and is cooldown-guarded against
@@ -161,18 +153,21 @@ export function processHookEvent(event, input = {}, at = Date.now()) {
161
153
  });
162
154
  break;
163
155
  }
164
- case 'PostToolUse': {
156
+ case 'PostToolUse':
157
+ case 'PostToolUseFailure': { // a failed call fires only the latter
158
+ const failed = event === 'PostToolUseFailure';
165
159
  const toolName = input.tool_name || input.toolName || '';
166
160
  const toolInput = input.tool_input || input.toolInput || {};
167
161
  const file = toolInput.file_path || toolInput.path || toolInput.notebook_path || null;
168
- // Just-shipped detection: any Bash command that contains `git push`
169
- // or `git commit`. Capture cwd + branch + last commit subject NOW
170
- // — by the time the daemon renders the next frame this info may be
171
- // gone (Claude often `cd`s after a commit).
162
+ // Just-shipped detection: a Bash command that pushes, commits, or opens
163
+ // a PR / issue / release (ships.classifyShip: push|commit|pr|issue|tag).
164
+ // Capture cwd + branch + last commit subject NOW — by the time the
165
+ // daemon renders the next frame this info may be gone (Claude often
166
+ // `cd`s after a commit).
172
167
  let shipKind = null;
173
168
  let shipSubject = null;
174
169
  let shipBranch = null;
175
- if (toolName === 'Bash') {
170
+ if (toolName === 'Bash' && !failed) { // a failed `git commit` shipped nothing
176
171
  shipKind = classifyShip(toolInput.command);
177
172
  if (shipKind) {
178
173
  const shipCwd = input.cwd || process.cwd();
@@ -243,9 +238,22 @@ export function processHookEvent(event, input = {}, at = Date.now()) {
243
238
  appendEvent({ type: 'precompact', ts: now, trigger: input.trigger || input.matcher || null, cwd: input.cwd || null });
244
239
  break;
245
240
  }
246
- // No PostCompact case: Claude Code has no such event. Post-compaction
247
- // arrives as SessionStart (source:'compact'), whose resetState clears the
248
- // compacting marker — so the `compacting` state ends without a handler.
241
+ case 'PostCompact': {
242
+ // Claude Code 2.1.76+. Older versions only re-fire SessionStart
243
+ // (source:'compact'), handled above. An auto-compaction resumes the turn
244
+ // that triggered it; a manual /compact leaves the session waiting on you.
245
+ update((s) => {
246
+ const manual = (input.trigger || s.compactTrigger) === 'manual';
247
+ delete s.compactStartedAt;
248
+ delete s.compactTrigger;
249
+ s.status = manual ? 'idle' : 'working';
250
+ s.lastActivity = now;
251
+ s.claudeClosed = false;
252
+ if (!s.sessionStart) s.sessionStart = now;
253
+ return s;
254
+ });
255
+ break;
256
+ }
249
257
  case 'SessionEnd': {
250
258
  // Authoritative "Claude Code is gone" signal — don't wait on the
251
259
  // staleSessionMin timeout. applyIdle short-circuits to stale when it
@@ -269,6 +277,7 @@ export function processHookEvent(event, input = {}, at = Date.now()) {
269
277
  setActivity({});
270
278
  break;
271
279
  }
280
+ case 'StopFailure': // the turn ended on an API error — Stop never fires
272
281
  case 'Stop':
273
282
  default: {
274
283
  setActivity({ status: 'idle', currentTool: null, currentFile: null });
@@ -283,9 +292,11 @@ export function processHookEvent(event, input = {}, at = Date.now()) {
283
292
  // ack always goes out.
284
293
  export function runHookCli(event) {
285
294
  try {
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));
295
+ // now − uptime = when this process was spawned, so dispatch order
296
+ // survives node's (variable) startup time — see `stale` above. (The same
297
+ // instant as performance.timeOrigin, to Date.now()'s 1ms resolution,
298
+ // without loading perf_hooks.)
299
+ processHookEvent(event, parseInput(), Math.round(Date.now() - process.uptime() * 1000));
289
300
  } catch { /* presence is best-effort; never break the user's turn */ }
290
301
  finally {
291
302
  try { process.stdout.write(JSON.stringify({ continue: true })); } catch { /* stdout closed */ }
package/src/insights.js CHANGED
@@ -7,7 +7,7 @@
7
7
  // mid-tier ROTATES — a fresh mix each run instead of the same five forever.
8
8
  // Pass opts.seed for a deterministic order (tests); it defaults to the clock.
9
9
 
10
- import { dayKey } from './scanner.js';
10
+ import { dayKeyAt } from './scanner.js';
11
11
  import { fmtCost } from './pricing.js';
12
12
  import { fmtNum, fmtHours } from './fmt.js';
13
13
 
@@ -62,10 +62,9 @@ function rng(seed) {
62
62
  // Sum activeMs across the last `days` days (inclusive of today).
63
63
  function windowActive(byDay, days, offset = 0) {
64
64
  let total = 0;
65
- const today = new Date(); today.setHours(0, 0, 0, 0);
65
+ const now = new Date();
66
66
  for (let i = offset; i < offset + days; i++) {
67
- const d = new Date(today); d.setDate(d.getDate() - i);
68
- total += (byDay?.[dayKey(d.getTime())] || {}).activeMs || 0;
67
+ total += (byDay?.[dayKeyAt(now, i)] || {}).activeMs || 0;
69
68
  }
70
69
  return total;
71
70
  }