claude-rpc 1.8.0 → 1.10.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/src/install.js CHANGED
@@ -455,6 +455,14 @@ function sweepStaleCanonicalBackups() {
455
455
  // Copy the running binary into CANONICAL_EXE if it's not already there.
456
456
  // Returns the path that hook entries should point at — canonical on success,
457
457
  // the original path as a fallback. Only meaningful in packaged mode.
458
+ // Pure: is a (the on-disk canonical exe's version) newer than b?
459
+ export function canonicalIsNewer(a, b) {
460
+ const p = (v) => String(v).split('.').map(Number);
461
+ const x = p(a), y = p(b);
462
+ for (let i = 0; i < 3; i++) if (x[i] !== y[i]) return x[i] > y[i];
463
+ return false;
464
+ }
465
+
458
466
  export function ensureCanonicalExe(currentExe) {
459
467
  if (!IS_PACKAGED) return currentExe;
460
468
  if (samePath(currentExe, CANONICAL_EXE)) return CANONICAL_EXE;
@@ -474,6 +482,17 @@ export function ensureCanonicalExe(currentExe) {
474
482
  } catch { /* stat failed — fall through to copy attempt */ }
475
483
  }
476
484
 
485
+ // The canonical exe self-updates (updater.js installPackaged), so it can be
486
+ // NEWER than the copy running setup — e.g. the desktop app re-running setup
487
+ // with its older bundled CLI. Never downgrade it.
488
+ if (existsSync(CANONICAL_EXE)) {
489
+ const m = /(\d+\.\d+\.\d+)/.exec(String(spawnSync(CANONICAL_EXE, ['--version'], { timeout: 15_000, windowsHide: true, encoding: 'utf8' }).stdout || ''));
490
+ if (m && canonicalIsNewer(m[1], VERSION)) {
491
+ noop(`exe already v${m[1]}`);
492
+ return CANONICAL_EXE;
493
+ }
494
+ }
495
+
477
496
  try {
478
497
  // Windows won't let you overwrite a currently-executing file. If
479
498
  // canonical is the running daemon, move it aside first — that succeeds
@@ -930,8 +949,13 @@ export async function install({ exePath } = {}) {
930
949
  // Cross-platform login autostart: Windows Run-key, macOS LaunchAgent, Linux
931
950
  // systemd --user. Best-effort — a failure leaves the SessionStart self-heal
932
951
  // as the (already reliable) fallback, so setup never fails on this.
933
- try { await addStartupEntry(target); }
934
- catch (e) { step(SYM_WARN, 'startup entry', `failed: ${e.message} — session self-heal still covers it`, console.warn); }
952
+ // autostart:false opts out of login autostart everywhere — setup, doctor
953
+ // --fix and the desktop app's post-update setup used to re-enable it.
954
+ if (readJson(CONFIG_PATH, {}).autostart === false) noop('login autostart off (autostart:false)');
955
+ else {
956
+ try { await addStartupEntry(target); }
957
+ catch (e) { step(SYM_WARN, 'startup entry', `failed: ${e.message} — session self-heal still covers it`, console.warn); }
958
+ }
935
959
  const cli = IS_PACKAGED ? await putCliOnPath(target) : { cmd: 'claude-rpc', newTerminal: false };
936
960
  // Nothing changed: the checklist above stayed silent, so say so in one line.
937
961
  if (!runDirty && probe.ok) {
@@ -983,6 +1007,18 @@ export async function uninstall() {
983
1007
  console.log('');
984
1008
  console.log(` ${c.bold}${c.magenta}◆ claude-rpc uninstall${c.reset}`);
985
1009
  console.log('');
1010
+ // Stop the daemon FIRST and leave the stop marker: a surviving daemon kept
1011
+ // running after uninstall, and its update self-heal re-added the hooks and
1012
+ // the login autostart (and its auto-updater could reinstall the package).
1013
+ // The marker also stops any straggler at its next watchdog tick; `setup`
1014
+ // clears it on a reinstall.
1015
+ {
1016
+ const { markStopped, stopDaemonAndWait } = await import('./ensure-daemon.js');
1017
+ markStopped();
1018
+ if (await stopDaemonAndWait()) step(SYM_OK, 'daemon', 'stopped');
1019
+ else step(SYM_WARN, 'daemon', 'still running — it exits on its own within 30s', console.warn);
1020
+ try { if (existsSync(VERSION_STAMP)) unlinkSync(VERSION_STAMP); } catch { /* best-effort */ }
1021
+ }
986
1022
  uninstallHooks();
987
1023
  await removeStartupEntry();
988
1024
  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');
@@ -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
- function signal(pid, sig) {
166
- try { process.kill(pid, sig); return true; } catch { return false; }
167
- }
168
-
169
- async function stop() {
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
@@ -8,17 +8,26 @@
8
8
  // is never touched: those get a one-line "update available" with the right
9
9
  // command. A new MAJOR is never installed unattended.
10
10
  //
11
+ // The packaged binary (claude-rpc.exe / the macOS arm64 binary — what the
12
+ // desktop app and the standalone download install as the canonical exe) also
13
+ // self-updates since 1.10: it downloads the release asset from GitHub, checks
14
+ // it against the release's SHA256SUMS, test-runs it, and swaps it in place. A
15
+ // release without SHA256SUMS (anything before 1.10) is never installed.
16
+ //
11
17
  // Pure decision functions up top (unit-tested); side effects below.
12
18
 
13
- import { readFileSync, writeFileSync, mkdirSync } from 'node:fs';
19
+ import { readFileSync, writeFileSync, mkdirSync, accessSync, renameSync, chmodSync, unlinkSync, existsSync, constants as fsConstants } from 'node:fs';
14
20
  import { join, dirname, delimiter } from 'node:path';
15
- import { STATE_DIR, ROOT, IS_PACKAGED, IS_NPM_INSTALL, IS_NPX } from './paths.js';
21
+ import { createHash } from 'node:crypto';
22
+ import { STATE_DIR, ROOT, IS_PACKAGED, IS_NPM_INSTALL, IS_NPX, CANONICAL_EXE } from './paths.js';
16
23
 
17
24
  export const UPDATE_STATE_PATH = join(STATE_DIR, 'update.json');
18
25
  export const REGISTRY_URL = 'https://registry.npmjs.org/claude-rpc/latest';
19
26
  const RETRY_FAILED_MS = 24 * 3_600_000; // don't hammer a version that failed to install
20
27
  const COOLDOWN_MS = 2 * 3_600_000; // a release must be seen this long before it's installed — a yank window
21
28
  const INSTALL_TIMEOUT_MS = 180_000;
29
+ export const RELEASE_BASE = 'https://github.com/rar-file/claude-rpc/releases/download';
30
+ const MAX_ASSET_BYTES = 250 * 1024 * 1024;
22
31
  const FETCH_TIMEOUT_MS = 8_000;
23
32
 
24
33
  const SEMVER = /^(\d+)\.(\d+)\.(\d+)$/; // no prereleases: only stable tags are ever considered
@@ -60,11 +69,31 @@ export function updateCommand(kind) {
60
69
  }
61
70
  }
62
71
 
72
+ // The release asset a packaged build of this platform updates from, or null
73
+ // when no prebuilt binary is published for it (those only get a notice).
74
+ export function packagedAsset(platform = process.platform, arch = process.arch) {
75
+ if (platform === 'win32' && arch === 'x64') return 'claude-rpc.exe';
76
+ if (platform === 'darwin' && arch === 'arm64') return 'claude-rpc';
77
+ return null;
78
+ }
79
+
80
+ // Can this packaged process replace itself? Only when it IS the canonical exe
81
+ // (the copy hooks + autostart launch) and a binary exists for this platform.
82
+ export function packagedSelfUpdatable({ packaged = IS_PACKAGED, execPath = process.execPath, canonical = CANONICAL_EXE, asset = packagedAsset() } = {}) {
83
+ if (!packaged || !asset) return false;
84
+ const norm = (x) => (process.platform === 'win32' ? String(x).toLowerCase() : String(x));
85
+ return norm(execPath) === norm(canonical);
86
+ }
87
+
63
88
  // → { action: 'none' | 'notify' | 'install', reason }
64
- export function planUpdate({ current, latest, auto = true, kind, failed = null, seen = null, cooldownMs = COOLDOWN_MS, now = Date.now() }) {
89
+ export function planUpdate({ current, latest, auto = true, kind, writable = true, failed = null, seen = null, cooldownMs = COOLDOWN_MS, now = Date.now(), packagedOk = false }) {
65
90
  if (!isNewer(latest, current)) return { action: 'none', reason: 'up to date' };
66
- if (kind !== 'npm-global') return { action: 'notify', reason: `installed via ${kind}` };
91
+ const selfUpdating = kind === 'npm-global' || (kind === 'packaged' && packagedOk);
92
+ if (!selfUpdating) return { action: 'notify', reason: `installed via ${kind}` };
67
93
  if (!auto) return { action: 'notify', reason: 'auto-update is off' };
94
+ // A root-owned global (system node, `sudo npm i -g`) fails with EACCES every
95
+ // single attempt — say so once instead of failing silently every day.
96
+ if (!writable) return { action: 'notify', reason: kind === 'packaged' ? 'the install folder is not writable — update manually' : 'the global npm folder needs admin rights — update manually' };
68
97
  if (!sameMajor(latest, current)) return { action: 'notify', reason: 'new major version — update manually' };
69
98
  if (failed && failed.version === latest && now - failed.at < RETRY_FAILED_MS) {
70
99
  return { action: 'notify', reason: 'last install attempt failed — retrying later' };
@@ -118,9 +147,85 @@ export async function installVersion(version) {
118
147
  });
119
148
  }
120
149
 
121
- // One check cycle. Returns { plan, latest, installed }. `install` is injectable
122
- // for tests; callers restart the daemon when `installed` is true.
123
- export async function checkForUpdate({ current, auto, kind = installKind(), fetchLatestFn = fetchLatest, install = installVersion, now = Date.now(), cooldownMs = COOLDOWN_MS, statePath = UPDATE_STATE_PATH } = {}) {
150
+ // Pure: the hex digest SHA256SUMS lists for `name` (sha256sum format:
151
+ // "<hex> <name>" or "<hex> *<name>"), or null.
152
+ export function checksumFor(sums, name) {
153
+ for (const line of String(sums || '').split(/\r?\n/)) {
154
+ const m = /^([0-9a-f]{64})\s+\*?(.+?)\s*$/i.exec(line);
155
+ if (m && m[2] === name) return m[1].toLowerCase();
156
+ }
157
+ return null;
158
+ }
159
+
160
+ async function fetchBuffer(url, { timeoutMs, maxBytes }) {
161
+ const res = await fetch(url, { signal: AbortSignal.timeout(timeoutMs), redirect: 'follow' });
162
+ if (!res.ok) throw new Error(`HTTP ${res.status} for ${url.split('/').slice(-2).join('/')}`);
163
+ const len = Number(res.headers.get('content-length') || 0);
164
+ if (len > maxBytes) throw new Error('download too large');
165
+ const buf = Buffer.from(await res.arrayBuffer());
166
+ if (buf.length > maxBytes) throw new Error('download too large');
167
+ return buf;
168
+ }
169
+
170
+ // Replace the packaged canonical exe with release `version`. Resolves
171
+ // { ok, output }. Nothing is swapped unless the download matches SHA256SUMS
172
+ // AND the new binary answers `--version` with exactly `version`. Windows can't
173
+ // overwrite a running exe but can rename it, so the running copy is moved to
174
+ // .old-<ts> (setup's sweepStaleCanonicalBackups removes it later).
175
+ export async function installPackaged(version, { exe = CANONICAL_EXE, asset = packagedAsset(), base = RELEASE_BASE, fetchFn = fetchBuffer, runVersion = runExeVersion } = {}) {
176
+ if (!parseVersion(version)) return { ok: false, output: 'bad version' };
177
+ if (!asset) return { ok: false, output: 'no prebuilt binary for this platform' };
178
+ const tmp = `${exe}.new`;
179
+ try {
180
+ const sums = (await fetchFn(`${base}/v${version}/SHA256SUMS`, { timeoutMs: 15_000, maxBytes: 64 * 1024 })).toString('utf8');
181
+ const want = checksumFor(sums, asset);
182
+ if (!want) return { ok: false, output: `SHA256SUMS for v${version} has no entry for ${asset}` };
183
+ const bin = await fetchFn(`${base}/v${version}/${asset}`, { timeoutMs: INSTALL_TIMEOUT_MS, maxBytes: MAX_ASSET_BYTES });
184
+ const got = createHash('sha256').update(bin).digest('hex');
185
+ if (got !== want) return { ok: false, output: `checksum mismatch for ${asset} (got ${got.slice(0, 12)}…, want ${want.slice(0, 12)}…)` };
186
+ writeFileSync(tmp, bin);
187
+ if (process.platform !== 'win32') chmodSync(tmp, 0o755);
188
+ const said = await runVersion(tmp);
189
+ if (said !== version) throw new Error(`downloaded binary reports ${said || 'nothing'}, expected ${version}`);
190
+ if (process.platform === 'win32' && existsSync(exe)) renameSync(exe, `${exe}.old-${Date.now()}`);
191
+ renameSync(tmp, exe);
192
+ return { ok: true, output: `replaced ${exe}` };
193
+ } catch (e) {
194
+ try { unlinkSync(tmp); } catch { /* never written */ }
195
+ return { ok: false, output: String(e?.message || e) };
196
+ }
197
+ }
198
+
199
+ // `<exe> --version` → "1.2.3" or null.
200
+ export async function runExeVersion(exe) {
201
+ const { execFile } = await import('node:child_process');
202
+ return new Promise((resolve) => {
203
+ execFile(exe, ['--version'], { timeout: 20_000, windowsHide: true }, (err, stdout) => {
204
+ if (err) return resolve(null);
205
+ const m = /(\d+\.\d+\.\d+)/.exec(String(stdout));
206
+ resolve(m ? m[1] : null);
207
+ });
208
+ });
209
+ }
210
+
211
+ // Can this process replace its own package? (npm writes the new copy into the
212
+ // folder that holds ours: …/lib/node_modules on POSIX, %AppData%\npm\node_modules.)
213
+ export function installDirWritable(root = ROOT) {
214
+ try { accessSync(dirname(root), fsConstants.W_OK); return true; } catch { return false; }
215
+ }
216
+
217
+ // The version now on disk where THIS copy lives. npm exiting 0 doesn't mean it
218
+ // replaced us: with a different npm prefix (volta, pnpm/yarn/bun globals, a
219
+ // changed `npm config prefix`) it installs somewhere else, the restart comes
220
+ // back up on the old code, and the daemon reinstalled again every 5 minutes.
221
+ export function installedVersion(root = ROOT) {
222
+ try { return JSON.parse(readFileSync(join(root, 'package.json'), 'utf8')).version || null; } catch { return null; }
223
+ }
224
+
225
+ // One check cycle. Returns { plan, latest, installed }. `install`, `verify`
226
+ // and `writable` are injectable for tests; callers restart the daemon when
227
+ // `installed` is true.
228
+ export async function checkForUpdate({ current, auto, kind = installKind(), packagedOk = kind === 'packaged' && packagedSelfUpdatable(), fetchLatestFn = fetchLatest, install = kind === 'packaged' ? installPackaged : installVersion, verify = kind === 'packaged' ? () => true : (v) => installedVersion() === v, writable = kind === 'packaged' ? () => installDirWritable(CANONICAL_EXE) : installDirWritable, now = Date.now(), cooldownMs = COOLDOWN_MS, statePath = UPDATE_STATE_PATH } = {}) {
124
229
  const latest = await fetchLatestFn();
125
230
  writeUpdateState({ checkedAt: now, ...(latest ? { latest } : {}) }, statePath);
126
231
  if (!latest) return { plan: { action: 'none', reason: 'registry unreachable' }, latest: null, installed: false };
@@ -129,9 +234,15 @@ export async function checkForUpdate({ current, auto, kind = installKind(), fetc
129
234
  writeUpdateState({ seen: { version: latest, at: now } }, statePath);
130
235
  state = readUpdateState(statePath);
131
236
  }
132
- const plan = planUpdate({ current, latest, auto, kind, failed: state.failed || null, seen: state.seen || null, cooldownMs, now });
237
+ const selfUpdating = kind === 'npm-global' || (kind === 'packaged' && packagedOk);
238
+ const plan = planUpdate({ current, latest, auto, kind, packagedOk, writable: selfUpdating ? writable() : true, failed: state.failed || null, seen: state.seen || null, cooldownMs, now });
239
+ writeUpdateState({ lastPlan: { action: plan.action, reason: plan.reason, latest, at: now } }, statePath);
133
240
  if (plan.action !== 'install') return { plan, latest, installed: false };
134
241
  const res = await install(latest);
242
+ if (res.ok && !verify(latest)) {
243
+ res.ok = false;
244
+ 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.`;
245
+ }
135
246
  if (res.ok) {
136
247
  writeUpdateState({ updatedFrom: current, updatedTo: latest, updatedAt: now, failed: null }, statePath);
137
248
  return { plan, latest, installed: true };
package/src/version.js CHANGED
@@ -11,7 +11,7 @@ import { readFileSync } from 'node:fs';
11
11
  import { join } from 'node:path';
12
12
  import { ROOT } from './paths.js';
13
13
 
14
- const BAKED = '1.8.0';
14
+ const BAKED = '1.10.0';
15
15
 
16
16
  function readPkgVersion() {
17
17
  try {