claude-rpc 1.5.1 → 1.5.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "claude-rpc",
3
- "version": "1.5.1",
3
+ "version": "1.5.2",
4
4
  "description": "Discord Rich Presence for Claude Code — live model, project, tokens, and lifetime stats driven by Claude Code's hook system.",
5
5
  "type": "module",
6
6
  "license": "MIT",
package/src/hook.js CHANGED
@@ -161,7 +161,9 @@ export function processHookEvent(event, input = {}, at = Date.now()) {
161
161
  });
162
162
  break;
163
163
  }
164
- case 'PostToolUse': {
164
+ case 'PostToolUse':
165
+ case 'PostToolUseFailure': { // a failed call fires only the latter
166
+ const failed = event === 'PostToolUseFailure';
165
167
  const toolName = input.tool_name || input.toolName || '';
166
168
  const toolInput = input.tool_input || input.toolInput || {};
167
169
  const file = toolInput.file_path || toolInput.path || toolInput.notebook_path || null;
@@ -172,7 +174,7 @@ export function processHookEvent(event, input = {}, at = Date.now()) {
172
174
  let shipKind = null;
173
175
  let shipSubject = null;
174
176
  let shipBranch = null;
175
- if (toolName === 'Bash') {
177
+ if (toolName === 'Bash' && !failed) { // a failed `git commit` shipped nothing
176
178
  shipKind = classifyShip(toolInput.command);
177
179
  if (shipKind) {
178
180
  const shipCwd = input.cwd || process.cwd();
@@ -243,9 +245,22 @@ export function processHookEvent(event, input = {}, at = Date.now()) {
243
245
  appendEvent({ type: 'precompact', ts: now, trigger: input.trigger || input.matcher || null, cwd: input.cwd || null });
244
246
  break;
245
247
  }
246
- // No PostCompact case: Claude Code has no such event. Post-compaction
247
- // arrives as SessionStart (source:'compact'), whose resetState clears the
248
- // compacting marker — so the `compacting` state ends without a handler.
248
+ case 'PostCompact': {
249
+ // Claude Code 2.1.76+. Older versions only re-fire SessionStart
250
+ // (source:'compact'), handled above. An auto-compaction resumes the turn
251
+ // that triggered it; a manual /compact leaves the session waiting on you.
252
+ update((s) => {
253
+ const manual = (input.trigger || s.compactTrigger) === 'manual';
254
+ delete s.compactStartedAt;
255
+ delete s.compactTrigger;
256
+ s.status = manual ? 'idle' : 'working';
257
+ s.lastActivity = now;
258
+ s.claudeClosed = false;
259
+ if (!s.sessionStart) s.sessionStart = now;
260
+ return s;
261
+ });
262
+ break;
263
+ }
249
264
  case 'SessionEnd': {
250
265
  // Authoritative "Claude Code is gone" signal — don't wait on the
251
266
  // staleSessionMin timeout. applyIdle short-circuits to stale when it
@@ -269,6 +284,7 @@ export function processHookEvent(event, input = {}, at = Date.now()) {
269
284
  setActivity({});
270
285
  break;
271
286
  }
287
+ case 'StopFailure': // the turn ended on an API error — Stop never fires
272
288
  case 'Stop':
273
289
  default: {
274
290
  setActivity({ status: 'idle', currentTool: null, currentFile: null });
package/src/install.js CHANGED
@@ -5,7 +5,7 @@
5
5
  import {
6
6
  existsSync, mkdirSync, readFileSync, writeFileSync,
7
7
  copyFileSync, chmodSync, renameSync, statSync,
8
- readdirSync, unlinkSync,
8
+ readdirSync, unlinkSync, openSync, readSync, closeSync,
9
9
  } from 'node:fs';
10
10
  import { dirname, join, resolve } from 'node:path';
11
11
  import { homedir } from 'node:os';
@@ -15,7 +15,7 @@ import {
15
15
  CLAUDE_SETTINGS, CONFIG_PATH, USER_CONFIG_DIR, ROOT,
16
16
  HOOK_SCRIPT, IS_PACKAGED, IS_NPM_INSTALL, IS_NPX,
17
17
  CANONICAL_EXE, CANONICAL_INSTALL_DIR, CANONICAL_EXE_NAME, VERSION_STAMP,
18
- DAEMON_SCRIPT,
18
+ DAEMON_SCRIPT, CLAUDE_PROJECTS,
19
19
  } from './paths.js';
20
20
  import { DEFAULT_CONFIG } from './default-config.js';
21
21
  import { VERSION } from './version.js';
@@ -65,7 +65,72 @@ export const EVENTS = [
65
65
  // Presence never feeds anything back to Claude, so nothing waits on them;
66
66
  // hook.js orders late arrivals by process start time. The once-per-turn events
67
67
  // stay synchronous so status transitions (prompt → Stop) are always ordered.
68
- export const ASYNC_EVENTS = new Set(['PreToolUse', 'PostToolUse']);
68
+ export const ASYNC_EVENTS = new Set(['PreToolUse', 'PostToolUse', 'PostToolUseFailure']);
69
+
70
+ // Hook events newer Claude Code versions added, with the first version that has
71
+ // each. An event name a Claude Code version doesn't know makes it reject the
72
+ // WHOLE hooks block (every hook in settings.json, the user's own too: checked
73
+ // on 2.0.0), so each is wired only once the installed Claude Code is known to
74
+ // support it, and unwired again if it isn't.
75
+ export const OPTIONAL_EVENTS = {
76
+ PostToolUseFailure: '2.0.56', // a failed tool call never fires PostToolUse
77
+ PostCompact: '2.1.76',
78
+ StopFailure: '2.1.78', // a turn that ends on an API error never fires Stop
79
+ };
80
+
81
+ export function versionAtLeast(v, min) {
82
+ const a = String(v || '').split('.').map(Number);
83
+ const b = String(min).split('.').map(Number);
84
+ for (let i = 0; i < 3; i++) {
85
+ if ((a[i] || 0) !== (b[i] || 0)) return (a[i] || 0) > (b[i] || 0);
86
+ }
87
+ return true;
88
+ }
89
+
90
+ // The Claude Code version from the newest transcript (every line carries
91
+ // "version"). Reading it off disk works where `claude --version` doesn't: the
92
+ // daemon's PATH often has no `claude`. Null when there's no transcript yet.
93
+ export function detectClaudeCodeVersion({ projectsDir = CLAUDE_PROJECTS } = {}) {
94
+ let newest = null;
95
+ let newestMtime = -1;
96
+ let projects;
97
+ try { projects = readdirSync(projectsDir); } catch { return null; }
98
+ for (const proj of projects) {
99
+ let files;
100
+ try { files = readdirSync(join(projectsDir, proj)); } catch { continue; }
101
+ for (const f of files) {
102
+ if (!f.endsWith('.jsonl')) continue;
103
+ try {
104
+ const m = statSync(join(projectsDir, proj, f)).mtimeMs;
105
+ if (m > newestMtime) { newestMtime = m; newest = join(projectsDir, proj, f); }
106
+ } catch { /* vanished mid-walk */ }
107
+ }
108
+ }
109
+ if (!newest) return null;
110
+ try {
111
+ const size = statSync(newest).size;
112
+ const len = Math.min(size, 65536);
113
+ const buf = Buffer.alloc(len);
114
+ const fd = openSync(newest, 'r');
115
+ try { readSync(fd, buf, 0, len, size - len); } finally { closeSync(fd); }
116
+ const all = [...buf.toString('utf8').matchAll(/"version":"(\d+\.\d+\.\d+)"/g)];
117
+ return all.length ? all[all.length - 1][1] : null;
118
+ } catch { return null; }
119
+ }
120
+
121
+ export function supportedOptionalEvents(ccVersion) {
122
+ if (!ccVersion) return [];
123
+ return Object.keys(OPTIONAL_EVENTS).filter((e) => versionAtLeast(ccVersion, OPTIONAL_EVENTS[e]));
124
+ }
125
+
126
+ function removeOurHooks(settings, event) {
127
+ const bucket = settings.hooks[event];
128
+ if (!Array.isArray(bucket)) return;
129
+ settings.hooks[event] = bucket
130
+ .map((entry) => ({ ...entry, hooks: (entry.hooks || []).filter((h) => !isOurHook(h)) }))
131
+ .filter((entry) => (entry.hooks || []).length > 0);
132
+ if (settings.hooks[event].length === 0) delete settings.hooks[event];
133
+ }
69
134
 
70
135
  function readJson(p, fb) {
71
136
  try { return JSON.parse(readFileSync(p, 'utf8')); }
@@ -93,7 +158,7 @@ export function isOurHook(h) {
93
158
  return !!h && (h._claudeRpc === true || isOurHookCommand(h.command));
94
159
  }
95
160
 
96
- export function installHooks(exePath, { silent = false } = {}) {
161
+ export function installHooks(exePath, { silent = false, ccVersion = detectClaudeCodeVersion() } = {}) {
97
162
  const settings = readJson(CLAUDE_SETTINGS, {});
98
163
  const before = JSON.stringify(settings.hooks || {});
99
164
  settings.hooks = settings.hooks || {};
@@ -113,7 +178,12 @@ export function installHooks(exePath, { silent = false } = {}) {
113
178
  ? (event) => `"${exePath}" hook ${event}`
114
179
  : (event) => `"${node}" "${HOOK_SCRIPT.replace(/\\/g, '/')}" ${event}`;
115
180
 
116
- for (const event of EVENTS) {
181
+ const optional = supportedOptionalEvents(ccVersion);
182
+ for (const event of Object.keys(OPTIONAL_EVENTS)) {
183
+ if (!optional.includes(event)) removeOurHooks(settings, event);
184
+ }
185
+ const events = [...EVENTS, ...optional];
186
+ for (const event of events) {
117
187
  const bucket = settings.hooks[event] = settings.hooks[event] || [];
118
188
  const wanted = cmdFor(event);
119
189
  const shape = (h) => {
@@ -134,25 +204,18 @@ export function installHooks(exePath, { silent = false } = {}) {
134
204
  }
135
205
  }
136
206
  if (JSON.stringify(settings.hooks) === before) {
137
- if (!silent) noop(`hooks wired (${EVENTS.length} events)`);
207
+ if (!silent) noop(`hooks wired (${events.length} events)`);
138
208
  return false;
139
209
  }
140
210
  writeJson(CLAUDE_SETTINGS, settings);
141
- if (!silent) dirtyStep(SYM_OK, 'hooks wired', `${EVENTS.length} events → ${CLAUDE_SETTINGS}`);
211
+ if (!silent) dirtyStep(SYM_OK, 'hooks wired', `${events.length} events → ${CLAUDE_SETTINGS}`);
142
212
  return true;
143
213
  }
144
214
 
145
215
  export function uninstallHooks() {
146
216
  const settings = readJson(CLAUDE_SETTINGS, {});
147
217
  if (!settings.hooks) return;
148
- for (const event of EVENTS) {
149
- const bucket = settings.hooks[event];
150
- if (!Array.isArray(bucket)) continue;
151
- settings.hooks[event] = bucket
152
- .map((entry) => ({ ...entry, hooks: (entry.hooks || []).filter((h) => !isOurHook(h)) }))
153
- .filter((entry) => (entry.hooks || []).length > 0);
154
- if (settings.hooks[event].length === 0) delete settings.hooks[event];
155
- }
218
+ for (const event of [...EVENTS, ...Object.keys(OPTIONAL_EVENTS)]) removeOurHooks(settings, event);
156
219
  writeJson(CLAUDE_SETTINGS, settings);
157
220
  step(SYM_OK, 'hooks removed', CLAUDE_SETTINGS);
158
221
  }
@@ -756,9 +819,17 @@ function warnIfStale() {
756
819
  // version. Best-effort and quiet by default; never throws into the caller.
757
820
  // Returns { changed, from, rewired }.
758
821
  export function selfHealOnUpdate({ exePath = null, silent = true } = {}) {
822
+ // Stamp = our version, plus (line 2) the optional hook events last wired, so
823
+ // a Claude Code update that unlocks a new event re-wires too.
759
824
  let from = null;
760
- try { from = (readFileSync(VERSION_STAMP, 'utf8') || '').trim() || null; } catch { /* first run / unreadable — treat as needing a heal */ }
761
- if (from === VERSION) return { changed: false, from, rewired: false };
825
+ let fromHooks = '';
826
+ try {
827
+ const [v, h] = (readFileSync(VERSION_STAMP, 'utf8') || '').trim().split('\n');
828
+ from = (v || '').trim() || null;
829
+ fromHooks = (h || '').trim();
830
+ } catch { /* first run / unreadable — treat as needing a heal */ }
831
+ const hooksLine = 'hooks:' + supportedOptionalEvents(detectClaudeCodeVersion()).join(',');
832
+ if (from === VERSION && fromHooks === hooksLine) return { changed: false, from, rewired: false };
762
833
  const exe = exePath || ((IS_PACKAGED && existsSync(CANONICAL_EXE)) ? CANONICAL_EXE : process.execPath);
763
834
  let rewired = false;
764
835
  try { rewired = installHooks(exe, { silent }); } catch { /* best-effort — a hook re-wire must never block daemon startup */ }
@@ -778,7 +849,7 @@ export function selfHealOnUpdate({ exePath = null, silent = true } = {}) {
778
849
  } catch { /* best-effort */ }
779
850
  try {
780
851
  mkdirSync(dirname(VERSION_STAMP), { recursive: true });
781
- writeFileSync(VERSION_STAMP, VERSION + '\n');
852
+ writeFileSync(VERSION_STAMP, VERSION + '\n' + hooksLine + '\n');
782
853
  } catch { /* unwritable — we'll just self-heal again next start, which is harmless (idempotent) */ }
783
854
  return { changed: true, from, rewired, autostart };
784
855
  }
package/src/pricing.js CHANGED
@@ -6,8 +6,18 @@
6
6
  // To customize: edit this file and run `claude-rpc rescan`.
7
7
 
8
8
  const PRICING = {
9
- // Fable family — Anthropic's frontier tier above Opus.
10
- 'fable-5': { input: 10.00, output: 50.00, cacheRead: 1.00, cacheWrite: 12.50 },
9
+ // Fable family — Anthropic's frontier tier above Opus. 5.1 cut cache reads 4x.
10
+ 'fable-5': { input: 10.00, output: 50.00, cacheRead: 1.00, cacheWrite: 12.50 },
11
+ 'fable-5-1': { input: 10.00, output: 50.00, cacheRead: 0.25, cacheWrite: 12.50 },
12
+
13
+ // 5.x generation (list prices checked 2026-10-14). Haiku 5.5 uses its
14
+ // <=100K-token-prompt rates; past 100K it's 5x, which a per-token table
15
+ // can't express — Claude Code prompts are usually under that.
16
+ 'opus-5': { input: 5.00, output: 25.00, cacheRead: 0.50, cacheWrite: 6.25 },
17
+ 'opus-5-5': { input: 4.00, output: 20.00, cacheRead: 0.20, cacheWrite: 5.00 },
18
+ 'sonnet-5': { input: 2.00, output: 10.00, cacheRead: 0.20, cacheWrite: 2.50 },
19
+ 'sonnet-5-5': { input: 2.00, output: 10.00, cacheRead: 0.10, cacheWrite: 2.50 },
20
+ 'haiku-5-5': { input: 0.10, output: 0.50, cacheRead: 0.01, cacheWrite: 0.125 },
11
21
 
12
22
  // Opus 4.x family. 4.0/4.1 launched at $15/$75; the list price dropped to
13
23
  // $5/$25 with Opus 4.5 and has held through 4.8.
@@ -49,7 +59,8 @@ const TIERS = new Set(['opus', 'sonnet', 'haiku', 'fable']);
49
59
  // → sonnet, in that order.
50
60
  export function pricingKeyFor(modelId) {
51
61
  if (!modelId) return 'sonnet';
52
- const parts = String(modelId).toLowerCase().split('-');
62
+ // Drop a context-window tag like `[1m]` (claude-opus-5-5[1m]) before parsing.
63
+ const parts = String(modelId).toLowerCase().replace(/\[[^\]]*\]/g, '').split('-');
53
64
 
54
65
  let tier = null;
55
66
  let tierIdx = -1;
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.5.1';
14
+ const BAKED = '1.5.2';
15
15
 
16
16
  function readPkgVersion() {
17
17
  try {