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/src/privacy.js CHANGED
@@ -99,13 +99,20 @@ function readPrivateList() {
99
99
  }
100
100
 
101
101
  function writePrivateList(list) {
102
- if (!existsSync(DATA_DIR)) mkdirSync(DATA_DIR, { recursive: true });
102
+ // The list's own dir (not DATA_DIR), so a CLAUDE_RPC_PRIVATE_LIST override
103
+ // doesn't also create ~/.claude-rpc.
104
+ mkdirSync(dirname(PRIVATE_LIST_PATH), { recursive: true });
103
105
  writeFileSync(PRIVATE_LIST_PATH, JSON.stringify(list, null, 2));
104
106
  }
105
107
 
108
+ // `claude-rpc private`. The GUI-managed visibility map below outranks this
109
+ // list, so a map entry for the cwd (or a parent) saying public / name-only
110
+ // would make the command a silent no-op: pin the cwd hidden in the map too.
106
111
  export function addPrivateCwd(cwd) {
107
- const list = readPrivateList();
108
112
  const abs = resolvePath(cwd);
113
+ const mapped = visibilityForCwd(abs);
114
+ if (mapped && mapped !== 'hidden') setCwdVisibility(abs, 'hidden');
115
+ const list = readPrivateList();
109
116
  if (!list.paths.includes(abs)) {
110
117
  list.paths.push(abs);
111
118
  writePrivateList(list);
@@ -113,9 +120,16 @@ export function addPrivateCwd(cwd) {
113
120
  return list.paths;
114
121
  }
115
122
 
123
+ // `claude-rpc public`. Same precedence in reverse: drop the cwd's own hiding
124
+ // map entry, and if a parent's entry would still hide it, mark it public.
125
+ // An explicit 'public' entry is kept — it also opts out of pattern/gh hiding.
116
126
  export function removePrivateCwd(cwd) {
117
- const list = readPrivateList();
118
127
  const abs = resolvePath(cwd);
128
+ const own = listVisibility()[abs];
129
+ if (own && own !== 'public') setCwdVisibility(abs, null);
130
+ const inherited = visibilityForCwd(abs);
131
+ if (inherited && inherited !== 'public') setCwdVisibility(abs, 'public');
132
+ const list = readPrivateList();
119
133
  list.paths = list.paths.filter((p) => p !== abs);
120
134
  writePrivateList(list);
121
135
  return list.paths;
@@ -279,11 +293,12 @@ export function projectNameIsPrivate(name, config = {}, clean = (s) => s) {
279
293
  return false;
280
294
  }
281
295
 
282
- // Glob-lite. '*' matches any run; otherwise plain text. Case-insensitive.
296
+ // Glob-lite. '*' matches any run; otherwise plain text. Case-insensitive on
297
+ // both sides, for plain and glob patterns alike ("ClientX" ≡ "clientx").
283
298
  function matchesPattern(name, pattern) {
284
- if (pattern === name) return true;
285
- if (!pattern.includes('*')) return false;
286
- const re = new RegExp('^' + pattern.split('*').map(escapeRe).join('.*') + '$', 'i');
299
+ const p = String(pattern);
300
+ if (!p.includes('*')) return p.toLowerCase() === String(name).toLowerCase();
301
+ const re = new RegExp('^' + p.split('*').map(escapeRe).join('.*') + '$', 'i');
287
302
  return re.test(name);
288
303
  }
289
304
  function escapeRe(s) { return s.replace(/[.+?^${}()|[\]\\]/g, '\\$&'); }
package/src/profile.js CHANGED
@@ -6,7 +6,6 @@
6
6
  // Output is pure SVG — GitHub renders it inline in a README <img>.
7
7
 
8
8
  import { fmtCost } from './pricing.js';
9
- import { VERSION } from './version.js';
10
9
  import { fmtNum, fmtHours, localDateStamp } from './fmt.js';
11
10
 
12
11
  const W = 520;
@@ -138,8 +137,3 @@ export function renderProfileCard(aggregate, { handle = '', generatedAt = new Da
138
137
  font-size="11" fill="${PALETTE.inkFaint}">${escapeXml(`best streak ${t.longestStreak}d · ≈${fmtCost(t.cost)} · claude-rpc.com`)}</text>
139
138
  </svg>`;
140
139
  }
141
-
142
- // Top-level convenience matching badge.js / card.js shape.
143
- export function profileCardSvg({ aggregate, handle = '' } = {}) {
144
- return renderProfileCard(aggregate, { handle });
145
- }
package/src/recap.js CHANGED
@@ -11,7 +11,8 @@
11
11
  // today and says so — Monday standups cover Friday.
12
12
  // week — the last 7 local days, ending today
13
13
  // YYYY-MM-DD — one explicit local day
14
- import { dayKey } from './scanner.js';
14
+ import { dayKeyAt } from './scanner.js';
15
+ import { fmtNum as fmtN } from './fmt.js';
15
16
 
16
17
  const WEEKDAYS = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
17
18
  const SHIP_LABELS = [
@@ -22,6 +23,8 @@ const SHIP_LABELS = [
22
23
  ['tag', 'release', 'releases'],
23
24
  ];
24
25
 
26
+ // Not fmt.fmtHours: a recap keeps one decimal past 10h ("23.4h" for a week)
27
+ // and prints an empty day as "0m".
25
28
  function fmtDur(ms) {
26
29
  const m = Math.round((ms || 0) / 60_000);
27
30
  if (m < 1) return '0m';
@@ -29,22 +32,6 @@ function fmtDur(ms) {
29
32
  return `${(m / 60).toFixed(1)}h`;
30
33
  }
31
34
 
32
- function fmtN(n) {
33
- if (!n) return '0';
34
- if (n < 1000) return String(Math.round(n));
35
- if (n < 1e6) return `${(n / 1e3).toFixed(1)}k`;
36
- if (n < 1e9) return `${(n / 1e6).toFixed(2)}M`;
37
- if (n < 1e12) return `${(n / 1e9).toFixed(2)}B`;
38
- return `${(n / 1e12).toFixed(2)}T`;
39
- }
40
-
41
- function dayKeyAt(now, offsetDays) {
42
- const d = new Date(now);
43
- d.setHours(0, 0, 0, 0);
44
- d.setDate(d.getDate() - offsetDays);
45
- return dayKey(d.getTime());
46
- }
47
-
48
35
  // "Tue 2026-07-01" — manual weekday names so output is locale-stable.
49
36
  function prettyDay(key) {
50
37
  const [y, m, d] = String(key).split('-').map(Number);
package/src/scanner.js CHANGED
@@ -1,11 +1,12 @@
1
1
  import { readdirSync, readFileSync, statSync, existsSync, writeFileSync, mkdirSync, openSync, readSync, closeSync, realpathSync } from 'node:fs';
2
- import { join, dirname, basename } from 'node:path';
2
+ import { join, basename } from 'node:path';
3
3
  import { homedir } from 'node:os';
4
4
  import { CLAUDE_PROJECTS, SCAN_CACHE_PATH, AGGREGATE_PATH, DATA_DIR, EVENTS_LOG_PATH } from './paths.js';
5
5
  import { languageOf } from './languages.js';
6
6
  import { costFor, pricingKeyFor } from './pricing.js';
7
7
  import { classifyShip } from './ships.js';
8
8
  import { renameSyncRetry } from './atomic-rename.js';
9
+ import { localDateStamp } from './fmt.js';
9
10
 
10
11
  // Bumping this forces a full re-parse on next scan. Increment whenever the
11
12
  // per-transcript summary schema changes in a way old caches can't satisfy.
@@ -14,7 +15,9 @@ import { renameSyncRetry } from './atomic-rename.js';
14
15
  // never assigned, leaving {startTimeLabel} permanently blank).
15
16
  // v7: per-day byModel buckets in transcript summaries — bump forces the one
16
17
  // full rescan that backfills model-mix history for already-scanned files.
17
- const CACHE_VERSION = 7;
18
+ // v8: usage counted at each message's final values (usageDelta), not its first
19
+ // line's — re-parse to correct output tokens/cost in existing history.
20
+ const CACHE_VERSION = 8;
18
21
 
19
22
  // Cap counted gap between consecutive timestamps. Anything larger is treated
20
23
  // as the user walking away — we count only what's plausibly active time.
@@ -22,8 +25,17 @@ const ACTIVE_GAP_CAP_MS = 5 * 60 * 1000;
22
25
 
23
26
  // Local-time YYYY-MM-DD key for bucketing.
24
27
  function dayKey(ts) {
25
- const d = new Date(ts);
26
- return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`;
28
+ return localDateStamp(new Date(ts));
29
+ }
30
+
31
+ // Day key `offsetDays` local calendar days before the day containing `now`.
32
+ // Steps with setDate from local midnight, so a 23h/25h DST day can't skip or
33
+ // repeat a key the way subtracting 24h spans would.
34
+ function dayKeyAt(now, offsetDays) {
35
+ const d = new Date(now);
36
+ d.setHours(0, 0, 0, 0);
37
+ d.setDate(d.getDate() - offsetDays);
38
+ return dayKey(d.getTime());
27
39
  }
28
40
 
29
41
  // ISO week key like "2026-W21" using local time. Monday-start.
@@ -42,6 +54,19 @@ function hourKey(ts) {
42
54
  return new Date(ts).getHours();
43
55
  }
44
56
 
57
+ // All three bucket keys for one record, from a single Date. weekKey depends
58
+ // only on the local calendar day (it floors to midnight first), so it's
59
+ // memoized per day key — building its three Dates for every record was the
60
+ // costliest step of bucketing.
61
+ const weekKeyByDay = new Map();
62
+ function bucketKeys(ts) {
63
+ const d = new Date(ts);
64
+ const day = localDateStamp(d);
65
+ let week = weekKeyByDay.get(day);
66
+ if (week === undefined) weekKeyByDay.set(day, (week = weekKey(ts)));
67
+ return { ts, day, week, hour: d.getHours() };
68
+ }
69
+
45
70
  // Reject malformed or implausible transcript timestamps before they poison
46
71
  // firstTs/lastTs (which drive wallMs) and the day/week/hour buckets. A NaN from
47
72
  // a bad string, a year-0 epoch artifact, or a far-future entry from a skewed
@@ -106,7 +131,6 @@ function countLines(text) {
106
131
  // Treat empty trailing newline as not contributing — line count is the
107
132
  // number of "\n"-separated chunks that actually have content, plus one for
108
133
  // the final segment if non-empty.
109
- if (text === '') return 0;
110
134
  const lines = text.split('\n');
111
135
  // Drop a single trailing empty string from a trailing newline.
112
136
  if (lines.length && lines[lines.length - 1] === '') lines.pop();
@@ -274,16 +298,43 @@ function blankTranscriptSummary() {
274
298
  // split while staying cheap to persist in the scan cache.
275
299
  const RECENT_IDS_MAX = 200;
276
300
 
301
+ // How much of this line's usage hasn't been counted yet for its message.id.
302
+ // Claude Code writes one line per content block of an assistant message, each
303
+ // repeating that message's usage. Input and cache counts repeat unchanged, but
304
+ // output_tokens is a running count while the message streams, so a later line
305
+ // can carry a larger value than the first (seen on Claude Code 2.1: counting
306
+ // only the first line under-counted output by ~8%). Each message.id is
307
+ // therefore counted once at its largest, final usage: the first line adds its
308
+ // whole usage, later lines only what grew. `recent` holds
309
+ // [id, input, output, cacheRead, cacheWrite] entries. Returns { first, delta }
310
+ // with delta in API usage shape, or null when nothing new is left to count.
311
+ function usageDelta(recent, msgId, u) {
312
+ const cur = [u?.input_tokens || 0, u?.output_tokens || 0, u?.cache_read_input_tokens || 0, u?.cache_creation_input_tokens || 0];
313
+ const shape = (v) => ({ input_tokens: v[0], output_tokens: v[1], cache_read_input_tokens: v[2], cache_creation_input_tokens: v[3] });
314
+ if (!msgId) return { first: true, delta: shape(cur) };
315
+ const hit = recent.find((e) => e[0] === msgId);
316
+ if (!hit) {
317
+ recent.push([msgId, ...cur]);
318
+ if (recent.length > RECENT_IDS_MAX) recent.shift();
319
+ return { first: true, delta: shape(cur) };
320
+ }
321
+ const grew = cur.map((v, i) => Math.max(0, v - hit[i + 1]));
322
+ if (!grew.some(Boolean)) return null;
323
+ for (let i = 0; i < 4; i++) hit[i + 1] = Math.max(hit[i + 1], cur[i]);
324
+ return { first: false, delta: shape(grew) };
325
+ }
326
+
277
327
  // Parse complete JSONL lines into `summary`, mutating it in place. `pstate`
278
328
  // carries the cross-chunk bookkeeping that incremental (append-only) parsing
279
329
  // needs to behave exactly like a full parse:
280
- // recentIds — recently counted assistant message.ids. Claude Code splits
281
- // one assistant message (a single message.id) across several
282
- // JSONL lines — one per content block — repeating the SAME
283
- // `usage` object on every line. Token/cost/turn counting must
284
- // happen once per message.id, or a 3-block turn counts 3×.
285
- // Content blocks themselves are distinct per line, so those
286
- // stay counted per line.
330
+ // recentIds — recently counted assistant messages, [id, ...usage counted]
331
+ // (see usageDelta). Claude Code splits one assistant message (a
332
+ // single message.id) across several JSONL lines — one per
333
+ // content block — repeating its `usage` on every line. Tokens
334
+ // and cost count once per message.id at its final usage, turns
335
+ // once per message.id, or a 3-block turn counts 3×. Content
336
+ // blocks themselves are distinct per line, so those stay
337
+ // counted per line.
287
338
  // lastRec — the previous chunk's final timestamped record, so the
288
339
  // active-time gap across a chunk boundary still accrues.
289
340
  function parseChunkInto(text, summary, pstate) {
@@ -301,13 +352,11 @@ function parseChunkInto(text, summary, pstate) {
301
352
  summary.project = cleanProjectName(basename(r.cwd));
302
353
  }
303
354
  const ts = parseTs(r.timestamp);
304
- const day = ts ? dayKey(ts) : null;
305
- const week = ts ? weekKey(ts) : null;
306
- const hour = ts ? hourKey(ts) : null;
307
- const dayBucket = day ? (summary.byDay[day] ||= blankDay()) : null;
308
- const weekBucket = week ? (summary.byWeek[week] ||= blankDay()) : null;
309
- const hourBucket = hour !== null ? (summary.byHour[hour] ||= blankDay()) : null;
310
- const allBuckets = [dayBucket, weekBucket, hourBucket].filter(Boolean);
355
+ const rec = ts ? bucketKeys(ts) : null; // { ts, day, week, hour }
356
+ const dayBucket = rec ? (summary.byDay[rec.day] ||= blankDay()) : null;
357
+ const weekBucket = rec ? (summary.byWeek[rec.week] ||= blankDay()) : null;
358
+ const hourBucket = rec ? (summary.byHour[rec.hour] ||= blankDay()) : null;
359
+ const allBuckets = rec ? [dayBucket, weekBucket, hourBucket] : [];
311
360
  // First/last activity within each bucket — blankDay declares these and
312
361
  // mergeDay merges them, but nothing assigned them, so "started 09:14"-style
313
362
  // labels never rendered.
@@ -320,19 +369,21 @@ function parseChunkInto(text, summary, pstate) {
320
369
 
321
370
  if (r.type === 'assistant') {
322
371
  const turnModel = r.message?.model || summary.model;
323
- const u = r.message?.usage;
324
- // Count usage/cost/turn only the first time we see this message.id (see
325
- // the pstate.recentIds note above). No id (rare/legacy) → count it.
326
- const msgId = r.message?.id;
327
- const firstSeen = !msgId || !pstate.recentIds.includes(msgId);
328
- if (msgId && firstSeen) {
329
- pstate.recentIds.push(msgId);
330
- if (pstate.recentIds.length > RECENT_IDS_MAX) pstate.recentIds.shift();
331
- }
372
+ // Count the turn once per message.id and its usage once, at the
373
+ // message's final values (see usageDelta). No id (rare/legacy) → count
374
+ // every line.
375
+ const counted = usageDelta(pstate.recentIds, r.message?.id, r.message?.usage);
376
+ const firstSeen = !!counted?.first;
377
+ const u = r.message?.usage ? counted?.delta : null;
332
378
  // Per-model split bucket, keyed by pricing key so cost/tokens/turns align.
333
379
  const mkey = turnModel ? pricingKeyFor(turnModel) : null;
334
380
  const mb = mkey ? (summary.byModel[mkey] ||= { turns: 0, tokens: 0, cost: 0 }) : null;
335
- if (u && firstSeen) {
381
+ // Per-day model split (day granularity only — week/hour stay lean).
382
+ // Powers model-mix-over-time; the all-time byModel can't trend.
383
+ const dm = (firstSeen || u) && mkey && dayBucket
384
+ ? ((dayBucket.byModel ||= {})[mkey] ||= { turns: 0, tokens: 0, cost: 0 })
385
+ : null;
386
+ if (u) {
336
387
  summary.inputTokens += u.input_tokens || 0;
337
388
  summary.outputTokens += u.output_tokens || 0;
338
389
  summary.cacheReadTokens += u.cache_read_input_tokens || 0;
@@ -343,17 +394,10 @@ function parseChunkInto(text, summary, pstate) {
343
394
  bucket.cacheReadTokens += u.cache_read_input_tokens || 0;
344
395
  bucket.cacheWriteTokens += u.cache_creation_input_tokens || 0;
345
396
  }
346
- if (mb) {
347
- mb.tokens += (u.input_tokens || 0) + (u.output_tokens || 0)
348
- + (u.cache_read_input_tokens || 0) + (u.cache_creation_input_tokens || 0);
349
- }
350
- // Per-day model split (day granularity only — week/hour stay lean).
351
- // Powers model-mix-over-time; the all-time byModel can't trend.
352
- if (mkey && dayBucket) {
353
- const dm = ((dayBucket.byModel ||= {})[mkey] ||= { turns: 0, tokens: 0, cost: 0 });
354
- dm.tokens += (u.input_tokens || 0) + (u.output_tokens || 0)
355
- + (u.cache_read_input_tokens || 0) + (u.cache_creation_input_tokens || 0);
356
- }
397
+ const turnTokens = (u.input_tokens || 0) + (u.output_tokens || 0)
398
+ + (u.cache_read_input_tokens || 0) + (u.cache_creation_input_tokens || 0);
399
+ if (mb) mb.tokens += turnTokens;
400
+ if (dm) dm.tokens += turnTokens;
357
401
  // Per-turn cost — uses this turn's model id, not the session's first-seen one.
358
402
  const turnCost = costFor({ model: turnModel, usage: u });
359
403
  if (turnCost > 0) {
@@ -365,8 +409,7 @@ function parseChunkInto(text, summary, pstate) {
365
409
  summary.costByModel[ck] = (summary.costByModel[ck] || 0) + turnCost;
366
410
  if (mb) mb.cost += turnCost;
367
411
  if (dayBucket) {
368
- const dm = ((dayBucket.byModel ||= {})[ck] ||= { turns: 0, tokens: 0, cost: 0 });
369
- dm.cost += turnCost;
412
+ ((dayBucket.byModel ||= {})[ck] ||= { turns: 0, tokens: 0, cost: 0 }).cost += turnCost;
370
413
  }
371
414
  for (const bucket of allBuckets) bucket.cost += turnCost;
372
415
  }
@@ -376,10 +419,7 @@ function parseChunkInto(text, summary, pstate) {
376
419
  if (firstSeen) {
377
420
  summary.modelsUsed[turnModel] = (summary.modelsUsed[turnModel] || 0) + 1;
378
421
  if (mb) mb.turns += 1;
379
- if (mkey && dayBucket) {
380
- const dm = ((dayBucket.byModel ||= {})[mkey] ||= { turns: 0, tokens: 0, cost: 0 });
381
- dm.turns += 1;
382
- }
422
+ if (dm) dm.turns += 1;
383
423
  }
384
424
  }
385
425
  const blocks = r.message?.content || [];
@@ -455,7 +495,7 @@ function parseChunkInto(text, summary, pstate) {
455
495
  summary.userMessages += 1;
456
496
  for (const bucket of allBuckets) bucket.userMessages += 1;
457
497
  }
458
- if (ts) records.push({ ts, day, week, hour });
498
+ if (rec) records.push(rec);
459
499
  }
460
500
 
461
501
  summary.files = Array.from(fileSet);
@@ -509,7 +549,7 @@ export function parseTranscript(filePath, prev = null, { chunkBytes = TRANSCRIPT
509
549
  && typeof prev._size === 'number' && st.size >= prev._size);
510
550
  const summary = canAppend ? structuredClone(prev) : blankTranscriptSummary();
511
551
  const pstate = canAppend
512
- ? { recentIds: (prev._parse.recentIds || []).slice(), lastRec: prev._parse.lastRec || null }
552
+ ? { recentIds: (prev._parse.recentIds || []).map((e) => e.slice()), lastRec: prev._parse.lastRec || null }
513
553
  : { recentIds: [], lastRec: null };
514
554
  const startOffset = canAppend ? prev._offset : 0;
515
555
 
@@ -578,10 +618,10 @@ function listTranscripts(projectsDir) {
578
618
  return results;
579
619
  }
580
620
 
581
- // Walk multiple project roots in one pass. Used by scan() to support
582
- // `additionalProjectsDirs` config + the `claude-rpc backfill <path>` command
583
- // for ad-hoc imports. Deduplicates by absolute path so overlapping roots
584
- // don't double-count.
621
+ // Walk multiple project roots in one pass. Used by scan() for its
622
+ // projectsDirs / extraDirs options — the latter is how `claude-rpc backfill
623
+ // <path>` adds an ad-hoc import root. Deduplicates by absolute path so
624
+ // overlapping roots don't double-count.
585
625
  function listAllTranscripts(dirs) {
586
626
  const all = new Set();
587
627
  for (const d of dirs) {
@@ -633,10 +673,10 @@ function readTranscriptCwd(path, mtimeMs) {
633
673
  const sessionTokenCache = new Map(); // path → { mtime, size, offset, tokens, seenIds, model }
634
674
 
635
675
  // Accumulate assistant-usage tokens from a chunk of complete JSONL lines.
636
- // Claude Code repeats the same `usage` object on every content-block line of
637
- // one assistant message, so count each message.id once (`seenIds`, the same
638
- // bounded-ring dedup parseChunkInto uses) — otherwise the live count drifts
639
- // above the lifetime aggregate on multi-block turns. Lines with no id
676
+ // Claude Code repeats a message's `usage` on every content-block line of that
677
+ // assistant message, so count each message.id once at its final usage
678
+ // (`seenIds`, the same usageDelta window parseChunkInto uses) — otherwise the
679
+ // live count drifts away from the lifetime aggregate. Lines with no id
640
680
  // (rare/legacy) are counted every time, matching the full scanner. Also
641
681
  // captures the newest turn's model so a mid-session /model switch is visible.
642
682
  function sumUsageLines(text, tokens, seenIds, meta) {
@@ -645,14 +685,10 @@ function sumUsageLines(text, tokens, seenIds, meta) {
645
685
  const r = safeJson(line);
646
686
  if (!r || r.type !== 'assistant') continue;
647
687
  if (meta && r.message?.model) meta.model = r.message.model;
648
- const u = r.message?.usage;
649
- if (!u) continue;
650
- const msgId = r.message?.id;
651
- if (msgId && seenIds) {
652
- if (seenIds.includes(msgId)) continue;
653
- seenIds.push(msgId);
654
- if (seenIds.length > RECENT_IDS_MAX) seenIds.shift();
655
- }
688
+ if (!r.message?.usage) continue;
689
+ const counted = usageDelta(seenIds || [], r.message?.id, r.message.usage);
690
+ if (!counted) continue;
691
+ const u = counted.delta;
656
692
  tokens.input += u.input_tokens || 0;
657
693
  tokens.output += u.output_tokens || 0;
658
694
  tokens.cacheRead += u.cache_read_input_tokens || 0;
@@ -840,7 +876,7 @@ export function readAggregate() {
840
876
  catch { return null; }
841
877
  }
842
878
 
843
- export { dayKey, weekKey, hourKey };
879
+ export { dayKey, dayKeyAt, weekKey, hourKey };
844
880
 
845
881
  export function aggregateFrom(cache) {
846
882
  const agg = {
@@ -1079,11 +1115,7 @@ export function aggregateFrom(cache) {
1079
1115
  agg.daysSinceFirst = todayNum - dayKeyNum(days[0]) + 1;
1080
1116
 
1081
1117
  // Current streak: walk back from today.
1082
- const has = (offset) => {
1083
- const d = new Date(today);
1084
- d.setDate(d.getDate() - offset);
1085
- return !!agg.byDay[dayKey(d)];
1086
- };
1118
+ const has = (offset) => !!agg.byDay[dayKeyAt(today, offset)];
1087
1119
  let streak = 0;
1088
1120
  let offset = has(0) ? 0 : 1; // if no activity today, start from yesterday
1089
1121
  while (has(offset)) { streak += 1; offset += 1; }
@@ -1264,7 +1296,7 @@ export function scan({ projectsDir, projectsDirs, onProgress, force = false, ext
1264
1296
  cache.files[fp] = summary;
1265
1297
  scanned += 1;
1266
1298
  if (onProgress) onProgress({ scanned, skipped, total: transcripts.length, file: fp });
1267
- } catch (e) {
1299
+ } catch {
1268
1300
  // skip corrupt file but keep prior cache entry
1269
1301
  }
1270
1302
  }
package/src/select.js ADDED
@@ -0,0 +1,60 @@
1
+ // A small arrow-key menu for interactive commands. ↑/↓ (or j/k) move, 1–9
2
+ // jump, Enter picks, Esc / q / Ctrl-C cancels (→ null). Disabled options are
3
+ // shown dimmed with their reason and skipped. Only call on a TTY.
4
+
5
+ import { c } from './ui.js';
6
+
7
+ export function select({ title, options, initial = 0, input = process.stdin, output = process.stdout }) {
8
+ const enabled = (i) => options[i] && !options[i].disabled;
9
+ let at = enabled(initial) ? initial : options.findIndex((o) => !o.disabled);
10
+ if (at === -1) return Promise.resolve(null);
11
+ let drawn = 0;
12
+ const labelW = options.reduce((m, o) => Math.max(m, o.label.length), 0);
13
+
14
+ const draw = () => {
15
+ if (drawn) output.write(`\x1b[${drawn}A`);
16
+ const lines = [` ${c.bold}${title}${c.reset} ${c.gray}↑↓ move · enter pick · esc cancel${c.reset}`];
17
+ options.forEach((o, i) => {
18
+ const n = i < 9 ? `${i + 1}` : ' ';
19
+ const hint = o.disabled ? o.disabled : (o.hint || '');
20
+ if (o.disabled) lines.push(` ${c.gray} ${n} ${o.label.padEnd(labelW)} ${hint}${c.reset}`);
21
+ else if (i === at) lines.push(` ${c.magenta}❯${c.reset} ${c.bold}${n} ${c.cyan}${o.label.padEnd(labelW)}${c.reset} ${c.dim}${hint}${c.reset}`);
22
+ else lines.push(` ${c.dim}${n}${c.reset} ${o.label.padEnd(labelW)} ${c.dim}${hint}${c.reset}`);
23
+ });
24
+ for (const l of lines) output.write(`\x1b[2K${l}\n`);
25
+ drawn = lines.length;
26
+ };
27
+
28
+ return new Promise((resolve) => {
29
+ const move = (d) => {
30
+ for (let i = 1; i <= options.length; i++) {
31
+ const j = (at + d * i + options.length * i) % options.length;
32
+ if (enabled(j)) { at = j; break; }
33
+ }
34
+ };
35
+ const done = (v) => {
36
+ input.off('data', onKey);
37
+ try { input.setRawMode(false); } catch { /* not a tty */ }
38
+ input.pause();
39
+ output.write('\x1b[?25h');
40
+ // Collapse the menu to one line showing the choice.
41
+ output.write(`\x1b[${drawn}A\x1b[0J`);
42
+ output.write(` ${c.bold}${title}${c.reset} ${v === null ? `${c.gray}cancelled${c.reset}` : `${c.cyan}${options[v].label}${c.reset}`}\n`);
43
+ resolve(v);
44
+ };
45
+ const onKey = (buf) => {
46
+ const k = buf.toString();
47
+ if (k === '\x03' || k === '\x1b' || k === 'q') return done(null);
48
+ if (k === '\r' || k === '\n') return done(at);
49
+ if (k === '\x1b[A' || k === 'k') move(-1);
50
+ else if (k === '\x1b[B' || k === 'j' || k === '\t') move(1);
51
+ else if (/^[1-9]$/.test(k) && enabled(Number(k) - 1)) { at = Number(k) - 1; draw(); return done(at); }
52
+ draw();
53
+ };
54
+ output.write('\x1b[?25l');
55
+ draw();
56
+ try { input.setRawMode(true); } catch { /* not a tty */ }
57
+ input.resume();
58
+ input.on('data', onKey);
59
+ });
60
+ }
package/src/server/api.js CHANGED
@@ -4,17 +4,12 @@
4
4
 
5
5
  import { basename } from 'node:path';
6
6
  import { readActiveState } from '../state.js';
7
- import { buildVars, fillTemplate, applyIdle, framePasses, humanModel } from '../format.js';
7
+ import { buildVars, fillTemplate, applyIdle, applyShipped, applyTrigger, framePasses, humanModel } from '../format.js';
8
+ import { pickFrames, resolveLargeImageKey } from '../presence.js';
8
9
  import { readAggregate, findLiveSessions, dayKey } from '../scanner.js';
9
- import { loadConfig as loadSharedConfig } from '../config.js';
10
-
11
- // Re-export under the historical name so any external callers (e.g. tests
12
- // that did `import { loadConfig } from '../api.js'`) still resolve.
13
- // Internally everything uses the shared loader so a bad config doesn't
14
- // blank out the dashboard with `{}` — it falls back to defaults.
15
- export function loadConfig() {
16
- return loadSharedConfig();
17
- }
10
+ // The shared loader: a bad config falls back to defaults instead of blanking
11
+ // the dashboard with `{}`.
12
+ import { loadConfig } from '../config.js';
18
13
 
19
14
  export function rangeToDays(range) {
20
15
  if (range === 'all') return Infinity;
@@ -26,12 +21,21 @@ export function rangeToDays(range) {
26
21
  return Number.isFinite(n) && n > 0 ? Math.min(n, 366) : 90;
27
22
  }
28
23
 
29
- // Filter byDay to a windowed slice; also recompute roll-ups (top files etc.)
30
- // scoped to that window. Returns a shape similar to the aggregate but trimmed.
24
+ const grandTokensOf = (o) =>
25
+ (o.inputTokens || 0) + (o.outputTokens || 0) + (o.cacheReadTokens || 0) + (o.cacheWriteTokens || 0);
26
+
27
+ // Slice the aggregate to the last `range` days. Only what byDay can answer is
28
+ // recomputed for the window: active time, prompts, tool calls, lines, cost,
29
+ // sessions, tokens (+ grandTokens) and the prior window's active time. Every
30
+ // other roll-up (projects, tools, files, languages, bash, domains, subagents,
31
+ // cost by model, hour/weekday histograms, streaks) passes through as the
32
+ // LIFETIME value, since the aggregate doesn't keep those per day; the dashboard
33
+ // labels those panels "all time". range=all returns the lifetime aggregate
34
+ // itself plus grandTokens, which the range and cost cards read.
31
35
  export function windowedAggregate(agg, range) {
32
36
  if (!agg) return null;
33
37
  const days = rangeToDays(range);
34
- if (!Number.isFinite(days)) return agg; // 'all' → pass through
38
+ if (!Number.isFinite(days)) return { ...agg, range, grandTokens: grandTokensOf(agg) };
35
39
 
36
40
  const today = new Date(); today.setHours(0, 0, 0, 0);
37
41
  const keepKeys = new Set();
@@ -83,7 +87,7 @@ export function windowedAggregate(agg, range) {
83
87
  sessions,
84
88
  inputTokens, outputTokens, cacheReadTokens, cacheWriteTokens,
85
89
  grandTokens: inputTokens + outputTokens + cacheReadTokens + cacheWriteTokens,
86
- // Pass-through global keys for context.
90
+ // Lifetime pass-through (see the comment above).
87
91
  streak: agg.streak,
88
92
  longestStreak: agg.longestStreak,
89
93
  daysSinceFirst: agg.daysSinceFirst,
@@ -106,23 +110,48 @@ export function windowedAggregate(agg, range) {
106
110
  };
107
111
  }
108
112
 
109
- // Live snapshot: current state + lifetime aggregate + rendered rotation frames.
110
- // Used by GET /api/state — the SSE 'state' event tells the client to refetch.
113
+ // The Discord preview for the current status: the frame set the daemon renders
114
+ // (daemon.js buildActivity → presence.js pickFrames, i.e. the presence.byStatus
115
+ // entry, or a legacy top-level presence.rotation only when byStatus has none),
116
+ // templated and truncated the same way. `passes` mirrors selectFrame's
117
+ // `requires` filter, including its fallback to the base frame when nothing
118
+ // passes.
119
+ export function presenceFrames(p, state, vars) {
120
+ const raw = state.status === 'trigger' && state._triggerFrame
121
+ ? [state._triggerFrame]
122
+ : pickFrames(p, state.status).frames;
123
+ const frames = raw.map((f) => ({
124
+ details: f.details ? fillTemplate(f.details, vars).slice(0, 128) : '',
125
+ state: f.state ? fillTemplate(f.state, vars).slice(0, 128) : '',
126
+ passes: framePasses(f, vars),
127
+ requires: f.requires || null,
128
+ }));
129
+ if (frames.length && !frames.some((f) => f.passes)) frames[0].passes = true;
130
+ return frames;
131
+ }
132
+
133
+ // Live snapshot: current state + lifetime aggregate + the Discord preview
134
+ // (frames + large image). Used by GET /api/state; the SSE 'state' event tells
135
+ // the client to refetch.
111
136
  export function snapshot() {
112
137
  const config = loadConfig();
113
138
  const live = findLiveSessions({ thresholdMs: 90_000 });
114
139
  let state = readActiveState();
115
140
  state.liveSessions = live;
141
+ // Same overlay chain as daemon.js resolvePresence (idle/stale, then the
142
+ // shipped and custom-trigger frames), so the status shown here is the one
143
+ // the card is rendering.
116
144
  state = applyIdle(state, config);
145
+ state = applyShipped(state, config);
146
+ state = applyTrigger(state, config);
117
147
  const aggregate = readAggregate() || {};
118
148
  const vars = buildVars(state, config, aggregate);
119
149
  const p = config.presence || {};
120
- const frames = (p.rotation || []).map((f) => ({
121
- details: fillTemplate(f.details || '', vars),
122
- state: fillTemplate(f.state || '', vars),
123
- passes: framePasses(f, vars),
124
- requires: f.requires || null,
125
- }));
150
+ const frames = presenceFrames(p, state, vars);
151
+ // The card's large image, same precedence as the daemon (statusAssets[status]
152
+ // > modelAssets[tier] > presence.largeImageKey), filled the same way.
153
+ const largeKeyTpl = resolveLargeImageKey(config, p, state.status, state.model);
154
+ const largeImage = largeKeyTpl ? fillTemplate(largeKeyTpl, vars) : null;
126
155
  return {
127
156
  now: Date.now(),
128
157
  state,
@@ -165,6 +194,7 @@ export function snapshot() {
165
194
  },
166
195
  vars,
167
196
  frames,
197
+ largeImage,
168
198
  };
169
199
  }
170
200
 
@@ -209,24 +239,22 @@ export function wrappedData() {
209
239
  };
210
240
  }
211
241
 
242
+ // GET /api/project/:name: one project's lifetime roll-up. The aggregate keeps
243
+ // only scalar totals per project (sessions, active time, tokens, prompts, tool
244
+ // calls, lines, cost). Edited files and the tool breakdown are tracked
245
+ // globally, not per project, so they are deliberately not included here.
246
+ // Own-property lookups so names like `constructor` aren't "found".
212
247
  export function projectDrilldown(name) {
213
- const agg = readAggregate() || {};
214
- const projects = agg.projects || {};
215
- const project = projects[name];
216
- if (!project) return null;
217
- return {
218
- name,
219
- ...project,
220
- files: (agg.topEditedFiles || []).slice(0, 25),
221
- tools: agg.toolBreakdown || {},
222
- };
248
+ const projects = (readAggregate() || {}).projects || {};
249
+ if (!Object.hasOwn(projects, name) || !projects[name]) return null;
250
+ return { name, ...projects[name] };
223
251
  }
224
252
 
253
+ // GET /api/day/:day: one byDay bucket, for the dashboard's day modal.
225
254
  export function dayDetail(dayKeyStr) {
226
- const agg = readAggregate() || {};
227
- const day = (agg.byDay || {})[dayKeyStr];
228
- if (!day) return null;
229
- return { day: dayKeyStr, ...day };
255
+ const byDay = (readAggregate() || {}).byDay || {};
256
+ if (!Object.hasOwn(byDay, dayKeyStr) || !byDay[dayKeyStr]) return null;
257
+ return { day: dayKeyStr, ...byDay[dayKeyStr] };
230
258
  }
231
259
 
232
260
  // Flatten the aggregate's byDay map into a daily-rows CSV for spreadsheet /