claude-rpc 1.8.0 → 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/package.json +1 -1
- package/src/cli.js +150 -47
- package/src/community.js +36 -2
- 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/settings.js +9 -16
- package/src/tui.js +3 -2
- package/src/updater.js +29 -6
- package/src/version.js +1 -1
package/package.json
CHANGED
package/src/cli.js
CHANGED
|
@@ -5,7 +5,7 @@ import './safe-stdio.js';
|
|
|
5
5
|
import { readFileSync, writeFileSync, existsSync, watchFile, unlinkSync } from 'node:fs';
|
|
6
6
|
import process from 'node:process';
|
|
7
7
|
import { basename, join } from 'node:path';
|
|
8
|
-
import { DAEMON_SCRIPT, STATE_PATH, STATE_DIR, LOG_PATH, AGGREGATE_PATH, CONFIG_PATH, USER_CONFIG_DIR, IS_PACKAGED, IS_NPX, EXE_PATH } from './paths.js';
|
|
8
|
+
import { DAEMON_SCRIPT, STATE_PATH, STATE_DIR, LOG_PATH, AGGREGATE_PATH, CONFIG_PATH, USER_CONFIG_DIR, IS_PACKAGED, IS_NPX, EXE_PATH, ROOT } from './paths.js';
|
|
9
9
|
import { VERSION } from './version.js';
|
|
10
10
|
import { c, fail, tailLines, heat, sparkline, fmtDelta, topPercentile, EX_USER_ERROR, EX_BAD_STATE, EX_SYS_ERROR } from './ui.js';
|
|
11
11
|
import * as lb from './leaderboard.js';
|
|
@@ -21,13 +21,14 @@ import { writeFileAtomic } from './atomic-rename.js';
|
|
|
21
21
|
// node:crypto, node:readline, node:child_process) are imported inside that
|
|
22
22
|
// command's handler, like doctor.js/card.js/mcp.js always were.
|
|
23
23
|
let readActiveState, statePathFor, loadConfig, hasUserConfig, spawnDaemonDetached, daemonAlive;
|
|
24
|
+
let stopDaemonAndWait, markStopped, clearStopped, isStopped, readDaemonInfo, shouldReplaceDaemon;
|
|
24
25
|
let buildVars, fillTemplate, humanProject, humanTool, applyIdle, framePasses, fmtNum, fmtHours;
|
|
25
26
|
let scan, readAggregate, findLiveSessions, dayKey, weekKey;
|
|
26
27
|
let fmtCost;
|
|
27
28
|
let readUsageCache, fetchUsage, writeUsageCache, fmtResetTime, fmtResetDay;
|
|
28
29
|
|
|
29
30
|
async function loadDaemonCtl() {
|
|
30
|
-
({ spawnDaemonDetached, daemonAlive } = await import('./ensure-daemon.js'));
|
|
31
|
+
({ spawnDaemonDetached, daemonAlive, stopDaemonAndWait, markStopped, clearStopped, isStopped, readDaemonInfo, shouldReplaceDaemon } = await import('./ensure-daemon.js'));
|
|
31
32
|
}
|
|
32
33
|
|
|
33
34
|
// Idempotent — repeat imports resolve from the module cache.
|
|
@@ -91,7 +92,19 @@ function splitEqArgs(argv) {
|
|
|
91
92
|
return out;
|
|
92
93
|
}
|
|
93
94
|
|
|
95
|
+
// " · v1.8.0 (update installed — restarting)" when the running daemon is not
|
|
96
|
+
// this copy's version, so a stale daemon is visible instead of silent.
|
|
97
|
+
function daemonVersionNote(pid) {
|
|
98
|
+
const info = readDaemonInfo();
|
|
99
|
+
if (!info || info.pid !== pid) return `${c.dim} · version unknown (pre-1.9 daemon — claude-rpc restart)${c.reset}`;
|
|
100
|
+
if (info.version === VERSION) return '';
|
|
101
|
+
return `${c.yellow} · running v${info.version}, installed v${VERSION} — claude-rpc restart${c.reset}`;
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
// An explicit start always clears a previous `stop` (the marker every launcher
|
|
105
|
+
// honors), so `start` after `stop` behaves the way it reads.
|
|
94
106
|
function startDaemon({ quiet = false } = {}) {
|
|
107
|
+
clearStopped();
|
|
95
108
|
const pid = daemonAlive();
|
|
96
109
|
if (pid) {
|
|
97
110
|
if (!quiet) console.log(` ${c.yellow}!${c.reset} ${'daemon running'.padEnd(16)}${c.dim}already up (pid ${pid}) · bounce it with ${c.reset}${c.cyan}claude-rpc restart${c.reset}`);
|
|
@@ -130,41 +143,40 @@ async function confirmDaemonUp({ timeoutMs = 3000, intervalMs = 100 } = {}) {
|
|
|
130
143
|
}
|
|
131
144
|
}
|
|
132
145
|
|
|
133
|
-
|
|
146
|
+
// `stop` is durable: the marker keeps the SessionStart hook, the login
|
|
147
|
+
// autostart and any straggler daemon from bringing it back until `start`.
|
|
148
|
+
// Waits for the process to actually exit (hard-kill after 3s) instead of
|
|
149
|
+
// reporting success for a signal that may not have landed.
|
|
150
|
+
async function stopDaemon({ quiet = false } = {}) {
|
|
151
|
+
markStopped();
|
|
134
152
|
const pid = daemonAlive();
|
|
135
|
-
if (!pid) {
|
|
136
|
-
|
|
137
|
-
process.kill(pid, 'SIGTERM');
|
|
138
|
-
if (!quiet) console.log(` ${c.green}✓${c.reset} ${'daemon stopping'.padEnd(16)}${c.dim}sent SIGTERM to pid ${pid}${c.reset}`);
|
|
153
|
+
if (!pid) {
|
|
154
|
+
if (!quiet) console.log(` ${c.cyan}·${c.reset} ${'daemon stopped'.padEnd(16)}${c.dim}wasn't running · stays off until ${c.reset}${c.cyan}claude-rpc start${c.reset}`);
|
|
139
155
|
return true;
|
|
140
|
-
} catch (e) {
|
|
141
|
-
if (!quiet) console.log(` ${c.red}✗${c.reset} ${'stop failed'.padEnd(16)}${c.dim}${e.message}${c.reset}`);
|
|
142
|
-
return false;
|
|
143
156
|
}
|
|
157
|
+
const ok = await stopDaemonAndWait();
|
|
158
|
+
if (quiet) return ok;
|
|
159
|
+
if (ok) console.log(` ${c.green}✓${c.reset} ${'daemon stopped'.padEnd(16)}${c.dim}pid ${pid} · stays off until ${c.reset}${c.cyan}claude-rpc start${c.reset}`);
|
|
160
|
+
else console.log(` ${c.red}✗${c.reset} ${'stop failed'.padEnd(16)}${c.dim}pid ${pid} is still running — it will exit at its next check (≤30s)${c.reset}`);
|
|
161
|
+
return ok;
|
|
144
162
|
}
|
|
145
163
|
|
|
146
|
-
//
|
|
147
|
-
//
|
|
148
|
-
function restartDaemon() {
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
return;
|
|
163
|
-
}
|
|
164
|
-
setTimeout(tick, 50);
|
|
165
|
-
};
|
|
166
|
-
setTimeout(tick, 50);
|
|
167
|
-
});
|
|
164
|
+
// Stop (and wait for) the running daemon, then start a fresh one. Resolves
|
|
165
|
+
// once the replacement has been spawned (true) or couldn't be (false).
|
|
166
|
+
async function restartDaemon() {
|
|
167
|
+
clearStopped();
|
|
168
|
+
await stopDaemonAndWait();
|
|
169
|
+
return startDaemon();
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
// After an update the running daemon still executes the OLD code. setup (and
|
|
173
|
+
// the desktop app's post-update setup) replaces a daemon older than this copy,
|
|
174
|
+
// or one too old to report its version.
|
|
175
|
+
async function replaceOutdatedDaemon() {
|
|
176
|
+
const pid = daemonAlive();
|
|
177
|
+
if (!pid || !shouldReplaceDaemon({ info: readDaemonInfo(), pid, version: VERSION })) return false;
|
|
178
|
+
await stopDaemonAndWait();
|
|
179
|
+
return true;
|
|
168
180
|
}
|
|
169
181
|
|
|
170
182
|
// ── Box drawing — auto-widens to fit longest line ────────────────────────────
|
|
@@ -422,7 +434,8 @@ async function showStatus() {
|
|
|
422
434
|
console.log('');
|
|
423
435
|
|
|
424
436
|
box('daemon', [
|
|
425
|
-
pair('status', pid ? `${c.green}● running${c.reset} pid ${pid}
|
|
437
|
+
pair('status', pid ? `${c.green}● running${c.reset} pid ${pid}${daemonVersionNote(pid)}`
|
|
438
|
+
: isStopped() ? `${c.yellow}○ stopped${c.reset} ${c.dim}(claude-rpc start to resume)${c.reset}` : `${c.red}○ not running${c.reset}`, ''),
|
|
426
439
|
pair('client', config.clientId || '—'),
|
|
427
440
|
pair('config', shortPath(CONFIG_PATH), c.gray),
|
|
428
441
|
// The file behind the session shown below (hooks write one per session),
|
|
@@ -1779,8 +1792,9 @@ function profileNextStep() {
|
|
|
1779
1792
|
}
|
|
1780
1793
|
}
|
|
1781
1794
|
|
|
1782
|
-
function profileStatus() {
|
|
1795
|
+
async function profileStatus() {
|
|
1783
1796
|
const p = (loadConfig().profile) || {};
|
|
1797
|
+
const { readProfileResult } = await import('./community.js');
|
|
1784
1798
|
const handleOk = lb.isValidHandle(p.handle);
|
|
1785
1799
|
const boardUrl = handleOk ? `https://claude-rpc.com/u/${encodeURIComponent(p.handle)}` : '';
|
|
1786
1800
|
|
|
@@ -1791,8 +1805,22 @@ function profileStatus() {
|
|
|
1791
1805
|
const githubLine = p.githubUser
|
|
1792
1806
|
? `${p.githubUser}${p.verified ? ` ${c.green}✓ verified${c.reset}` : ` ${c.dim}(unverified)${c.reset}`}`
|
|
1793
1807
|
: `${c.dim}—${c.reset}`;
|
|
1808
|
+
const last = readProfileResult();
|
|
1809
|
+
const ago = (t) => {
|
|
1810
|
+
const m = Math.round((Date.now() - t) / 60_000);
|
|
1811
|
+
return m < 60 ? `${m}m ago` : m < 2880 ? `${Math.round(m / 60)}h ago` : `${Math.round(m / 1440)}d ago`;
|
|
1812
|
+
};
|
|
1813
|
+
const lastLines = [];
|
|
1814
|
+
if (p.enabled && last) {
|
|
1815
|
+
if (last.ok === false) {
|
|
1816
|
+
lastLines.push(pair('last', `${c.red}✗ refused ${ago(last.failedAt)}${c.reset} ${c.dim}${last.reason}${last.error ? ` · ${last.error}` : ''}${c.reset}`, ''));
|
|
1817
|
+
} else if (last.at) {
|
|
1818
|
+
lastLines.push(pair('last', `${c.green}✓${c.reset} ${c.dim}published ${ago(last.at)}${c.reset}`, ''));
|
|
1819
|
+
}
|
|
1820
|
+
}
|
|
1794
1821
|
box('profile', [
|
|
1795
1822
|
pair('state', p.enabled ? `${c.green}● publishing${c.reset}` : `${c.dim}○ off${c.reset}`, ''),
|
|
1823
|
+
...lastLines,
|
|
1796
1824
|
pair('handle', handleOk ? `${c.cyan}${p.handle}${c.reset}` : `${c.dim}(unset)${c.reset}`, ''),
|
|
1797
1825
|
pair('name', p.displayName || `${c.dim}—${c.reset}`, ''),
|
|
1798
1826
|
pair('github', githubLine, ''),
|
|
@@ -1803,6 +1831,15 @@ function profileStatus() {
|
|
|
1803
1831
|
// Setup checklist — same shape every time, so the user always sees where
|
|
1804
1832
|
// they are and the exact next command. This is the screen the daemon's
|
|
1805
1833
|
// breadcrumbs point back to.
|
|
1834
|
+
if (p.enabled && last?.ok === false) {
|
|
1835
|
+
const hint = publishFailHint(last);
|
|
1836
|
+
for (const h of [].concat(hint)) console.log(` ${c.yellow}!${c.reset} ${c.dim}${h}${c.reset}`);
|
|
1837
|
+
console.log('');
|
|
1838
|
+
}
|
|
1839
|
+
if (p.enabled && last?.site) {
|
|
1840
|
+
for (const line of siteBreakdown(last)) console.log(` ${line}`);
|
|
1841
|
+
console.log('');
|
|
1842
|
+
}
|
|
1806
1843
|
const steps = profileSteps(p);
|
|
1807
1844
|
if (steps.every((s) => s.done)) {
|
|
1808
1845
|
console.log(` ${c.green}✓${c.reset} all set — you're live at ${c.cyan}${boardUrl}${c.reset}`);
|
|
@@ -1912,16 +1949,51 @@ async function profilePublish() {
|
|
|
1912
1949
|
hint: 'claude-rpc profile set --handle <name> && claude-rpc profile on', code: EX_BAD_STATE,
|
|
1913
1950
|
});
|
|
1914
1951
|
}
|
|
1915
|
-
const { flushProfile } = await import('./community.js');
|
|
1952
|
+
const { flushProfile, recordProfileResult } = await import('./community.js');
|
|
1916
1953
|
console.log(` ${c.dim}publishing @${cfg.profile.handle} to the board…${c.reset}`);
|
|
1917
1954
|
const r = await flushProfile(cfg);
|
|
1955
|
+
recordProfileResult(r);
|
|
1918
1956
|
if (r.ok) {
|
|
1919
1957
|
console.log(` ${c.green}✓${c.reset} published — see it at ${c.cyan}https://claude-rpc.com/u/${encodeURIComponent(cfg.profile.handle)}${c.reset}`);
|
|
1958
|
+
for (const line of siteBreakdown({ ok: true, at: Date.now(), totals: r.totals, site: r.site })) console.log(` ${line}`);
|
|
1920
1959
|
} else if (r.reason === 'rate-limited') {
|
|
1921
1960
|
console.log(` ${c.yellow}!${c.reset} rate-limited — already published in the last minute; the board has you`);
|
|
1922
1961
|
} else {
|
|
1923
|
-
return fail(`publish failed: ${r.reason}${r.error ? ' (' + r.error + ')' : ''}`, { code: EX_SYS_ERROR });
|
|
1962
|
+
return fail(`publish failed: ${r.reason}${r.error ? ' (' + r.error + ')' : ''}`, { hint: publishFailHint(r), code: EX_SYS_ERROR });
|
|
1963
|
+
}
|
|
1964
|
+
}
|
|
1965
|
+
|
|
1966
|
+
// Why a publish was refused, in terms of what to do. A 409 is almost always a
|
|
1967
|
+
// second machine that was never linked: its local handle is the one its main
|
|
1968
|
+
// machine already owns, so every flush is refused and its usage never reaches
|
|
1969
|
+
// the board.
|
|
1970
|
+
function publishFailHint(r) {
|
|
1971
|
+
if (r.reason === 'http-409') {
|
|
1972
|
+
return ['this machine isn\'t linked to the identity that owns that handle',
|
|
1973
|
+
'run `claude-rpc link` on a linked machine, then `claude-rpc link <code>` here'];
|
|
1974
|
+
}
|
|
1975
|
+
if (r.reason === 'network') return 'no connection to the board — the daemon retries every 30 min';
|
|
1976
|
+
return 'run `claude-rpc doctor`';
|
|
1977
|
+
}
|
|
1978
|
+
|
|
1979
|
+
// Lines describing where the board's number comes from: this machine's share,
|
|
1980
|
+
// the identity total, and any linked machine that has stopped reporting.
|
|
1981
|
+
function siteBreakdown(rec) {
|
|
1982
|
+
const out = [];
|
|
1983
|
+
if (!rec?.site) return out;
|
|
1984
|
+
const ms = rec.site.machines;
|
|
1985
|
+
const n = Array.isArray(ms) ? ms.length : null;
|
|
1986
|
+
const mine = rec.totals?.tokens;
|
|
1987
|
+
out.push(`${c.dim}this machine ${fmtNum(mine || 0)} tokens · board total ${fmtNum(rec.site.tokens || 0)}${n && n > 1 ? ` across ${n} linked machines` : ''}${c.reset}`);
|
|
1988
|
+
if (n && n > 1) {
|
|
1989
|
+
const quietDays = 3;
|
|
1990
|
+
const stale = ms.filter((m) => !m.self && m.updatedAt && Date.now() - m.updatedAt > quietDays * 86_400_000);
|
|
1991
|
+
for (const m of stale) {
|
|
1992
|
+
const days = Math.round((Date.now() - m.updatedAt) / 86_400_000);
|
|
1993
|
+
out.push(`${c.yellow}!${c.reset} ${c.dim}a linked machine (${fmtNum(m.tokens)} tokens) hasn't published in ${days} days — run ${c.reset}${c.cyan}claude-rpc profile publish${c.reset}${c.dim} there; if its daemon is down, ${c.reset}${c.cyan}claude-rpc start${c.reset}`);
|
|
1994
|
+
}
|
|
1924
1995
|
}
|
|
1996
|
+
return out;
|
|
1925
1997
|
}
|
|
1926
1998
|
|
|
1927
1999
|
// The gist-verification dance shared by `profile verify` and setup's optional
|
|
@@ -2204,8 +2276,27 @@ async function doUpdate(argv) {
|
|
|
2204
2276
|
}
|
|
2205
2277
|
if (sub === 'status') {
|
|
2206
2278
|
const st = readUpdateState();
|
|
2279
|
+
const ago = (t) => {
|
|
2280
|
+
const m = Math.round((Date.now() - t) / 60_000);
|
|
2281
|
+
return m < 60 ? `${m}m ago` : m < 2880 ? `${Math.round(m / 60)}h ago` : `${Math.round(m / 1440)}d ago`;
|
|
2282
|
+
};
|
|
2207
2283
|
console.log(` ${c.cyan}·${c.reset} v${VERSION} · installed via ${kind} · auto-update ${auto && kind === 'npm-global' ? 'on' : kind === 'npm-global' ? 'off' : 'n/a'}`);
|
|
2208
|
-
|
|
2284
|
+
const { daemonAlive: alive, readDaemonInfo: info } = await import('./ensure-daemon.js');
|
|
2285
|
+
const pid = alive();
|
|
2286
|
+
const di = info();
|
|
2287
|
+
if (pid) {
|
|
2288
|
+
const dv = di && di.pid === pid ? di.version : null;
|
|
2289
|
+
if (!dv) console.log(` ${c.yellow}!${c.reset} ${c.dim}the running daemon predates version reporting — ${c.reset}${c.cyan}claude-rpc restart${c.reset}${c.dim} to run v${VERSION}${c.reset}`);
|
|
2290
|
+
else if (dv !== VERSION) console.log(` ${c.yellow}!${c.reset} ${c.dim}the running daemon is v${dv} — ${c.reset}${c.cyan}claude-rpc restart${c.reset}${c.dim} to run v${VERSION}${c.reset}`);
|
|
2291
|
+
}
|
|
2292
|
+
if (st.checkedAt) console.log(` ${c.dim}last check: ${ago(st.checkedAt)}${st.latest ? ` · latest v${st.latest}` : ' · registry unreachable'}${c.reset}`);
|
|
2293
|
+
else console.log(` ${c.dim}no check yet — the daemon checks 5 min after it starts, then every 6h${c.reset}`);
|
|
2294
|
+
if (st.latest && isNewer(st.latest, VERSION)) {
|
|
2295
|
+
const why = st.lastPlan?.latest === st.latest ? st.lastPlan.reason : null;
|
|
2296
|
+
console.log(` ${c.yellow}!${c.reset} v${st.latest} is out${why ? ` ${c.dim}(${why})${c.reset}` : ''} — ${c.cyan}${kind === 'npm-global' ? 'claude-rpc update now' : updateCommand(kind)}${c.reset}`);
|
|
2297
|
+
}
|
|
2298
|
+
if (st.failed) console.log(` ${c.red}✗${c.reset} ${c.dim}install of v${st.failed.version} failed ${ago(st.failed.at)}: ${String(st.failed.output || '').split('\n').pop().slice(0, 160)}${c.reset}`);
|
|
2299
|
+
if (st.updatedTo) console.log(` ${c.dim}last auto-update: ${st.updatedFrom} → ${st.updatedTo}${st.updatedAt ? ` (${ago(st.updatedAt)})` : ''}${c.reset}`);
|
|
2209
2300
|
return;
|
|
2210
2301
|
}
|
|
2211
2302
|
if (sub !== 'check' && sub !== 'now') {
|
|
@@ -2226,9 +2317,17 @@ async function doUpdate(argv) {
|
|
|
2226
2317
|
console.log(` ${c.dim}installing…${c.reset}`);
|
|
2227
2318
|
const res = await installVersion(latest);
|
|
2228
2319
|
if (!res.ok) fail('install failed', { hint: [res.output.slice(-300) || 'npm exited non-zero', `try: ${updateCommand(kind)}`], code: EX_BAD_STATE });
|
|
2320
|
+
const { installedVersion } = await import('./updater.js');
|
|
2321
|
+
if (installedVersion() !== latest) {
|
|
2322
|
+
fail(`npm finished, but this copy is still v${VERSION}`, {
|
|
2323
|
+
hint: [`npm installs its globals somewhere other than ${ROOT} (npm prefix / volta / pnpm)`, 'update with the tool that installed claude-rpc'],
|
|
2324
|
+
code: EX_BAD_STATE,
|
|
2325
|
+
});
|
|
2326
|
+
}
|
|
2229
2327
|
writeUpdateState({ updatedFrom: VERSION, updatedTo: latest, updatedAt: Date.now(), failed: null });
|
|
2230
2328
|
console.log(` ${c.green}✓${c.reset} updated to v${latest}`);
|
|
2231
|
-
|
|
2329
|
+
// Restart a running daemon onto the new code; a stopped one stays stopped.
|
|
2330
|
+
if (daemonAlive()) await restartDaemon();
|
|
2232
2331
|
}
|
|
2233
2332
|
|
|
2234
2333
|
function tailLog() {
|
|
@@ -2286,6 +2385,7 @@ function overview() {
|
|
|
2286
2385
|
const vars = buildVars(state, cfg, aggregate);
|
|
2287
2386
|
const dot = pid
|
|
2288
2387
|
? `${c.green}●${c.reset} running ${c.dim}pid ${pid}${c.reset}`
|
|
2388
|
+
: isStopped() ? `${c.yellow}○${c.reset} ${c.dim}daemon stopped — ${c.reset}${c.cyan}claude-rpc start${c.reset}${c.dim} to resume${c.reset}`
|
|
2289
2389
|
: `${c.yellow}○${c.reset} ${c.dim}daemon not running${c.reset}`;
|
|
2290
2390
|
if (pid) {
|
|
2291
2391
|
console.log(` ${dot} ${c.gray}·${c.reset} ${c.bold}${vars.modelPretty}${c.reset} in ${c.bold}${vars.project}${c.reset} ${c.gray}·${c.reset} ${statusColor(vars.status)}${vars.statusVerbose}${c.reset}`);
|
|
@@ -2517,7 +2617,13 @@ process.on('unhandledRejection', (e) => {
|
|
|
2517
2617
|
// immediately, instead of making the user run a separate `start`.
|
|
2518
2618
|
// Best-effort — a start hiccup must never make `setup` look failed.
|
|
2519
2619
|
try {
|
|
2520
|
-
|
|
2620
|
+
// `--auto` = the desktop app re-running setup after its own update:
|
|
2621
|
+
// it must not undo a `claude-rpc stop`. A person running setup means it.
|
|
2622
|
+
if (!args.includes('--auto')) clearStopped();
|
|
2623
|
+
if (!isStopped()) await replaceOutdatedDaemon();
|
|
2624
|
+
if (isStopped()) {
|
|
2625
|
+
console.log(` ${c.cyan}·${c.reset} ${'daemon stopped'.padEnd(16)}${c.dim}left off (you ran stop) · ${c.reset}${c.cyan}claude-rpc start${c.reset}${c.dim} to resume${c.reset}`);
|
|
2626
|
+
} else if (IS_NPX) {
|
|
2521
2627
|
// Our own tree is npm's throwaway _npx cache; launch from the global
|
|
2522
2628
|
// install setup just promoted to. The global copy must be resolved
|
|
2523
2629
|
// EXPLICITLY (npm root -g): inside an npx run, PATH has the _npx
|
|
@@ -2601,7 +2707,7 @@ process.on('unhandledRejection', (e) => {
|
|
|
2601
2707
|
if (!(await import('./install.js')).migrateConfig()) console.log(` ${c.green}✓${c.reset} config already current — nothing to migrate`);
|
|
2602
2708
|
break;
|
|
2603
2709
|
case 'start': if (startDaemon()) await confirmDaemonUp(); break;
|
|
2604
|
-
case 'stop': stopDaemon(); break;
|
|
2710
|
+
case 'stop': await stopDaemon(); break;
|
|
2605
2711
|
case 'restart': if (await restartDaemon()) await confirmDaemonUp(); break;
|
|
2606
2712
|
case 'status': {
|
|
2607
2713
|
const dumpFlag = args.some((a) => a === '--dump' || a === '-d');
|
|
@@ -2747,14 +2853,11 @@ process.on('unhandledRejection', (e) => {
|
|
|
2747
2853
|
} catch (e) {
|
|
2748
2854
|
console.warn(` ${c.yellow}!${c.reset} ${'refresh skipped'.padEnd(16)}${c.dim}${e.message}${c.reset}`);
|
|
2749
2855
|
}
|
|
2750
|
-
|
|
2856
|
+
// Wait for the old daemon to really exit (a fixed 700ms sleep let
|
|
2857
|
+
// startDaemon see it "still up" and no-op, leaving none running).
|
|
2858
|
+
await stopDaemonAndWait();
|
|
2751
2859
|
try { if (existsSync(STATE_PATH)) unlinkSync(STATE_PATH); } catch { /* state.json locked or already gone — next hook will recreate it */ }
|
|
2752
|
-
|
|
2753
|
-
// Brief wait for the OS to release the pid file before we spawn.
|
|
2754
|
-
setTimeout(() => startDaemon(), 700);
|
|
2755
|
-
} else {
|
|
2756
|
-
startDaemon();
|
|
2757
|
-
}
|
|
2860
|
+
startDaemon();
|
|
2758
2861
|
}
|
|
2759
2862
|
} else if (!cmd) {
|
|
2760
2863
|
// True no-args invocation in dev/npm mode → one-screen overview.
|
package/src/community.js
CHANGED
|
@@ -45,6 +45,10 @@ import { adoptLegacyFile, writeFileAtomic } from './atomic-rename.js';
|
|
|
45
45
|
// wipes; ensureCursor / markCursorFresh move it here once.
|
|
46
46
|
export const CURSOR_PATH = join(DATA_DIR, 'community-cursor.json');
|
|
47
47
|
export const LEGACY_CURSOR_PATH = join(STATE_DIR, 'community-cursor.json');
|
|
48
|
+
// Last profile publish result — what `claude-rpc profile` shows, so a machine
|
|
49
|
+
// whose publishes are rejected (unlinked → "handle taken"), or a linked machine
|
|
50
|
+
// that went quiet, is visible instead of a silently low site total.
|
|
51
|
+
export const PROFILE_STATUS_PATH = join(DATA_DIR, 'profile-status.json');
|
|
48
52
|
|
|
49
53
|
export function readCursor(path = CURSOR_PATH) {
|
|
50
54
|
if (!existsSync(path)) return { sessions: 0, tokens: 0, ts: 0 };
|
|
@@ -368,11 +372,41 @@ export async function flushProfile(cfg, {
|
|
|
368
372
|
const payload = buildProfilePayload(aggregate, profile, { instanceId });
|
|
369
373
|
const { res, fail } = await postJson(fetchImpl, community.endpoint, '/profile', payload);
|
|
370
374
|
if (fail) return fail;
|
|
375
|
+
let body = null;
|
|
376
|
+
try { body = await res.json(); } catch { /* non-JSON body */ }
|
|
371
377
|
if (!res.ok) {
|
|
372
378
|
if (res.status === 429) return { ok: false, reason: 'rate-limited' };
|
|
373
|
-
return { ok: false, reason: `http-${res.status}
|
|
379
|
+
return { ok: false, reason: `http-${res.status}`, ...(body?.error ? { error: String(body.error).slice(0, 200) } : {}) };
|
|
374
380
|
}
|
|
375
|
-
return {
|
|
381
|
+
return {
|
|
382
|
+
ok: true,
|
|
383
|
+
totals: { tokens: payload.tokens, sessions: payload.sessions, activeMs: payload.activeMs },
|
|
384
|
+
// What the board shows for the whole identity, and per linked machine
|
|
385
|
+
// (no ids — just "this one" and when each last reported). Older workers
|
|
386
|
+
// don't send `machines`.
|
|
387
|
+
site: body?.profile ? {
|
|
388
|
+
tokens: body.profile.tokens || 0,
|
|
389
|
+
machines: Array.isArray(body.machines) ? body.machines.map((m) => ({
|
|
390
|
+
self: !!m.self, tokens: Number(m.tokens) || 0, updatedAt: Number(m.updatedAt) || null,
|
|
391
|
+
})) : null,
|
|
392
|
+
} : null,
|
|
393
|
+
};
|
|
394
|
+
}
|
|
395
|
+
|
|
396
|
+
// Persist a flushProfile result for `claude-rpc profile`. Rate-limited results
|
|
397
|
+
// carry no news and are skipped; a failure keeps the last success alongside it.
|
|
398
|
+
export function recordProfileResult(result, { path = PROFILE_STATUS_PATH, now = Date.now() } = {}) {
|
|
399
|
+
if (!result || result.reason === 'rate-limited' || result.reason === 'disabled') return;
|
|
400
|
+
let prev = {};
|
|
401
|
+
try { prev = JSON.parse(readFileSync(path, 'utf8')) || {}; } catch { /* first write */ }
|
|
402
|
+
const next = result.ok
|
|
403
|
+
? { ok: true, at: now, totals: result.totals, site: result.site || null }
|
|
404
|
+
: { ...prev, ok: false, failedAt: now, reason: result.reason, error: result.error || null };
|
|
405
|
+
try { writeFileAtomic(path, JSON.stringify(next)); } catch { /* advisory */ }
|
|
406
|
+
}
|
|
407
|
+
|
|
408
|
+
export function readProfileResult(path = PROFILE_STATUS_PATH) {
|
|
409
|
+
try { return JSON.parse(readFileSync(path, 'utf8')); } catch { return null; }
|
|
376
410
|
}
|
|
377
411
|
|
|
378
412
|
// Single best-effort flush. Returns { ok, reason, delta? } — never throws.
|
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');
|
package/src/server/settings.js
CHANGED
|
@@ -21,7 +21,7 @@ import { DEFAULT_CONFIG } from '../default-config.js';
|
|
|
21
21
|
import { loadConfig, mergeConfig } from '../config.js';
|
|
22
22
|
import { applyEdits } from '../config-edit.js';
|
|
23
23
|
import { writeFileAtomic } from '../atomic-rename.js';
|
|
24
|
-
import { daemonAlive, spawnDaemonDetached } from '../ensure-daemon.js';
|
|
24
|
+
import { daemonAlive, spawnDaemonDetached, stopDaemonAndWait, markStopped, clearStopped, isStopped } from '../ensure-daemon.js';
|
|
25
25
|
import { ipcStateFromLog, bridgeFromLog, classifyClientId } from '../doctor.js';
|
|
26
26
|
import { readActiveState } from '../state.js';
|
|
27
27
|
import { findLiveSessions, readAggregate } from '../scanner.js';
|
|
@@ -63,7 +63,7 @@ function tailLog(lines = 80) {
|
|
|
63
63
|
// kind from the log tail — the same reading `claude-rpc doctor` reports.
|
|
64
64
|
export function daemonStatus() {
|
|
65
65
|
const pid = daemonAlive();
|
|
66
|
-
if (!pid) return { running: false, pid: null, ipc: 'down', client: null };
|
|
66
|
+
if (!pid) return { running: false, pid: null, ipc: 'down', client: null, stopped: isStopped() };
|
|
67
67
|
const log = tailLog(200);
|
|
68
68
|
return { running: true, pid, ipc: ipcStateFromLog(log), client: bridgeFromLog(log) };
|
|
69
69
|
}
|
|
@@ -162,22 +162,15 @@ async function waitDaemon(want, timeoutMs) {
|
|
|
162
162
|
}
|
|
163
163
|
}
|
|
164
164
|
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
}
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
const pid = daemonAlive();
|
|
171
|
-
if (!pid) return true;
|
|
172
|
-
signal(pid, 'SIGTERM');
|
|
173
|
-
if (await waitDaemon(false, 3000)) return true;
|
|
174
|
-
// Wedged: it ignored SIGTERM for 3s. Don't leave the user with a daemon
|
|
175
|
-
// they asked to stop.
|
|
176
|
-
signal(pid, 'SIGKILL');
|
|
177
|
-
return waitDaemon(false, 1500);
|
|
165
|
+
// Same semantics as `claude-rpc stop`: durable (the marker keeps the hook and
|
|
166
|
+
// login autostart from bringing it back) and confirmed (hard-kill if wedged).
|
|
167
|
+
async function stop({ mark = true } = {}) {
|
|
168
|
+
if (mark) markStopped();
|
|
169
|
+
return stopDaemonAndWait();
|
|
178
170
|
}
|
|
179
171
|
|
|
180
172
|
async function start() {
|
|
173
|
+
clearStopped();
|
|
181
174
|
if (daemonAlive()) return true;
|
|
182
175
|
const child = spawnDaemonDetached();
|
|
183
176
|
if (!child || !child.pid) return false;
|
|
@@ -190,7 +183,7 @@ export async function daemonAction(action) {
|
|
|
190
183
|
let ok;
|
|
191
184
|
if (action === 'start') ok = await start();
|
|
192
185
|
else if (action === 'stop') ok = await stop();
|
|
193
|
-
else if (action === 'restart') ok = (await stop()) && (await start());
|
|
186
|
+
else if (action === 'restart') ok = (await stop({ mark: false })) && (await start());
|
|
194
187
|
else return { error: 'unknown action' };
|
|
195
188
|
const daemon = daemonStatus();
|
|
196
189
|
if (ok) return { ok: true, daemon };
|
package/src/tui.js
CHANGED
|
@@ -11,7 +11,7 @@ import { readActiveState } from './state.js';
|
|
|
11
11
|
import { readAggregate, findLiveSessions, dayKey } from './scanner.js';
|
|
12
12
|
import { buildVars, applyIdle, humanProject, fmtNum } from './format.js';
|
|
13
13
|
import { loadConfig } from './config.js';
|
|
14
|
-
import { daemonAlive } from './ensure-daemon.js';
|
|
14
|
+
import { daemonAlive, isStopped } from './ensure-daemon.js';
|
|
15
15
|
import { fmtCost } from './pricing.js';
|
|
16
16
|
import { heat } from './ui.js';
|
|
17
17
|
|
|
@@ -175,7 +175,7 @@ export function loadSnapshot() {
|
|
|
175
175
|
const aggregate = readAggregate() || {};
|
|
176
176
|
const vars = buildVars(state, config, aggregate);
|
|
177
177
|
// daemonAlive treats EPERM as alive (the pid exists, we just can't signal it).
|
|
178
|
-
return { state, config, aggregate, vars, pid: daemonAlive() || null };
|
|
178
|
+
return { state, config, aggregate, vars, pid: daemonAlive() || null, stopped: isStopped() };
|
|
179
179
|
}
|
|
180
180
|
|
|
181
181
|
const WD = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
|
|
@@ -418,6 +418,7 @@ export function renderFrame(data, { width, height, tab }) {
|
|
|
418
418
|
|
|
419
419
|
const status = data.pid
|
|
420
420
|
? `${C.green}●${C.reset} ${C.dim}running · pid ${data.pid}${C.reset}`
|
|
421
|
+
: data.stopped ? `${C.yellow}○${C.reset} ${C.dim}daemon stopped · claude-rpc start${C.reset}`
|
|
421
422
|
: `${C.red}○${C.reset} ${C.dim}daemon not running${C.reset}`;
|
|
422
423
|
const tabBar = TABS.map((t, i) => (i === tab
|
|
423
424
|
? `${C.bold}${C.cyan}‹ ${t.label} ›${C.reset}`
|
package/src/updater.js
CHANGED
|
@@ -10,7 +10,7 @@
|
|
|
10
10
|
//
|
|
11
11
|
// Pure decision functions up top (unit-tested); side effects below.
|
|
12
12
|
|
|
13
|
-
import { readFileSync, writeFileSync, mkdirSync } from 'node:fs';
|
|
13
|
+
import { readFileSync, writeFileSync, mkdirSync, accessSync, constants as fsConstants } from 'node:fs';
|
|
14
14
|
import { join, dirname, delimiter } from 'node:path';
|
|
15
15
|
import { STATE_DIR, ROOT, IS_PACKAGED, IS_NPM_INSTALL, IS_NPX } from './paths.js';
|
|
16
16
|
|
|
@@ -61,10 +61,13 @@ export function updateCommand(kind) {
|
|
|
61
61
|
}
|
|
62
62
|
|
|
63
63
|
// → { action: 'none' | 'notify' | 'install', reason }
|
|
64
|
-
export function planUpdate({ current, latest, auto = true, kind, failed = null, seen = null, cooldownMs = COOLDOWN_MS, now = Date.now() }) {
|
|
64
|
+
export function planUpdate({ current, latest, auto = true, kind, writable = true, failed = null, seen = null, cooldownMs = COOLDOWN_MS, now = Date.now() }) {
|
|
65
65
|
if (!isNewer(latest, current)) return { action: 'none', reason: 'up to date' };
|
|
66
66
|
if (kind !== 'npm-global') return { action: 'notify', reason: `installed via ${kind}` };
|
|
67
67
|
if (!auto) return { action: 'notify', reason: 'auto-update is off' };
|
|
68
|
+
// A root-owned global (system node, `sudo npm i -g`) fails with EACCES every
|
|
69
|
+
// single attempt — say so once instead of failing silently every day.
|
|
70
|
+
if (!writable) return { action: 'notify', reason: 'the global npm folder needs admin rights — update manually' };
|
|
68
71
|
if (!sameMajor(latest, current)) return { action: 'notify', reason: 'new major version — update manually' };
|
|
69
72
|
if (failed && failed.version === latest && now - failed.at < RETRY_FAILED_MS) {
|
|
70
73
|
return { action: 'notify', reason: 'last install attempt failed — retrying later' };
|
|
@@ -118,9 +121,24 @@ export async function installVersion(version) {
|
|
|
118
121
|
});
|
|
119
122
|
}
|
|
120
123
|
|
|
121
|
-
//
|
|
122
|
-
//
|
|
123
|
-
export
|
|
124
|
+
// Can this process replace its own package? (npm writes the new copy into the
|
|
125
|
+
// folder that holds ours: …/lib/node_modules on POSIX, %AppData%\npm\node_modules.)
|
|
126
|
+
export function installDirWritable(root = ROOT) {
|
|
127
|
+
try { accessSync(dirname(root), fsConstants.W_OK); return true; } catch { return false; }
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
// The version now on disk where THIS copy lives. npm exiting 0 doesn't mean it
|
|
131
|
+
// replaced us: with a different npm prefix (volta, pnpm/yarn/bun globals, a
|
|
132
|
+
// changed `npm config prefix`) it installs somewhere else, the restart comes
|
|
133
|
+
// back up on the old code, and the daemon reinstalled again every 5 minutes.
|
|
134
|
+
export function installedVersion(root = ROOT) {
|
|
135
|
+
try { return JSON.parse(readFileSync(join(root, 'package.json'), 'utf8')).version || null; } catch { return null; }
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
// One check cycle. Returns { plan, latest, installed }. `install`, `verify`
|
|
139
|
+
// and `writable` are injectable for tests; callers restart the daemon when
|
|
140
|
+
// `installed` is true.
|
|
141
|
+
export async function checkForUpdate({ current, auto, kind = installKind(), fetchLatestFn = fetchLatest, install = installVersion, verify = (v) => installedVersion() === v, writable = installDirWritable, now = Date.now(), cooldownMs = COOLDOWN_MS, statePath = UPDATE_STATE_PATH } = {}) {
|
|
124
142
|
const latest = await fetchLatestFn();
|
|
125
143
|
writeUpdateState({ checkedAt: now, ...(latest ? { latest } : {}) }, statePath);
|
|
126
144
|
if (!latest) return { plan: { action: 'none', reason: 'registry unreachable' }, latest: null, installed: false };
|
|
@@ -129,9 +147,14 @@ export async function checkForUpdate({ current, auto, kind = installKind(), fetc
|
|
|
129
147
|
writeUpdateState({ seen: { version: latest, at: now } }, statePath);
|
|
130
148
|
state = readUpdateState(statePath);
|
|
131
149
|
}
|
|
132
|
-
const plan = planUpdate({ current, latest, auto, kind, failed: state.failed || null, seen: state.seen || null, cooldownMs, now });
|
|
150
|
+
const plan = planUpdate({ current, latest, auto, kind, writable: kind === 'npm-global' ? writable() : true, failed: state.failed || null, seen: state.seen || null, cooldownMs, now });
|
|
151
|
+
writeUpdateState({ lastPlan: { action: plan.action, reason: plan.reason, latest, at: now } }, statePath);
|
|
133
152
|
if (plan.action !== 'install') return { plan, latest, installed: false };
|
|
134
153
|
const res = await install(latest);
|
|
154
|
+
if (res.ok && !verify(latest)) {
|
|
155
|
+
res.ok = false;
|
|
156
|
+
res.output = `npm reported success but this copy (${ROOT}) is still v${current} — npm installs its globals somewhere else here (npm prefix / volta / pnpm). Update with the tool that installed claude-rpc.`;
|
|
157
|
+
}
|
|
135
158
|
if (res.ok) {
|
|
136
159
|
writeUpdateState({ updatedFrom: current, updatedTo: latest, updatedAt: now, failed: null }, statePath);
|
|
137
160
|
return { plan, latest, installed: true };
|