claude-rpc 1.4.3 → 1.5.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.
package/README.md CHANGED
@@ -147,7 +147,19 @@ claude-rpc readme # prints paste-ready README badge markdown
147
147
  claude-rpc readme --raw | pbcopy # straight to your clipboard
148
148
  ```
149
149
 
150
- **Live card + badges, paste once.** With a public profile (`claude-rpc profile set --handle <you> && claude-rpc profile on`), your stats are served as an always-current card (and badges) from the community worker — no `gh`, no gist, nothing to re-run:
150
+ **Live stats + year heatmap, paste once.** With a public profile (`claude-rpc profile set --handle <you> && claude-rpc profile on`), the community worker serves an always-current stats card with your last 12 months as a heatmap. You don't need `gh` or a gist, and there's nothing to re-run:
151
+
152
+ ```md
153
+ [![Claude Code stats](https://claude-rpc-totals.claude-rpc.workers.dev/stats/<you>.svg)](https://claude-rpc.com/u/<you>)
154
+ ```
155
+
156
+ <div align="center">
157
+ <img src="site/examples/stats-heatmap.svg" width="680" alt="Stats card: lifetime tokens, sessions, hours and streak above a 12-month heatmap of tokens per day, with busiest day, daily average, longest run and best weekday" />
158
+ </div>
159
+
160
+ `?metric=hours` shades the grid by time instead of tokens. `/heatmap/<you>.svg` is the grid on its own. If you link several machines, their days are added together. Shading is relative to your own year, so light and heavy users both get a readable map. To publish lifetime totals only, set `"profile": { "heatmap": false }` in config.json; the next flush also clears the stored days.
161
+
162
+ The smaller card and badges are still there:
151
163
 
152
164
  ```md
153
165
  [![Claude Code stats](https://claude-rpc-totals.claude-rpc.workers.dev/card/<you>.svg)](https://claude-rpc.com/u/<you>)
@@ -164,6 +176,8 @@ claude-rpc badge --metric hours --range 7d --out claude-hours.svg
164
176
  claude-rpc badge --metric streak --out claude-streak.svg
165
177
  claude-rpc badge --metric hours --gist # publish to a gist (live README badge)
166
178
  claude-rpc card --range year --out year-on-claude.svg
179
+ claude-rpc calendar --metric tokens --out heatmap.svg # year heatmap (hours by default)
180
+ claude-rpc calendar --card --out stats.svg # stats + heatmap, offline
167
181
  ```
168
182
 
169
183
  <div align="center">
@@ -314,7 +328,7 @@ It's a thin bootstrapper — on the first session it just runs `npx claude-rpc@l
314
328
  | `badge` | Shields-style SVG (`--metric` `--range` `--out` `--gist`) |
315
329
  | `card` | Poster-style SVG (`--range year\|month\|week\|all`) |
316
330
  | `github-stat` | Embeddable profile stat card (`--handle` `--out` `--gist`) |
317
- | `calendar` | Year activity heatmap SVG (`--out` `--gist`) |
331
+ | `calendar` | Year activity heatmap SVG (`--metric hours\|tokens` `--card` `--out` `--gist`) |
318
332
  | `session-card` | Recap card for the current session (`--out`) |
319
333
  | `readme` | Paste-ready README badge markdown for your profile (`--raw` to pipe) |
320
334
  | `statusline` | One-line status for tmux/shell prompts (`--template`) |
package/SECURITY.md CHANGED
@@ -199,7 +199,8 @@ anonymous 3a report, this one carries your chosen public identity. The
199
199
  "sessions": 1200,
200
200
  "activeMs": 360000000,
201
201
  "streak": 23,
202
- "version": "0.16.2",
202
+ "daily": { "end": "2026-10-02", "tokens": [0, 41200000, …], "activeMin": [0, 95, …] },
203
+ "version": "1.5.0",
203
204
  "osFamily": "linux",
204
205
  "ts": 1716500000000
205
206
  }
@@ -208,6 +209,15 @@ anonymous 3a report, this one carries your chosen public identity. The
208
209
  It sends absolute totals (not deltas) and is idempotent worker-side (a SET, not
209
210
  an add). `profile off` stops it.
210
211
 
212
+ **Per-day series (v1.5).** `daily` holds up to 371 days of two numbers per
213
+ **local** calendar day: total tokens and active minutes. It contains no project,
214
+ file, model or prompt data. It feeds the public `/heatmap/<handle>.svg` and
215
+ `/stats/<handle>.svg` images, which show anyone *which days* you used Claude
216
+ Code and how heavily. That reveals more than lifetime totals do, so there's a
217
+ switch: `"profile": { "heatmap": false }` sends `daily: null`, which deletes
218
+ the stored series on the next flush and keeps it off from then on. The series
219
+ is never returned by `GET /profile` or `/leaderboard`.
220
+
211
221
  **The setup-time "connect GitHub?" question.** Since v1.4, an interactive
212
222
  `claude-rpc setup` ends with one explicit y/N: *connect GitHub?* Answering
213
223
  **y** runs the standard opt-in flow above (public profile, handle defaulting
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "claude-rpc",
3
- "version": "1.4.3",
3
+ "version": "1.5.0",
4
4
  "description": "Discord Rich Presence for Claude Code — live model, project, tokens, and lifetime stats driven by Claude Code's hook system.",
5
5
  "type": "module",
6
6
  "license": "MIT",
package/src/calendar.js CHANGED
@@ -1,94 +1,48 @@
1
1
  // Activity calendar — a GitHub-contributions-style year heatmap of Claude
2
2
  // Code activity, rendered as an embeddable SVG (paper/terracotta brand).
3
- // `claude-rpc calendar --out cal.svg [--gist]`.
3
+ // `claude-rpc calendar [--metric tokens|hours] [--card] --out cal.svg [--gist]`.
4
+ //
5
+ // Drawing lives in heatmap.js, shared with the worker's live /heatmap and
6
+ // /stats endpoints, so a local render and the live README card look the same.
4
7
 
5
- import { dayKey } from './scanner.js';
8
+ import { buildDailySeries } from './community.js';
9
+ import { renderHeatmap, renderStatsCard } from './heatmap.js';
6
10
  import { localDateStamp } from './fmt.js';
7
11
  import { VERSION } from './version.js';
8
12
 
9
- const PALETTE = {
10
- paper: '#f4ede0',
11
- ink: '#1a1611',
12
- inkMute:'#5c5147',
13
- inkFaint:'#8a7c6d',
14
- empty: '#e1d6c0',
15
- l1: '#f6dccb',
16
- l2: '#f08a4a',
17
- l3: '#c2491e',
18
- l4: '#8f3415',
19
- };
20
-
21
- const MONTHS = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];
22
-
23
- function escapeXml(s) {
24
- return String(s == null ? '' : s).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
13
+ function lifetimeTokens(a) {
14
+ return (a?.inputTokens || 0) + (a?.outputTokens || 0) + (a?.cacheReadTokens || 0) + (a?.cacheWriteTokens || 0);
25
15
  }
26
16
 
27
- // activeMs → one of 5 intensity buckets (0..4). 4h saturates.
28
- function level(ms) {
29
- if (!ms) return 0;
30
- const h = ms / 3_600_000;
31
- if (h < 0.5) return 1;
32
- if (h < 1.5) return 2;
33
- if (h < 3) return 3;
34
- return 4;
17
+ export function renderCalendar(aggregate, { metric = 'hours', generatedAt = new Date() } = {}) {
18
+ const series = buildDailySeries(aggregate, generatedAt.getTime());
19
+ return renderHeatmap({
20
+ series,
21
+ metric,
22
+ footer: `as of ${localDateStamp(generatedAt)} · claude-rpc.com · v${VERSION}`,
23
+ });
35
24
  }
36
- const FILL = [PALETTE.empty, PALETTE.l1, PALETTE.l2, PALETTE.l3, PALETTE.l4];
37
-
38
- export function renderCalendar(aggregate, { weeks = 53, generatedAt = new Date() } = {}) {
39
- const byDay = aggregate?.byDay || {};
40
- const cell = 12, gap = 3, step = cell + gap;
41
- const padX = 36, padTop = 68, padBottom = 30;
42
-
43
- // Build the grid ending today. Align the last column to today's weekday so
44
- // rows read Sun..Sat like GitHub. We render `weeks` columns back from today.
45
- const today = new Date(generatedAt);
46
- today.setHours(0, 0, 0, 0);
47
- const todayDow = today.getDay(); // 0=Sun
48
- const totalDays = (weeks - 1) * 7 + todayDow + 1;
49
-
50
- let cells = '';
51
- let monthLabels = '';
52
- let lastMonth = -1;
53
- let totalActiveMs = 0, activeDays = 0;
54
-
55
- for (let i = 0; i < totalDays; i++) {
56
- const d = new Date(today);
57
- d.setDate(d.getDate() - (totalDays - 1 - i));
58
- const col = Math.floor(i / 7);
59
- const row = d.getDay();
60
- const key = dayKey(d);
61
- const ms = byDay[key]?.activeMs || 0;
62
- if (ms > 0) { totalActiveMs += ms; activeDays += 1; }
63
- const x = padX + col * step;
64
- const y = padTop + row * step;
65
- cells += `<rect x="${x}" y="${y}" width="${cell}" height="${cell}" rx="2" fill="${FILL[level(ms)]}" stroke="${PALETTE.ink}" stroke-width="0.4"/>`;
66
- // Month label when a new month starts in the top row region.
67
- if (d.getMonth() !== lastMonth && d.getDate() <= 7) {
68
- lastMonth = d.getMonth();
69
- monthLabels += `<text x="${x}" y="${padTop - 9}" font-family="JetBrains Mono, ui-monospace, monospace" font-size="10" fill="${PALETTE.inkMute}">${MONTHS[d.getMonth()]}</text>`;
70
- }
71
- }
72
-
73
- const W = padX + weeks * step + 14;
74
- const H = padTop + 7 * step + padBottom;
75
- const totalHours = (totalActiveMs / 3_600_000).toFixed(0);
76
- let legend = '';
77
- for (let l = 0; l < 5; l++) {
78
- legend += `<rect x="${W - 150 + l * 16}" y="${H - 20}" width="${cell}" height="${cell}" rx="2" fill="${FILL[l]}" stroke="${PALETTE.ink}" stroke-width="0.4"/>`;
79
- }
80
25
 
81
- return `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 ${W} ${H}" width="${W}" height="${H}" role="img" aria-label="Claude Code activity calendar">
82
- <rect width="${W}" height="${H}" fill="${PALETTE.paper}"/>
83
- <text x="${padX}" y="28" font-family="Space Grotesk, Inter, system-ui, sans-serif" font-size="20" font-weight="800" fill="${PALETTE.ink}">a year on Claude Code</text>
84
- <text x="${padX}" y="44" font-family="JetBrains Mono, ui-monospace, monospace" font-size="11" fill="${PALETTE.inkMute}">${escapeXml(activeDays)} active days · ${escapeXml(totalHours)}h · as of ${localDateStamp(generatedAt)}</text>
85
- ${monthLabels}
86
- ${cells}
87
- <text x="${W - 170}" y="${H - 10}" font-family="JetBrains Mono, ui-monospace, monospace" font-size="9" fill="${PALETTE.inkFaint}">less</text>
88
- ${legend}
89
- <text x="${W - 28}" y="${H - 10}" font-family="JetBrains Mono, ui-monospace, monospace" font-size="9" fill="${PALETTE.inkFaint}">more</text>
90
- <text x="${padX}" y="${H - 8}" font-family="JetBrains Mono, ui-monospace, monospace" font-size="9" fill="${PALETTE.inkFaint}">claude-rpc.com · v${VERSION}</text>
91
- </svg>`;
26
+ // Stats card + heatmap from the local aggregate — the offline twin of the
27
+ // worker's /stats/<handle>.svg.
28
+ export function renderCalendarCard(aggregate, { metric = 'tokens', handle = '', generatedAt = new Date() } = {}) {
29
+ const series = buildDailySeries(aggregate, generatedAt.getTime());
30
+ const h = String(handle || '').replace(/^@/, '');
31
+ const p = {
32
+ handle: h || 'you',
33
+ displayName: h ? null : 'Claude Code',
34
+ verified: false,
35
+ githubUser: null,
36
+ tokens: lifetimeTokens(aggregate),
37
+ sessions: aggregate?.sessions || 0,
38
+ activeMs: aggregate?.activeMs || 0,
39
+ streak: aggregate?.streak || 0,
40
+ };
41
+ return renderStatsCard(p, series, {
42
+ metric,
43
+ kicker: h ? 'Claude Code' : 'my year',
44
+ footer: `as of ${localDateStamp(generatedAt)} · v${VERSION}`,
45
+ });
92
46
  }
93
47
 
94
48
  export function calendarSvg({ aggregate } = {}) {
@@ -35,18 +35,24 @@ export function looksLikeClaudeCode(name, cmdline) {
35
35
  const n = String(name || '').toLowerCase();
36
36
  const c = String(cmdline || '').replace(/\\/g, '/').toLowerCase();
37
37
  // The Claude DESKTOP app's binary is ALSO named claude(.exe) — Windows
38
- // installs under …/AnthropicClaude/, macOS ships as Claude.app. It is not
39
- // Claude Code; matching it would pin the card up whenever the chat app is
40
- // open. Path check comes first so nothing below can re-admit it.
41
- if (c.includes('anthropicclaude') || c.includes('claude.app/')) return false;
38
+ // installs under …/AnthropicClaude/, macOS ships as Claude.app, Linux builds
39
+ // as …/claude-desktop/claude-desktop. It is not Claude Code; matching it
40
+ // would pin the card up whenever the chat app is open. Path check comes
41
+ // first so nothing below can re-admit it.
42
+ if (c.includes('anthropicclaude') || c.includes('claude.app/') || c.includes('/claude-desktop')) {
43
+ return false;
44
+ }
42
45
  // npm / npx install: node …/node_modules/@anthropic-ai/claude-code/cli.js
43
46
  if (c.includes('@anthropic-ai/claude-code/')) return true;
44
47
  // Native-install version store: …/.local/share/claude/versions/<v>
45
48
  if (c.includes('/share/claude/versions/')) return true;
46
49
  // A command-line token that IS `claude` / `claude.exe` — bare (as typed in a
47
50
  // shell, argv[0] preserved) or as the tail of a path. The boundary required
48
- // right after "claude" is what keeps claude-rpc from matching.
49
- if (/(^|[/"'])claude(\.exe)?["']?(\s|$)/.test(c)) return true;
51
+ // right after "claude" is what keeps claude-rpc from matching. `--flag=value`
52
+ // tokens are dropped first: Electron children carry a profile path like
53
+ // --user-data-dir=/home/o/.config/Claude, which is a directory, not a binary.
54
+ const tokens = c.replace(/(^|\s)--?[\w-]+=("[^"]*"|\S*)/g, '$1');
55
+ if (/(^|[/"'])claude(\.exe)?["']?(\s|$)/.test(tokens)) return true;
50
56
  // No command line to inspect (platform hid it) — fall back to the process
51
57
  // name alone. Only safe here because the desktop-app exclusion above could
52
58
  // not run; a bare-name match is still far likelier Code than the chat app
package/src/cli.js CHANGED
@@ -1216,18 +1216,27 @@ function doStatusline(argv) {
1216
1216
  }
1217
1217
 
1218
1218
  // Activity calendar — GitHub-contributions-style year heatmap SVG.
1219
+ // --metric hours (default) | tokens; --card wraps it in the stats card.
1219
1220
  async function doCalendar(argv) {
1220
1221
  argv = splitEqArgs(argv);
1221
- const opts = { out: '', gist: false };
1222
+ const opts = { out: '', gist: false, metric: 'hours', card: false };
1222
1223
  for (let i = 0; i < argv.length; i++) {
1223
1224
  if (argv[i] === '--out' || argv[i] === '-o') opts.out = takeValue(argv[++i], '--out');
1224
1225
  else if (argv[i] === '--gist') opts.gist = true;
1226
+ else if (argv[i] === '--card') opts.card = true;
1227
+ else if (argv[i] === '--metric') opts.metric = takeValue(argv[++i], '--metric');
1228
+ }
1229
+ if (!['hours', 'tokens'].includes(opts.metric)) {
1230
+ fail(`unknown --metric \`${opts.metric}\``, { hint: 'use --metric hours or --metric tokens', code: EX_USER_ERROR });
1225
1231
  }
1226
1232
  const aggregate = readAggregate();
1227
1233
  if (!aggregate) fail('no aggregate yet — nothing to render', { hint: 'run `claude-rpc scan` first', code: EX_BAD_STATE });
1228
- const { renderCalendar } = await import('./calendar.js');
1229
- const svg = renderCalendar(aggregate, {});
1230
- if (opts.gist) return publishBadgeToGist(svg, { metric: 'calendar', range: 'year' }, 'calendar');
1234
+ const { renderCalendar, renderCalendarCard } = await import('./calendar.js');
1235
+ const svg = opts.card
1236
+ ? renderCalendarCard(aggregate, { metric: opts.metric, handle: loadConfig().profile?.handle })
1237
+ : renderCalendar(aggregate, { metric: opts.metric });
1238
+ const kind = opts.card ? 'stats' : 'calendar';
1239
+ if (opts.gist) return publishBadgeToGist(svg, { metric: kind, range: 'year' }, kind);
1231
1240
  if (opts.out) {
1232
1241
  writeFileSync(opts.out, svg);
1233
1242
  console.log(` ${c.green}✓${c.reset} wrote ${c.cyan}${opts.out}${c.reset} ${c.dim}(${svg.length} bytes)${c.reset}`);
@@ -1268,12 +1277,13 @@ function doReadme(argv) {
1268
1277
  ['streak', 'Claude Code streak'],
1269
1278
  ['tokens', 'Claude Code tokens'],
1270
1279
  ];
1271
- // The hero: a live stat card that auto-refreshes from your published profile.
1280
+ // The hero: live stats + year heatmap, auto-refreshing from your profile.
1281
+ const statsMd = (h) => `[![Claude Code stats](${endpoint}/stats/${h}.svg)](${site}/u/${h})`;
1272
1282
  const cardMd = (h) => `[![Claude Code stats](${endpoint}/card/${h}.svg)](${site}/u/${h})`;
1273
1283
  const badgesMd = (h) => metrics
1274
1284
  .map(([m, alt]) => `[![${alt}](${endpoint}/badge/${h}.svg?metric=${m})](${site}/?ref=badge)`)
1275
1285
  .join('\n');
1276
- const liveMd = (h) => `${cardMd(h)}\n\n${badgesMd(h)}`;
1286
+ const liveMd = (h) => `${statsMd(h)}\n\n${badgesMd(h)}`;
1277
1287
 
1278
1288
  // Raw mode: just the markdown, for `claude-rpc readme --raw | pbcopy`.
1279
1289
  if (raw) {
@@ -1288,10 +1298,19 @@ function doReadme(argv) {
1288
1298
  console.log('');
1289
1299
 
1290
1300
  if (live) {
1291
- console.log(` ${c.dim}Live stat card for ${c.reset}${c.cyan}@${handle}${c.reset}${c.dim} — paste once; it auto-updates as you work:${c.reset}`);
1301
+ console.log(` ${c.dim}Live stats + year heatmap for ${c.reset}${c.cyan}@${handle}${c.reset}${c.dim} — paste once; it auto-updates as you work:${c.reset}`);
1302
+ console.log('');
1303
+ console.log(` ${statsMd(handle)}`);
1304
+ if (profile.heatmap === false) {
1305
+ console.log(` ${c.yellow}profile.heatmap is off — the heatmap stays empty until you turn it back on${c.reset}`);
1306
+ }
1307
+ console.log('');
1308
+ console.log(` ${c.dim}…the compact card (totals only):${c.reset}`);
1292
1309
  console.log('');
1293
1310
  console.log(` ${cardMd(handle)}`);
1294
1311
  console.log('');
1312
+ console.log(` ${c.dim}…just the heatmap:${c.reset} ${c.cyan}${endpoint}/heatmap/${handle}.svg${c.reset}${c.dim} (?metric=hours for time)${c.reset}`);
1313
+ console.log('');
1295
1314
  console.log(` ${c.dim}…or compact badges:${c.reset}`);
1296
1315
  console.log('');
1297
1316
  for (const line of badgesMd(handle).split('\n')) console.log(` ${line}`);
@@ -1304,6 +1323,8 @@ function doReadme(argv) {
1304
1323
  console.log(` ${c.cyan}claude-rpc profile set --handle <name> && claude-rpc profile on${c.reset}`);
1305
1324
  console.log('');
1306
1325
  console.log(` ${c.dim}Then your card + badges live here (self-refreshing — paste once):${c.reset}`);
1326
+ console.log(` ${c.cyan}${endpoint}/stats/<handle>.svg${c.reset} ${c.dim}# stats + year heatmap${c.reset}`);
1327
+ console.log(` ${c.cyan}${endpoint}/heatmap/<handle>.svg${c.reset}`);
1307
1328
  console.log(` ${c.cyan}${endpoint}/card/<handle>.svg${c.reset}`);
1308
1329
  console.log(` ${c.cyan}${endpoint}/badge/<handle>.svg?metric=hours${c.reset}`);
1309
1330
  }
@@ -2392,7 +2413,7 @@ function help() {
2392
2413
  ['card', 'Render a poster-style SVG summary (--range year|month|week|all)'],
2393
2414
  ['github-stat', 'Render an embeddable profile stat card (--handle --out --gist)'],
2394
2415
  ['statusline', 'One-line status for tmux/shell prompts (--template)'],
2395
- ['calendar', 'Year activity heatmap SVG (--out --gist)'],
2416
+ ['calendar', 'Year activity heatmap SVG (--metric hours|tokens --card --out --gist)'],
2396
2417
  ['session-card', 'Recap card for the current session (--out)'],
2397
2418
  ['readme', 'Paste-ready README card + badges for your profile (--raw to pipe)'],
2398
2419
  ['mcp install', 'Wire the stats MCP server into Claude Code (one command)'],
package/src/community.js CHANGED
@@ -25,7 +25,8 @@ import { AGGREGATE_PATH, STATE_DIR } from './paths.js';
25
25
  import { VERSION } from './version.js';
26
26
  import { profileIsPublishable } from './leaderboard.js';
27
27
  import { projectNameIsPrivate } from './privacy.js';
28
- import { cleanProjectName } from './scanner.js';
28
+ import { cleanProjectName, dayKey } from './scanner.js';
29
+ import { HEATMAP_DAYS } from './heatmap.js';
29
30
  import { humanModel } from './format.js';
30
31
 
31
32
  const CURSOR_PATH = join(STATE_DIR, 'community-cursor.json');
@@ -103,6 +104,28 @@ function totalTokens(aggregate) {
103
104
  // cursor, no double-count risk, and the board matches your real aggregate
104
105
  // exactly. (Deltas were wrong here: the first publish carried the entire
105
106
  // lifetime total, which blew past the per-report caps for any established user.)
107
+ // The last year of per-day tokens + active minutes, for the live heatmap
108
+ // (/heatmap/<h>.svg, /stats/<h>.svg). Keyed by LOCAL date like aggregate.byDay;
109
+ // oldest → newest with leading empty days trimmed. Only day totals — nothing
110
+ // about projects, files, or prompts. Opt out with profile.heatmap: false.
111
+ export function buildDailySeries(aggregate, now = Date.now(), days = HEATMAP_DAYS) {
112
+ const byDay = aggregate?.byDay || {};
113
+ const tokens = [], activeMin = [];
114
+ const d = new Date(now);
115
+ d.setHours(12, 0, 0, 0); // noon: DST shifts can't skip or repeat a date
116
+ const end = dayKey(d.getTime());
117
+ d.setDate(d.getDate() - (days - 1));
118
+ for (let i = 0; i < days; i++) {
119
+ const b = byDay[dayKey(d.getTime())];
120
+ tokens.push(b ? totalTokens(b) : 0);
121
+ activeMin.push(b ? Math.round((b.activeMs || 0) / 60_000) : 0);
122
+ d.setDate(d.getDate() + 1);
123
+ }
124
+ let first = 0;
125
+ while (first < days && !tokens[first] && !activeMin[first]) first++;
126
+ return { end, tokens: tokens.slice(first), activeMin: activeMin.slice(first) };
127
+ }
128
+
106
129
  export function buildProfilePayload(aggregate, profileCfg, { instanceId, now = Date.now() }) {
107
130
  return {
108
131
  instanceId,
@@ -113,6 +136,9 @@ export function buildProfilePayload(aggregate, profileCfg, { instanceId, now = D
113
136
  sessions: aggregate?.sessions || 0,
114
137
  activeMs: aggregate?.activeMs || 0,
115
138
  streak: aggregate?.streak || 0,
139
+ // null (not omitted) on opt-out: the worker keeps a stored series when the
140
+ // field is absent (older clients), so clearing has to be explicit.
141
+ daily: profileCfg.heatmap === false ? null : buildDailySeries(aggregate, now),
116
142
  version: VERSION,
117
143
  osFamily: osFamily(),
118
144
  ts: now,
@@ -165,6 +165,9 @@ export const DEFAULT_CONFIG = {
165
165
  handle: null,
166
166
  displayName: null,
167
167
  githubUser: null,
168
+ // Also publish per-day token + active-minute totals (last year) so the
169
+ // live /heatmap and /stats cards can draw your year. false = totals only.
170
+ heatmap: true,
168
171
  },
169
172
  showElapsed: true,
170
173
  activityType: 0,
package/src/fmt.js CHANGED
@@ -7,7 +7,7 @@
7
7
  // deploys dependency-free and can't import across the package boundary. Keep
8
8
  // the two in sync; test/format.test.js pins fmtNum's tier behavior.
9
9
 
10
- // Compact integer: 999 → "999", 1_500 → "1.5k", 1_500_000 → "1.50M", up to "B".
10
+ // Compact integer: 999 → "999", 1_500 → "1.5k", 1_500_000 → "1.50M", up to "T".
11
11
  // The unit is chosen from the ROUNDED value, so 999_999 → "1.00M" (not the old
12
12
  // "1000.0k") and 999_999_999 → "1.00B".
13
13
  export function fmtNum(n) {
@@ -15,11 +15,11 @@ export function fmtNum(n) {
15
15
  const neg = n < 0 ? '-' : '';
16
16
  const v = Math.abs(n);
17
17
  if (v < 1000) return neg + Math.round(v);
18
- for (const [suf, div, prec] of [['k', 1e3, 1], ['M', 1e6, 2], ['B', 1e9, 2]]) {
18
+ for (const [suf, div, prec] of [['k', 1e3, 1], ['M', 1e6, 2], ['B', 1e9, 2], ['T', 1e12, 2]]) {
19
19
  const s = (v / div).toFixed(prec);
20
20
  if (Number(s) < 1000) return neg + s + suf;
21
21
  }
22
- return neg + (v / 1e9).toFixed(2) + 'B'; // ≥ ~1e12 stays in the B tier
22
+ return neg + (v / 1e12).toFixed(2) + 'T';
23
23
  }
24
24
 
25
25
  // Duration from ms: <60m → "42m", <10h → "2.5h", else "12h". Rounds to whole
package/src/heatmap.js ADDED
@@ -0,0 +1,342 @@
1
+ // Year heatmap + stats-with-heatmap card — ONE renderer shared by the CLI
2
+ // (`claude-rpc calendar`) and the worker's live /heatmap/<h>.svg and
3
+ // /stats/<h>.svg endpoints. The worker imports this file across the package
4
+ // boundary (wrangler bundles it), so it must stay PURE: no imports, no Node
5
+ // APIs, no Date-of-the-local-machine assumptions. Every date is a
6
+ // 'YYYY-MM-DD' string handled with UTC arithmetic, so the same series
7
+ // renders identically on a laptop and in a Cloudflare isolate.
8
+ //
9
+ // Input series shape (also the profile payload's `daily` field):
10
+ // { end: 'YYYY-MM-DD', tokens: number[], activeMin: number[] }
11
+ // Arrays run oldest → newest; the LAST element is `end`. Arrays may be
12
+ // shorter than a year (leading zeros trimmed) — missing days read as 0.
13
+
14
+ export const HEATMAP_WEEKS = 53;
15
+ export const HEATMAP_DAYS = HEATMAP_WEEKS * 7; // 371 — always covers the 53-column grid
16
+
17
+ const MONTHS = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
18
+ const WEEKDAYS = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
19
+ const DAY_MS = 86_400_000;
20
+
21
+ const PALETTE = {
22
+ paper: '#f4ede0', paper2: '#ebe2d2', empty: '#e1d6c0',
23
+ ink: '#1a1611', inkMute: '#5c5147', inkFaint: '#8a7c6d',
24
+ rust: '#c2491e', amber: '#c0851f', blue: '#3f6f9f', grass: '#4a9462', tape: '#f2d76e',
25
+ };
26
+
27
+ // Per-metric 4-step ramps (level 1..4); level 0 is always PALETTE.empty.
28
+ const RAMPS = {
29
+ tokens: ['#f6dccb', '#f08a4a', '#c2491e', '#8f3415'],
30
+ hours: ['#d5e6c8', '#8fc27a', '#4a9462', '#2c6b3f'],
31
+ };
32
+
33
+ const MONO = 'JetBrains Mono, ui-monospace, monospace';
34
+ const DISPLAY = 'Space Grotesk, Inter, system-ui, sans-serif';
35
+
36
+ function escapeXml(s) {
37
+ return String(s == null ? '' : s)
38
+ .replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
39
+ }
40
+
41
+ // Same rules as src/fmt.js fmtNum / fmtHours (inlined — this module is pure).
42
+ function fmtNum(n) {
43
+ if (!n) return '0';
44
+ const v = Math.abs(n);
45
+ if (v < 1000) return String(Math.round(v));
46
+ for (const [suf, div, prec] of [['k', 1e3, 1], ['M', 1e6, 2], ['B', 1e9, 2], ['T', 1e12, 2]]) {
47
+ const s = (v / div).toFixed(prec);
48
+ if (Number(s) < 1000) return s + suf;
49
+ }
50
+ return (v / 1e12).toFixed(2) + 'T';
51
+ }
52
+ function fmtMinutes(min) {
53
+ if (!min) return '0m';
54
+ if (min < 60) return `${Math.round(min)}m`;
55
+ const h = min / 60;
56
+ return h < 10 ? `${h.toFixed(1)}h` : `${Math.round(h)}h`;
57
+ }
58
+
59
+ // ── dates (UTC arithmetic on YYYY-MM-DD) ─────────────────────────────────
60
+
61
+ export function isDayKey(s) {
62
+ if (typeof s !== 'string' || !/^\d{4}-\d{2}-\d{2}$/.test(s)) return false;
63
+ const t = Date.parse(`${s}T00:00:00Z`);
64
+ return Number.isFinite(t) && new Date(t).toISOString().slice(0, 10) === s;
65
+ }
66
+ export function dayToMs(key) { return Date.parse(`${key}T00:00:00Z`); }
67
+ export function msToDay(ms) { return new Date(ms).toISOString().slice(0, 10); }
68
+ function shortDate(key) {
69
+ const d = new Date(dayToMs(key));
70
+ return `${MONTHS[d.getUTCMonth()]} ${d.getUTCDate()}`;
71
+ }
72
+
73
+ // Normalize a series to exactly `days` values ending at `end` for one metric.
74
+ // metric: 'tokens' | 'hours' (hours reads activeMin).
75
+ export function seriesValues(series, metric = 'tokens', days = HEATMAP_DAYS) {
76
+ const src = (metric === 'hours' ? series?.activeMin : series?.tokens) || [];
77
+ const out = new Array(days).fill(0);
78
+ const n = Math.min(src.length, days);
79
+ for (let i = 0; i < n; i++) {
80
+ const v = Number(src[src.length - 1 - i]);
81
+ out[days - 1 - i] = Number.isFinite(v) && v > 0 ? v : 0;
82
+ }
83
+ return out;
84
+ }
85
+
86
+ // Intensity cutoffs from the user's OWN distribution (quartiles of non-zero
87
+ // days, like GitHub). Token days span 5+ orders of magnitude between users, so
88
+ // fixed thresholds would paint one person all-dark and another all-pale.
89
+ export function levelCutoffs(values) {
90
+ const nz = values.filter((v) => v > 0).sort((a, b) => a - b);
91
+ if (!nz.length) return [Infinity, Infinity, Infinity];
92
+ const q = (p) => nz[Math.min(nz.length - 1, Math.floor(p * nz.length))];
93
+ return [q(0.25), q(0.5), q(0.75)];
94
+ }
95
+ export function levelOf(v, cut) {
96
+ if (!(v > 0)) return 0;
97
+ if (v < cut[0]) return 1;
98
+ if (v < cut[1]) return 2;
99
+ if (v < cut[2]) return 3;
100
+ return 4;
101
+ }
102
+
103
+ // Facts the card prints under the grid. All computed over the visible window.
104
+ export function seriesFacts(series, metric = 'tokens', days = HEATMAP_DAYS) {
105
+ const end = isDayKey(series?.end) ? series.end : null;
106
+ const vals = seriesValues(series, metric, days);
107
+ const endMs = end ? dayToMs(end) : 0;
108
+ let total = 0, activeDays = 0, busiest = null, run = 0, longestRun = 0;
109
+ const byWeekday = new Array(7).fill(0);
110
+ for (let i = 0; i < vals.length; i++) {
111
+ const v = vals[i];
112
+ if (v > 0) {
113
+ total += v; activeDays++; run++;
114
+ longestRun = Math.max(longestRun, run);
115
+ if (end) {
116
+ const key = msToDay(endMs - (vals.length - 1 - i) * DAY_MS);
117
+ if (!busiest || v > busiest.value) busiest = { date: key, value: v };
118
+ byWeekday[new Date(dayToMs(key)).getUTCDay()] += v;
119
+ }
120
+ } else run = 0;
121
+ }
122
+ // Current run: ending today, or yesterday (today may simply not have started).
123
+ let current = 0;
124
+ for (let i = vals.length - 1; i >= 0; i--) {
125
+ if (vals[i] > 0) current++;
126
+ else if (i === vals.length - 1) continue;
127
+ else break;
128
+ }
129
+ let bestWeekday = null;
130
+ for (let d = 0; d < 7; d++) if (byWeekday[d] > 0 && (bestWeekday == null || byWeekday[d] > byWeekday[bestWeekday])) bestWeekday = d;
131
+ return {
132
+ total, activeDays, longestRun, currentRun: current,
133
+ busiest,
134
+ avgPerActiveDay: activeDays ? total / activeDays : 0,
135
+ bestWeekday: bestWeekday == null ? null : WEEKDAYS[bestWeekday],
136
+ };
137
+ }
138
+
139
+ function fmtMetric(v, metric) { return metric === 'hours' ? fmtMinutes(v) : fmtNum(v); }
140
+
141
+ // ── the grid ─────────────────────────────────────────────────────────────
142
+
143
+ // Returns { svg, width, height } for a 53-column Sun..Sat grid at (x, y),
144
+ // month labels above, Mon/Wed/Fri labels to the left (inside x).
145
+ function grid(x, y, series, metric, { cell = 12, gap = 3, empty = false } = {}) {
146
+ const step = cell + gap;
147
+ const end = isDayKey(series?.end) ? series.end : null;
148
+ const ramp = RAMPS[metric] || RAMPS.tokens;
149
+ const fill = (l) => (l === 0 ? PALETTE.empty : ramp[l - 1]);
150
+ const endMs = end ? dayToMs(end) : 0;
151
+ const endDow = end ? new Date(endMs).getUTCDay() : 6;
152
+ const total = (HEATMAP_WEEKS - 1) * 7 + endDow + 1; // last column ends on `end`
153
+ const vals = seriesValues(series, metric, total);
154
+ const cut = levelCutoffs(vals);
155
+ const labelW = 30;
156
+ const gx = x + labelW;
157
+
158
+ let cells = '', months = '', lastMonth = -1, lastLabelCol = -9;
159
+ for (let i = 0; i < total; i++) {
160
+ const col = Math.floor(i / 7), row = i % 7;
161
+ const cx = gx + col * step, cy = y + row * step;
162
+ const key = end ? msToDay(endMs - (total - 1 - i) * DAY_MS) : null;
163
+ const v = vals[i];
164
+ const l = empty ? 0 : levelOf(v, cut);
165
+ const title = key ? `<title>${escapeXml(`${shortDate(key)}: ${fmtMetric(v, metric)}`)}</title>` : '';
166
+ cells += `<rect x="${cx}" y="${cy}" width="${cell}" height="${cell}" rx="2" fill="${fill(l)}" stroke="${PALETTE.ink}" stroke-width="0.4" stroke-opacity="0.55">${title}</rect>`;
167
+ if (row === 0 && key) {
168
+ const m = new Date(dayToMs(key)).getUTCMonth();
169
+ if (m !== lastMonth) {
170
+ // Skip a label squeezed against the previous one (partial first month).
171
+ if (col - lastLabelCol >= 3) {
172
+ months += `<text x="${cx}" y="${y - 7}" font-family="${MONO}" font-size="10" fill="${PALETTE.inkMute}">${MONTHS[m]}</text>`;
173
+ lastLabelCol = col;
174
+ }
175
+ lastMonth = m;
176
+ }
177
+ }
178
+ }
179
+ let rows = '';
180
+ for (const [r, name] of [[1, 'Mon'], [3, 'Wed'], [5, 'Fri']]) {
181
+ rows += `<text x="${x}" y="${y + r * step + cell - 2}" font-family="${MONO}" font-size="9" fill="${PALETTE.inkFaint}">${name}</text>`;
182
+ }
183
+ return { svg: months + rows + cells, width: labelW + HEATMAP_WEEKS * step - gap, height: 7 * step - gap };
184
+ }
185
+
186
+ function legend(xRight, y, metric) {
187
+ const ramp = RAMPS[metric] || RAMPS.tokens;
188
+ const fills = [PALETTE.empty, ...ramp];
189
+ const sw = 12, sg = 4;
190
+ const x0 = xRight - fills.length * (sw + sg) + sg;
191
+ let s = `<text x="${x0 - 8}" y="${y + 10}" text-anchor="end" font-family="${MONO}" font-size="9" fill="${PALETTE.inkFaint}">less</text>`;
192
+ fills.forEach((f, i) => {
193
+ s += `<rect x="${x0 + i * (sw + sg)}" y="${y}" width="${sw}" height="${sw}" rx="2" fill="${f}" stroke="${PALETTE.ink}" stroke-width="0.4" stroke-opacity="0.55"/>`;
194
+ });
195
+ s += `<text x="${xRight + 8}" y="${y + 10}" font-family="${MONO}" font-size="9" fill="${PALETTE.inkFaint}">more</text>`;
196
+ return s;
197
+ }
198
+
199
+ function frame(W, H, inner, label) {
200
+ return `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 ${W} ${H}" width="${W}" height="${H}" role="img" aria-label="${escapeXml(label)}">
201
+ <defs>
202
+ <pattern id="dg" width="22" height="22" patternUnits="userSpaceOnUse">
203
+ <circle cx="1" cy="1" r="1" fill="${PALETTE.ink}" opacity="0.07"/>
204
+ </pattern>
205
+ </defs>
206
+ <rect x="3" y="4" width="${W - 6}" height="${H - 7}" fill="${PALETTE.ink}"/>
207
+ <rect x="0.75" y="0.75" width="${W - 7}" height="${H - 9}" fill="${PALETTE.paper}" stroke="${PALETTE.ink}" stroke-width="2"/>
208
+ <rect x="0.75" y="0.75" width="${W - 7}" height="${H - 9}" fill="url(#dg)"/>
209
+ ${inner}
210
+ </svg>`;
211
+ }
212
+
213
+ function spark(cx, cy, r, fill) {
214
+ const i = r * 0.16;
215
+ return `<path d="M ${cx} ${cy - r} C ${cx + i} ${cy - i} ${cx + i} ${cy - i} ${cx + r} ${cy} C ${cx + i} ${cy + i} ${cx + i} ${cy + i} ${cx} ${cy + r} C ${cx - i} ${cy + i} ${cx - i} ${cy + i} ${cx - r} ${cy} C ${cx - i} ${cy - i} ${cx - i} ${cy - i} ${cx} ${cy - r} Z" fill="${fill}"/>`;
216
+ }
217
+
218
+ function verifiedStamp(x, y) {
219
+ return `<g transform="translate(${x} ${y})">
220
+ <circle r="11" fill="${PALETTE.grass}"/>
221
+ <path d="M -4.6 0 L -1.4 3.4 L 5 -4" fill="none" stroke="#fff" stroke-width="2.4" stroke-linecap="round" stroke-linejoin="round"/>
222
+ </g>`;
223
+ }
224
+
225
+ function clip(s, n) { s = String(s || ''); return s.length > n ? `${s.slice(0, n - 1)}…` : s; }
226
+
227
+ function metricOf(m) { return m === 'hours' ? 'hours' : 'tokens'; }
228
+
229
+ // ── standalone heatmap (GET /heatmap/<h>.svg, `claude-rpc calendar`) ─────
230
+
231
+ // opts: { series, metric, title?, subtitle?, footer? , empty? }
232
+ export function renderHeatmap({ series, metric = 'tokens', title, subtitle, footer, empty = false } = {}) {
233
+ metric = metricOf(metric);
234
+ const W = 880;
235
+ const g = grid(28, 98, series, metric, { empty });
236
+ const H = 98 + g.height + 56;
237
+ const f = seriesFacts(series, metric);
238
+ const what = metric === 'hours' ? 'hours' : 'tokens';
239
+ const sub = subtitle != null ? subtitle
240
+ : `${f.activeDays} active days · ${fmtMetric(f.total, metric)}${metric === 'hours' ? ' with Claude' : ' tokens'} in the last year`;
241
+ const inner = `
242
+ ${spark(40, 37, 10, metric === 'hours' ? PALETTE.grass : PALETTE.rust)}
243
+ <text x="58" y="44" font-family="${DISPLAY}" font-size="22" font-weight="800" letter-spacing="-0.6" fill="${PALETTE.ink}">${escapeXml(clip(title || 'a year on Claude Code', 48))}</text>
244
+ <text x="28" y="66" font-family="${MONO}" font-size="11" fill="${PALETTE.inkMute}">${escapeXml(sub)}</text>
245
+ ${g.svg}
246
+ <text x="28" y="${H - 24}" font-family="${MONO}" font-size="10" fill="${PALETTE.inkFaint}">${escapeXml(footer || 'claude-rpc.com')}</text>
247
+ ${legend(W - 66, H - 34, metric)}`;
248
+ return frame(W, H, inner, `Claude Code ${what} heatmap`);
249
+ }
250
+
251
+ // ── stats card with heatmap (GET /stats/<h>.svg, `calendar --card`) ──────
252
+
253
+ function tile(x, y, w, value, label, color) {
254
+ return `<g transform="translate(${x} ${y})">
255
+ <rect x="2" y="3" width="${w}" height="64" fill="${PALETTE.ink}"/>
256
+ <rect x="0" y="0" width="${w}" height="64" fill="${PALETTE.paper2}" stroke="${PALETTE.ink}" stroke-width="1.5"/>
257
+ <rect x="0" y="0" width="5" height="64" fill="${color}"/>
258
+ <text x="18" y="35" font-family="${DISPLAY}" font-size="26" font-weight="800" letter-spacing="-0.5" fill="${color}">${escapeXml(value)}</text>
259
+ <text x="18" y="53" font-family="${MONO}" font-size="9.5" font-weight="700" letter-spacing="1.4" fill="${PALETTE.inkMute}">${escapeXml(label.toUpperCase())}</text>
260
+ </g>`;
261
+ }
262
+
263
+ function fact(x, y, label, value) {
264
+ return `<text x="${x}" y="${y}" font-family="${MONO}" font-size="9" font-weight="700" letter-spacing="1.3" fill="${PALETTE.inkFaint}">${escapeXml(label.toUpperCase())}</text>
265
+ <text x="${x}" y="${y + 18}" font-family="${DISPLAY}" font-size="15" font-weight="700" fill="${PALETTE.ink}">${escapeXml(value)}</text>`;
266
+ }
267
+
268
+ // p: { handle, displayName, verified, githubUser, tokens, sessions, activeMs, streak } | null
269
+ // series: the merged daily series (or null — profile predates heatmap sync).
270
+ // kicker: the subtitle's lead-in ('Claude Code' live; the local card passes
271
+ // its own so a handle-less render doesn't read "Claude Code · Claude Code").
272
+ export function renderStatsCard(p, series, { metric = 'tokens', footer, kicker = 'Claude Code' } = {}) {
273
+ metric = metricOf(metric);
274
+ const W = 880;
275
+ const has = !!p;
276
+ const hasSeries = has && !!series && isDayKey(series.end);
277
+ const name = clip(has ? (p.displayName || `@${p.handle}`) : 'claude-rpc', 30);
278
+ const verified = has && !!p.verified;
279
+ const what = metric === 'hours' ? 'hours' : 'tokens';
280
+ const f = seriesFacts(series, metric);
281
+ const sub = !has ? 'no public profile yet'
282
+ : !hasSeries ? `${kicker} · heatmap fills in after the next profile sync`
283
+ : `${kicker}${verified ? ' · verified' : ''} · ${f.activeDays} active days in the last year`;
284
+
285
+ const dash = '—';
286
+ const tw = 194, tg = 14, tx = 28, ty = 92;
287
+ const tiles = [
288
+ tile(tx, ty, tw, has ? fmtNum(p.tokens || 0) : dash, 'tokens', PALETTE.rust),
289
+ tile(tx + (tw + tg), ty, tw, has ? fmtNum(p.sessions || 0) : dash, 'sessions', PALETTE.blue),
290
+ tile(tx + (tw + tg) * 2, ty, tw, has ? fmtMinutes((p.activeMs || 0) / 60000) : dash, 'hours', PALETTE.amber),
291
+ tile(tx + (tw + tg) * 3, ty, tw, has ? `${p.streak || 0}d` : dash, 'streak', PALETTE.grass),
292
+ ].join('');
293
+
294
+ const gy = 204;
295
+ const g = grid(28, gy, series, metric, { empty: !hasSeries });
296
+ const fy = gy + g.height + 30;
297
+ const facts = hasSeries ? [
298
+ fact(58, fy, 'busiest day', f.busiest ? `${shortDate(f.busiest.date)} · ${fmtMetric(f.busiest.value, metric)}` : dash),
299
+ fact(258, fy, `avg / active day`, fmtMetric(f.avgPerActiveDay, metric)),
300
+ fact(428, fy, 'longest run', `${f.longestRun}d`),
301
+ fact(568, fy, 'best weekday', f.bestWeekday || dash),
302
+ ].join('') : '';
303
+ const H = fy + 62;
304
+ const gh = has && p.githubUser ? `github.com/${p.githubUser}` : 'claude-rpc.com';
305
+
306
+ const inner = `
307
+ ${spark(40, 45, 11, PALETTE.rust)}
308
+ <text x="60" y="54" font-family="${DISPLAY}" font-size="27" font-weight="800" letter-spacing="-1" fill="${PALETTE.ink}">${escapeXml(name)}</text>
309
+ <text x="61" y="74" font-family="${MONO}" font-size="12" fill="${PALETTE.inkMute}">${escapeXml(sub)}</text>
310
+ ${verified ? verifiedStamp(W - 44, 46) : ''}
311
+ ${tiles}
312
+ <text x="28" y="${gy - 24}" font-family="${MONO}" font-size="9" font-weight="700" letter-spacing="1.4" fill="${PALETTE.inkMute}">${escapeXml(`${what} per day · last 12 months`.toUpperCase())}</text>
313
+ ${g.svg}
314
+ ${facts}
315
+ ${legend(W - 66, fy + 4, metric)}
316
+ <text x="28" y="${H - 20}" font-family="${MONO}" font-size="10" fill="${PALETTE.inkFaint}">${escapeXml(footer || gh)}</text>
317
+ <text x="${W - 30}" y="${H - 20}" text-anchor="end" font-family="${MONO}" font-size="10" fill="${PALETTE.inkFaint}">claude-rpc.com</text>`;
318
+ return frame(W, H, inner, `Claude Code stats: ${name}`);
319
+ }
320
+
321
+ // ── series merge (worker: one person, several machines) ──────────────────
322
+
323
+ // Sum several machines' series day-by-day onto one grid ending at `end`.
324
+ // Token and minute totals from different machines come from DIFFERENT
325
+ // transcripts, so summing is right (unlike calendar-day counts, which overlap).
326
+ export function mergeSeries(list, end, days = HEATMAP_DAYS) {
327
+ const endMs = dayToMs(end);
328
+ const tokens = new Array(days).fill(0), activeMin = new Array(days).fill(0);
329
+ let any = false;
330
+ for (const s of list) {
331
+ if (!s || !isDayKey(s.end)) continue;
332
+ any = true;
333
+ const shift = Math.round((endMs - dayToMs(s.end)) / DAY_MS); // days s.end is before `end`
334
+ for (const [src, dst] of [[s.tokens || [], tokens], [s.activeMin || [], activeMin]]) {
335
+ for (let i = 0; i < src.length; i++) {
336
+ const idx = days - 1 - shift - (src.length - 1 - i);
337
+ if (idx >= 0 && idx < days) dst[idx] += Number(src[i]) || 0;
338
+ }
339
+ }
340
+ }
341
+ return any ? { end, tokens, activeMin } : null;
342
+ }
package/src/mcp.js CHANGED
@@ -17,7 +17,8 @@ function fmtN(n) {
17
17
  if (n < 1000) return String(Math.round(n));
18
18
  if (n < 1e6) return `${(n / 1e3).toFixed(1)}k`;
19
19
  if (n < 1e9) return `${(n / 1e6).toFixed(2)}M`;
20
- return `${(n / 1e9).toFixed(2)}B`;
20
+ if (n < 1e12) return `${(n / 1e9).toFixed(2)}B`;
21
+ return `${(n / 1e12).toFixed(2)}T`;
21
22
  }
22
23
 
23
24
  // ── Tool handlers — pure(aggregate) → string. Exported for tests. ──────────
package/src/recap.js CHANGED
@@ -34,7 +34,8 @@ function fmtN(n) {
34
34
  if (n < 1000) return String(Math.round(n));
35
35
  if (n < 1e6) return `${(n / 1e3).toFixed(1)}k`;
36
36
  if (n < 1e9) return `${(n / 1e6).toFixed(2)}M`;
37
- return `${(n / 1e9).toFixed(2)}B`;
37
+ if (n < 1e12) return `${(n / 1e9).toFixed(2)}B`;
38
+ return `${(n / 1e12).toFixed(2)}T`;
38
39
  }
39
40
 
40
41
  function dayKeyAt(now, offsetDays) {
@@ -49,7 +49,8 @@
49
49
  if (n < 1000) return String(n);
50
50
  if (n < 1e6) return (n / 1e3).toFixed(1) + 'k';
51
51
  if (n < 1e9) return (n / 1e6).toFixed(2) + 'M';
52
- return (n / 1e9).toFixed(2) + 'B';
52
+ if (n < 1e12) return (n / 1e9).toFixed(2) + 'B';
53
+ return (n / 1e12).toFixed(2) + 'T';
53
54
  };
54
55
  const fmtCost = (usd) => {
55
56
  if (!usd) return '$0';
@@ -8,7 +8,8 @@
8
8
  if (n < 1000) return String(Math.round(n));
9
9
  if (n < 1e6) return (n / 1e3).toFixed(1).replace(/\.0$/, '') + 'k';
10
10
  if (n < 1e9) return (n / 1e6).toFixed(2).replace(/\.?0+$/, '') + 'M';
11
- return (n / 1e9).toFixed(2).replace(/\.?0+$/, '') + 'B';
11
+ if (n < 1e12) return (n / 1e9).toFixed(2).replace(/\.?0+$/, '') + 'B';
12
+ return (n / 1e12).toFixed(2).replace(/\.?0+$/, '') + 'T';
12
13
  };
13
14
  const fmtHours = (ms) => { const h = (ms || 0) / 3.6e6; return h < 1 ? Math.round(h * 60) + 'm' : h < 10 ? h.toFixed(1) + 'h' : Math.round(h) + 'h'; };
14
15
  const esc = (s) => String(s == null ? '' : s).replace(/[&<>]/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;' }[c]));
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.4.3';
14
+ const BAKED = '1.5.0';
15
15
 
16
16
  function readPkgVersion() {
17
17
  try {