claude-rpc 1.6.0 → 1.7.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 +1 -1
- package/SECURITY.md +22 -6
- package/package.json +1 -1
- package/src/cli.js +42 -0
- package/src/commands.js +3 -0
- package/src/daemon.js +27 -1
- package/src/default-config.js +10 -3
- package/src/install.js +2 -0
- package/src/updater.js +141 -0
- package/src/version.js +1 -1
package/README.md
CHANGED
|
@@ -15,7 +15,7 @@
|
|
|
15
15
|
|
|
16
16
|
**Discord Rich Presence for [Claude Code](https://claude.com/claude-code)** — your live model, project, tokens, and lifetime stats, driven by the hooks Claude Code already fires.
|
|
17
17
|
|
|
18
|
-
**[claude-rpc.com →](https://claude-rpc.com)** — see it in one page.
|
|
18
|
+
**[claude-rpc.com →](https://claude-rpc.com)** — see it in one page. · **[Discord →](https://claude-rpc.com/discord?s=readme)** — help, ideas, show your card.
|
|
19
19
|
|
|
20
20
|
[](#community-totals) [](#community-totals)
|
|
21
21
|
|
package/SECURITY.md
CHANGED
|
@@ -137,11 +137,11 @@ described under **Scope** below.
|
|
|
137
137
|
|
|
138
138
|
## 3. Outbound network
|
|
139
139
|
|
|
140
|
-
There are
|
|
140
|
+
There are seven distinct network behaviors: community totals (3a), gist
|
|
141
141
|
publishing (3b), squads/web login (3c), subscription-usage polling (3d),
|
|
142
|
-
the cosmetic GIF assets (3e),
|
|
143
|
-
independently optional. The separate
|
|
144
|
-
additionally auto-updates itself (3g).
|
|
142
|
+
the cosmetic GIF assets (3e), the opt-in status webhook (3f), and the
|
|
143
|
+
CLI auto-update check (3h). Each is independently optional. The separate
|
|
144
|
+
desktop dashboard app, if installed, additionally auto-updates itself (3g).
|
|
145
145
|
|
|
146
146
|
### 3a. Community totals (telemetry) — ON by default for fresh installs
|
|
147
147
|
|
|
@@ -342,20 +342,36 @@ removing `webhook.url`.
|
|
|
342
342
|
|
|
343
343
|
### 3g. Desktop dashboard auto-update — the optional Electron app only
|
|
344
344
|
|
|
345
|
-
**Source:** `dashboard/main.js` (`initAutoUpdater`, electron-updater). The
|
|
346
|
-
CLI package never auto-updates. The *separate* desktop dashboard app, if you
|
|
345
|
+
**Source:** `dashboard/main.js` (`initAutoUpdater`, electron-updater). The *separate* desktop dashboard app, if you
|
|
347
346
|
install it, polls GitHub Releases hourly and downloads + installs updates on
|
|
348
347
|
quit (`autoDownload` / `autoInstallOnAppQuit`) over HTTPS. The release binaries
|
|
349
348
|
are currently **unsigned**, so update integrity rests on GitHub Releases + TLS
|
|
350
349
|
rather than a code signature — a known gap tracked for provenance + published
|
|
351
350
|
checksums. Avoid it by not installing the dashboard.
|
|
352
351
|
|
|
352
|
+
### 3h. CLI auto-update — ON by default, npm global installs only
|
|
353
|
+
|
|
354
|
+
**Source:** `src/updater.js`, called from the daemon; settings in
|
|
355
|
+
`default-config.js` (`update`). Every ~6 hours the daemon sends one plain
|
|
356
|
+
`GET https://registry.npmjs.org/claude-rpc/latest` (no identifiers, no
|
|
357
|
+
payload) and reads the `version` field. If a newer **same-major** release
|
|
358
|
+
exists and this copy was installed with `npm install -g`, it runs
|
|
359
|
+
`npm install -g claude-rpc@<exact version>` and restarts itself — the same
|
|
360
|
+
package, same npm integrity and provenance checks as a manual install.
|
|
361
|
+
Homebrew, `npx`, the packaged exe and source checkouts are never modified (they
|
|
362
|
+
only log that an update exists). A new major version is never installed
|
|
363
|
+
unattended, a failed install is not retried for 24 hours, and the version
|
|
364
|
+
string is validated as `x.y.z` before it reaches the command line.
|
|
365
|
+
**Turn it off:** `claude-rpc update off` (or `update.auto: false`).
|
|
366
|
+
`claude-rpc update` checks by hand; `claude-rpc update now` installs.
|
|
367
|
+
|
|
353
368
|
## 4. Local subprocesses
|
|
354
369
|
|
|
355
370
|
Every binary the package can spawn, with its trigger and argument shape. All
|
|
356
371
|
arguments are static constants or values we control — none interpolate
|
|
357
372
|
untrusted or remote input into a shell:
|
|
358
373
|
|
|
374
|
+
- `npm install -g claude-rpc@<x.y.z>` — auto-update / `update now` (`src/updater.js`, 3h).
|
|
359
375
|
- `reg.exe add/delete` — the Windows Run key (`src/install.js`).
|
|
360
376
|
- `wscript.exe` — runs the generated windowless startup shim (`src/install.js`).
|
|
361
377
|
- `powershell.exe -NoProfile -NonInteractive -EncodedCommand …` — packaged
|
package/package.json
CHANGED
package/src/cli.js
CHANGED
|
@@ -2190,6 +2190,47 @@ async function doCommunity(argv) {
|
|
|
2190
2190
|
});
|
|
2191
2191
|
}
|
|
2192
2192
|
|
|
2193
|
+
async function doUpdate(argv) {
|
|
2194
|
+
const sub = (argv[0] || 'check').toLowerCase();
|
|
2195
|
+
const { installKind, updateCommand, fetchLatest, isNewer, sameMajor, installVersion, readUpdateState, writeUpdateState } = await import('./updater.js');
|
|
2196
|
+
const kind = installKind();
|
|
2197
|
+
const userCfg = readJson(CONFIG_PATH, {});
|
|
2198
|
+
const auto = loadConfig().update?.auto !== false;
|
|
2199
|
+
if (sub === 'on' || sub === 'off') {
|
|
2200
|
+
userCfg.update = { ...userCfg.update, auto: sub === 'on' };
|
|
2201
|
+
writeUserConfig(userCfg);
|
|
2202
|
+
console.log(` ${c.green}✓${c.reset} auto-update ${sub === 'on' ? 'on' : 'off'}`);
|
|
2203
|
+
return;
|
|
2204
|
+
}
|
|
2205
|
+
if (sub === 'status') {
|
|
2206
|
+
const st = readUpdateState();
|
|
2207
|
+
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
|
+
if (st.updatedTo) console.log(` ${c.dim}last auto-update: ${st.updatedFrom} → ${st.updatedTo}${c.reset}`);
|
|
2209
|
+
return;
|
|
2210
|
+
}
|
|
2211
|
+
if (sub !== 'check' && sub !== 'now') {
|
|
2212
|
+
fail(`unknown update subcommand: ${sub}`, { hint: 'try: update [check|now|on|off|status]', code: EX_USER_ERROR });
|
|
2213
|
+
}
|
|
2214
|
+
const latest = await fetchLatest();
|
|
2215
|
+
if (!latest) fail('could not reach the npm registry', { hint: 'check your connection and try again', code: EX_BAD_STATE });
|
|
2216
|
+
if (!isNewer(latest, VERSION)) {
|
|
2217
|
+
console.log(` ${c.green}✓${c.reset} up to date ${c.dim}(v${VERSION})${c.reset}`);
|
|
2218
|
+
return;
|
|
2219
|
+
}
|
|
2220
|
+
console.log(` ${c.yellow}!${c.reset} v${latest} is available ${c.dim}(you have v${VERSION})${c.reset}`);
|
|
2221
|
+
if (kind !== 'npm-global' || sub === 'check') {
|
|
2222
|
+
console.log(` ${c.gray}↳ ${c.reset}${c.cyan}${kind === 'npm-global' ? 'claude-rpc update now' : updateCommand(kind)}${c.reset}`);
|
|
2223
|
+
return;
|
|
2224
|
+
}
|
|
2225
|
+
if (!sameMajor(latest, VERSION)) console.log(` ${c.dim}new major version — check the changelog first${c.reset}`);
|
|
2226
|
+
console.log(` ${c.dim}installing…${c.reset}`);
|
|
2227
|
+
const res = await installVersion(latest);
|
|
2228
|
+
if (!res.ok) fail('install failed', { hint: [res.output.slice(-300) || 'npm exited non-zero', `try: ${updateCommand(kind)}`], code: EX_BAD_STATE });
|
|
2229
|
+
writeUpdateState({ updatedFrom: VERSION, updatedTo: latest, updatedAt: Date.now(), failed: null });
|
|
2230
|
+
console.log(` ${c.green}✓${c.reset} updated to v${latest}`);
|
|
2231
|
+
await restartDaemon();
|
|
2232
|
+
}
|
|
2233
|
+
|
|
2193
2234
|
function tailLog() {
|
|
2194
2235
|
if (!existsSync(LOG_PATH)) {
|
|
2195
2236
|
console.log(` ${c.yellow}!${c.reset} no log yet ${c.dim}${LOG_PATH}${c.reset}`);
|
|
@@ -2588,6 +2629,7 @@ process.on('unhandledRejection', (e) => {
|
|
|
2588
2629
|
case 'public': await doPublic(); break;
|
|
2589
2630
|
case 'privacy': await doPrivacy(); break;
|
|
2590
2631
|
case 'community': await doCommunity(args); break;
|
|
2632
|
+
case 'update': await doUpdate(args); break;
|
|
2591
2633
|
case 'profile': await doProfile(args); break;
|
|
2592
2634
|
case 'squad': await doSquadCmd(args); break;
|
|
2593
2635
|
case 'link': await doLink(args); break;
|
package/src/commands.js
CHANGED
|
@@ -103,6 +103,9 @@ export const COMMANDS = [
|
|
|
103
103
|
{ name: 'community', group: 'online', summary: 'Anonymous community totals', usage: '[status|on|off|report]',
|
|
104
104
|
subs: [['status', 'Show it'], ['on', 'Opt in'], ['off', 'Opt out'], ['report', 'Send now']] },
|
|
105
105
|
|
|
106
|
+
{ name: 'update', group: 'daemon', summary: 'Check for a new version (and auto-update)', usage: '[check|now|on|off|status]',
|
|
107
|
+
subs: [['check', 'Look for a newer release'], ['now', 'Install it now'], ['on', 'Auto-update (default)'], ['off', 'Never update unattended'], ['status', 'Show settings']] },
|
|
108
|
+
|
|
106
109
|
// ── Daemon ──
|
|
107
110
|
{ name: 'start', group: 'daemon', summary: 'Start the Discord daemon' },
|
|
108
111
|
{ name: 'stop', group: 'daemon', summary: 'Stop it' },
|
package/src/daemon.js
CHANGED
|
@@ -18,7 +18,8 @@ import { desktopNotify, postWebhook, shouldWebhook, shouldNotify, sanitizeLabel
|
|
|
18
18
|
import { CONFIG_PATH, STATE_PATH, PID_PATH, LOG_PATH, STATE_DIR, AGGREGATE_PATH, PAUSE_PATH } from './paths.js';
|
|
19
19
|
import { readUsageCache, pollUsage } from './usage.js';
|
|
20
20
|
import { pollDecision, pollIntervalMs } from './watch-poll.js';
|
|
21
|
-
import { claimSingleInstance } from './ensure-daemon.js';
|
|
21
|
+
import { claimSingleInstance, spawnDaemonDetached } from './ensure-daemon.js';
|
|
22
|
+
import { checkForUpdate } from './updater.js';
|
|
22
23
|
import { scanInChild } from './scan-worker.js';
|
|
23
24
|
|
|
24
25
|
if (!existsSync(STATE_DIR)) mkdirSync(STATE_DIR, { recursive: true });
|
|
@@ -975,6 +976,31 @@ async function runCommunityFlush() {
|
|
|
975
976
|
const communityFlushMs = Math.max(60_000, (config.community?.flushIntervalMin || 30) * 60 * 1000);
|
|
976
977
|
setInterval(runCommunityFlush, communityFlushMs);
|
|
977
978
|
|
|
979
|
+
// Auto-update: check the registry, install a newer same-major release (npm
|
|
980
|
+
// global installs only), then hand over to a fresh daemon. The PID file is
|
|
981
|
+
// removed first so the replacement's single-instance claim succeeds while this
|
|
982
|
+
// process is still winding down.
|
|
983
|
+
async function runUpdateCheck() {
|
|
984
|
+
try {
|
|
985
|
+
const r = await checkForUpdate({ current: VERSION, auto: config.update?.auto !== false });
|
|
986
|
+
if (r.installed) {
|
|
987
|
+
log(`auto-update: ${VERSION} → ${r.latest} installed; restarting`);
|
|
988
|
+
try { if (existsSync(PID_PATH)) unlinkSync(PID_PATH); } catch { /* shutdown() retries */ }
|
|
989
|
+
spawnDaemonDetached();
|
|
990
|
+
setTimeout(shutdown, 500);
|
|
991
|
+
} else if (r.error) {
|
|
992
|
+
log(`auto-update: install of ${r.latest} failed: ${String(r.error).slice(-200)}`);
|
|
993
|
+
} else if (r.plan.action === 'notify') {
|
|
994
|
+
log(`auto-update: ${r.latest} available (${r.plan.reason})`);
|
|
995
|
+
}
|
|
996
|
+
} catch (e) {
|
|
997
|
+
log('auto-update check threw:', e.message);
|
|
998
|
+
}
|
|
999
|
+
}
|
|
1000
|
+
const updateEveryMs = Math.max(3_600_000, (config.update?.checkIntervalHours || 6) * 3_600_000);
|
|
1001
|
+
setInterval(runUpdateCheck, updateEveryMs);
|
|
1002
|
+
setTimeout(runUpdateCheck, 5 * 60_000);
|
|
1003
|
+
|
|
978
1004
|
// Subscription-usage poll (feeds {usageWeeklyPct} & friends + `claude-rpc
|
|
979
1005
|
// usage`). Only while something is live — no point burning requests against
|
|
980
1006
|
// an idle account — and backs off to hourly retries after a bad run, since
|
package/src/default-config.js
CHANGED
|
@@ -146,6 +146,13 @@ export const DEFAULT_CONFIG = {
|
|
|
146
146
|
endpoint: "https://claude-rpc-totals.claude-rpc.workers.dev",
|
|
147
147
|
flushIntervalMin: 30,
|
|
148
148
|
},
|
|
149
|
+
// Auto-update (npm global installs only; brew/npx/exe/source just get a
|
|
150
|
+
// notice). Same-major releases are installed unattended and the daemon
|
|
151
|
+
// restarts itself. Kill switch: `claude-rpc update off`. SECURITY.md §3h.
|
|
152
|
+
update: {
|
|
153
|
+
auto: true,
|
|
154
|
+
checkIntervalHours: 6,
|
|
155
|
+
},
|
|
149
156
|
// Subscription usage — the numbers Claude Code's own /usage screen shows
|
|
150
157
|
// (5h session %, weekly %). The daemon reads Claude Code's OAuth token
|
|
151
158
|
// LOCALLY and asks api.anthropic.com — the token's issuer — for the
|
|
@@ -258,10 +265,10 @@ export const DEFAULT_CONFIG = {
|
|
|
258
265
|
buttons: [
|
|
259
266
|
// The card others see in Discord is the project's main distribution
|
|
260
267
|
// surface — make the button a real call-to-action, not a bare repo link.
|
|
261
|
-
//
|
|
262
|
-
// from a presence card. (When the cwd is a github repo the daemon also
|
|
268
|
+
// Lands on /get (install first, then the Discord invite). ?ref=discord
|
|
269
|
+
// lets that page attribute installs that originate from a presence card. (When the cwd is a github repo the daemon also
|
|
263
270
|
// prepends a "View on GitHub →" button, so both can show.)
|
|
264
|
-
{ label: "Get claude-rpc →", url: "https://claude-rpc.com
|
|
271
|
+
{ label: "Get claude-rpc →", url: "https://claude-rpc.com/get?ref=discord" },
|
|
265
272
|
],
|
|
266
273
|
},
|
|
267
274
|
statusIcons: {
|
package/src/install.js
CHANGED
|
@@ -649,6 +649,7 @@ export function migrateConfig({ silent = false } = {}) {
|
|
|
649
649
|
const SHIPPED_DEFAULT_BTNS = [
|
|
650
650
|
{ label: 'Claude Code', url: 'https://claude.com/claude-code' },
|
|
651
651
|
{ label: 'Claude Code', url: 'https://github.com/rar-file/claude-rpc' },
|
|
652
|
+
{ label: 'Get claude-rpc →', url: 'https://claude-rpc.com/?ref=discord' }, // v0.13–1.6 CTA → /get
|
|
652
653
|
];
|
|
653
654
|
if (NEW_BTN && Array.isArray(cfg.presence?.buttons)) {
|
|
654
655
|
let changed = false;
|
|
@@ -942,6 +943,7 @@ export function setupOutro(target, changed = true, cli = { cmd: 'claude-rpc', ne
|
|
|
942
943
|
const run = cli.cmd || 'claude-rpc';
|
|
943
944
|
console.log('');
|
|
944
945
|
console.log(` ${SYM_OK} ${c.bold}setup complete${c.reset} — open Claude Code and send a prompt; your card goes live in Discord.`);
|
|
946
|
+
point('community', 'claude-rpc.com/discord?s=cli', 'questions, show your card');
|
|
945
947
|
point('verify wiring', `${run} doctor`, cli.newTerminal ? 'in a new terminal' : '');
|
|
946
948
|
if (IS_PACKAGED) point('start daemon', `"${target}" daemon`, 'also runs automatically at login');
|
|
947
949
|
else point('manage daemon', `${run} start · stop · status`);
|
package/src/updater.js
ADDED
|
@@ -0,0 +1,141 @@
|
|
|
1
|
+
// Auto-update for npm global installs.
|
|
2
|
+
//
|
|
3
|
+
// The daemon checks the npm registry every few hours; when a newer release in
|
|
4
|
+
// the SAME major line exists it runs `npm install -g claude-rpc@<exact
|
|
5
|
+
// version>`, then restarts itself. Hooks and config follow on their own — the
|
|
6
|
+
// daemon's self-heal-on-update (daemon.js) re-wires them on first boot of the
|
|
7
|
+
// new version. Everything else (brew, npx, the packaged exe, a source checkout)
|
|
8
|
+
// is never touched: those get a one-line "update available" with the right
|
|
9
|
+
// command. A new MAJOR is never installed unattended.
|
|
10
|
+
//
|
|
11
|
+
// Pure decision functions up top (unit-tested); side effects below.
|
|
12
|
+
|
|
13
|
+
import { readFileSync, writeFileSync, mkdirSync } from 'node:fs';
|
|
14
|
+
import { join, dirname, delimiter } from 'node:path';
|
|
15
|
+
import { STATE_DIR, ROOT, IS_PACKAGED, IS_NPM_INSTALL, IS_NPX } from './paths.js';
|
|
16
|
+
|
|
17
|
+
export const UPDATE_STATE_PATH = join(STATE_DIR, 'update.json');
|
|
18
|
+
export const REGISTRY_URL = 'https://registry.npmjs.org/claude-rpc/latest';
|
|
19
|
+
const RETRY_FAILED_MS = 24 * 3_600_000; // don't hammer a version that failed to install
|
|
20
|
+
const COOLDOWN_MS = 2 * 3_600_000; // a release must be seen this long before it's installed — a yank window
|
|
21
|
+
const INSTALL_TIMEOUT_MS = 180_000;
|
|
22
|
+
const FETCH_TIMEOUT_MS = 8_000;
|
|
23
|
+
|
|
24
|
+
const SEMVER = /^(\d+)\.(\d+)\.(\d+)$/; // no prereleases: only stable tags are ever considered
|
|
25
|
+
|
|
26
|
+
export function parseVersion(v) {
|
|
27
|
+
const m = SEMVER.exec(String(v || '').trim());
|
|
28
|
+
return m ? [Number(m[1]), Number(m[2]), Number(m[3])] : null;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export function isNewer(latest, current) {
|
|
32
|
+
const a = parseVersion(latest), b = parseVersion(current);
|
|
33
|
+
if (!a || !b) return false;
|
|
34
|
+
for (let i = 0; i < 3; i++) if (a[i] !== b[i]) return a[i] > b[i];
|
|
35
|
+
return false;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export function sameMajor(a, b) {
|
|
39
|
+
const x = parseVersion(a), y = parseVersion(b);
|
|
40
|
+
return !!x && !!y && x[0] === y[0];
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
// How this copy was installed → whether we may update it ourselves and what to
|
|
44
|
+
// tell the user otherwise.
|
|
45
|
+
export function installKind({ packaged = IS_PACKAGED, npm = IS_NPM_INSTALL, npx = IS_NPX, root = ROOT } = {}) {
|
|
46
|
+
if (packaged) return 'packaged';
|
|
47
|
+
if (npx) return 'npx';
|
|
48
|
+
if (/[\\/]Cellar[\\/]/.test(root)) return 'brew';
|
|
49
|
+
if (npm) return 'npm-global';
|
|
50
|
+
return 'dev';
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
export function updateCommand(kind) {
|
|
54
|
+
switch (kind) {
|
|
55
|
+
case 'packaged': return 'download the latest release from https://github.com/rar-file/claude-rpc/releases/latest';
|
|
56
|
+
case 'npx': return 'npx claude-rpc@latest setup';
|
|
57
|
+
case 'brew': return 'brew upgrade claude-rpc';
|
|
58
|
+
case 'dev': return 'git pull';
|
|
59
|
+
default: return 'npm install -g claude-rpc@latest';
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
|
|
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() }) {
|
|
65
|
+
if (!isNewer(latest, current)) return { action: 'none', reason: 'up to date' };
|
|
66
|
+
if (kind !== 'npm-global') return { action: 'notify', reason: `installed via ${kind}` };
|
|
67
|
+
if (!auto) return { action: 'notify', reason: 'auto-update is off' };
|
|
68
|
+
if (!sameMajor(latest, current)) return { action: 'notify', reason: 'new major version — update manually' };
|
|
69
|
+
if (failed && failed.version === latest && now - failed.at < RETRY_FAILED_MS) {
|
|
70
|
+
return { action: 'notify', reason: 'last install attempt failed — retrying later' };
|
|
71
|
+
}
|
|
72
|
+
if (cooldownMs > 0 && !(seen && seen.version === latest && now - seen.at >= cooldownMs)) {
|
|
73
|
+
return { action: 'notify', reason: 'new release is settling — installing after the cooldown' };
|
|
74
|
+
}
|
|
75
|
+
return { action: 'install', reason: 'newer release available' };
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
export function readUpdateState(path = UPDATE_STATE_PATH) {
|
|
79
|
+
try { return JSON.parse(readFileSync(path, 'utf8')) || {}; } catch { return {}; }
|
|
80
|
+
}
|
|
81
|
+
export function writeUpdateState(patch, path = UPDATE_STATE_PATH) {
|
|
82
|
+
try {
|
|
83
|
+
mkdirSync(STATE_DIR, { recursive: true });
|
|
84
|
+
writeFileSync(path, JSON.stringify({ ...readUpdateState(path), ...patch }));
|
|
85
|
+
} catch { /* best-effort: state is advisory */ }
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
// Latest published version, or null on any failure. Only the version string is
|
|
89
|
+
// read; nothing about this machine is sent (a bare GET to the public registry).
|
|
90
|
+
export async function fetchLatest({ url = REGISTRY_URL, timeoutMs = FETCH_TIMEOUT_MS } = {}) {
|
|
91
|
+
try {
|
|
92
|
+
const res = await fetch(url, { signal: AbortSignal.timeout(timeoutMs), headers: { accept: 'application/json' } });
|
|
93
|
+
if (!res.ok) return null;
|
|
94
|
+
const v = (await res.json())?.version;
|
|
95
|
+
return parseVersion(v) ? v : null;
|
|
96
|
+
} catch { return null; }
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
// Install exactly `version` globally. Resolves { ok, output }. `npm` is a .cmd
|
|
100
|
+
// shim on Windows, which only spawns through a shell.
|
|
101
|
+
export async function installVersion(version) {
|
|
102
|
+
if (!parseVersion(version)) return { ok: false, output: 'bad version' }; // also keeps the shell arg safe
|
|
103
|
+
const { spawn } = await import('node:child_process');
|
|
104
|
+
return new Promise((resolve) => {
|
|
105
|
+
let out = '';
|
|
106
|
+
const win = process.platform === 'win32';
|
|
107
|
+
const child = spawn(win ? 'npm.cmd' : 'npm', ['install', '-g', `claude-rpc@${version}`, '--no-fund', '--no-audit'],
|
|
108
|
+
// Put the running node's own dir first so `npm` is the one that belongs to
|
|
109
|
+
// this node (nvm/fnm/volta installs; a login-launched daemon often has a
|
|
110
|
+
// bare PATH) — i.e. the npm that created the global we're replacing.
|
|
111
|
+
{ shell: win, windowsHide: true, stdio: ['ignore', 'pipe', 'pipe'],
|
|
112
|
+
env: { ...process.env, PATH: `${dirname(process.execPath)}${delimiter}${process.env.PATH || ''}` } });
|
|
113
|
+
const timer = setTimeout(() => { try { child.kill(); } catch { /* gone */ } }, INSTALL_TIMEOUT_MS);
|
|
114
|
+
const take = (d) => { out = (out + d).slice(-2000); };
|
|
115
|
+
child.stdout.on('data', take); child.stderr.on('data', take);
|
|
116
|
+
child.on('error', (e) => { clearTimeout(timer); resolve({ ok: false, output: e.message }); });
|
|
117
|
+
child.on('close', (code) => { clearTimeout(timer); resolve({ ok: code === 0, output: out.trim() }); });
|
|
118
|
+
});
|
|
119
|
+
}
|
|
120
|
+
|
|
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 } = {}) {
|
|
124
|
+
const latest = await fetchLatestFn();
|
|
125
|
+
writeUpdateState({ checkedAt: now, ...(latest ? { latest } : {}) }, statePath);
|
|
126
|
+
if (!latest) return { plan: { action: 'none', reason: 'registry unreachable' }, latest: null, installed: false };
|
|
127
|
+
let state = readUpdateState(statePath);
|
|
128
|
+
if (state.seen?.version !== latest) { // first sighting starts the cooldown clock
|
|
129
|
+
writeUpdateState({ seen: { version: latest, at: now } }, statePath);
|
|
130
|
+
state = readUpdateState(statePath);
|
|
131
|
+
}
|
|
132
|
+
const plan = planUpdate({ current, latest, auto, kind, failed: state.failed || null, seen: state.seen || null, cooldownMs, now });
|
|
133
|
+
if (plan.action !== 'install') return { plan, latest, installed: false };
|
|
134
|
+
const res = await install(latest);
|
|
135
|
+
if (res.ok) {
|
|
136
|
+
writeUpdateState({ updatedFrom: current, updatedTo: latest, updatedAt: now, failed: null }, statePath);
|
|
137
|
+
return { plan, latest, installed: true };
|
|
138
|
+
}
|
|
139
|
+
writeUpdateState({ failed: { version: latest, at: now, output: res.output.slice(-300) } }, statePath);
|
|
140
|
+
return { plan: { action: 'notify', reason: 'install failed' }, latest, installed: false, error: res.output };
|
|
141
|
+
}
|