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
@@ -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/help.js ADDED
@@ -0,0 +1,117 @@
1
+ // `claude-rpc help` and `claude-rpc help <command>`, both rendered from the
2
+ // command table in commands.js.
3
+
4
+ import { c } from './ui.js';
5
+ import { VERSION } from './version.js';
6
+ import { GROUPS, ALIAS_HINT, findCommand, visibleCommands } from './commands.js';
7
+
8
+ const GROUP_STYLE = {
9
+ start: [c.green, '▸'],
10
+ stats: [c.cyan, '▤'],
11
+ share: [c.magenta, '↗'],
12
+ privacy: [c.yellow, '◐'],
13
+ online: [c.blue, '◎'],
14
+ daemon: [c.green, '●'],
15
+ fix: [c.red, '✚'],
16
+ };
17
+
18
+ const width = () => Math.max(60, Math.min(process.stdout.columns || 100, 110));
19
+
20
+ // Word-wrap `text` to `w` columns, continuation lines indented by `pad`.
21
+ function wrap(text, w, pad) {
22
+ if (w < 20 || text.length <= w) return text;
23
+ const out = [];
24
+ let line = '';
25
+ for (const word of text.split(' ')) {
26
+ if (line && line.length + 1 + word.length > w) { out.push(line); line = word; }
27
+ else line = line ? `${line} ${word}` : word;
28
+ }
29
+ if (line) out.push(line);
30
+ return out.join(`\n${' '.repeat(pad)}`);
31
+ }
32
+
33
+ function banner() {
34
+ const title = `${c.bold}${c.magenta}◆ claude-rpc${c.reset}`;
35
+ const tag = `${c.dim}Discord Rich Presence for Claude Code${c.reset}`;
36
+ const ver = `${c.gray}v${VERSION}${c.reset}`;
37
+ return `\n ${title} ${tag} ${ver}\n`;
38
+ }
39
+
40
+ export function renderHelp() {
41
+ const cmds = visibleCommands();
42
+ // Long synopses (recap's date forms) collapse to the bare name; `help <cmd>` has them.
43
+ const MAX = 24;
44
+ const label = (cmd) => {
45
+ const full = cmd.name + (cmd.usage ? ` ${cmd.usage}` : '');
46
+ return full.length > MAX ? cmd.name : full;
47
+ };
48
+ const colW = cmds.reduce((m, cmd) => Math.max(m, label(cmd).length), 0);
49
+ const descW = width() - colW - 8;
50
+ const lines = [banner()];
51
+
52
+ lines.push(` ${c.dim}Usage:${c.reset} ${c.bold}claude-rpc${c.reset} ${c.cyan}<command>${c.reset} ${c.dim}[options]${c.reset}\n`);
53
+
54
+ for (const [key, title] of GROUPS) {
55
+ const [color, icon] = GROUP_STYLE[key] || [c.cyan, '·'];
56
+ const inGroup = cmds.filter((cmd) => cmd.group === key);
57
+ if (!inGroup.length) continue;
58
+ lines.push(` ${color}${icon}${c.reset} ${c.bold}${title}${c.reset}`);
59
+ for (const cmd of inGroup) {
60
+ const shown = label(cmd);
61
+ const usage = shown !== cmd.name ? `${c.dim}${cmd.usage}${c.reset}` : '';
62
+ const head = `${c.cyan}${c.bold}${cmd.name}${c.reset}${usage ? ` ${usage}` : ''}`;
63
+ const pad = ' '.repeat(colW - shown.length + 2);
64
+ lines.push(` ${head}${pad}${wrap(cmd.summary, descW, colW + 6)}`);
65
+ }
66
+ lines.push('');
67
+ }
68
+
69
+ const tips = [
70
+ ['one command in detail', 'claude-rpc help <command>'],
71
+ ['tab completion', 'claude-rpc completion install'],
72
+ ['something off?', 'claude-rpc doctor --fix'],
73
+ ['docs', 'https://claude-rpc.com/docs'],
74
+ ];
75
+ const tipW = tips.reduce((m, [k]) => Math.max(m, k.length), 0);
76
+ for (const [k, v] of tips) lines.push(` ${c.gray}${k.padEnd(tipW)}${c.reset} ${c.cyan}${v}${c.reset}`);
77
+ lines.push('');
78
+ lines.push(` ${c.gray}exit codes: 0 ok · 1 usage error · 2 system error · 3 wrong state${c.reset}`);
79
+ lines.push('');
80
+ return lines.join('\n');
81
+ }
82
+
83
+ export function renderCommandHelp(name) {
84
+ const cmd = findCommand(name);
85
+ if (!cmd) return null;
86
+ const lines = [''];
87
+ const viaAlias = cmd.name !== name ? ` ${c.dim}(\`${name}\` still works — it's \`claude-rpc ${ALIAS_HINT[name] || cmd.name}\` now)${c.reset}` : '';
88
+ lines.push(` ${c.bold}${c.magenta}◆ claude-rpc ${cmd.name}${c.reset}${viaAlias}`);
89
+ lines.push(` ${cmd.summary}`);
90
+ lines.push('');
91
+ lines.push(` ${c.dim}Usage${c.reset}`);
92
+ lines.push(` ${c.bold}claude-rpc${c.reset} ${c.cyan}${cmd.name}${c.reset}${cmd.usage ? ` ${cmd.usage}` : ''}${cmd.flags?.length ? ` ${c.dim}[options]${c.reset}` : ''}`);
93
+ lines.push('');
94
+
95
+ const table = (title, rows) => {
96
+ if (!rows.length) return;
97
+ const w = rows.reduce((m, [k]) => Math.max(m, k.length), 0);
98
+ lines.push(` ${c.dim}${title}${c.reset}`);
99
+ for (const [k, d] of rows) lines.push(` ${c.cyan}${k.padEnd(w)}${c.reset} ${d}`);
100
+ lines.push('');
101
+ };
102
+ table('Choices', (cmd.subs || []).map(([s, d]) => [s, d]));
103
+ table('Options', (cmd.flags || []).map(([f, d, v]) => {
104
+ const val = Array.isArray(v) ? ` <${v.join('|')}>` : v === 'file' ? ' [file]' : v ? ' <value>' : '';
105
+ return [f + val, d];
106
+ }));
107
+ if (cmd.examples?.length) {
108
+ lines.push(` ${c.dim}Examples${c.reset}`);
109
+ for (const ex of cmd.examples) lines.push(` ${c.gray}$${c.reset} ${ex}`);
110
+ lines.push('');
111
+ }
112
+ if (cmd.aliases?.length) {
113
+ lines.push(` ${c.gray}also answers to: ${cmd.aliases.join(', ')}${c.reset}`);
114
+ lines.push('');
115
+ }
116
+ return lines.join('\n');
117
+ }
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
@@ -167,10 +159,11 @@ export function processHookEvent(event, input = {}, at = Date.now()) {
167
159
  const toolName = input.tool_name || input.toolName || '';
168
160
  const toolInput = input.tool_input || input.toolInput || {};
169
161
  const file = toolInput.file_path || toolInput.path || toolInput.notebook_path || null;
170
- // Just-shipped detection: any Bash command that contains `git push`
171
- // or `git commit`. Capture cwd + branch + last commit subject NOW
172
- // — by the time the daemon renders the next frame this info may be
173
- // 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).
174
167
  let shipKind = null;
175
168
  let shipSubject = null;
176
169
  let shipBranch = null;
@@ -299,9 +292,11 @@ export function processHookEvent(event, input = {}, at = Date.now()) {
299
292
  // ack always goes out.
300
293
  export function runHookCli(event) {
301
294
  try {
302
- // performance.timeOrigin = when this process was spawned, so dispatch
303
- // order survives node's (variable) startup time — see `stale` above.
304
- 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));
305
300
  } catch { /* presence is best-effort; never break the user's turn */ }
306
301
  finally {
307
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
  }