claude-rpc 1.5.4 → 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.
@@ -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/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
@@ -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
- // ?ref=discord lets the landing page attribute installs that originate
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/?ref=discord" },
271
+ { label: "Get claude-rpc →", url: "https://claude-rpc.com/get?ref=discord" },
265
272
  ],
266
273
  },
267
274
  statusIcons: {
package/src/doctor.js CHANGED
@@ -414,7 +414,7 @@ function checkAggregate() {
414
414
  `${agg.sessions || 0} sessions · ${hours}h · refreshed ${ageMin.toFixed(0)} min ago`);
415
415
  } catch (e) {
416
416
  check('aggregate built', 'fail', `parse error: ${e.message}`,
417
- 'run `claude-rpc rescan` to rebuild the aggregate from scratch', 'rescan');
417
+ 'run `claude-rpc scan --force` to rebuild the aggregate from scratch', 'rescan');
418
418
  }
419
419
  }
420
420
 
package/src/help.js ADDED
@@ -0,0 +1,117 @@
1
+ // `claude-rpc help` and `claude-rpc help <command>`, both rendered from the
2
+ // command table in commands.js.
3
+
4
+ import { c } from './ui.js';
5
+ import { VERSION } from './version.js';
6
+ import { GROUPS, ALIAS_HINT, findCommand, visibleCommands } from './commands.js';
7
+
8
+ const GROUP_STYLE = {
9
+ start: [c.green, '▸'],
10
+ stats: [c.cyan, '▤'],
11
+ share: [c.magenta, '↗'],
12
+ privacy: [c.yellow, '◐'],
13
+ online: [c.blue, '◎'],
14
+ daemon: [c.green, '●'],
15
+ fix: [c.red, '✚'],
16
+ };
17
+
18
+ const width = () => Math.max(60, Math.min(process.stdout.columns || 100, 110));
19
+
20
+ // Word-wrap `text` to `w` columns, continuation lines indented by `pad`.
21
+ function wrap(text, w, pad) {
22
+ if (w < 20 || text.length <= w) return text;
23
+ const out = [];
24
+ let line = '';
25
+ for (const word of text.split(' ')) {
26
+ if (line && line.length + 1 + word.length > w) { out.push(line); line = word; }
27
+ else line = line ? `${line} ${word}` : word;
28
+ }
29
+ if (line) out.push(line);
30
+ return out.join(`\n${' '.repeat(pad)}`);
31
+ }
32
+
33
+ function banner() {
34
+ const title = `${c.bold}${c.magenta}◆ claude-rpc${c.reset}`;
35
+ const tag = `${c.dim}Discord Rich Presence for Claude Code${c.reset}`;
36
+ const ver = `${c.gray}v${VERSION}${c.reset}`;
37
+ return `\n ${title} ${tag} ${ver}\n`;
38
+ }
39
+
40
+ export function renderHelp() {
41
+ const cmds = visibleCommands();
42
+ // Long synopses (recap's date forms) collapse to the bare name; `help <cmd>` has them.
43
+ const MAX = 24;
44
+ const label = (cmd) => {
45
+ const full = cmd.name + (cmd.usage ? ` ${cmd.usage}` : '');
46
+ return full.length > MAX ? cmd.name : full;
47
+ };
48
+ const colW = cmds.reduce((m, cmd) => Math.max(m, label(cmd).length), 0);
49
+ const descW = width() - colW - 8;
50
+ const lines = [banner()];
51
+
52
+ lines.push(` ${c.dim}Usage:${c.reset} ${c.bold}claude-rpc${c.reset} ${c.cyan}<command>${c.reset} ${c.dim}[options]${c.reset}\n`);
53
+
54
+ for (const [key, title] of GROUPS) {
55
+ const [color, icon] = GROUP_STYLE[key] || [c.cyan, '·'];
56
+ const inGroup = cmds.filter((cmd) => cmd.group === key);
57
+ if (!inGroup.length) continue;
58
+ lines.push(` ${color}${icon}${c.reset} ${c.bold}${title}${c.reset}`);
59
+ for (const cmd of inGroup) {
60
+ const shown = label(cmd);
61
+ const usage = shown !== cmd.name ? `${c.dim}${cmd.usage}${c.reset}` : '';
62
+ const head = `${c.cyan}${c.bold}${cmd.name}${c.reset}${usage ? ` ${usage}` : ''}`;
63
+ const pad = ' '.repeat(colW - shown.length + 2);
64
+ lines.push(` ${head}${pad}${wrap(cmd.summary, descW, colW + 6)}`);
65
+ }
66
+ lines.push('');
67
+ }
68
+
69
+ const tips = [
70
+ ['one command in detail', 'claude-rpc help <command>'],
71
+ ['tab completion', 'claude-rpc completion install'],
72
+ ['something off?', 'claude-rpc doctor --fix'],
73
+ ['docs', 'https://claude-rpc.com/docs'],
74
+ ];
75
+ const tipW = tips.reduce((m, [k]) => Math.max(m, k.length), 0);
76
+ for (const [k, v] of tips) lines.push(` ${c.gray}${k.padEnd(tipW)}${c.reset} ${c.cyan}${v}${c.reset}`);
77
+ lines.push('');
78
+ lines.push(` ${c.gray}exit codes: 0 ok · 1 usage error · 2 system error · 3 wrong state${c.reset}`);
79
+ lines.push('');
80
+ return lines.join('\n');
81
+ }
82
+
83
+ export function renderCommandHelp(name) {
84
+ const cmd = findCommand(name);
85
+ if (!cmd) return null;
86
+ const lines = [''];
87
+ const viaAlias = cmd.name !== name ? ` ${c.dim}(\`${name}\` still works — it's \`claude-rpc ${ALIAS_HINT[name] || cmd.name}\` now)${c.reset}` : '';
88
+ lines.push(` ${c.bold}${c.magenta}◆ claude-rpc ${cmd.name}${c.reset}${viaAlias}`);
89
+ lines.push(` ${cmd.summary}`);
90
+ lines.push('');
91
+ lines.push(` ${c.dim}Usage${c.reset}`);
92
+ lines.push(` ${c.bold}claude-rpc${c.reset} ${c.cyan}${cmd.name}${c.reset}${cmd.usage ? ` ${cmd.usage}` : ''}${cmd.flags?.length ? ` ${c.dim}[options]${c.reset}` : ''}`);
93
+ lines.push('');
94
+
95
+ const table = (title, rows) => {
96
+ if (!rows.length) return;
97
+ const w = rows.reduce((m, [k]) => Math.max(m, k.length), 0);
98
+ lines.push(` ${c.dim}${title}${c.reset}`);
99
+ for (const [k, d] of rows) lines.push(` ${c.cyan}${k.padEnd(w)}${c.reset} ${d}`);
100
+ lines.push('');
101
+ };
102
+ table('Choices', (cmd.subs || []).map(([s, d]) => [s, d]));
103
+ table('Options', (cmd.flags || []).map(([f, d, v]) => {
104
+ const val = Array.isArray(v) ? ` <${v.join('|')}>` : v === 'file' ? ' [file]' : v ? ' <value>' : '';
105
+ return [f + val, d];
106
+ }));
107
+ if (cmd.examples?.length) {
108
+ lines.push(` ${c.dim}Examples${c.reset}`);
109
+ for (const ex of cmd.examples) lines.push(` ${c.gray}$${c.reset} ${ex}`);
110
+ lines.push('');
111
+ }
112
+ if (cmd.aliases?.length) {
113
+ lines.push(` ${c.gray}also answers to: ${cmd.aliases.join(', ')}${c.reset}`);
114
+ lines.push('');
115
+ }
116
+ return lines.join('\n');
117
+ }
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/nudge.js CHANGED
@@ -46,7 +46,7 @@ export function pickShareNudge(agg, shown = new Set()) {
46
46
  const m = reached(streak, [3, 7, 14, 30, 50, 100, 200, 365]);
47
47
  if (m) out.push({
48
48
  key: `streak:${m}`, weight: 1000 + m,
49
- message: `${m}-day streak — a personal record. Drop a live badge in your README: \`claude-rpc badge --metric streak --gist\``,
49
+ message: `${m}-day streak — a personal record. Drop a live badge in your README: \`claude-rpc statcards badge --metric streak --link\``,
50
50
  });
51
51
  }
52
52
 
@@ -54,7 +54,7 @@ export function pickShareNudge(agg, shown = new Set()) {
54
54
  const s = reached(sessions, [50, 100, 250, 500, 1000, 2500, 5000, 10000]);
55
55
  if (s) out.push({
56
56
  key: `sessions:${s}`, weight: s / 50,
57
- message: `${fmt(s)} Claude Code sessions logged. Show it off: \`claude-rpc card --range all --out claude.svg\` (or --gist for a live one).`,
57
+ message: `${fmt(s)} Claude Code sessions logged. Show it off: \`claude-rpc statcards poster --range all --png\`.`,
58
58
  });
59
59
 
60
60
  const hours = Math.floor((agg.activeMs || 0) / 3_600_000);
package/src/png.js ADDED
@@ -0,0 +1,135 @@
1
+ // SVG → PNG with whatever the machine already has, so claude-rpc stays at zero
2
+ // dependencies: rsvg-convert, then a Chromium-family browser in headless mode
3
+ // (Chrome, Edge, Brave, Chromium — Edge ships with every Windows 10/11), then
4
+ // ImageMagick or Inkscape. CLAUDE_RPC_BROWSER points at a browser binary
5
+ // explicitly.
6
+
7
+ import { existsSync, mkdtempSync, writeFileSync, readFileSync, rmSync, statSync, openSync, closeSync } from 'node:fs';
8
+ import { tmpdir } from 'node:os';
9
+ import { join, delimiter } from 'node:path';
10
+ import { pathToFileURL } from 'node:url';
11
+
12
+ const PNG_MAGIC = Buffer.from([0x89, 0x50, 0x4e, 0x47]);
13
+
14
+ // Width/height of the root <svg>, from width/height or the viewBox.
15
+ export function svgSize(svg) {
16
+ const tag = (svg.match(/<svg\b[^>]*>/i) || [''])[0];
17
+ const num = (name) => {
18
+ const m = tag.match(new RegExp(`\\s${name}="([\\d.]+)(px)?"`, 'i'));
19
+ return m ? Number(m[1]) : null;
20
+ };
21
+ let w = num('width');
22
+ let h = num('height');
23
+ if (!w || !h) {
24
+ const vb = tag.match(/viewBox="[\d.-]+[\s,]+[\d.-]+[\s,]+([\d.]+)[\s,]+([\d.]+)"/i);
25
+ if (vb) { w = w || Number(vb[1]); h = h || Number(vb[2]); }
26
+ }
27
+ return { width: Math.ceil(w || 600), height: Math.ceil(h || 300) };
28
+ }
29
+
30
+ function onPath(name, env = process.env, platform = process.platform) {
31
+ const exts = platform === 'win32' ? (env.PATHEXT || '.EXE;.CMD;.BAT').split(';') : [''];
32
+ for (const dir of (env.PATH || env.Path || '').split(delimiter)) {
33
+ if (!dir) continue;
34
+ for (const ext of exts) {
35
+ const p = join(dir, name + ext);
36
+ try { if (statSync(p).isFile()) return p; } catch { /* not here */ }
37
+ }
38
+ }
39
+ return null;
40
+ }
41
+
42
+ function browserCandidates(env = process.env, platform = process.platform) {
43
+ if (platform === 'darwin') {
44
+ return ['Google Chrome', 'Microsoft Edge', 'Brave Browser', 'Chromium']
45
+ .map((app) => `/Applications/${app}.app/Contents/MacOS/${app}`);
46
+ }
47
+ if (platform === 'win32') {
48
+ const roots = [env.ProgramFiles, env['ProgramFiles(x86)'], env.LOCALAPPDATA].filter(Boolean);
49
+ const rel = ['Microsoft\\Edge\\Application\\msedge.exe', 'Google\\Chrome\\Application\\chrome.exe',
50
+ 'BraveSoftware\\Brave-Browser\\Application\\brave.exe'];
51
+ return roots.flatMap((r) => rel.map((p) => join(r, p)));
52
+ }
53
+ return [];
54
+ }
55
+
56
+ // The first available renderer as { kind, bin }, or null.
57
+ export function findRasterizer(env = process.env, platform = process.platform) {
58
+ if (env.CLAUDE_RPC_BROWSER) return existsSync(env.CLAUDE_RPC_BROWSER) ? { kind: 'browser', bin: env.CLAUDE_RPC_BROWSER } : null;
59
+ const rsvg = onPath('rsvg-convert', env, platform);
60
+ if (rsvg) return { kind: 'rsvg', bin: rsvg };
61
+ for (const p of browserCandidates(env, platform)) if (existsSync(p)) return { kind: 'browser', bin: p };
62
+ for (const name of ['google-chrome', 'google-chrome-stable', 'chromium', 'chromium-browser', 'microsoft-edge', 'brave-browser', 'msedge', 'chrome']) {
63
+ const p = onPath(name, env, platform);
64
+ if (p) return { kind: 'browser', bin: p };
65
+ }
66
+ const magick = onPath('magick', env, platform);
67
+ if (magick) return { kind: 'magick', bin: magick };
68
+ const inkscape = onPath('inkscape', env, platform);
69
+ if (inkscape) return { kind: 'inkscape', bin: inkscape };
70
+ return null;
71
+ }
72
+
73
+ // The argv for one renderer. Exported for tests.
74
+ export function rasterArgs(kind, { svgFile, htmlFile, out, width, height, scale, profileDir, root = false }) {
75
+ switch (kind) {
76
+ case 'rsvg': return ['-z', String(scale), '-b', 'none', '-o', out, svgFile];
77
+ case 'magick': return ['-background', 'none', '-density', String(96 * scale), svgFile, out];
78
+ case 'inkscape': return ['--export-type=png', `--export-filename=${out}`, `--export-dpi=${96 * scale}`, svgFile];
79
+ case 'browser': return [
80
+ '--headless=new', '--disable-gpu', '--hide-scrollbars', '--no-first-run', '--no-default-browser-check',
81
+ `--user-data-dir=${profileDir}`, '--default-background-color=00000000',
82
+ `--force-device-scale-factor=${scale}`, `--window-size=${width},${height}`,
83
+ `--screenshot=${out}`, ...(root ? ['--no-sandbox'] : []), pathToFileURL(htmlFile).href,
84
+ ];
85
+ default: throw new Error(`unknown rasterizer ${kind}`);
86
+ }
87
+ }
88
+
89
+ // Render `svg` to a PNG at `out` (2× by default). Throws with a readable
90
+ // message when nothing on the machine can do it.
91
+ export async function svgToPng(svg, out, { scale = 2, env = process.env } = {}) {
92
+ const r = findRasterizer(env);
93
+ if (!r) {
94
+ const e = new Error('no SVG renderer found');
95
+ e.hint = process.platform === 'darwin'
96
+ ? 'install Chrome, or `brew install librsvg` — or use --svg / --link instead'
97
+ : process.platform === 'win32'
98
+ ? 'Microsoft Edge does it — or set CLAUDE_RPC_BROWSER to a Chrome/Edge exe; --svg / --link work without one'
99
+ : 'install librsvg (rsvg-convert) or Chromium — or use --svg / --link instead';
100
+ throw e;
101
+ }
102
+ const { spawnSync } = await import('node:child_process');
103
+ const dir = mkdtempSync(join(tmpdir(), 'claude-rpc-png-'));
104
+ try {
105
+ const { width, height } = svgSize(svg);
106
+ const svgFile = join(dir, 'card.svg');
107
+ const htmlFile = join(dir, 'card.html');
108
+ writeFileSync(svgFile, svg);
109
+ writeFileSync(htmlFile, `<!doctype html><meta charset="utf-8"><style>html,body{margin:0;background:transparent;overflow:hidden}svg{display:block}</style>${svg}`);
110
+ const args = rasterArgs(r.kind, {
111
+ svgFile, htmlFile, out, width, height, scale,
112
+ profileDir: join(dir, 'profile'), root: typeof process.getuid === 'function' && process.getuid() === 0,
113
+ });
114
+ // stdio to a file, not a pipe: Chrome's crashpad helper inherits the pipe
115
+ // and outlives the browser, so spawnSync would wait on it until timeout.
116
+ const errFile = join(dir, 'err.log');
117
+ const fd = openSync(errFile, 'w');
118
+ let res;
119
+ try { res = spawnSync(r.bin, args, { stdio: ['ignore', fd, fd], timeout: 45_000, windowsHide: true }); } finally { closeSync(fd); }
120
+ try { res.stderr = readFileSync(errFile, 'utf8'); } catch { /* keep whatever spawnSync had */ }
121
+ let ok = false;
122
+ try { ok = readFileSync(out).subarray(0, 4).equals(PNG_MAGIC); } catch { /* not written */ }
123
+ if (!ok) {
124
+ const why = (res.error?.message || res.stderr || '').trim().split('\n').slice(-2).join(' ');
125
+ throw new Error(`${basenameOf(r.bin)} could not render the PNG${why ? `: ${why.slice(0, 200)}` : ''}`);
126
+ }
127
+ return { out, via: basenameOf(r.bin), width: width * scale, height: height * scale };
128
+ } finally {
129
+ try { rmSync(dir, { recursive: true, force: true }); } catch { /* temp cleanup is best-effort */ }
130
+ }
131
+ }
132
+
133
+ function basenameOf(p) {
134
+ return String(p).split(/[\\/]/).pop();
135
+ }
package/src/pricing.js CHANGED
@@ -3,7 +3,7 @@
3
3
  // what your Claude Code subscription actually charges. Treat the resulting
4
4
  // `costEstimate` as a usage-weighted rough order of magnitude, not a bill.
5
5
  //
6
- // To customize: edit this file and run `claude-rpc rescan`.
6
+ // To customize: edit this file and run `claude-rpc scan --force`.
7
7
 
8
8
  const PRICING = {
9
9
  // Fable family — Anthropic's frontier tier above Opus. 5.1 cut cache reads 4x.
package/src/select.js ADDED
@@ -0,0 +1,60 @@
1
+ // A small arrow-key menu for interactive commands. ↑/↓ (or j/k) move, 1–9
2
+ // jump, Enter picks, Esc / q / Ctrl-C cancels (→ null). Disabled options are
3
+ // shown dimmed with their reason and skipped. Only call on a TTY.
4
+
5
+ import { c } from './ui.js';
6
+
7
+ export function select({ title, options, initial = 0, input = process.stdin, output = process.stdout }) {
8
+ const enabled = (i) => options[i] && !options[i].disabled;
9
+ let at = enabled(initial) ? initial : options.findIndex((o) => !o.disabled);
10
+ if (at === -1) return Promise.resolve(null);
11
+ let drawn = 0;
12
+ const labelW = options.reduce((m, o) => Math.max(m, o.label.length), 0);
13
+
14
+ const draw = () => {
15
+ if (drawn) output.write(`\x1b[${drawn}A`);
16
+ const lines = [` ${c.bold}${title}${c.reset} ${c.gray}↑↓ move · enter pick · esc cancel${c.reset}`];
17
+ options.forEach((o, i) => {
18
+ const n = i < 9 ? `${i + 1}` : ' ';
19
+ const hint = o.disabled ? o.disabled : (o.hint || '');
20
+ if (o.disabled) lines.push(` ${c.gray} ${n} ${o.label.padEnd(labelW)} ${hint}${c.reset}`);
21
+ else if (i === at) lines.push(` ${c.magenta}❯${c.reset} ${c.bold}${n} ${c.cyan}${o.label.padEnd(labelW)}${c.reset} ${c.dim}${hint}${c.reset}`);
22
+ else lines.push(` ${c.dim}${n}${c.reset} ${o.label.padEnd(labelW)} ${c.dim}${hint}${c.reset}`);
23
+ });
24
+ for (const l of lines) output.write(`\x1b[2K${l}\n`);
25
+ drawn = lines.length;
26
+ };
27
+
28
+ return new Promise((resolve) => {
29
+ const move = (d) => {
30
+ for (let i = 1; i <= options.length; i++) {
31
+ const j = (at + d * i + options.length * i) % options.length;
32
+ if (enabled(j)) { at = j; break; }
33
+ }
34
+ };
35
+ const done = (v) => {
36
+ input.off('data', onKey);
37
+ try { input.setRawMode(false); } catch { /* not a tty */ }
38
+ input.pause();
39
+ output.write('\x1b[?25h');
40
+ // Collapse the menu to one line showing the choice.
41
+ output.write(`\x1b[${drawn}A\x1b[0J`);
42
+ output.write(` ${c.bold}${title}${c.reset} ${v === null ? `${c.gray}cancelled${c.reset}` : `${c.cyan}${options[v].label}${c.reset}`}\n`);
43
+ resolve(v);
44
+ };
45
+ const onKey = (buf) => {
46
+ const k = buf.toString();
47
+ if (k === '\x03' || k === '\x1b' || k === 'q') return done(null);
48
+ if (k === '\r' || k === '\n') return done(at);
49
+ if (k === '\x1b[A' || k === 'k') move(-1);
50
+ else if (k === '\x1b[B' || k === 'j' || k === '\t') move(1);
51
+ else if (/^[1-9]$/.test(k) && enabled(Number(k) - 1)) { at = Number(k) - 1; draw(); return done(at); }
52
+ draw();
53
+ };
54
+ output.write('\x1b[?25l');
55
+ draw();
56
+ try { input.setRawMode(true); } catch { /* not a tty */ }
57
+ input.resume();
58
+ input.on('data', onKey);
59
+ });
60
+ }