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