claude-rpc 1.7.4 → 1.9.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +5 -4
- package/SECURITY.md +20 -0
- package/package.json +1 -1
- package/src/cli.js +153 -48
- package/src/commands.js +1 -0
- package/src/community.js +36 -2
- package/src/config-edit.js +59 -0
- package/src/daemon.js +120 -30
- package/src/doctor.js +23 -1
- package/src/ensure-daemon.js +155 -8
- package/src/install.js +19 -2
- package/src/paths.js +9 -0
- package/src/server/assets/dashboard.html +1 -0
- package/src/server/assets/settings.client.js +422 -0
- package/src/server/assets/settings.css +145 -0
- package/src/server/assets/settings.html +176 -0
- package/src/server/index.js +67 -16
- package/src/server/page.js +17 -3
- package/src/server/routes.js +16 -0
- package/src/server/settings.js +227 -0
- package/src/tui.js +3 -2
- package/src/updater.js +29 -6
- package/src/version.js +1 -1
package/src/daemon.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import './safe-stdio.js';
|
|
3
|
-
import { existsSync, unlinkSync, watch, appendFileSync, mkdirSync, statSync, renameSync, readdirSync } from 'node:fs';
|
|
3
|
+
import { existsSync, unlinkSync, watch, appendFileSync, mkdirSync, statSync, renameSync, readdirSync, readFileSync, writeFileSync } from 'node:fs';
|
|
4
4
|
import { basename, dirname, join } from 'node:path';
|
|
5
5
|
import { Client, isBridgeUser } from './discord-ipc.js';
|
|
6
6
|
import { readState, sweepStaleStateTmp, listSessionStates, sweepStaleSessionStates } from './state.js';
|
|
@@ -15,10 +15,10 @@ import { loadConfig } from './config.js';
|
|
|
15
15
|
import { selfHealOnUpdate } from './install.js';
|
|
16
16
|
import { VERSION } from './version.js';
|
|
17
17
|
import { desktopNotify, postWebhook, shouldWebhook, shouldNotify, sanitizeLabel } from './notify.js';
|
|
18
|
-
import { CONFIG_PATH, STATE_PATH, PID_PATH, LOG_PATH, STATE_DIR, AGGREGATE_PATH, PAUSE_PATH } from './paths.js';
|
|
18
|
+
import { CONFIG_PATH, STATE_PATH, PID_PATH, LOG_PATH, STATE_DIR, AGGREGATE_PATH, PAUSE_PATH, DAEMON_INFO_PATH, ROOT, IS_PACKAGED, CANONICAL_EXE } from './paths.js';
|
|
19
19
|
import { readUsageCache, pollUsage } from './usage.js';
|
|
20
20
|
import { pollDecision, pollIntervalMs } from './watch-poll.js';
|
|
21
|
-
import { claimSingleInstance, spawnDaemonDetached } from './ensure-daemon.js';
|
|
21
|
+
import { claimSingleInstance, spawnDaemonDetached, isStopped, readPid, isAlive, readDaemonInfo, writeDaemonInfo, BEAT_EVERY_MS, BEAT_STALE_MS } from './ensure-daemon.js';
|
|
22
22
|
import { checkForUpdate } from './updater.js';
|
|
23
23
|
import { scanInChild } from './scan-worker.js';
|
|
24
24
|
|
|
@@ -69,6 +69,42 @@ process.on('unhandledRejection', (e) => {
|
|
|
69
69
|
try { log('unhandledRejection (continuing):', e?.stack || e?.message || String(e)); } catch { /* see above */ }
|
|
70
70
|
});
|
|
71
71
|
|
|
72
|
+
// Signal handlers go in before the pid-file claim below: a SIGTERM that lands
|
|
73
|
+
// between the claim and a late handler install killed the daemon the default
|
|
74
|
+
// way and stranded its pid file. (shutdown is hoisted; it tolerates the
|
|
75
|
+
// not-yet-initialised IPC client.)
|
|
76
|
+
process.on('SIGINT', shutdown);
|
|
77
|
+
process.on('SIGTERM', shutdown);
|
|
78
|
+
process.on('SIGHUP', shutdown);
|
|
79
|
+
|
|
80
|
+
// `claude-rpc stop` is durable — it holds across sessions and reboots. A login
|
|
81
|
+
// autostart entry (or anything else) that launches us while stopped exits
|
|
82
|
+
// cleanly (code 0, so systemd's Restart=on-failure leaves it be).
|
|
83
|
+
if (isStopped()) {
|
|
84
|
+
log('Stopped by `claude-rpc stop` — not starting. Run `claude-rpc start` to resume.');
|
|
85
|
+
process.exit(0);
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
// Single-instance guard — an ATOMIC claim (see ensure-daemon.claimSingleInstance).
|
|
89
|
+
// Many launchers can fire at once now that the SessionStart hook self-heals the
|
|
90
|
+
// daemon: a manual `start`, a Windows Run entry, and several concurrent sessions'
|
|
91
|
+
// hooks could all spawn a daemon in the same instant. A second daemon would
|
|
92
|
+
// fight over setActivity every ~4s and double-count the additive community
|
|
93
|
+
// total. The exclusive-create claim makes exactly one survive; a live owner →
|
|
94
|
+
// we exit; a stale pid (dead, or recycled with a stale heartbeat) → we reclaim.
|
|
95
|
+
// Claimed BEFORE the update self-heal below so a losing duplicate never
|
|
96
|
+
// re-wires hooks or touches the login autostart.
|
|
97
|
+
const ownerPid = claimSingleInstance();
|
|
98
|
+
if (ownerPid) {
|
|
99
|
+
log(`Another daemon (pid ${ownerPid}) is already running — exiting.`);
|
|
100
|
+
process.exit(0);
|
|
101
|
+
}
|
|
102
|
+
const STARTED_AT = Date.now();
|
|
103
|
+
function beat() {
|
|
104
|
+
writeDaemonInfo({ pid: process.pid, version: VERSION, startedAt: STARTED_AT, beatAt: Date.now() });
|
|
105
|
+
}
|
|
106
|
+
beat();
|
|
107
|
+
|
|
72
108
|
// Wrap loadConfig so a parse/IO failure logs once and the daemon keeps
|
|
73
109
|
// running on baked-in defaults. The Electron settings GUI saves the file
|
|
74
110
|
// atomically but mid-edit hand-edits used to brick the daemon — this is
|
|
@@ -165,20 +201,6 @@ const sessionPathMemo = new Map();
|
|
|
165
201
|
// either case would make startTimestamp jump on every rotation.
|
|
166
202
|
let effectiveSessionStart = null;
|
|
167
203
|
|
|
168
|
-
// Single-instance guard — an ATOMIC claim (see ensure-daemon.claimSingleInstance).
|
|
169
|
-
// Many launchers can fire at once now that the SessionStart hook self-heals the
|
|
170
|
-
// daemon: a manual `start`, a Windows Run entry, and several concurrent sessions'
|
|
171
|
-
// hooks could all spawn a daemon in the same instant. A second daemon would
|
|
172
|
-
// fight over setActivity every ~4s and double-count the additive community
|
|
173
|
-
// total. The old read-then-write guard had a window where two starters both saw
|
|
174
|
-
// "no live owner" and both wrote their pid; the exclusive-create claim closes it
|
|
175
|
-
// so exactly one survives. A live owner → we exit; a stale pid → we reclaim it.
|
|
176
|
-
const ownerPid = claimSingleInstance();
|
|
177
|
-
if (ownerPid) {
|
|
178
|
-
log(`Another daemon (pid ${ownerPid}) is already running — exiting.`);
|
|
179
|
-
process.exit(0);
|
|
180
|
-
}
|
|
181
|
-
|
|
182
204
|
// Reclaim any per-pid state tmp files orphaned by a hard-killed writer, plus
|
|
183
205
|
// per-session state files from sessions that ended long ago. The session-state
|
|
184
206
|
// sweep repeats every 30 min — a daemon runs for weeks, and every file left
|
|
@@ -816,17 +838,85 @@ async function runBackgroundScan({ force = false } = {}) {
|
|
|
816
838
|
|
|
817
839
|
function shutdown() {
|
|
818
840
|
log('Shutting down…');
|
|
819
|
-
//
|
|
820
|
-
//
|
|
821
|
-
//
|
|
822
|
-
|
|
823
|
-
|
|
841
|
+
// Best-effort cleanup on the way out the door. Only remove the pid/info
|
|
842
|
+
// files if they are still OURS: during an update handover the replacement
|
|
843
|
+
// daemon claims the pid file while we wind down, and deleting it blindly
|
|
844
|
+
// orphaned the replacement (`status` said "not running", the next hook
|
|
845
|
+
// spawned a second daemon, and `stop` could only ever kill one of them).
|
|
846
|
+
try { client?.destroy(); } catch { /* IPC already gone (or not created yet) */ }
|
|
847
|
+
try { if (readPid() === process.pid) unlinkSync(PID_PATH); } catch { /* race vs another shutdown */ }
|
|
848
|
+
try { if (readDaemonInfo()?.pid === process.pid) unlinkSync(DAEMON_INFO_PATH); } catch { /* gone */ }
|
|
824
849
|
process.exit(0);
|
|
825
850
|
}
|
|
826
851
|
|
|
827
|
-
|
|
828
|
-
|
|
829
|
-
|
|
852
|
+
// ── Lifecycle watchdog ──────────────────────────────────────────────────────
|
|
853
|
+
// Every BEAT_EVERY_MS: honor a `stop` (any daemon still alive — a duplicate the
|
|
854
|
+
// signal missed, one a launcher started anyway — exits), reconcile the pid file
|
|
855
|
+
// (a tmp cleaner deleting it used to let every SessionStart add one more
|
|
856
|
+
// daemon), refresh the heartbeat, and hand over to new code once an update has
|
|
857
|
+
// replaced the files on disk.
|
|
858
|
+
function onDiskVersion() {
|
|
859
|
+
if (IS_PACKAGED) {
|
|
860
|
+
// The packaged exe can't be read for a version; its file changing under us
|
|
861
|
+
// (setup/the desktop app copying a new build over the canonical exe) is the
|
|
862
|
+
// signal. Only meaningful when we ARE the canonical exe.
|
|
863
|
+
const norm = (x) => (process.platform === 'win32' ? x.toLowerCase() : x);
|
|
864
|
+
if (norm(process.execPath) !== norm(CANONICAL_EXE)) return null;
|
|
865
|
+
try { const st = statSync(CANONICAL_EXE); return `${st.size}:${st.mtimeMs}`; } catch { return null; }
|
|
866
|
+
}
|
|
867
|
+
try { return JSON.parse(readFileSync(join(ROOT, 'package.json'), 'utf8')).version || null; } catch { return null; }
|
|
868
|
+
}
|
|
869
|
+
const BOOT_DISK_VERSION = onDiskVersion();
|
|
870
|
+
let diskChangeSeen = null; // needs two consecutive sightings — npm may be mid-extract
|
|
871
|
+
let handingOver = false;
|
|
872
|
+
let handoverBlockedUntil = 0;
|
|
873
|
+
|
|
874
|
+
// Spawn a fresh daemon from whatever is on disk and exit once it has claimed
|
|
875
|
+
// the pid file. If it never comes up, keep running (better old code than none)
|
|
876
|
+
// and don't try again for an hour.
|
|
877
|
+
function handOver(reason) {
|
|
878
|
+
if (handingOver || Date.now() < handoverBlockedUntil) return;
|
|
879
|
+
handingOver = true;
|
|
880
|
+
log(`${reason} — handing over to a fresh daemon`);
|
|
881
|
+
try { if (readPid() === process.pid) unlinkSync(PID_PATH); } catch { /* gone */ }
|
|
882
|
+
spawnDaemonDetached();
|
|
883
|
+
const deadline = Date.now() + 8000;
|
|
884
|
+
const poll = setInterval(() => {
|
|
885
|
+
const cur = readPid();
|
|
886
|
+
if (cur && cur !== process.pid && isAlive(cur)) { clearInterval(poll); shutdown(); return; }
|
|
887
|
+
if (Date.now() < deadline) return;
|
|
888
|
+
clearInterval(poll);
|
|
889
|
+
log('Handover failed: the new daemon never came up — staying on this one');
|
|
890
|
+
try { writeFileSync(PID_PATH, String(process.pid)); } catch { /* unwritable */ }
|
|
891
|
+
handingOver = false;
|
|
892
|
+
handoverBlockedUntil = Date.now() + 60 * 60_000;
|
|
893
|
+
}, 250);
|
|
894
|
+
}
|
|
895
|
+
|
|
896
|
+
function lifecycleTick() {
|
|
897
|
+
if (handingOver) return;
|
|
898
|
+
if (isStopped()) { log('Stop requested (`claude-rpc stop`)'); shutdown(); return; }
|
|
899
|
+
const cur = readPid();
|
|
900
|
+
if (cur !== process.pid) {
|
|
901
|
+
const info = readDaemonInfo();
|
|
902
|
+
if (cur && isAlive(cur) && info?.pid === cur && Date.now() - (info.beatAt || 0) < BEAT_STALE_MS) {
|
|
903
|
+
log(`Another daemon (pid ${cur}) owns the pid file — exiting as a duplicate`);
|
|
904
|
+
try { client?.destroy(); } catch { /* gone */ }
|
|
905
|
+
process.exit(0);
|
|
906
|
+
}
|
|
907
|
+
try { writeFileSync(PID_PATH, String(process.pid)); log(`Pid file ${cur ? `named pid ${cur}` : 'was missing'} — restored`); }
|
|
908
|
+
catch { /* unwritable — run lockless */ }
|
|
909
|
+
}
|
|
910
|
+
beat();
|
|
911
|
+
const disk = onDiskVersion();
|
|
912
|
+
if (disk && BOOT_DISK_VERSION && disk !== BOOT_DISK_VERSION) {
|
|
913
|
+
if (diskChangeSeen === disk) handOver(`Update on disk (${IS_PACKAGED ? 'new exe' : `${VERSION} → ${disk}`})`);
|
|
914
|
+
diskChangeSeen = disk;
|
|
915
|
+
} else {
|
|
916
|
+
diskChangeSeen = null;
|
|
917
|
+
}
|
|
918
|
+
}
|
|
919
|
+
setInterval(lifecycleTick, BEAT_EVERY_MS);
|
|
830
920
|
|
|
831
921
|
log('Claude RPC daemon starting. clientId=', config.clientId);
|
|
832
922
|
if (!config.clientId || config.clientId === '1234567890123456789') {
|
|
@@ -949,7 +1039,7 @@ async function runCommunityFlush() {
|
|
|
949
1039
|
// independent of community totals but reuses the same anonymous instanceId.
|
|
950
1040
|
if (!config.community?.enabled && !config.profile?.enabled) return;
|
|
951
1041
|
try {
|
|
952
|
-
const { flushCommunity, flushProfile } = await import('./community.js');
|
|
1042
|
+
const { flushCommunity, flushProfile, recordProfileResult } = await import('./community.js');
|
|
953
1043
|
if (config.community?.enabled) {
|
|
954
1044
|
const result = await flushCommunity(config);
|
|
955
1045
|
if (result.ok && result.delta) {
|
|
@@ -960,6 +1050,7 @@ async function runCommunityFlush() {
|
|
|
960
1050
|
}
|
|
961
1051
|
if (config.profile?.enabled) {
|
|
962
1052
|
const pr = await flushProfile(config);
|
|
1053
|
+
recordProfileResult(pr);
|
|
963
1054
|
if (pr.ok && pr.totals) {
|
|
964
1055
|
log(`profile: published @${config.profile.handle} (${pr.totals.tokens} tokens)`);
|
|
965
1056
|
} else if (!pr.ok && pr.reason !== 'rate-limited' && pr.reason !== 'disabled') {
|
|
@@ -988,10 +1079,9 @@ async function runUpdateCheck() {
|
|
|
988
1079
|
try {
|
|
989
1080
|
const r = await checkForUpdate({ current: VERSION, auto: config.update?.auto !== false });
|
|
990
1081
|
if (r.installed) {
|
|
991
|
-
|
|
992
|
-
|
|
993
|
-
|
|
994
|
-
setTimeout(shutdown, 500);
|
|
1082
|
+
handOver(`auto-update: ${VERSION} → ${r.latest} installed`);
|
|
1083
|
+
} else if (r.plan.reason === 'registry unreachable') {
|
|
1084
|
+
log('auto-update: could not reach the npm registry — will retry');
|
|
995
1085
|
} else if (r.error) {
|
|
996
1086
|
log(`auto-update: install of ${r.latest} failed: ${String(r.error).slice(-200)}`);
|
|
997
1087
|
} else if (r.plan.action === 'notify') {
|
package/src/doctor.js
CHANGED
|
@@ -17,8 +17,9 @@ import {
|
|
|
17
17
|
} from './paths.js';
|
|
18
18
|
import { findLiveSessions } from './scanner.js';
|
|
19
19
|
import { listSessionStates, readActiveState } from './state.js';
|
|
20
|
-
import { isAlive } from './ensure-daemon.js';
|
|
20
|
+
import { isAlive, isStopped, readDaemonInfo, BEAT_STALE_MS } from './ensure-daemon.js';
|
|
21
21
|
import { detectGithubUrl } from './git.js';
|
|
22
|
+
import { VERSION } from './version.js';
|
|
22
23
|
import { resolveVisibility, listPrivateCwds, detectGithubPrivate } from './privacy.js';
|
|
23
24
|
import { readClaudeCredentials, readUsageCache } from './usage.js';
|
|
24
25
|
import { EVENTS as HOOK_EVENTS, isOurHook } from './install.js';
|
|
@@ -295,6 +296,11 @@ function checkCliOnPath() {
|
|
|
295
296
|
}
|
|
296
297
|
|
|
297
298
|
function checkDaemon() {
|
|
299
|
+
if (isStopped()) {
|
|
300
|
+
// A deliberate `claude-rpc stop` is not a fault; --fix leaves it alone.
|
|
301
|
+
check('daemon running', 'warn', 'stopped (you ran `claude-rpc stop`)', 'run `claude-rpc start` to resume');
|
|
302
|
+
return false;
|
|
303
|
+
}
|
|
298
304
|
if (!existsSync(PID_PATH)) {
|
|
299
305
|
check('daemon running', 'warn', 'no pid file',
|
|
300
306
|
'run `claude-rpc start` to launch the daemon', 'daemon');
|
|
@@ -306,6 +312,22 @@ function checkDaemon() {
|
|
|
306
312
|
'run `claude-rpc start` — old daemon died without cleaning up', 'daemon');
|
|
307
313
|
return false;
|
|
308
314
|
}
|
|
315
|
+
const info = readDaemonInfo();
|
|
316
|
+
if (info && info.pid === pid && Date.now() - (info.beatAt || 0) > BEAT_STALE_MS) {
|
|
317
|
+
check('daemon running', 'fail', `pid ${pid} is alive but the daemon's heartbeat stopped — a recycled pid or a wedged daemon`,
|
|
318
|
+
'run `claude-rpc restart`', 'daemon');
|
|
319
|
+
return false;
|
|
320
|
+
}
|
|
321
|
+
if (!info || info.pid !== pid) {
|
|
322
|
+
check('daemon running', 'warn', `pid ${pid} — started by an older claude-rpc, still running its code`,
|
|
323
|
+
'run `claude-rpc restart` to run this version', 'daemon');
|
|
324
|
+
return true;
|
|
325
|
+
}
|
|
326
|
+
if (info.version !== VERSION) {
|
|
327
|
+
check('daemon running', 'warn', `pid ${pid} is running v${info.version}, installed is v${VERSION}`,
|
|
328
|
+
'run `claude-rpc restart` to run this version', 'daemon');
|
|
329
|
+
return true;
|
|
330
|
+
}
|
|
309
331
|
check('daemon running', 'pass', `pid ${pid}`);
|
|
310
332
|
return true;
|
|
311
333
|
}
|
package/src/ensure-daemon.js
CHANGED
|
@@ -12,8 +12,12 @@
|
|
|
12
12
|
// daemon survives.
|
|
13
13
|
|
|
14
14
|
import { createRequire } from 'node:module';
|
|
15
|
-
import { join } from 'node:path';
|
|
16
|
-
import {
|
|
15
|
+
import { dirname, join } from 'node:path';
|
|
16
|
+
import {
|
|
17
|
+
PID_PATH, STATE_DIR, DAEMON_SCRIPT, CANONICAL_EXE, IS_PACKAGED, DAEMON_INFO_PATH, STOPPED_PATH,
|
|
18
|
+
} from './paths.js';
|
|
19
|
+
import { renameSyncRetry, sleepSync } from './atomic-rename.js';
|
|
20
|
+
import { VERSION } from './version.js';
|
|
17
21
|
|
|
18
22
|
// require()d, not imported — on the hook hot path; see hook.js.
|
|
19
23
|
const require = createRequire(import.meta.url);
|
|
@@ -21,6 +25,17 @@ const {
|
|
|
21
25
|
openSync, closeSync, writeFileSync, readFileSync, unlinkSync, existsSync, statSync, mkdirSync,
|
|
22
26
|
} = require('node:fs');
|
|
23
27
|
|
|
28
|
+
// The daemon rewrites its heartbeat (DAEMON_INFO_PATH.beatAt) this often (its
|
|
29
|
+
// lifecycle watchdog tick); a
|
|
30
|
+
// beat older than BEAT_STALE_MS means the pid in the pid file is not our daemon
|
|
31
|
+
// any more (it died without cleanup and the OS recycled the pid — common after a
|
|
32
|
+
// Windows/macOS reboot, where the tmp dir and its stale pid file survive) or the
|
|
33
|
+
// daemon is wedged. Generous on purpose: a laptop waking from sleep shows a stale
|
|
34
|
+
// beat for up to one interval, and the cost of a false "dead" is one duplicate
|
|
35
|
+
// spawn that the daemons' own pid-file check reaps within a watchdog tick.
|
|
36
|
+
export const BEAT_EVERY_MS = 30_000;
|
|
37
|
+
export const BEAT_STALE_MS = 5 * 60_000;
|
|
38
|
+
|
|
24
39
|
// mtime of this marker = last time any launcher attempted a spawn. A short
|
|
25
40
|
// cooldown stops concurrent SessionStart hooks (several sessions opening at
|
|
26
41
|
// once) and any startup crash-loop from spawning a swarm of throwaway daemons —
|
|
@@ -42,10 +57,91 @@ export function readPid(pidPath = PID_PATH) {
|
|
|
42
57
|
catch { return 0; }
|
|
43
58
|
}
|
|
44
59
|
|
|
60
|
+
// { pid, version, startedAt, beatAt } written by daemons from 1.9.0 on, or null
|
|
61
|
+
// (missing, unreadable, or an older daemon that never wrote one).
|
|
62
|
+
export function readDaemonInfo(infoPath = DAEMON_INFO_PATH) {
|
|
63
|
+
try {
|
|
64
|
+
const j = JSON.parse(readFileSync(infoPath, 'utf8'));
|
|
65
|
+
return j && typeof j === 'object' && Number.isFinite(j.pid) ? j : null;
|
|
66
|
+
} catch { return null; }
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
export function writeDaemonInfo(info, infoPath = DAEMON_INFO_PATH) {
|
|
70
|
+
try {
|
|
71
|
+
mkdirSync(dirname(infoPath), { recursive: true });
|
|
72
|
+
const tmp = `${infoPath}.${process.pid}.tmp`;
|
|
73
|
+
writeFileSync(tmp, JSON.stringify(info));
|
|
74
|
+
renameSyncRetry(tmp, infoPath);
|
|
75
|
+
} catch { /* advisory — liveness falls back to the bare pid probe */ }
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
// Pure: is `pid` our live daemon? A live pid is only trusted when the heartbeat
|
|
79
|
+
// written for THAT pid is fresh; with no heartbeat for it (a pre-1.9 daemon, or
|
|
80
|
+
// the info file belongs to someone else) the bare probe is all we have.
|
|
81
|
+
export function pidIsDaemon(pid, { info = null, alive = isAlive, now = Date.now(), staleMs = BEAT_STALE_MS } = {}) {
|
|
82
|
+
if (!pid || !alive(pid)) return false;
|
|
83
|
+
if (info && info.pid === pid && Number.isFinite(info.beatAt) && now - info.beatAt > staleMs) return false;
|
|
84
|
+
return true;
|
|
85
|
+
}
|
|
86
|
+
|
|
45
87
|
// The pid of the live daemon, or 0 if none is running.
|
|
46
|
-
export function daemonAlive(pidPath = PID_PATH) {
|
|
88
|
+
export function daemonAlive(pidPath = PID_PATH, infoPath = DAEMON_INFO_PATH) {
|
|
47
89
|
const pid = readPid(pidPath);
|
|
48
|
-
return pid
|
|
90
|
+
return pidIsDaemon(pid, { info: pid ? readDaemonInfo(infoPath) : null }) ? pid : 0;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
// ── stop intent ──────────────────────────────────────────────────────────
|
|
94
|
+
// `stop` used to send one signal and record nothing, so the very next
|
|
95
|
+
// SessionStart hook (any new session, /clear, a `claude -p` run) spawned the
|
|
96
|
+
// daemon right back. The marker makes a stop stick: the hook, the login
|
|
97
|
+
// autostart (the daemon checks it at boot) and running daemons (their watchdog
|
|
98
|
+
// checks it) all honor it until start/restart/setup clears it.
|
|
99
|
+
export function isStopped(path = STOPPED_PATH) {
|
|
100
|
+
return existsSync(path);
|
|
101
|
+
}
|
|
102
|
+
export function markStopped(path = STOPPED_PATH) {
|
|
103
|
+
try { mkdirSync(dirname(path), { recursive: true }); writeFileSync(path, String(Date.now())); return true; }
|
|
104
|
+
catch { return false; }
|
|
105
|
+
}
|
|
106
|
+
export function clearStopped(path = STOPPED_PATH) {
|
|
107
|
+
try { if (existsSync(path)) unlinkSync(path); } catch { /* best-effort */ }
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
// Stop the daemon and wait until it is really gone. SIGTERM, then SIGKILL if it
|
|
111
|
+
// ignored that for `graceMs` (on Windows process.kill is always a hard kill).
|
|
112
|
+
// A hard kill skips the daemon's own cleanup, so a pid file still naming the
|
|
113
|
+
// dead pid is removed here — otherwise a recycled pid reads as "running".
|
|
114
|
+
// Resolves true when no daemon is left. `kill`/`sleep` are injectable for tests.
|
|
115
|
+
export async function stopDaemonAndWait({
|
|
116
|
+
pidPath = PID_PATH, infoPath = DAEMON_INFO_PATH, graceMs = 3000, killMs = 1500,
|
|
117
|
+
kill = (pid, sig) => process.kill(pid, sig), sleep = (ms) => new Promise((r) => setTimeout(r, ms)),
|
|
118
|
+
} = {}) {
|
|
119
|
+
const pid = daemonAlive(pidPath, infoPath);
|
|
120
|
+
if (!pid) { cleanupPidFile(0, pidPath); return true; }
|
|
121
|
+
const gone = async (ms) => {
|
|
122
|
+
const deadline = Date.now() + ms;
|
|
123
|
+
for (;;) {
|
|
124
|
+
if (!isAlive(pid)) return true;
|
|
125
|
+
if (Date.now() >= deadline) return false;
|
|
126
|
+
await sleep(50);
|
|
127
|
+
}
|
|
128
|
+
};
|
|
129
|
+
try { kill(pid, 'SIGTERM'); } catch { /* already gone / not ours */ }
|
|
130
|
+
let ok = await gone(graceMs);
|
|
131
|
+
if (!ok) {
|
|
132
|
+
try { kill(pid, 'SIGKILL'); } catch { /* already gone */ }
|
|
133
|
+
ok = await gone(killMs);
|
|
134
|
+
}
|
|
135
|
+
if (ok) cleanupPidFile(pid, pidPath);
|
|
136
|
+
return ok;
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
// Remove the pid file if it still names `pid` (or a dead process when pid=0).
|
|
140
|
+
function cleanupPidFile(pid, pidPath = PID_PATH) {
|
|
141
|
+
try {
|
|
142
|
+
const cur = readPid(pidPath);
|
|
143
|
+
if (cur && (cur === pid || (!pid && !isAlive(cur)))) unlinkSync(pidPath);
|
|
144
|
+
} catch { /* gone already */ }
|
|
49
145
|
}
|
|
50
146
|
|
|
51
147
|
// The single source of truth for HOW to launch the daemon, shared by every
|
|
@@ -79,8 +175,9 @@ export function spawnDaemonDetached() {
|
|
|
79
175
|
|
|
80
176
|
// Pure decision for the hook's self-heal: should THIS SessionStart spawn a
|
|
81
177
|
// daemon? Separated from the side effects so it's unit-testable.
|
|
82
|
-
export function shouldSpawnDaemon({ autostart, daemonPid, lastAttemptMs, now, cooldownMs }) {
|
|
178
|
+
export function shouldSpawnDaemon({ autostart, stopped = false, daemonPid, lastAttemptMs, now, cooldownMs }) {
|
|
83
179
|
if (autostart === false) return false; // explicit opt-out
|
|
180
|
+
if (stopped) return false; // `claude-rpc stop` sticks
|
|
84
181
|
if (daemonPid) return false; // already running
|
|
85
182
|
if (lastAttemptMs && now - lastAttemptMs < cooldownMs) return false; // within the cooldown
|
|
86
183
|
return true;
|
|
@@ -94,10 +191,60 @@ export function shouldSpawnDaemon({ autostart, daemonPid, lastAttemptMs, now, co
|
|
|
94
191
|
export function ensureDaemonRunning({ autostart = true, now = Date.now(), cooldownMs = SPAWN_COOLDOWN_MS } = {}) {
|
|
95
192
|
let lastAttemptMs = 0;
|
|
96
193
|
try { if (existsSync(SPAWN_MARKER)) lastAttemptMs = statSync(SPAWN_MARKER).mtimeMs; } catch { /* unreadable — treat as never */ }
|
|
97
|
-
|
|
194
|
+
const stopped = isStopped();
|
|
195
|
+
let daemonPid = daemonAlive();
|
|
196
|
+
// An update swaps the files on disk but the running daemon keeps executing
|
|
197
|
+
// the old code — forever, since nothing restarted it (`npm i -g`, the
|
|
198
|
+
// desktop app's updater, a re-downloaded exe). The hook is the newer code, so
|
|
199
|
+
// it replaces a daemon that is older than itself (or too old to say).
|
|
200
|
+
if (daemonPid && autostart !== false && !stopped
|
|
201
|
+
&& shouldReplaceDaemon({ info: readDaemonInfo(), pid: daemonPid, version: VERSION, lastAttemptMs, now })) {
|
|
202
|
+
stampSpawn(now);
|
|
203
|
+
if (!replaceDaemonSync(daemonPid)) return null;
|
|
204
|
+
daemonPid = 0;
|
|
205
|
+
lastAttemptMs = 0;
|
|
206
|
+
}
|
|
207
|
+
if (!shouldSpawnDaemon({ autostart, stopped, daemonPid, lastAttemptMs, now, cooldownMs })) return null;
|
|
208
|
+
stampSpawn(now);
|
|
209
|
+
return spawnDaemonDetached();
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
function stampSpawn(now) {
|
|
98
213
|
try { mkdirSync(STATE_DIR, { recursive: true }); } catch { /* exists / unwritable */ }
|
|
99
214
|
try { writeFileSync(SPAWN_MARKER, String(now)); } catch { /* best-effort cooldown */ }
|
|
100
|
-
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
// Pure: should a launcher at `version` replace the running daemon? Yes when the
|
|
218
|
+
// daemon reports an older version, or reports nothing (pre-1.9 daemons never
|
|
219
|
+
// wrote daemon.json). The no-info case is rate-limited to one attempt per
|
|
220
|
+
// REPLACE_COOLDOWN_MS so an unwritable tmp dir can't restart it every session.
|
|
221
|
+
const REPLACE_COOLDOWN_MS = 30 * 60_000;
|
|
222
|
+
export function shouldReplaceDaemon({ info, pid, version, lastAttemptMs = 0, now = Date.now(), cooldownMs = REPLACE_COOLDOWN_MS }) {
|
|
223
|
+
if (info && info.pid === pid) return typeof info.version === 'string' && isNewerVersion(version, info.version);
|
|
224
|
+
return !(lastAttemptMs && now - lastAttemptMs < cooldownMs);
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
export function isNewerVersion(a, b) {
|
|
228
|
+
const p = (v) => (/^(\d+)\.(\d+)\.(\d+)/.exec(String(v || '')) || []).slice(1).map(Number);
|
|
229
|
+
const x = p(a), y = p(b);
|
|
230
|
+
if (x.length !== 3 || y.length !== 3) return false;
|
|
231
|
+
for (let i = 0; i < 3; i++) if (x[i] !== y[i]) return x[i] > y[i];
|
|
232
|
+
return false;
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
// Synchronous stop for the hook (it can't await): SIGTERM, wait ≤2s for the
|
|
236
|
+
// process to go, hard-kill if it didn't. True once it's gone.
|
|
237
|
+
function replaceDaemonSync(pid) {
|
|
238
|
+
const waitGone = (ms) => {
|
|
239
|
+
const deadline = Date.now() + ms;
|
|
240
|
+
while (Date.now() < deadline) { if (!isAlive(pid)) return true; sleepSync(50); }
|
|
241
|
+
return !isAlive(pid);
|
|
242
|
+
};
|
|
243
|
+
try { process.kill(pid, 'SIGTERM'); } catch { /* gone */ }
|
|
244
|
+
let gone = waitGone(2000);
|
|
245
|
+
if (!gone) { try { process.kill(pid, 'SIGKILL'); } catch { /* gone */ } gone = waitGone(1000); }
|
|
246
|
+
if (gone) cleanupPidFile(pid);
|
|
247
|
+
return gone;
|
|
101
248
|
}
|
|
102
249
|
|
|
103
250
|
// Atomic single-instance claim, called once by the daemon at startup. Returns
|
|
@@ -107,7 +254,7 @@ export function ensureDaemonRunning({ autostart = true, now = Date.now(), cooldo
|
|
|
107
254
|
// losers read the winner's live pid and step aside. A stale file (dead owner,
|
|
108
255
|
// empty, or our own recycled pid) is reclaimed and the create retried — so a
|
|
109
256
|
// crashed daemon never blocks its successor.
|
|
110
|
-
export function claimSingleInstance({ pidPath = PID_PATH, pid = process.pid, alive =
|
|
257
|
+
export function claimSingleInstance({ pidPath = PID_PATH, pid = process.pid, alive = (p) => pidIsDaemon(p, { info: readDaemonInfo() }) } = {}) {
|
|
111
258
|
for (let attempt = 0; attempt < 4; attempt++) {
|
|
112
259
|
let fd;
|
|
113
260
|
try {
|
package/src/install.js
CHANGED
|
@@ -930,8 +930,13 @@ export async function install({ exePath } = {}) {
|
|
|
930
930
|
// Cross-platform login autostart: Windows Run-key, macOS LaunchAgent, Linux
|
|
931
931
|
// systemd --user. Best-effort — a failure leaves the SessionStart self-heal
|
|
932
932
|
// as the (already reliable) fallback, so setup never fails on this.
|
|
933
|
-
|
|
934
|
-
|
|
933
|
+
// autostart:false opts out of login autostart everywhere — setup, doctor
|
|
934
|
+
// --fix and the desktop app's post-update setup used to re-enable it.
|
|
935
|
+
if (readJson(CONFIG_PATH, {}).autostart === false) noop('login autostart off (autostart:false)');
|
|
936
|
+
else {
|
|
937
|
+
try { await addStartupEntry(target); }
|
|
938
|
+
catch (e) { step(SYM_WARN, 'startup entry', `failed: ${e.message} — session self-heal still covers it`, console.warn); }
|
|
939
|
+
}
|
|
935
940
|
const cli = IS_PACKAGED ? await putCliOnPath(target) : { cmd: 'claude-rpc', newTerminal: false };
|
|
936
941
|
// Nothing changed: the checklist above stayed silent, so say so in one line.
|
|
937
942
|
if (!runDirty && probe.ok) {
|
|
@@ -983,6 +988,18 @@ export async function uninstall() {
|
|
|
983
988
|
console.log('');
|
|
984
989
|
console.log(` ${c.bold}${c.magenta}◆ claude-rpc uninstall${c.reset}`);
|
|
985
990
|
console.log('');
|
|
991
|
+
// Stop the daemon FIRST and leave the stop marker: a surviving daemon kept
|
|
992
|
+
// running after uninstall, and its update self-heal re-added the hooks and
|
|
993
|
+
// the login autostart (and its auto-updater could reinstall the package).
|
|
994
|
+
// The marker also stops any straggler at its next watchdog tick; `setup`
|
|
995
|
+
// clears it on a reinstall.
|
|
996
|
+
{
|
|
997
|
+
const { markStopped, stopDaemonAndWait } = await import('./ensure-daemon.js');
|
|
998
|
+
markStopped();
|
|
999
|
+
if (await stopDaemonAndWait()) step(SYM_OK, 'daemon', 'stopped');
|
|
1000
|
+
else step(SYM_WARN, 'daemon', 'still running — it exits on its own within 30s', console.warn);
|
|
1001
|
+
try { if (existsSync(VERSION_STAMP)) unlinkSync(VERSION_STAMP); } catch { /* best-effort */ }
|
|
1002
|
+
}
|
|
986
1003
|
uninstallHooks();
|
|
987
1004
|
await removeStartupEntry();
|
|
988
1005
|
const { removeCliFromPath } = await import('./cli-path.js');
|
package/src/paths.js
CHANGED
|
@@ -81,6 +81,11 @@ export const STATE_DIR = join(tmpdir(), 'claude-rpc');
|
|
|
81
81
|
export const STATE_PATH = join(STATE_DIR, 'state.json');
|
|
82
82
|
export const PID_PATH = join(STATE_DIR, 'daemon.pid');
|
|
83
83
|
export const LOG_PATH = join(STATE_DIR, 'daemon.log');
|
|
84
|
+
// The running daemon's identity + heartbeat ({ pid, version, startedAt, beatAt }).
|
|
85
|
+
// The pid file alone can't tell a live daemon from a recycled pid after a
|
|
86
|
+
// reboot or crash (Windows/macOS keep the tmp dir across reboots) — the
|
|
87
|
+
// heartbeat can. See ensure-daemon.daemonAlive.
|
|
88
|
+
export const DAEMON_INFO_PATH = join(STATE_DIR, 'daemon.json');
|
|
84
89
|
// Presence snooze marker (`claude-rpc pause`). Lives in the tmp state dir on
|
|
85
90
|
// purpose — a reboot clearing a forgotten pause is the right failure mode.
|
|
86
91
|
export const PAUSE_PATH = join(STATE_DIR, 'pause.json');
|
|
@@ -95,6 +100,10 @@ export const EVENTS_LOG_PATH = join(DATA_DIR, 'events.jsonl');
|
|
|
95
100
|
// migrate). Persistent (under ~/.claude-rpc) so an update is detected across
|
|
96
101
|
// reboots — see install.selfHealOnUpdate.
|
|
97
102
|
export const VERSION_STAMP = join(DATA_DIR, 'version');
|
|
103
|
+
// `claude-rpc stop` marker. Persistent on purpose: a stopped daemon stays
|
|
104
|
+
// stopped across sessions AND reboots until `start`/`restart`/`setup`. Every
|
|
105
|
+
// launcher (hook self-heal, login autostart, the daemon's own boot) honors it.
|
|
106
|
+
export const STOPPED_PATH = join(DATA_DIR, 'stopped');
|
|
98
107
|
export const CLAUDE_HOME = join(homedir(), '.claude');
|
|
99
108
|
export const CLAUDE_PROJECTS = join(CLAUDE_HOME, 'projects');
|
|
100
109
|
export const CLAUDE_SETTINGS = join(CLAUDE_HOME, 'settings.json');
|
|
@@ -28,6 +28,7 @@
|
|
|
28
28
|
<button data-range="all">All</button>
|
|
29
29
|
</div>
|
|
30
30
|
<a class="wrapped-link" href="/wrapped" title="Your animated year-in-review">✦ Wrapped</a>
|
|
31
|
+
<a class="wrapped-link" href="/settings" title="Card, daemon and privacy settings">Settings</a>
|
|
31
32
|
<span class="model" id="model">—</span>
|
|
32
33
|
<span class="status"><span id="statustext">—</span></span>
|
|
33
34
|
</div>
|