claude-rpc 1.5.0 → 1.5.2
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 +3 -3
- package/SECURITY.md +1 -1
- package/package.json +1 -1
- package/src/cli.js +1 -0
- package/src/daemon.js +20 -1
- package/src/hook.js +63 -29
- package/src/install.js +103 -19
- package/src/pricing.js +14 -3
- package/src/scan-worker.js +50 -0
- package/src/scanner.js +27 -15
- package/src/version.js +1 -1
package/README.md
CHANGED
|
@@ -220,9 +220,9 @@ For a complete account of the sensitive things claude-rpc does — startup persi
|
|
|
220
220
|
|
|
221
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`).
|
|
222
222
|
|
|
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.
|
|
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. 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.
|
|
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.
|
|
226
226
|
|
|
227
227
|
Persistent state, all human-readable JSON:
|
|
228
228
|
|
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 |
|
package/package.json
CHANGED
package/src/cli.js
CHANGED
|
@@ -2674,6 +2674,7 @@ process.on('unhandledRejection', (e) => {
|
|
|
2674
2674
|
case 'log': tailLog(); break;
|
|
2675
2675
|
case 'hook': runHookCli(process.argv[3] || 'unknown'); break;
|
|
2676
2676
|
case 'daemon': await import('./daemon.js'); break;
|
|
2677
|
+
case 'scan-worker': (await import('./scan-worker.js')).runScanWorker(process.argv.includes('--force')); break;
|
|
2677
2678
|
default: {
|
|
2678
2679
|
if (packagedDefault) {
|
|
2679
2680
|
if (!isInstalled()) {
|
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/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);
|
|
@@ -147,7 +161,9 @@ export function processHookEvent(event, input = {}) {
|
|
|
147
161
|
});
|
|
148
162
|
break;
|
|
149
163
|
}
|
|
150
|
-
case 'PostToolUse':
|
|
164
|
+
case 'PostToolUse':
|
|
165
|
+
case 'PostToolUseFailure': { // a failed call fires only the latter
|
|
166
|
+
const failed = event === 'PostToolUseFailure';
|
|
151
167
|
const toolName = input.tool_name || input.toolName || '';
|
|
152
168
|
const toolInput = input.tool_input || input.toolInput || {};
|
|
153
169
|
const file = toolInput.file_path || toolInput.path || toolInput.notebook_path || null;
|
|
@@ -158,7 +174,7 @@ export function processHookEvent(event, input = {}) {
|
|
|
158
174
|
let shipKind = null;
|
|
159
175
|
let shipSubject = null;
|
|
160
176
|
let shipBranch = null;
|
|
161
|
-
if (toolName === 'Bash') {
|
|
177
|
+
if (toolName === 'Bash' && !failed) { // a failed `git commit` shipped nothing
|
|
162
178
|
shipKind = classifyShip(toolInput.command);
|
|
163
179
|
if (shipKind) {
|
|
164
180
|
const shipCwd = input.cwd || process.cwd();
|
|
@@ -170,11 +186,13 @@ export function processHookEvent(event, input = {}) {
|
|
|
170
186
|
}
|
|
171
187
|
}
|
|
172
188
|
}
|
|
173
|
-
update((s) => {
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
189
|
+
update((s, stale) => {
|
|
190
|
+
if (!stale) {
|
|
191
|
+
s.currentTool = null;
|
|
192
|
+
s.toolStartedAt = null;
|
|
193
|
+
s.lastActivity = now;
|
|
194
|
+
s.claudeClosed = false;
|
|
195
|
+
}
|
|
178
196
|
if (!s.sessionStart) s.sessionStart = now;
|
|
179
197
|
if (file && (toolName === 'Write' || toolName === 'Edit' || toolName === 'NotebookEdit')) {
|
|
180
198
|
s.filesEdited = pushUnique(s.filesEdited, file);
|
|
@@ -227,9 +245,22 @@ export function processHookEvent(event, input = {}) {
|
|
|
227
245
|
appendEvent({ type: 'precompact', ts: now, trigger: input.trigger || input.matcher || null, cwd: input.cwd || null });
|
|
228
246
|
break;
|
|
229
247
|
}
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
248
|
+
case 'PostCompact': {
|
|
249
|
+
// Claude Code 2.1.76+. Older versions only re-fire SessionStart
|
|
250
|
+
// (source:'compact'), handled above. An auto-compaction resumes the turn
|
|
251
|
+
// that triggered it; a manual /compact leaves the session waiting on you.
|
|
252
|
+
update((s) => {
|
|
253
|
+
const manual = (input.trigger || s.compactTrigger) === 'manual';
|
|
254
|
+
delete s.compactStartedAt;
|
|
255
|
+
delete s.compactTrigger;
|
|
256
|
+
s.status = manual ? 'idle' : 'working';
|
|
257
|
+
s.lastActivity = now;
|
|
258
|
+
s.claudeClosed = false;
|
|
259
|
+
if (!s.sessionStart) s.sessionStart = now;
|
|
260
|
+
return s;
|
|
261
|
+
});
|
|
262
|
+
break;
|
|
263
|
+
}
|
|
233
264
|
case 'SessionEnd': {
|
|
234
265
|
// Authoritative "Claude Code is gone" signal — don't wait on the
|
|
235
266
|
// staleSessionMin timeout. applyIdle short-circuits to stale when it
|
|
@@ -253,6 +284,7 @@ export function processHookEvent(event, input = {}) {
|
|
|
253
284
|
setActivity({});
|
|
254
285
|
break;
|
|
255
286
|
}
|
|
287
|
+
case 'StopFailure': // the turn ended on an API error — Stop never fires
|
|
256
288
|
case 'Stop':
|
|
257
289
|
default: {
|
|
258
290
|
setActivity({ status: 'idle', currentTool: null, currentFile: null });
|
|
@@ -267,7 +299,9 @@ export function processHookEvent(event, input = {}) {
|
|
|
267
299
|
// ack always goes out.
|
|
268
300
|
export function runHookCli(event) {
|
|
269
301
|
try {
|
|
270
|
-
|
|
302
|
+
// performance.timeOrigin = when this process was spawned, so dispatch
|
|
303
|
+
// order survives node's (variable) startup time — see `stale` above.
|
|
304
|
+
processHookEvent(event, parseInput(), Math.round(performance.timeOrigin));
|
|
271
305
|
} catch { /* presence is best-effort; never break the user's turn */ }
|
|
272
306
|
finally {
|
|
273
307
|
try { process.stdout.write(JSON.stringify({ continue: true })); } catch { /* stdout closed */ }
|
package/src/install.js
CHANGED
|
@@ -5,7 +5,7 @@
|
|
|
5
5
|
import {
|
|
6
6
|
existsSync, mkdirSync, readFileSync, writeFileSync,
|
|
7
7
|
copyFileSync, chmodSync, renameSync, statSync,
|
|
8
|
-
readdirSync, unlinkSync,
|
|
8
|
+
readdirSync, unlinkSync, openSync, readSync, closeSync,
|
|
9
9
|
} from 'node:fs';
|
|
10
10
|
import { dirname, join, resolve } from 'node:path';
|
|
11
11
|
import { homedir } from 'node:os';
|
|
@@ -15,7 +15,7 @@ import {
|
|
|
15
15
|
CLAUDE_SETTINGS, CONFIG_PATH, USER_CONFIG_DIR, ROOT,
|
|
16
16
|
HOOK_SCRIPT, IS_PACKAGED, IS_NPM_INSTALL, IS_NPX,
|
|
17
17
|
CANONICAL_EXE, CANONICAL_INSTALL_DIR, CANONICAL_EXE_NAME, VERSION_STAMP,
|
|
18
|
-
DAEMON_SCRIPT,
|
|
18
|
+
DAEMON_SCRIPT, CLAUDE_PROJECTS,
|
|
19
19
|
} from './paths.js';
|
|
20
20
|
import { DEFAULT_CONFIG } from './default-config.js';
|
|
21
21
|
import { VERSION } from './version.js';
|
|
@@ -60,6 +60,78 @@ 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', 'PostToolUseFailure']);
|
|
69
|
+
|
|
70
|
+
// Hook events newer Claude Code versions added, with the first version that has
|
|
71
|
+
// each. An event name a Claude Code version doesn't know makes it reject the
|
|
72
|
+
// WHOLE hooks block (every hook in settings.json, the user's own too: checked
|
|
73
|
+
// on 2.0.0), so each is wired only once the installed Claude Code is known to
|
|
74
|
+
// support it, and unwired again if it isn't.
|
|
75
|
+
export const OPTIONAL_EVENTS = {
|
|
76
|
+
PostToolUseFailure: '2.0.56', // a failed tool call never fires PostToolUse
|
|
77
|
+
PostCompact: '2.1.76',
|
|
78
|
+
StopFailure: '2.1.78', // a turn that ends on an API error never fires Stop
|
|
79
|
+
};
|
|
80
|
+
|
|
81
|
+
export function versionAtLeast(v, min) {
|
|
82
|
+
const a = String(v || '').split('.').map(Number);
|
|
83
|
+
const b = String(min).split('.').map(Number);
|
|
84
|
+
for (let i = 0; i < 3; i++) {
|
|
85
|
+
if ((a[i] || 0) !== (b[i] || 0)) return (a[i] || 0) > (b[i] || 0);
|
|
86
|
+
}
|
|
87
|
+
return true;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
// The Claude Code version from the newest transcript (every line carries
|
|
91
|
+
// "version"). Reading it off disk works where `claude --version` doesn't: the
|
|
92
|
+
// daemon's PATH often has no `claude`. Null when there's no transcript yet.
|
|
93
|
+
export function detectClaudeCodeVersion({ projectsDir = CLAUDE_PROJECTS } = {}) {
|
|
94
|
+
let newest = null;
|
|
95
|
+
let newestMtime = -1;
|
|
96
|
+
let projects;
|
|
97
|
+
try { projects = readdirSync(projectsDir); } catch { return null; }
|
|
98
|
+
for (const proj of projects) {
|
|
99
|
+
let files;
|
|
100
|
+
try { files = readdirSync(join(projectsDir, proj)); } catch { continue; }
|
|
101
|
+
for (const f of files) {
|
|
102
|
+
if (!f.endsWith('.jsonl')) continue;
|
|
103
|
+
try {
|
|
104
|
+
const m = statSync(join(projectsDir, proj, f)).mtimeMs;
|
|
105
|
+
if (m > newestMtime) { newestMtime = m; newest = join(projectsDir, proj, f); }
|
|
106
|
+
} catch { /* vanished mid-walk */ }
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
if (!newest) return null;
|
|
110
|
+
try {
|
|
111
|
+
const size = statSync(newest).size;
|
|
112
|
+
const len = Math.min(size, 65536);
|
|
113
|
+
const buf = Buffer.alloc(len);
|
|
114
|
+
const fd = openSync(newest, 'r');
|
|
115
|
+
try { readSync(fd, buf, 0, len, size - len); } finally { closeSync(fd); }
|
|
116
|
+
const all = [...buf.toString('utf8').matchAll(/"version":"(\d+\.\d+\.\d+)"/g)];
|
|
117
|
+
return all.length ? all[all.length - 1][1] : null;
|
|
118
|
+
} catch { return null; }
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
export function supportedOptionalEvents(ccVersion) {
|
|
122
|
+
if (!ccVersion) return [];
|
|
123
|
+
return Object.keys(OPTIONAL_EVENTS).filter((e) => versionAtLeast(ccVersion, OPTIONAL_EVENTS[e]));
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
function removeOurHooks(settings, event) {
|
|
127
|
+
const bucket = settings.hooks[event];
|
|
128
|
+
if (!Array.isArray(bucket)) return;
|
|
129
|
+
settings.hooks[event] = bucket
|
|
130
|
+
.map((entry) => ({ ...entry, hooks: (entry.hooks || []).filter((h) => !isOurHook(h)) }))
|
|
131
|
+
.filter((entry) => (entry.hooks || []).length > 0);
|
|
132
|
+
if (settings.hooks[event].length === 0) delete settings.hooks[event];
|
|
133
|
+
}
|
|
134
|
+
|
|
63
135
|
function readJson(p, fb) {
|
|
64
136
|
try { return JSON.parse(readFileSync(p, 'utf8')); }
|
|
65
137
|
catch { return fb; }
|
|
@@ -86,7 +158,7 @@ export function isOurHook(h) {
|
|
|
86
158
|
return !!h && (h._claudeRpc === true || isOurHookCommand(h.command));
|
|
87
159
|
}
|
|
88
160
|
|
|
89
|
-
export function installHooks(exePath, { silent = false } = {}) {
|
|
161
|
+
export function installHooks(exePath, { silent = false, ccVersion = detectClaudeCodeVersion() } = {}) {
|
|
90
162
|
const settings = readJson(CLAUDE_SETTINGS, {});
|
|
91
163
|
const before = JSON.stringify(settings.hooks || {});
|
|
92
164
|
settings.hooks = settings.hooks || {};
|
|
@@ -106,40 +178,44 @@ export function installHooks(exePath, { silent = false } = {}) {
|
|
|
106
178
|
? (event) => `"${exePath}" hook ${event}`
|
|
107
179
|
: (event) => `"${node}" "${HOOK_SCRIPT.replace(/\\/g, '/')}" ${event}`;
|
|
108
180
|
|
|
109
|
-
|
|
181
|
+
const optional = supportedOptionalEvents(ccVersion);
|
|
182
|
+
for (const event of Object.keys(OPTIONAL_EVENTS)) {
|
|
183
|
+
if (!optional.includes(event)) removeOurHooks(settings, event);
|
|
184
|
+
}
|
|
185
|
+
const events = [...EVENTS, ...optional];
|
|
186
|
+
for (const event of events) {
|
|
110
187
|
const bucket = settings.hooks[event] = settings.hooks[event] || [];
|
|
111
188
|
const wanted = cmdFor(event);
|
|
189
|
+
const shape = (h) => {
|
|
190
|
+
const { async: _drop, ...rest } = h;
|
|
191
|
+
return ASYNC_EVENTS.has(event)
|
|
192
|
+
? { ...rest, type: 'command', command: wanted, async: true, _claudeRpc: true }
|
|
193
|
+
: { ...rest, type: 'command', command: wanted, _claudeRpc: true };
|
|
194
|
+
};
|
|
112
195
|
const existingEntry = bucket.find((b) =>
|
|
113
196
|
Array.isArray(b.hooks) && b.hooks.some((h) => isOurHook(h))
|
|
114
197
|
);
|
|
115
198
|
if (existingEntry) {
|
|
116
199
|
existingEntry.hooks = existingEntry.hooks.map((h) =>
|
|
117
|
-
isOurHook(h) ?
|
|
200
|
+
isOurHook(h) ? shape(h) : h
|
|
118
201
|
);
|
|
119
202
|
} else {
|
|
120
|
-
bucket.push({ matcher: '', hooks: [{
|
|
203
|
+
bucket.push({ matcher: '', hooks: [shape({})] });
|
|
121
204
|
}
|
|
122
205
|
}
|
|
123
206
|
if (JSON.stringify(settings.hooks) === before) {
|
|
124
|
-
if (!silent) noop(`hooks wired (${
|
|
207
|
+
if (!silent) noop(`hooks wired (${events.length} events)`);
|
|
125
208
|
return false;
|
|
126
209
|
}
|
|
127
210
|
writeJson(CLAUDE_SETTINGS, settings);
|
|
128
|
-
if (!silent) dirtyStep(SYM_OK, 'hooks wired', `${
|
|
211
|
+
if (!silent) dirtyStep(SYM_OK, 'hooks wired', `${events.length} events → ${CLAUDE_SETTINGS}`);
|
|
129
212
|
return true;
|
|
130
213
|
}
|
|
131
214
|
|
|
132
215
|
export function uninstallHooks() {
|
|
133
216
|
const settings = readJson(CLAUDE_SETTINGS, {});
|
|
134
217
|
if (!settings.hooks) return;
|
|
135
|
-
for (const event of EVENTS)
|
|
136
|
-
const bucket = settings.hooks[event];
|
|
137
|
-
if (!Array.isArray(bucket)) continue;
|
|
138
|
-
settings.hooks[event] = bucket
|
|
139
|
-
.map((entry) => ({ ...entry, hooks: (entry.hooks || []).filter((h) => !isOurHook(h)) }))
|
|
140
|
-
.filter((entry) => (entry.hooks || []).length > 0);
|
|
141
|
-
if (settings.hooks[event].length === 0) delete settings.hooks[event];
|
|
142
|
-
}
|
|
218
|
+
for (const event of [...EVENTS, ...Object.keys(OPTIONAL_EVENTS)]) removeOurHooks(settings, event);
|
|
143
219
|
writeJson(CLAUDE_SETTINGS, settings);
|
|
144
220
|
step(SYM_OK, 'hooks removed', CLAUDE_SETTINGS);
|
|
145
221
|
}
|
|
@@ -743,9 +819,17 @@ function warnIfStale() {
|
|
|
743
819
|
// version. Best-effort and quiet by default; never throws into the caller.
|
|
744
820
|
// Returns { changed, from, rewired }.
|
|
745
821
|
export function selfHealOnUpdate({ exePath = null, silent = true } = {}) {
|
|
822
|
+
// Stamp = our version, plus (line 2) the optional hook events last wired, so
|
|
823
|
+
// a Claude Code update that unlocks a new event re-wires too.
|
|
746
824
|
let from = null;
|
|
747
|
-
|
|
748
|
-
|
|
825
|
+
let fromHooks = '';
|
|
826
|
+
try {
|
|
827
|
+
const [v, h] = (readFileSync(VERSION_STAMP, 'utf8') || '').trim().split('\n');
|
|
828
|
+
from = (v || '').trim() || null;
|
|
829
|
+
fromHooks = (h || '').trim();
|
|
830
|
+
} catch { /* first run / unreadable — treat as needing a heal */ }
|
|
831
|
+
const hooksLine = 'hooks:' + supportedOptionalEvents(detectClaudeCodeVersion()).join(',');
|
|
832
|
+
if (from === VERSION && fromHooks === hooksLine) return { changed: false, from, rewired: false };
|
|
749
833
|
const exe = exePath || ((IS_PACKAGED && existsSync(CANONICAL_EXE)) ? CANONICAL_EXE : process.execPath);
|
|
750
834
|
let rewired = false;
|
|
751
835
|
try { rewired = installHooks(exe, { silent }); } catch { /* best-effort — a hook re-wire must never block daemon startup */ }
|
|
@@ -765,7 +849,7 @@ export function selfHealOnUpdate({ exePath = null, silent = true } = {}) {
|
|
|
765
849
|
} catch { /* best-effort */ }
|
|
766
850
|
try {
|
|
767
851
|
mkdirSync(dirname(VERSION_STAMP), { recursive: true });
|
|
768
|
-
writeFileSync(VERSION_STAMP, VERSION + '\n');
|
|
852
|
+
writeFileSync(VERSION_STAMP, VERSION + '\n' + hooksLine + '\n');
|
|
769
853
|
} catch { /* unwritable — we'll just self-heal again next start, which is harmless (idempotent) */ }
|
|
770
854
|
return { changed: true, from, rewired, autostart };
|
|
771
855
|
}
|
package/src/pricing.js
CHANGED
|
@@ -6,8 +6,18 @@
|
|
|
6
6
|
// To customize: edit this file and run `claude-rpc rescan`.
|
|
7
7
|
|
|
8
8
|
const PRICING = {
|
|
9
|
-
// Fable family — Anthropic's frontier tier above Opus.
|
|
10
|
-
'fable-5':
|
|
9
|
+
// Fable family — Anthropic's frontier tier above Opus. 5.1 cut cache reads 4x.
|
|
10
|
+
'fable-5': { input: 10.00, output: 50.00, cacheRead: 1.00, cacheWrite: 12.50 },
|
|
11
|
+
'fable-5-1': { input: 10.00, output: 50.00, cacheRead: 0.25, cacheWrite: 12.50 },
|
|
12
|
+
|
|
13
|
+
// 5.x generation (list prices checked 2026-10-14). Haiku 5.5 uses its
|
|
14
|
+
// <=100K-token-prompt rates; past 100K it's 5x, which a per-token table
|
|
15
|
+
// can't express — Claude Code prompts are usually under that.
|
|
16
|
+
'opus-5': { input: 5.00, output: 25.00, cacheRead: 0.50, cacheWrite: 6.25 },
|
|
17
|
+
'opus-5-5': { input: 4.00, output: 20.00, cacheRead: 0.20, cacheWrite: 5.00 },
|
|
18
|
+
'sonnet-5': { input: 2.00, output: 10.00, cacheRead: 0.20, cacheWrite: 2.50 },
|
|
19
|
+
'sonnet-5-5': { input: 2.00, output: 10.00, cacheRead: 0.10, cacheWrite: 2.50 },
|
|
20
|
+
'haiku-5-5': { input: 0.10, output: 0.50, cacheRead: 0.01, cacheWrite: 0.125 },
|
|
11
21
|
|
|
12
22
|
// Opus 4.x family. 4.0/4.1 launched at $15/$75; the list price dropped to
|
|
13
23
|
// $5/$25 with Opus 4.5 and has held through 4.8.
|
|
@@ -49,7 +59,8 @@ const TIERS = new Set(['opus', 'sonnet', 'haiku', 'fable']);
|
|
|
49
59
|
// → sonnet, in that order.
|
|
50
60
|
export function pricingKeyFor(modelId) {
|
|
51
61
|
if (!modelId) return 'sonnet';
|
|
52
|
-
|
|
62
|
+
// Drop a context-window tag like `[1m]` (claude-opus-5-5[1m]) before parsing.
|
|
63
|
+
const parts = String(modelId).toLowerCase().replace(/\[[^\]]*\]/g, '').split('-');
|
|
53
64
|
|
|
54
65
|
let tier = null;
|
|
55
66
|
let tierIdx = -1;
|
|
@@ -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
|