claude-rpc 1.4.1 → 1.4.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/package.json +2 -2
- package/src/atomic-rename.js +46 -0
- package/src/discord-ipc.js +38 -21
- package/src/install.js +16 -5
- package/src/notify.js +10 -3
- package/src/scanner.js +4 -3
- package/src/server/sse.js +48 -10
- package/src/state.js +2 -2
- package/src/version.js +1 -1
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "claude-rpc",
|
|
3
|
-
"version": "1.4.
|
|
3
|
+
"version": "1.4.2",
|
|
4
4
|
"description": "Discord Rich Presence for Claude Code — live model, project, tokens, and lifetime stats driven by Claude Code's hook system.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"license": "MIT",
|
|
@@ -31,7 +31,7 @@
|
|
|
31
31
|
"prep:dashboard": "node ./scripts/prep-dashboard.js",
|
|
32
32
|
"dist:mac": "npm run build:exe && npm run prep:dashboard && npm --prefix dashboard run dist:mac",
|
|
33
33
|
"dist:win": "npm run build:exe && npm run prep:dashboard && npm --prefix dashboard run dist:win",
|
|
34
|
-
"test": "node
|
|
34
|
+
"test": "node ./scripts/run-tests.mjs",
|
|
35
35
|
"lint": "eslint src test vscode-extension",
|
|
36
36
|
"format": "prettier --write \"src/**/*.js\" \"test/**/*.js\"",
|
|
37
37
|
"format:check": "prettier --check \"src/**/*.js\" \"test/**/*.js\"",
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
// Windows can transiently refuse a rename onto an existing path — EPERM (or
|
|
2
|
+
// occasionally EBUSY/EACCES) — while something else briefly holds a handle
|
|
3
|
+
// on the destination: AV/Search-Indexer scans, or (confirmed live in CI) a
|
|
4
|
+
// directory being watched via fs.watch/ReadDirectoryChangesW, which every
|
|
5
|
+
// file this guards (state.json, the scan cache, aggregate.json) sits under.
|
|
6
|
+
// POSIX rename() is atomic and doesn't contend like this, so this is a
|
|
7
|
+
// no-op there. The lock is held single-digit milliseconds; a handful of
|
|
8
|
+
// immediate retries clears it without changing behavior anywhere else.
|
|
9
|
+
import { renameSync } from 'node:fs';
|
|
10
|
+
|
|
11
|
+
const RETRY_CODES = new Set(['EPERM', 'EBUSY', 'EACCES']);
|
|
12
|
+
const MAX_ATTEMPTS = 5;
|
|
13
|
+
const RETRY_DELAY_MS = 20;
|
|
14
|
+
|
|
15
|
+
// Blocks the calling thread synchronously — the standard dependency-free way
|
|
16
|
+
// to sleep inside a sync call. Best-effort: if SharedArrayBuffer is ever
|
|
17
|
+
// unavailable, the retry loop just spins with no delay instead of failing.
|
|
18
|
+
function sleepSync(ms) {
|
|
19
|
+
try {
|
|
20
|
+
Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
|
|
21
|
+
} catch {
|
|
22
|
+
/* no SharedArrayBuffer — retry immediately instead */
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
// Drop-in for fs.renameSync that tolerates Windows' transient rename locks.
|
|
27
|
+
// `platform`/`rename`/`sleep` are injectable so the retry loop is testable
|
|
28
|
+
// without a real Windows filesystem.
|
|
29
|
+
export function renameSyncRetry(src, dest, {
|
|
30
|
+
platform = process.platform,
|
|
31
|
+
rename = renameSync,
|
|
32
|
+
sleep = sleepSync,
|
|
33
|
+
} = {}) {
|
|
34
|
+
if (platform !== 'win32') return rename(src, dest);
|
|
35
|
+
let lastErr;
|
|
36
|
+
for (let attempt = 0; attempt < MAX_ATTEMPTS; attempt++) {
|
|
37
|
+
try {
|
|
38
|
+
return rename(src, dest);
|
|
39
|
+
} catch (e) {
|
|
40
|
+
lastErr = e;
|
|
41
|
+
if (!RETRY_CODES.has(e.code)) throw e;
|
|
42
|
+
sleep(RETRY_DELAY_MS);
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
throw lastErr;
|
|
46
|
+
}
|
package/src/discord-ipc.js
CHANGED
|
@@ -184,29 +184,46 @@ export class Client extends EventEmitter {
|
|
|
184
184
|
this._decode = null;
|
|
185
185
|
}
|
|
186
186
|
|
|
187
|
+
// Try one candidate path; resolves the connected socket, or null on
|
|
188
|
+
// error/timeout. Never rejects — callers race/sequence these freely.
|
|
189
|
+
_tryConnect(p) {
|
|
190
|
+
return new Promise((resolve) => {
|
|
191
|
+
const s = net.createConnection(p);
|
|
192
|
+
let timer = null;
|
|
193
|
+
const cleanup = () => {
|
|
194
|
+
clearTimeout(timer);
|
|
195
|
+
s.removeListener('connect', onOk);
|
|
196
|
+
s.removeListener('error', onErr);
|
|
197
|
+
};
|
|
198
|
+
const onErr = () => { cleanup(); resolve(null); };
|
|
199
|
+
const onOk = () => { cleanup(); resolve(s); };
|
|
200
|
+
// A peer that accepts then stalls would otherwise never settle this
|
|
201
|
+
// candidate and block the rest each discovery cycle (and leak the fd).
|
|
202
|
+
timer = setTimeout(() => { cleanup(); s.destroy(); resolve(null); }, SOCKET_CONNECT_TIMEOUT_MS);
|
|
203
|
+
if (typeof timer === 'object' && 'unref' in timer) timer.unref();
|
|
204
|
+
s.once('connect', onOk);
|
|
205
|
+
s.once('error', onErr);
|
|
206
|
+
});
|
|
207
|
+
}
|
|
208
|
+
|
|
187
209
|
async _openSocket() {
|
|
188
210
|
const paths = this._pathList ?? candidatePaths();
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
s.once('error', onErr);
|
|
206
|
-
});
|
|
207
|
-
if (socket) return socket;
|
|
208
|
-
}
|
|
209
|
-
return null;
|
|
211
|
+
// Race every candidate concurrently rather than trying them one at a
|
|
212
|
+
// time. On posix this list is already existence-filtered (usually just
|
|
213
|
+
// one path), so it barely matters — but on Windows all 10 named-pipe
|
|
214
|
+
// paths are probed unconditionally (no existence pre-check is possible),
|
|
215
|
+
// so a sequential loop pays up to 10× SOCKET_CONNECT_TIMEOUT_MS in the
|
|
216
|
+
// worst case (Discord not running). Racing caps discovery at one timeout
|
|
217
|
+
// regardless of candidate count. `Promise.all` (not `race`) so a losing
|
|
218
|
+
// socket can still be found and destroyed rather than leaked, and so the
|
|
219
|
+
// winner is picked by path order — preserving "prefer discord-ipc-0" even
|
|
220
|
+
// when more than one candidate accepts (e.g. a bridge alongside real
|
|
221
|
+
// Discord).
|
|
222
|
+
const sockets = await Promise.all(paths.map((p) => this._tryConnect(p)));
|
|
223
|
+
const winner = sockets.findIndex((s) => s !== null);
|
|
224
|
+
if (winner === -1) return null;
|
|
225
|
+
sockets.forEach((s, i) => { if (s && i !== winner) { try { s.destroy(); } catch { /* already gone */ } } });
|
|
226
|
+
return sockets[winner];
|
|
210
227
|
}
|
|
211
228
|
|
|
212
229
|
// Connect, handshake, and resolve once Discord sends READY (which also
|
package/src/install.js
CHANGED
|
@@ -200,6 +200,20 @@ export function launchdPlist({ exe, args }) {
|
|
|
200
200
|
].join('\n');
|
|
201
201
|
}
|
|
202
202
|
|
|
203
|
+
// Windows Run-key command + windowless .vbs shim content — pure, exported so
|
|
204
|
+
// they're unit-testable without touching reg.exe/wscript or the real
|
|
205
|
+
// filesystem (mirrors launchdPlist/systemdUnit above).
|
|
206
|
+
export function windowsRunCommand({ exe, args }) {
|
|
207
|
+
return [exe, ...args].map((p) => `"${p}"`).join(' ');
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
export function windowsVbsShim({ exe, args }) {
|
|
211
|
+
// In a VBS string literal a doubled quote is an escaped quote, so each
|
|
212
|
+
// `""x""` below reaches the shell as `"x"`.
|
|
213
|
+
const vbsCmd = [exe, ...args].map((p) => `""${p}""`).join(' ');
|
|
214
|
+
return `CreateObject("WScript.Shell").Run "${vbsCmd}", 0, False\r\n`;
|
|
215
|
+
}
|
|
216
|
+
|
|
203
217
|
export function systemdUnit({ exe, args }) {
|
|
204
218
|
const execStart = [exe, ...args].map((a) => `"${a}"`).join(' '); // quote each token (paths with spaces)
|
|
205
219
|
return [
|
|
@@ -289,13 +303,10 @@ export async function addStartupEntry(exePath) {
|
|
|
289
303
|
// a Run entry of `"node.exe" daemon` (no script path) and login-autostart
|
|
290
304
|
// silently launched nothing.
|
|
291
305
|
const launch = daemonLaunch(exePath);
|
|
292
|
-
let runCmd =
|
|
306
|
+
let runCmd = windowsRunCommand(launch);
|
|
293
307
|
try {
|
|
294
308
|
mkdirSync(CANONICAL_INSTALL_DIR, { recursive: true });
|
|
295
|
-
|
|
296
|
-
// `""x""` below reaches the shell as `"x"`.
|
|
297
|
-
const vbsCmd = [launch.exe, ...launch.args].map((p) => `""${p}""`).join(' ');
|
|
298
|
-
writeFileSync(STARTUP_VBS, `CreateObject("WScript.Shell").Run "${vbsCmd}", 0, False\r\n`);
|
|
309
|
+
writeFileSync(STARTUP_VBS, windowsVbsShim(launch));
|
|
299
310
|
runCmd = `wscript.exe "${STARTUP_VBS}"`;
|
|
300
311
|
} catch { /* couldn't write the shim — fall back to the direct (windowed) entry */ }
|
|
301
312
|
await regCommand([
|
package/src/notify.js
CHANGED
|
@@ -29,9 +29,9 @@ export function sanitizeLabel(s) {
|
|
|
29
29
|
* @param {string} [body] - Notification body text.
|
|
30
30
|
* @returns {boolean} true if a notifier was spawned, false on failure.
|
|
31
31
|
*/
|
|
32
|
-
export function desktopNotify(title, body = '', { spawn: spawnFn = spawn } = {}) {
|
|
32
|
+
export function desktopNotify(title, body = '', { spawn: spawnFn = spawn, platform: platformFn = platform } = {}) {
|
|
33
33
|
try {
|
|
34
|
-
const p =
|
|
34
|
+
const p = platformFn();
|
|
35
35
|
// A missing notifier binary (e.g. no `notify-send`) makes spawn emit an
|
|
36
36
|
// async 'error' event — with no listener that surfaces as an UNCAUGHT
|
|
37
37
|
// exception that the sync try/catch below can't stop, which would crash
|
|
@@ -45,10 +45,17 @@ export function desktopNotify(title, body = '', { spawn: spawnFn = spawn } = {})
|
|
|
45
45
|
const script = `display notification ${JSON.stringify(body)} with title ${JSON.stringify(title)}`;
|
|
46
46
|
swallow(spawnFn('osascript', ['-e', script], { stdio: 'ignore', detached: true }));
|
|
47
47
|
} else if (p === 'win32') {
|
|
48
|
+
// ShowBalloonTip is async — it returns as soon as the toast is queued,
|
|
49
|
+
// not once it's rendered. Without holding the process open, PowerShell
|
|
50
|
+
// reaches end-of-script and exits immediately after, tearing down the
|
|
51
|
+
// NotifyIcon before Windows ever draws the balloon, so it silently
|
|
52
|
+
// never appears. Sleep past the tip's own 5s display window before
|
|
53
|
+
// disposing, so the process outlives what it just asked for.
|
|
48
54
|
const script = `Add-Type -AssemblyName System.Windows.Forms;`
|
|
49
55
|
+ `$n=New-Object System.Windows.Forms.NotifyIcon;`
|
|
50
56
|
+ `$n.Icon=[System.Drawing.SystemIcons]::Information;$n.Visible=$true;`
|
|
51
|
-
+ `$n.ShowBalloonTip(5000, ${JSON.stringify(title)}, ${JSON.stringify(body)}, 'Info')
|
|
57
|
+
+ `$n.ShowBalloonTip(5000, ${JSON.stringify(title)}, ${JSON.stringify(body)}, 'Info');`
|
|
58
|
+
+ `Start-Sleep -Seconds 6;$n.Dispose()`;
|
|
52
59
|
swallow(spawnFn('powershell', ['-NoProfile', '-NonInteractive', '-Command', script], { stdio: 'ignore', detached: true, windowsHide: true }));
|
|
53
60
|
} else {
|
|
54
61
|
swallow(spawnFn('notify-send', ['-a', 'Claude Code', title, body], { stdio: 'ignore', detached: true }));
|
package/src/scanner.js
CHANGED
|
@@ -1,10 +1,11 @@
|
|
|
1
|
-
import { readdirSync, readFileSync, statSync, existsSync, writeFileSync, mkdirSync,
|
|
1
|
+
import { readdirSync, readFileSync, statSync, existsSync, writeFileSync, mkdirSync, openSync, readSync, closeSync, realpathSync } from 'node:fs';
|
|
2
2
|
import { join, dirname, basename } from 'node:path';
|
|
3
3
|
import { homedir } from 'node:os';
|
|
4
4
|
import { CLAUDE_PROJECTS, SCAN_CACHE_PATH, AGGREGATE_PATH, DATA_DIR, EVENTS_LOG_PATH } from './paths.js';
|
|
5
5
|
import { languageOf } from './languages.js';
|
|
6
6
|
import { costFor, pricingKeyFor } from './pricing.js';
|
|
7
7
|
import { classifyShip } from './ships.js';
|
|
8
|
+
import { renameSyncRetry } from './atomic-rename.js';
|
|
8
9
|
|
|
9
10
|
// Bumping this forces a full re-parse on next scan. Increment whenever the
|
|
10
11
|
// per-transcript summary schema changes in a way old caches can't satisfy.
|
|
@@ -783,7 +784,7 @@ function writeCache(cache) {
|
|
|
783
784
|
// rename land a half-written file (or ENOENT the other's rename).
|
|
784
785
|
const tmp = `${SCAN_CACHE_PATH}.${process.pid}.tmp`;
|
|
785
786
|
writeFileSync(tmp, JSON.stringify(cache));
|
|
786
|
-
|
|
787
|
+
renameSyncRetry(tmp, SCAN_CACHE_PATH);
|
|
787
788
|
}
|
|
788
789
|
|
|
789
790
|
// Per-day notification counts come from a hook-side append log, since
|
|
@@ -818,7 +819,7 @@ function writeAggregate(agg) {
|
|
|
818
819
|
ensureDataDir();
|
|
819
820
|
const tmp = `${AGGREGATE_PATH}.${process.pid}.tmp`;
|
|
820
821
|
writeFileSync(tmp, JSON.stringify(agg, null, 2));
|
|
821
|
-
|
|
822
|
+
renameSyncRetry(tmp, AGGREGATE_PATH);
|
|
822
823
|
}
|
|
823
824
|
|
|
824
825
|
export function readAggregate() {
|
package/src/server/sse.js
CHANGED
|
@@ -3,9 +3,10 @@
|
|
|
3
3
|
// Replaces the old 2-second poll. Two debounced fs.watch handles, one
|
|
4
4
|
// shared client set.
|
|
5
5
|
|
|
6
|
-
import { watch } from 'node:fs';
|
|
6
|
+
import { watch, existsSync, statSync } from 'node:fs';
|
|
7
7
|
import { dirname, basename } from 'node:path';
|
|
8
8
|
import { STATE_PATH, AGGREGATE_PATH } from '../paths.js';
|
|
9
|
+
import { pollDecision, pollIntervalMs } from '../watch-poll.js';
|
|
9
10
|
|
|
10
11
|
export const sseClients = new Set();
|
|
11
12
|
|
|
@@ -60,14 +61,51 @@ export function watchFile(filePath, callback) {
|
|
|
60
61
|
}
|
|
61
62
|
}
|
|
62
63
|
|
|
64
|
+
function statMtime(filePath) {
|
|
65
|
+
try {
|
|
66
|
+
return existsSync(filePath) ? statSync(filePath).mtimeMs : undefined;
|
|
67
|
+
} catch {
|
|
68
|
+
return undefined; // mid-rename; a later observation records it
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
|
|
63
72
|
export function watchSources() {
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
+
const targets = [
|
|
74
|
+
{ path: STATE_PATH, type: 'state' },
|
|
75
|
+
{ path: AGGREGATE_PATH, type: 'aggregate' },
|
|
76
|
+
];
|
|
77
|
+
|
|
78
|
+
// Last mtime we've reacted to, per target. Updated by BOTH the watcher and
|
|
79
|
+
// the poll fallback below, so a change one path already handled resolves
|
|
80
|
+
// to a no-op for the other instead of a duplicate broadcast — same shared-
|
|
81
|
+
// baseline trick the daemon's own watchFiles() uses.
|
|
82
|
+
const lastMtime = new Map();
|
|
83
|
+
const debounceTimers = new Map();
|
|
84
|
+
const recordMtime = (t) => {
|
|
85
|
+
const m = statMtime(t.path);
|
|
86
|
+
if (m !== undefined) lastMtime.set(t.path, m);
|
|
87
|
+
};
|
|
88
|
+
targets.forEach(recordMtime); // seed baselines before watching starts
|
|
89
|
+
|
|
90
|
+
const fire = (t) => {
|
|
91
|
+
recordMtime(t); // record before the debounced broadcast so a re-entrant tick can't double-fire
|
|
92
|
+
clearTimeout(debounceTimers.get(t.path));
|
|
93
|
+
debounceTimers.set(t.path, setTimeout(() => broadcast({ type: t.type }), 200));
|
|
94
|
+
};
|
|
95
|
+
|
|
96
|
+
for (const t of targets) watchFile(t.path, () => fire(t));
|
|
97
|
+
|
|
98
|
+
// Mtime-poll fallback. fs.watch drops atomic-rename events on Windows (see
|
|
99
|
+
// watch-poll.js), and unlike the daemon this watcher previously had no
|
|
100
|
+
// backstop at all — a missed event left the dashboard silently stale until
|
|
101
|
+
// some unrelated broadcast happened to fire. Same cadence as the daemon's
|
|
102
|
+
// fallback: fast on Windows, lazy on macOS/Linux.
|
|
103
|
+
setInterval(() => {
|
|
104
|
+
for (const t of targets) {
|
|
105
|
+
const cur = statMtime(t.path);
|
|
106
|
+
const decision = pollDecision(lastMtime.get(t.path), cur);
|
|
107
|
+
if (decision === 'seed') lastMtime.set(t.path, cur);
|
|
108
|
+
else if (decision === 'fire') fire(t);
|
|
109
|
+
}
|
|
110
|
+
}, pollIntervalMs());
|
|
73
111
|
}
|
package/src/state.js
CHANGED
|
@@ -3,7 +3,6 @@ import {
|
|
|
3
3
|
mkdirSync,
|
|
4
4
|
readFileSync,
|
|
5
5
|
writeFileSync,
|
|
6
|
-
renameSync,
|
|
7
6
|
openSync,
|
|
8
7
|
closeSync,
|
|
9
8
|
unlinkSync,
|
|
@@ -14,6 +13,7 @@ import {
|
|
|
14
13
|
import { basename, join } from 'node:path';
|
|
15
14
|
import { STATE_PATH, STATE_DIR } from './paths.js';
|
|
16
15
|
import { pickActiveSession } from './presence.js';
|
|
16
|
+
import { renameSyncRetry } from './atomic-rename.js';
|
|
17
17
|
|
|
18
18
|
const DEFAULT_STATE = {
|
|
19
19
|
sessionStart: null,
|
|
@@ -190,7 +190,7 @@ export function writeState(next, sessionId) {
|
|
|
190
190
|
// atomic-rename guarantee intact even on the best-effort lockless path.
|
|
191
191
|
const tmp = `${path}.${process.pid}.tmp`;
|
|
192
192
|
writeFileSync(tmp, JSON.stringify(next, null, 2));
|
|
193
|
-
|
|
193
|
+
renameSyncRetry(tmp, path);
|
|
194
194
|
}
|
|
195
195
|
|
|
196
196
|
// Best-effort sweep of orphaned per-pid tmp files (`state.json.<pid>.tmp`) left
|