claude-rpc 1.5.2 → 1.6.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.
Files changed (52) hide show
  1. package/README.md +72 -62
  2. package/SECURITY.md +99 -20
  3. package/package.json +2 -1
  4. package/src/atomic-rename.js +45 -2
  5. package/src/badge.js +3 -4
  6. package/src/card.js +1 -22
  7. package/src/cli-path.js +286 -0
  8. package/src/cli.js +430 -459
  9. package/src/commands.js +245 -0
  10. package/src/community.js +101 -60
  11. package/src/completion.js +196 -0
  12. package/src/config.js +4 -1
  13. package/src/daemon.js +45 -47
  14. package/src/default-config.js +4 -3
  15. package/src/discord-ipc.js +24 -13
  16. package/src/doctor.js +64 -38
  17. package/src/ensure-daemon.js +11 -4
  18. package/src/fmt.js +8 -6
  19. package/src/format.js +8 -13
  20. package/src/gist.js +8 -18
  21. package/src/git.js +4 -1
  22. package/src/help.js +117 -0
  23. package/src/hook.js +27 -32
  24. package/src/insights.js +3 -4
  25. package/src/install.js +100 -79
  26. package/src/leaderboard.js +3 -2
  27. package/src/mcp.js +2 -8
  28. package/src/nudge.js +10 -5
  29. package/src/png.js +135 -0
  30. package/src/pricing.js +25 -3
  31. package/src/privacy.js +22 -7
  32. package/src/profile.js +0 -6
  33. package/src/recap.js +4 -17
  34. package/src/scanner.js +103 -71
  35. package/src/select.js +60 -0
  36. package/src/server/api.js +64 -36
  37. package/src/server/assets/dashboard.client.js +75 -44
  38. package/src/server/assets/dashboard.css +18 -18
  39. package/src/server/assets/dashboard.html +13 -15
  40. package/src/server/assets/wrapped.client.js +26 -11
  41. package/src/server/assets/wrapped.css +2 -2
  42. package/src/server/index.js +43 -32
  43. package/src/server/page.js +6 -3
  44. package/src/server/sse.js +90 -34
  45. package/src/session-card.js +3 -1
  46. package/src/statcards.js +278 -0
  47. package/src/state.js +14 -24
  48. package/src/tui.js +3 -12
  49. package/src/ui.js +7 -5
  50. package/src/verify.js +3 -7
  51. package/src/version.js +1 -1
  52. package/src/week.js +4 -4
@@ -0,0 +1,196 @@
1
+ // Shell tab completion. Each script is a thin shim that asks
2
+ // `claude-rpc __complete <words…>` for candidates, so the command table in
3
+ // commands.js is the only list — new commands complete without reinstalling.
4
+ //
5
+ // claude-rpc completion <bash|zsh|fish|powershell> print the script
6
+ // claude-rpc completion install [shell] turn it on
7
+ // claude-rpc completion uninstall turn it off everywhere
8
+ //
9
+ // install writes the script under <config dir>/completion/ and adds one
10
+ // marked line to the shell's rc file (fish needs no rc line: its completions
11
+ // dir autoloads). Re-running is a no-op; uninstall removes exactly the marked
12
+ // block.
13
+
14
+ import { existsSync, mkdirSync, readFileSync, writeFileSync, unlinkSync } from 'node:fs';
15
+ import { homedir } from 'node:os';
16
+ import { join, dirname, basename } from 'node:path';
17
+ import { SHELLS, FILES } from './commands.js';
18
+
19
+ const BEGIN = '# >>> claude-rpc completion >>>';
20
+ const END = '# <<< claude-rpc completion <<<';
21
+
22
+ export function scriptFor(shell) {
23
+ switch (shell) {
24
+ case 'bash': return `# claude-rpc tab completion (bash)
25
+ _claude_rpc() {
26
+ local cur=\${COMP_WORDS[COMP_CWORD]} line
27
+ local -a words=("\${COMP_WORDS[@]:1:COMP_CWORD}")
28
+ COMPREPLY=()
29
+ while IFS= read -r line; do
30
+ [ "$line" = "${FILES}" ] && { COMPREPLY=($(compgen -f -- "$cur")); return; }
31
+ [ -n "$line" ] && COMPREPLY+=("\${line%%$'\\t'*}")
32
+ done < <(claude-rpc __complete "\${words[@]}" 2>/dev/null)
33
+ }
34
+ complete -o nosort -F _claude_rpc claude-rpc 2>/dev/null || complete -F _claude_rpc claude-rpc
35
+ `;
36
+ case 'zsh': return `#compdef claude-rpc
37
+ # claude-rpc tab completion (zsh)
38
+ _claude_rpc() {
39
+ local -a lines items
40
+ local l
41
+ lines=("\${(@f)$(claude-rpc __complete "\${(@)words[2,CURRENT]}" 2>/dev/null)}")
42
+ if [[ "\${lines[1]}" == "${FILES}" ]]; then _files; return; fi
43
+ for l in $lines; do
44
+ [[ -z $l ]] && continue
45
+ if [[ $l == *$'\\t'* ]]; then items+=("\${\${l%%$'\\t'*}//:/\\\\:}:\${l#*$'\\t'}")
46
+ else items+=("\${l//:/\\\\:}"); fi
47
+ done
48
+ _describe -V 'claude-rpc' items
49
+ }
50
+ if (( ! $+functions[compdef] )); then autoload -Uz compinit && compinit; fi
51
+ compdef _claude_rpc claude-rpc
52
+ `;
53
+ case 'fish': return `# claude-rpc tab completion (fish)
54
+ function __claude_rpc_complete
55
+ set -l tokens (commandline -opc) (commandline -ct)
56
+ set -l out (claude-rpc __complete $tokens[2..-1] 2>/dev/null)
57
+ if test "$out[1]" = "${FILES}"
58
+ __fish_complete_path (commandline -ct)
59
+ else
60
+ printf '%s\\n' $out
61
+ end
62
+ end
63
+ complete -c claude-rpc -f -k -a '(__claude_rpc_complete)'
64
+ `;
65
+ case 'powershell': return `# claude-rpc tab completion (PowerShell)
66
+ Register-ArgumentCompleter -Native -CommandName claude-rpc, claude-rpc.exe -ScriptBlock {
67
+ param($wordToComplete, $commandAst, $cursorPosition)
68
+ # Words before the cursor; the one being typed goes via env because
69
+ # Windows PowerShell drops empty-string arguments to native commands.
70
+ $words = @($commandAst.CommandElements | Select-Object -Skip 1 |
71
+ Where-Object { $_.Extent.EndOffset -lt $cursorPosition } | ForEach-Object { $_.Extent.Text })
72
+ $env:CLAUDE_RPC_COMP_CUR = $wordToComplete
73
+ $out = @(& claude-rpc __complete @words 2>$null)
74
+ Remove-Item Env:CLAUDE_RPC_COMP_CUR -ErrorAction SilentlyContinue
75
+ if ($out.Count -gt 0 -and $out[0] -eq '${FILES}') { return }
76
+ foreach ($l in $out) {
77
+ if (-not $l) { continue }
78
+ $p = $l -split "\`t", 2
79
+ $tip = if ($p.Count -gt 1) { $p[1] } else { $p[0] }
80
+ [System.Management.Automation.CompletionResult]::new($p[0], $p[0], 'ParameterValue', $tip)
81
+ }
82
+ }
83
+ `;
84
+ default: return null;
85
+ }
86
+ }
87
+
88
+ // The shell the user is most likely typing in.
89
+ export function detectShell(env = process.env, platform = process.platform) {
90
+ const sh = basename(env.SHELL || '').replace(/\.exe$/i, '');
91
+ if (SHELLS.includes(sh)) return sh;
92
+ if (sh === 'pwsh') return 'powershell';
93
+ if (platform === 'win32') return 'powershell';
94
+ return platform === 'darwin' ? 'zsh' : 'bash';
95
+ }
96
+
97
+ export function completionDir(configDir) {
98
+ return join(configDir, 'completion');
99
+ }
100
+
101
+ // Where each shell's pieces live. `rc` null → no rc edit needed.
102
+ export function targets(shell, { configDir, env = process.env, home = homedir(), profilePath, platform = process.platform } = {}) {
103
+ const dir = completionDir(configDir);
104
+ switch (shell) {
105
+ // macOS Terminal opens login shells, which read .bash_profile, not .bashrc.
106
+ case 'bash': return { script: join(dir, 'claude-rpc.bash'), rc: join(home, platform === 'darwin' ? '.bash_profile' : '.bashrc') };
107
+ case 'zsh': return { script: join(dir, 'claude-rpc.zsh'), rc: join(env.ZDOTDIR || home, '.zshrc') };
108
+ case 'fish': return { script: join(env.XDG_CONFIG_HOME || join(home, '.config'), 'fish', 'completions', 'claude-rpc.fish'), rc: null };
109
+ case 'powershell': return { script: join(dir, 'claude-rpc.ps1'), rc: profilePath || null };
110
+ default: return null;
111
+ }
112
+ }
113
+
114
+ function sourceLine(shell, script) {
115
+ if (shell === 'powershell') return `if (Test-Path '${script}') { . '${script}' }`;
116
+ return `[ -f '${script}' ] && . '${script}'`;
117
+ }
118
+
119
+ // rc text with our marked block added (idempotent) or removed.
120
+ export function withBlock(text, line) {
121
+ const clean = withoutBlock(text);
122
+ const sep = clean && !clean.endsWith('\n') ? '\n' : '';
123
+ return `${clean}${sep}${BEGIN}\n${line}\n${END}\n`;
124
+ }
125
+
126
+ export function withoutBlock(text) {
127
+ const a = text.indexOf(BEGIN);
128
+ if (a === -1) return text;
129
+ const b = text.indexOf(END, a);
130
+ if (b === -1) return text;
131
+ let tail = text.slice(b + END.length);
132
+ if (tail.startsWith('\r\n')) tail = tail.slice(2);
133
+ else if (tail.startsWith('\n')) tail = tail.slice(1);
134
+ return text.slice(0, a) + tail;
135
+ }
136
+
137
+ // PowerShell's $PROFILE path (CurrentUserCurrentHost), asked from the shell.
138
+ export async function powershellProfile() {
139
+ const { spawnSync } = await import('node:child_process');
140
+ for (const exe of ['pwsh', 'powershell']) {
141
+ try {
142
+ const r = spawnSync(exe, ['-NoProfile', '-NoLogo', '-Command', '$PROFILE'], { encoding: 'utf8', timeout: 8000, windowsHide: true });
143
+ const p = (r.stdout || '').trim();
144
+ if (r.status === 0 && p) return p;
145
+ } catch { /* not installed — try the next one */ }
146
+ }
147
+ return null;
148
+ }
149
+
150
+ export function isInstalled(shell, opts) {
151
+ const t = targets(shell, opts);
152
+ if (!t || !existsSync(t.script)) return false;
153
+ if (!t.rc) return true;
154
+ try { return readFileSync(t.rc, 'utf8').includes(BEGIN); } catch { return false; }
155
+ }
156
+
157
+ // Install for one shell. Returns { script, rc, changed }.
158
+ export function install(shell, opts) {
159
+ const t = targets(shell, opts);
160
+ if (!t) throw new Error(`unknown shell: ${shell}`);
161
+ if (shell === 'powershell' && !t.rc) throw new Error('could not find your PowerShell $PROFILE');
162
+ const body = scriptFor(shell);
163
+ let changed = false;
164
+ const prev = existsSync(t.script) ? readFileSync(t.script, 'utf8') : null;
165
+ if (prev !== body) {
166
+ mkdirSync(dirname(t.script), { recursive: true });
167
+ writeFileSync(t.script, body);
168
+ changed = true;
169
+ }
170
+ if (t.rc) {
171
+ const before = existsSync(t.rc) ? readFileSync(t.rc, 'utf8') : '';
172
+ const after = withBlock(before, sourceLine(shell, t.script));
173
+ if (after !== before) {
174
+ mkdirSync(dirname(t.rc), { recursive: true });
175
+ writeFileSync(t.rc, after);
176
+ changed = true;
177
+ }
178
+ }
179
+ return { ...t, changed };
180
+ }
181
+
182
+ // Remove from every shell we may have touched. Returns the paths changed.
183
+ export function uninstall(opts) {
184
+ const touched = [];
185
+ for (const shell of SHELLS) {
186
+ const t = targets(shell, opts);
187
+ if (!t) continue;
188
+ if (existsSync(t.script)) { try { unlinkSync(t.script); touched.push(t.script); } catch { /* locked — leave it */ } }
189
+ if (t.rc && existsSync(t.rc)) {
190
+ const before = readFileSync(t.rc, 'utf8');
191
+ const after = withoutBlock(before);
192
+ if (after !== before) { writeFileSync(t.rc, after); touched.push(t.rc); }
193
+ }
194
+ }
195
+ return touched;
196
+ }
package/src/config.js CHANGED
@@ -17,10 +17,13 @@
17
17
  // All callers (daemon, server/api, tui, cli) should go through
18
18
  // `loadConfig()` rather than reading CONFIG_PATH directly.
19
19
 
20
- import { readFileSync, existsSync } from 'node:fs';
20
+ import { createRequire } from 'node:module';
21
21
  import { CONFIG_PATH } from './paths.js';
22
22
  import { DEFAULT_CONFIG } from './default-config.js';
23
23
 
24
+ // require()d, not imported — on the hook hot path; see hook.js.
25
+ const { readFileSync, existsSync } = createRequire(import.meta.url)('node:fs');
26
+
24
27
  // "Has the user run setup?" — a separate signal from `loadConfig` because
25
28
  // loadConfig now always returns merged defaults (the daemon needs them
26
29
  // even if the file isn't there yet). Callers that want to distinguish
package/src/daemon.js CHANGED
@@ -5,7 +5,7 @@ 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';
7
7
  import { makeRotationCursor, pickFrames, selectFrame, resolveLargeImageKey, shouldShowGithubButton, pickActiveSession, throttleDecision } from './presence.js';
8
- import { buildVars, fillTemplate, framePasses, applyIdle, applyShipped, applyTrigger } from './format.js';
8
+ import { buildVars, fillTemplate, framePasses, applyIdle, applyShipped, applyTrigger, humanProject } from './format.js';
9
9
  import { scan, readAggregate, findLiveSessions, readSessionTokens, readSessionModel } from './scanner.js';
10
10
  import { detectClaudeProcess } from './claude-proc.js';
11
11
  import { detectGithubUrl } from './git.js';
@@ -15,7 +15,6 @@ 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 { humanProject } from './format.js';
19
18
  import { CONFIG_PATH, STATE_PATH, PID_PATH, LOG_PATH, STATE_DIR, AGGREGATE_PATH, PAUSE_PATH } from './paths.js';
20
19
  import { readUsageCache, pollUsage } from './usage.js';
21
20
  import { pollDecision, pollIntervalMs } from './watch-poll.js';
@@ -77,19 +76,14 @@ function loadConfigWithLog() {
77
76
  return loadConfig({ onError: (msg) => log(msg) });
78
77
  }
79
78
 
80
- // Bring an existing config.json up to date with the current defaults before
81
- // we load it. This is how upgrades reach users who just `npm update` + restart
82
- // the daemon without re-running `claude-rpc setup` — e.g. the v0.8.1 button-URL
83
- // move. Idempotent: only writes when something actually changes, so steady-state
84
- // restarts are a no-op and can't loop the config watcher. Best-effort — a
85
- // migration failure must never stop the daemon from starting.
86
79
  // Self-heal on update — when this daemon is a newer version than the last one
87
80
  // that ran, re-wire hooks (their command/path drifts across versions) and
88
81
  // migrate config to the current shape, then stamp the version. This is how an
89
82
  // `npm update` reaches users who never re-run setup: there is no install script
90
83
  // (by design), so the daemon — itself brought up by the SessionStart self-heal —
91
84
  // carries the update forward. A since-0.1.0 install converges to the current
92
- // hooks + config the first time it's used after updating.
85
+ // hooks + config the first time it's used after updating. Runs before the
86
+ // config load below; best-effort — a failure must never stop the daemon.
93
87
  try {
94
88
  const healed = selfHealOnUpdate({ silent: true });
95
89
  if (healed.changed) {
@@ -206,36 +200,31 @@ if (sweepTimer.unref) sweepTimer.unref();
206
200
  // clear-vs-push decision and the rendered frame are guaranteed to agree —
207
201
  // previously this chain ran twice and only buildActivity applied the trigger
208
202
  // overlay, so the two could diverge.
209
- function resolvePresence(opts = {}) {
203
+ function resolvePresence() {
210
204
  let state;
211
- if (opts.state) {
212
- state = opts.state; // standalone caller (preview/api) passes an explicit state
205
+ // Multi-session: each session writes its own state-<id>.json. Pick which one
206
+ // to show, sticking with the current session while it's active so the card
207
+ // doesn't thrash between projects (which also stabilizes the elapsed timer
208
+ // and the GitHub button — both follow the displayed session). Fall back to
209
+ // the legacy global state.json when there are no per-session files.
210
+ const sessions = listSessionStates();
211
+ if (sessions.length) {
212
+ const idleMs = Math.max(30_000, (config.idleThresholdSec || 60) * 1000);
213
+ const picked = pickActiveSession(sessions, displayedSessionId, Date.now(), idleMs);
214
+ displayedSessionId = picked.sessionId;
215
+ state = picked.state || readState();
216
+ // Party count from the SAME per-session list we selected from, so the
217
+ // "N sessions" field stays consistent with the card instead of wobbling
218
+ // on transcript-mtime timing.
219
+ state._liveCount = picked.liveCount;
213
220
  } else {
214
- // Multi-session: each session writes its own state-<id>.json. Pick which one
215
- // to show, sticking with the current session while it's active so the card
216
- // doesn't thrash between projects (which also stabilizes the elapsed timer
217
- // and the GitHub button — both follow the displayed session). Fall back to
218
- // the legacy global state.json when there are no per-session files.
219
- const sessions = listSessionStates();
220
- if (sessions.length) {
221
- const idleMs = Math.max(30_000, (config.idleThresholdSec || 60) * 1000);
222
- const picked = pickActiveSession(sessions, displayedSessionId, Date.now(), idleMs);
223
- displayedSessionId = picked.sessionId;
224
- state = picked.state || readState();
225
- // Party count from the SAME per-session list we selected from, so the
226
- // "N sessions" field stays consistent with the card instead of wobbling
227
- // on transcript-mtime timing.
228
- state._liveCount = picked.liveCount;
229
- } else {
230
- state = readState();
231
- }
221
+ state = readState();
232
222
  }
233
223
  // Attach live sessions BEFORE applyIdle so the stale/idle decision can
234
224
  // see ongoing transcript activity, not just this daemon's hook state.
235
- state.liveSessions = opts.liveSessions || liveSessions;
236
- // Same injection pattern for OS-level process liveness — standalone callers
237
- // (preview/api) that pass an explicit state simply leave it undefined and
238
- // get the historical transcript-only behavior.
225
+ state.liveSessions = liveSessions;
226
+ // Same for OS-level process liveness (claude-proc poll), unless the state
227
+ // already carries a verdict.
239
228
  if (state.claudeProcessAlive === undefined) state.claudeProcessAlive = claudeProcAlive;
240
229
  state = applyIdle(state, config);
241
230
  // Shipped overlay sits on top of idle/working/thinking — but never over
@@ -298,15 +287,13 @@ function resolvePresence(opts = {}) {
298
287
  return state;
299
288
  }
300
289
 
301
- function buildActivity(opts = {}) {
302
- // opts.resolved is an already-resolved state (the common path, from
303
- // pushPresence). Fall back to resolving here for any standalone caller.
304
- const state = opts.resolved || resolvePresence(opts);
305
-
290
+ // Render the Discord activity for a state resolvePresence() already resolved
291
+ // (pushPresence's single resolution per tick).
292
+ function buildActivity(state) {
306
293
  // Subscription usage rides in like liveSessions: injected onto state so
307
294
  // buildVars stays pure. Stale/missing cache → null → usage frames vanish.
308
295
  state.usage = readUsageCache();
309
- const vars = buildVars(state, config, opts.aggregate || aggregate);
296
+ const vars = buildVars(state, config, aggregate);
310
297
  const p = config.presence || {};
311
298
 
312
299
  // Pick the active set of frames + any status-level largeImageText override.
@@ -471,7 +458,7 @@ function pushPresence() {
471
458
  return;
472
459
  }
473
460
 
474
- const activity = buildActivity({ resolved });
461
+ const activity = buildActivity(resolved);
475
462
  transmit('set', activity, `Presence updated: ${activity.details || '-'} | ${activity.state || '-'}`);
476
463
  } catch (e) {
477
464
  log('pushPresence failed:', e.message);
@@ -618,9 +605,19 @@ async function connect() {
618
605
  // both hold, so the watchdog's "down, nothing pending" branch would spawn a
619
606
  // second connect() that overwrites `client` and orphans this socket. Block it.
620
607
  connecting = true;
621
- client = new Client({ clientId: config.clientId, transport: { type: 'ipc' } });
608
+ // Retire the previous client before replacing it. Left alive, a socket it
609
+ // still held (e.g. from a login that timed out) would close later and its
610
+ // 'disconnected' would mark the NEW, healthy client down and reconnect.
611
+ if (client) {
612
+ client.removeAllListeners();
613
+ try { client.destroy(); } catch { /* already gone */ }
614
+ }
615
+ const self = new Client({ clientId: config.clientId, transport: { type: 'ipc' } });
616
+ client = self;
622
617
 
623
- client.on('ready', () => {
618
+ // Every handler ignores events from a client that has since been replaced.
619
+ self.on('ready', () => {
620
+ if (client !== self) return;
624
621
  connected = true;
625
622
  // Reset backoff so the next outage also starts at RECONNECT_BASE_MS.
626
623
  reconnectDelayMs = RECONNECT_BASE_MS;
@@ -636,15 +633,16 @@ async function connect() {
636
633
  resetTransmit();
637
634
  pushPresence();
638
635
  });
639
- client.on('disconnected', () => {
636
+ self.on('disconnected', () => {
637
+ if (client !== self) return;
640
638
  connected = false;
641
639
  scheduleReconnect('Discord disconnected');
642
640
  });
643
- try { await client.login(); }
641
+ try { await self.login(); }
644
642
  catch (e) {
645
- scheduleReconnect(`Discord login failed: ${e.message}`);
643
+ if (client === self) scheduleReconnect(`Discord login failed: ${e.message}`);
646
644
  } finally {
647
- connecting = false;
645
+ if (client === self) connecting = false;
648
646
  }
649
647
  }
650
648
 
@@ -16,9 +16,10 @@ export const DEFAULT_CONFIG = {
16
16
  rotationIntervalMs: 12000,
17
17
  // Self-heal: the SessionStart hook (re)starts the daemon whenever it isn't
18
18
  // already running, so presence is assured whenever you use Claude Code —
19
- // surviving reboots, crashes, OS sleep, and platforms with no login-autostart
20
- // entry (macOS/Linux). Set false to disable that and manage the daemon
21
- // yourself with `claude-rpc start` / `stop`.
19
+ // surviving reboots, crashes, OS sleep, and a login-autostart entry (Run key
20
+ // / LaunchAgent / systemd --user) that's missing or unsupported. Set false
21
+ // to disable that and manage the daemon yourself with `claude-rpc start` /
22
+ // `stop`.
22
23
  autostart: true,
23
24
  // Minimum gap (ms) between Discord SET_ACTIVITY writes. Discord hard-limits
24
25
  // activity updates (~5 per 20s); blowing past it makes the client EMPTY the
@@ -177,6 +177,8 @@ export class Client extends EventEmitter {
177
177
  // pathList override is used by tests to point at a fake server; production
178
178
  // leaves it undefined and we discover the real Discord socket.
179
179
  this._pathList = options.transport?.pathList;
180
+ // Likewise test-only: how long login() waits for READY.
181
+ this._readyTimeoutMs = options.readyTimeoutMs ?? CONNECT_TIMEOUT_MS;
180
182
  this.socket = null;
181
183
  this.user = null;
182
184
  this._pending = new Map(); // nonce → { resolve, reject }
@@ -243,7 +245,7 @@ export class Client extends EventEmitter {
243
245
  const err = new Error('Connection timed out');
244
246
  err.code = 'ETIMEDOUT';
245
247
  reject(err);
246
- }, CONNECT_TIMEOUT_MS);
248
+ }, this._readyTimeoutMs);
247
249
  if (typeof timer === 'object' && 'unref' in timer) timer.unref();
248
250
  this._readyResolve = () => {
249
251
  clearTimeout(timer);
@@ -261,7 +263,18 @@ export class Client extends EventEmitter {
261
263
 
262
264
  this._send(OP_HANDSHAKE, { v: 1, client_id: this.clientId });
263
265
 
264
- await ready;
266
+ try {
267
+ await ready;
268
+ } catch (e) {
269
+ // A failed login must not leave its socket behind. After a READY timeout
270
+ // it used to stay open, and when the peer closed it later this client
271
+ // emitted 'disconnected' — which the daemon read as its (by then
272
+ // replaced, healthy) connection dropping, and reconnected again.
273
+ this._readyResolve = this._readyReject = null;
274
+ this._teardownSocket();
275
+ this._connected = false;
276
+ throw e;
277
+ }
265
278
  // No OAuth scopes are ever requested, so READY === ready, same as the lib.
266
279
  this.emit('ready');
267
280
  }
@@ -355,16 +368,20 @@ export class Client extends EventEmitter {
355
368
  };
356
369
  }
357
370
 
358
- _onClose(reason) {
359
- const wasConnected = this._connected || !!this.socket;
360
- // Fail any in-flight requests so awaiters don't hang forever.
371
+ // Fail every in-flight request so awaiters don't hang forever.
372
+ _rejectPending(message) {
361
373
  for (const { reject, timer } of this._pending.values()) {
362
374
  clearTimeout(timer);
363
- const err = new Error(typeof reason === 'string' ? reason : 'Connection closed');
375
+ const err = new Error(message);
364
376
  err.code = 'ECONNRESET';
365
377
  reject(err);
366
378
  }
367
379
  this._pending.clear();
380
+ }
381
+
382
+ _onClose(reason) {
383
+ const wasConnected = this._connected || !!this.socket;
384
+ this._rejectPending(typeof reason === 'string' ? reason : 'Connection closed');
368
385
  if (this._readyReject && !this._connected) {
369
386
  const err = new Error('Connection closed before ready');
370
387
  err.code = 'ECONNRESET';
@@ -394,13 +411,7 @@ export class Client extends EventEmitter {
394
411
  // Reject in-flight requests (mirrors _onClose) — a pushPresence parked on
395
412
  // `await setActivity` when the watchdog tears the client down must settle,
396
413
  // not leak as a forever-pending promise.
397
- for (const { reject, timer } of this._pending.values()) {
398
- clearTimeout(timer);
399
- const err = new Error('Client destroyed');
400
- err.code = 'ECONNRESET';
401
- reject(err);
402
- }
403
- this._pending.clear();
414
+ this._rejectPending('Client destroyed');
404
415
  this._teardownSocket();
405
416
  this._connected = false;
406
417
  }
package/src/doctor.js CHANGED
@@ -6,20 +6,23 @@
6
6
  // run repeatedly. Exit code 0 when everything passes, 1 when any check fails.
7
7
 
8
8
  import { existsSync, readFileSync, statSync, readdirSync } from 'node:fs';
9
- import { join, basename } from 'node:path';
9
+ import { join } from 'node:path';
10
10
  import {
11
- IS_PACKAGED, IS_NPM_INSTALL, IS_INSTALLED,
11
+ IS_PACKAGED, IS_NPM_INSTALL,
12
12
  CONFIG_PATH, CANONICAL_EXE, USER_CONFIG_DIR, HOOK_SCRIPT,
13
13
  STATE_PATH, PID_PATH, LOG_PATH,
14
- AGGREGATE_PATH, SCAN_CACHE_PATH,
14
+ AGGREGATE_PATH,
15
15
  CLAUDE_HOME, CLAUDE_PROJECTS, CLAUDE_SETTINGS,
16
16
  } from './paths.js';
17
17
  import { findLiveSessions } from './scanner.js';
18
+ import { listSessionStates, readActiveState } from './state.js';
19
+ import { isAlive } from './ensure-daemon.js';
18
20
  import { detectGithubUrl } from './git.js';
19
21
  import { resolveVisibility, listPrivateCwds, detectGithubPrivate } from './privacy.js';
20
22
  import { readClaudeCredentials, readUsageCache } from './usage.js';
21
23
  import { EVENTS as HOOK_EVENTS, isOurHook } from './install.js';
22
24
  import { c, check as uiCheck } from './ui.js';
25
+ import { findOnPath, pathExportHint } from './cli-path.js';
23
26
 
24
27
  const counters = { pass: 0, fail: 0, warn: 0 };
25
28
 
@@ -69,18 +72,9 @@ function checkNodeVersion() {
69
72
  }
70
73
 
71
74
  function checkMode() {
72
- let mode, detail;
73
- if (IS_PACKAGED) {
74
- mode = 'pass';
75
- detail = `packaged exe at ${process.execPath}`;
76
- } else if (IS_NPM_INSTALL) {
77
- mode = 'pass';
78
- detail = 'npm install (global or local node_modules)';
79
- } else {
80
- mode = 'pass';
81
- detail = 'dev source (cloned repo, no node_modules wrapper)';
82
- }
83
- check('execution mode', mode, detail);
75
+ check('execution mode', 'pass', IS_PACKAGED ? `packaged exe at ${process.execPath}`
76
+ : IS_NPM_INSTALL ? 'npm install (global or local node_modules)'
77
+ : 'dev source (cloned repo, no node_modules wrapper)');
84
78
  }
85
79
 
86
80
  // Pure classifiers — extracted so doctor's decision logic is unit-testable
@@ -283,8 +277,18 @@ function checkCanonicalExe() {
283
277
  }
284
278
  }
285
279
 
286
- function isAlive(pid) {
287
- try { process.kill(pid, 0); return true; } catch { return false; }
280
+ // Every command setup, doctor and the docs print is `claude-rpc …`, which only
281
+ // works when the shell can find it. Packaged installs live in <config dir>/bin,
282
+ // off PATH; setup puts them on it (see cli-path.js).
283
+ function checkCliOnPath() {
284
+ if (!IS_PACKAGED) return;
285
+ const found = findOnPath('claude-rpc');
286
+ if (found) { check('claude-rpc on PATH', 'pass', found); return; }
287
+ check('claude-rpc on PATH', 'warn', `not found — this terminal can run it as "${CANONICAL_EXE}"`,
288
+ process.platform === 'win32'
289
+ ? 'run `setup` again to add it to your user PATH (or `doctor --fix`), then open a new terminal'
290
+ : `run \`setup\` again (or \`doctor --fix\`) to link ~/.local/bin/claude-rpc; if ~/.local/bin isn't on PATH: ${pathExportHint()}`,
291
+ 'setup');
288
292
  }
289
293
 
290
294
  function checkDaemon() {
@@ -353,23 +357,47 @@ function checkDaemonLog() {
353
357
  }
354
358
  }
355
359
 
360
+ // Hook-written session state. Real sessions write per-session
361
+ // state-<sid>.json files (the global state.json only backs hook payloads
362
+ // without a session id), so judge the session the card would show. An old
363
+ // last hook event is only a problem while Claude Code is visibly active —
364
+ // that's hooks not firing; otherwise it's just an idle machine.
365
+ export const STATE_FRESH_MS = 5 * 60_000;
366
+
367
+ export function classifySessionState({ sessionCount, legacyExists, active, liveTranscripts, now = Date.now() }) {
368
+ if (!sessionCount && !legacyExists) {
369
+ return { label: 'session state', status: 'warn', detail: 'none yet', hint: 'created by the first hook event of a Claude Code session' };
370
+ }
371
+ const ageMs = active?.lastActivity ? now - active.lastActivity : Infinity;
372
+ const ageLabel = ageMs === Infinity ? 'never' : `${(ageMs / 60_000).toFixed(1)} min ago`;
373
+ const files = sessionCount ? `${sessionCount} session${sessionCount === 1 ? '' : 's'}` : 'legacy state.json only';
374
+ const detail = `${files} · status=${active?.status} · last hook event ${ageLabel}`;
375
+ if (ageMs <= STATE_FRESH_MS) return { label: 'session state fresh', status: 'pass', detail };
376
+ if (liveTranscripts) {
377
+ return {
378
+ label: 'session state fresh', status: 'warn', detail,
379
+ hint: 'claude code is writing a transcript but no hook has updated the state — run `claude-rpc setup` to re-wire the hooks',
380
+ fixKind: 'setup',
381
+ };
382
+ }
383
+ return { label: 'session state', status: 'info', detail: `${detail} · no session active` };
384
+ }
385
+
356
386
  function checkState() {
357
- if (!existsSync(STATE_PATH)) {
358
- check('state.json', 'warn', 'not present', 'created by the first hook event');
359
- return;
360
- }
361
- let state;
362
- try { state = JSON.parse(readFileSync(STATE_PATH, 'utf8')); }
363
- catch (e) {
364
- check('state.json', 'fail', `parse error: ${e.message}`,
365
- `delete ${STATE_PATH} and let the next hook event recreate it`);
366
- return;
387
+ try {
388
+ const sessions = listSessionStates();
389
+ let liveTranscripts = false;
390
+ try { liveTranscripts = findLiveSessions({ thresholdMs: 90_000 }).length > 0; } catch { /* unknown → treat as idle */ }
391
+ const r = classifySessionState({
392
+ sessionCount: sessions.length,
393
+ legacyExists: existsSync(STATE_PATH),
394
+ active: readActiveState(),
395
+ liveTranscripts,
396
+ });
397
+ check(r.label, r.status, r.detail, r.hint, r.fixKind);
398
+ } catch (e) {
399
+ check('session state', 'warn', `lookup failed: ${e.message}`);
367
400
  }
368
- const ageMin = state.lastActivity
369
- ? (Date.now() - state.lastActivity) / 60_000
370
- : Infinity;
371
- const ageLabel = ageMin === Infinity ? 'never' : `${ageMin.toFixed(1)} min ago`;
372
- check('state.json fresh', 'pass', `status=${state.status} · last activity ${ageLabel}`);
373
401
  }
374
402
 
375
403
  function checkAggregate() {
@@ -386,7 +414,7 @@ function checkAggregate() {
386
414
  `${agg.sessions || 0} sessions · ${hours}h · refreshed ${ageMin.toFixed(0)} min ago`);
387
415
  } catch (e) {
388
416
  check('aggregate built', 'fail', `parse error: ${e.message}`,
389
- 'run `claude-rpc rescan` to rebuild the aggregate from scratch', 'rescan');
417
+ 'run `claude-rpc scan --force` to rebuild the aggregate from scratch', 'rescan');
390
418
  }
391
419
  }
392
420
 
@@ -402,11 +430,8 @@ function checkPrivacy(cfg) {
402
430
  : visibility === 'name-only' ? 'warn'
403
431
  : 'pass';
404
432
  check('current directory visibility', status, detail);
405
- if (listed.length) {
406
- check('private-list entries', 'pass', `${listed.length} ${listed.length === 1 ? 'path' : 'paths'} marked private`);
407
- } else {
408
- check('private-list entries', 'pass', 'none');
409
- }
433
+ check('private-list entries', 'pass',
434
+ listed.length ? `${listed.length} ${listed.length === 1 ? 'path' : 'paths'} marked private` : 'none');
410
435
  // Private-repo guard. The "View on GitHub →" button URL is read from
411
436
  // .git/config (no gh needed), but auto-hiding a PRIVATE repo needs the gh
412
437
  // CLI. On a github repo here where the button would show (public verdict,
@@ -489,6 +514,7 @@ export function runDoctor() {
489
514
  checkNodeVersion();
490
515
  checkMode();
491
516
  checkCanonicalExe();
517
+ checkCliOnPath();
492
518
 
493
519
  section('Config');
494
520
  checkDataDir();