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