claude-rpc 1.7.2 → 1.7.4

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.7.2",
3
+ "version": "1.7.4",
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/daemon.js CHANGED
@@ -4,7 +4,7 @@ import { existsSync, unlinkSync, watch, appendFileSync, mkdirSync, statSync, ren
4
4
  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
- import { makeRotationCursor, pickFrames, selectFrame, resolveLargeImageKey, shouldShowGithubButton, pickActiveSession, throttleDecision } from './presence.js';
7
+ import { makeRotationCursor, pickFrames, selectFrame, resolveLargeImageKey, shouldShowGithubButton, pickActiveSession, throttleDecision, reconnectPlan, RECONNECT_BASE_MS } from './presence.js';
8
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';
@@ -139,14 +139,15 @@ let recentSends = [];
139
139
  // Tracked separately from the render hash so we fire once per transition.
140
140
  let lastNotifiedStatus = null;
141
141
  let reconnectTimer = null;
142
- // Exponential backoff for Discord reconnect: 5s → 10s → 20s → … → 300s cap.
143
- // Reset to RECONNECT_BASE_MS on a successful connect so the next outage
144
- // also starts gentle. Jitter (±30%) keeps multiple daemons (e.g. a user
145
- // running both packaged and dev simultaneously) from synchronizing
146
- // reconnect storms against Discord's IPC socket.
147
- const RECONNECT_BASE_MS = 5_000;
148
- const RECONNECT_CAP_MS = 300_000;
142
+ // Current Discord reconnect step — pacing lives in presence.reconnectPlan
143
+ // (fast flat poll while Discord isn't running, exponential backoff to 5min
144
+ // when a live client keeps failing). Reset on a successful connect.
149
145
  let reconnectDelayMs = RECONNECT_BASE_MS;
146
+ // The "Discord isn't running" poll is every ~15s; logging each miss would
147
+ // write ~5,700 lines a day. One line per this interval keeps the log quiet
148
+ // while still landing inside the tail doctor reads for IPC state.
149
+ const ABSENT_LOG_EVERY_MS = 5 * 60_000;
150
+ let lastAbsentLogAt = 0;
150
151
  // Rotation cursor (index + lastAt + status). selectFrame in presence.js resets
151
152
  // it on a status transition — otherwise the cursor carries over from idle's
152
153
  // 12-frame rotation into a single-frame working state and back, producing a
@@ -622,6 +623,7 @@ async function connect() {
622
623
  connected = true;
623
624
  // Reset backoff so the next outage also starts at RECONNECT_BASE_MS.
624
625
  reconnectDelayMs = RECONNECT_BASE_MS;
626
+ lastAbsentLogAt = 0;
625
627
  bridgeClient = isBridgeUser(client.user);
626
628
  if (bridgeClient) {
627
629
  // Doctor greps this line: "connected as" feeds ipcStateFromLog, "arrpc"
@@ -641,24 +643,26 @@ async function connect() {
641
643
  });
642
644
  try { await self.login(); }
643
645
  catch (e) {
644
- if (client === self) scheduleReconnect(`Discord login failed: ${e.message}`);
646
+ // ECONNREFUSED is login()'s "no IPC socket accepted" — Discord isn't
647
+ // running, as opposed to a client that answered and then failed.
648
+ if (client === self) scheduleReconnect(`Discord login failed: ${e.message}`, { absent: e.code === 'ECONNREFUSED' });
645
649
  } finally {
646
650
  if (client === self) connecting = false;
647
651
  }
648
652
  }
649
653
 
650
- function scheduleReconnect(reason = 'reconnect') {
654
+ function scheduleReconnect(reason = 'reconnect', { absent = false } = {}) {
651
655
  connected = false;
652
656
  if (reconnectTimer) return;
653
- // ±30% jitter on the current step. Cheap protection against
654
- // synchronized reconnect storms from sibling daemons.
655
- const jitter = 0.7 + Math.random() * 0.6;
656
- const wait = Math.round(reconnectDelayMs * jitter);
657
- log(`${reason} — retry in ${Math.round(wait / 1000)}s. Is Discord desktop running?`);
658
- reconnectTimer = setTimeout(() => { reconnectTimer = null; connect(); }, wait);
659
- // Step the base for the *next* failure. Cap at 5min so a long Discord
660
- // outage doesn't push us into multi-hour silences.
661
- reconnectDelayMs = Math.min(RECONNECT_CAP_MS, reconnectDelayMs * 2);
657
+ const { waitMs, nextDelayMs } = reconnectPlan({ delayMs: reconnectDelayMs, absent });
658
+ const now = Date.now();
659
+ if (!absent || now - lastAbsentLogAt >= ABSENT_LOG_EVERY_MS) {
660
+ // Doctor greps "retry in Ns" (ipcStateFromLog) — keep the token if rewording.
661
+ log(`${reason} — retry in ${Math.round(waitMs / 1000)}s. Is Discord desktop running?`);
662
+ if (absent) lastAbsentLogAt = now;
663
+ }
664
+ reconnectTimer = setTimeout(() => { reconnectTimer = null; connect(); }, waitMs);
665
+ reconnectDelayMs = nextDelayMs;
662
666
  }
663
667
 
664
668
  function watchFiles() {
package/src/presence.js CHANGED
@@ -162,6 +162,31 @@ export function throttleDecision({ hash, lastSentHash, lastSentAt, now, gapMs, f
162
162
  return { action: 'defer', waitMs };
163
163
  }
164
164
 
165
+ // Discord reconnect pacing. Two different outages, two different caps:
166
+ //
167
+ // absent — no IPC socket accepted at all (Discord isn't running). A probe is
168
+ // a handful of local connects that fail instantly and touches no
169
+ // Discord process, so we keep polling fast. Otherwise someone who
170
+ // opens Discord after Claude Code waits out a multi-minute backoff
171
+ // and reads it as "presence doesn't work".
172
+ // present — a socket answered and then failed (handshake error, drop). Here
173
+ // the backoff protects a struggling client, so it climbs to 5min.
174
+ //
175
+ // `delayMs` is the current step; the caller stores `nextDelayMs` for the next
176
+ // failure and resets to RECONNECT_BASE_MS on a successful connect. ±30% jitter
177
+ // keeps sibling daemons from retrying in lockstep.
178
+ export const RECONNECT_BASE_MS = 5_000;
179
+ export const RECONNECT_CAP_MS = 300_000;
180
+ export const RECONNECT_ABSENT_CAP_MS = 15_000;
181
+ export function reconnectPlan({ delayMs, absent, rand = Math.random() }) {
182
+ const cap = absent ? RECONNECT_ABSENT_CAP_MS : RECONNECT_CAP_MS;
183
+ const step = Math.min(cap, Math.max(RECONNECT_BASE_MS, delayMs || 0));
184
+ return {
185
+ waitMs: Math.round(step * (0.7 + rand * 0.6)),
186
+ nextDelayMs: Math.min(cap, step * 2),
187
+ };
188
+ }
189
+
165
190
  // Large-image key precedence (returns the TEMPLATE string; the caller fills it):
166
191
  // 1. statusAssets[status] per-status art ("working" gif, etc.)
167
192
  // 2. modelAssets[fable|opus|sonnet|haiku|default] per-model art, never stale
package/src/pricing.js CHANGED
@@ -6,21 +6,26 @@
6
6
  // To customize: edit this file and run `claude-rpc scan --force`.
7
7
 
8
8
  const PRICING = {
9
- // Fable family — Anthropic's frontier tier above Opus. 5.1 cut cache reads 4x.
9
+ // List prices checked 2026-11-12 against platform.claude.com/docs/en/about-claude/pricing.
10
+
11
+ // Fable family — Anthropic's frontier tier above Opus. 5.1 cut cache reads
12
+ // 4x; 5.2 cut the base rates to $8/$40.
10
13
  'fable-5': { input: 10.00, output: 50.00, cacheRead: 1.00, cacheWrite: 12.50 },
11
14
  'fable-5-1': { input: 10.00, output: 50.00, cacheRead: 0.25, cacheWrite: 12.50 },
15
+ 'fable-5-2': { input: 8.00, output: 40.00, cacheRead: 0.20, cacheWrite: 10.00 },
12
16
 
13
- // Mythos (Project Glasswing only): Fable-tier capabilities and prices.
17
+ // Mythos (limited availability): Fable-tier capabilities and prices.
14
18
  'mythos-5': { input: 10.00, output: 50.00, cacheRead: 1.00, cacheWrite: 12.50 },
15
19
  'mythos-5-1': { input: 10.00, output: 50.00, cacheRead: 0.25, cacheWrite: 12.50 },
20
+ 'mythos-5-2': { input: 8.00, output: 40.00, cacheRead: 0.20, cacheWrite: 10.00 },
16
21
 
17
- // 5.x generation (list prices checked 2026-10-14). Haiku 5.5 uses its
18
- // <=100K-token-prompt rates; past 100K it's 5x, which a per-token table
19
- // can't express — Claude Code prompts are usually under that.
22
+ // 5.x generation. Haiku 5.5 uses its <=100K-token-prompt rates; past 100K
23
+ // it's 5x, which a per-token table can't express — Claude Code prompts are
24
+ // usually under that.
20
25
  'opus-5': { input: 5.00, output: 25.00, cacheRead: 0.50, cacheWrite: 6.25 },
21
26
  'opus-5-5': { input: 4.00, output: 20.00, cacheRead: 0.20, cacheWrite: 5.00 },
22
27
  'sonnet-5': { input: 2.00, output: 10.00, cacheRead: 0.20, cacheWrite: 2.50 },
23
- 'sonnet-5-5': { input: 2.00, output: 10.00, cacheRead: 0.20, cacheWrite: 2.50 },
28
+ 'sonnet-5-5': { input: 2.00, output: 10.00, cacheRead: 0.10, cacheWrite: 2.50 },
24
29
  'haiku-5': { input: 0.10, output: 0.50, cacheRead: 0.01, cacheWrite: 0.125 },
25
30
  'haiku-5-5': { input: 0.10, output: 0.50, cacheRead: 0.01, cacheWrite: 0.125 },
26
31
 
@@ -40,34 +45,45 @@ const PRICING = {
40
45
  // Haiku 4.x family
41
46
  'haiku-4': { input: 1.00, output: 5.00, cacheRead: 0.10, cacheWrite: 1.25 },
42
47
  'haiku-4-5': { input: 1.00, output: 5.00, cacheRead: 0.10, cacheWrite: 1.25 },
43
-
44
- // Generic fallbacks by tier. Opus uses the current-generation rates —
45
- // unknown/future opus ids are far more likely to be 4.5+ than 4.1-era.
46
- 'fable': { input: 10.00, output: 50.00, cacheRead: 1.00, cacheWrite: 12.50 },
47
- 'mythos': { input: 10.00, output: 50.00, cacheRead: 1.00, cacheWrite: 12.50 },
48
- 'opus': { input: 5.00, output: 25.00, cacheRead: 0.50, cacheWrite: 6.25 },
49
- 'sonnet': { input: 3.00, output: 15.00, cacheRead: 0.30, cacheWrite: 3.75 },
50
- 'haiku': { input: 1.00, output: 5.00, cacheRead: 0.10, cacheWrite: 1.25 },
51
48
  };
52
49
 
50
+ const TIERS = new Set(['opus', 'sonnet', 'haiku', 'fable', 'mythos']);
51
+
52
+ // Known versions per tier, oldest → newest, derived from the table above so
53
+ // adding a row is the only step when a model ships.
54
+ const VERSIONS = {};
55
+ for (const key of Object.keys(PRICING)) {
56
+ const [tier, major, minor = '0'] = key.split('-');
57
+ (VERSIONS[tier] ||= []).push({ key, major: Number(major), minor: Number(minor) });
58
+ }
59
+ for (const list of Object.values(VERSIONS)) list.sort((a, b) => a.major - b.major || a.minor - b.minor);
60
+
61
+ // Generic tier keys (`opus`, `sonnet`, …) for ids that name a tier but no
62
+ // version. They alias the newest known row: an id we can't place is far more
63
+ // likely to be a current model than a retired one.
64
+ for (const [tier, list] of Object.entries(VERSIONS)) PRICING[tier] = PRICING[list.at(-1).key];
65
+
53
66
  const DEFAULT = PRICING.sonnet;
54
67
 
55
- const TIERS = new Set(['opus', 'sonnet', 'haiku', 'fable', 'mythos']);
68
+ // A version token is 1–2 digits; anything longer is a date stamp (20251101).
69
+ const isVer = (t) => typeof t === 'string' && /^\d{1,2}$/.test(t);
56
70
 
57
71
  // Map a model id like "claude-opus-4-7-20251101" to a pricing key.
58
72
  //
59
- // The old implementation did `s.includes(key)` against the PRICING keys
60
- // sorted by descending length, which silently mis-routed any future model
61
- // id whose name contained one of those substrings out of order
62
- // (e.g. `claude-sonneteer-x` matching `sonnet`). Now: split the id on `-`,
63
- // find the first explicit tier token, then read the version digits that
64
- // follow. Falls back from `tier-major-minor` → `tier-major` → tier generic
65
- // → sonnet, in that order.
73
+ // Split the id on `-`, find the first explicit tier token (a whole token, so
74
+ // `claude-sonneteer-x` doesn't match `sonnet`), then read the version digits
75
+ // after it — or before it, for legacy ids like `claude-3-5-sonnet-20241022`.
76
+ //
77
+ // An exact row wins. Otherwise the nearest EARLIER known version of that tier
78
+ // prices it: a model released after this table was written (fable-5-3,
79
+ // opus-6) costs what its closest predecessor does, not what the oldest row or
80
+ // a years-old generic rate says. Versions older than every row use the oldest.
81
+ // No tier at all → sonnet-class fallback.
66
82
  //
67
83
  // Memoized per id string: the scanner calls this (directly and via costFor)
68
84
  // for every assistant turn of every transcript, but a corpus only ever holds a
69
- // handful of distinct model ids. PRICING is never mutated, so the cache can't
70
- // go stale; the size cap just bounds a pathological transcript.
85
+ // handful of distinct model ids. PRICING is never mutated after load, so the
86
+ // cache can't go stale; the size cap just bounds a pathological transcript.
71
87
  const keyCache = new Map();
72
88
  export function pricingKeyFor(modelId) {
73
89
  if (typeof modelId !== 'string') return resolvePricingKey(modelId);
@@ -79,29 +95,57 @@ export function pricingKeyFor(modelId) {
79
95
  return k;
80
96
  }
81
97
 
82
- function resolvePricingKey(modelId) {
83
- if (!modelId) return 'sonnet';
98
+ // Pull { tier, major, minor } out of a model id. tier is null when the id
99
+ // names no known family; major is null when it names a tier but no version.
100
+ function parseModel(modelId) {
84
101
  // Drop a context-window tag like `[1m]` (claude-opus-5-5[1m]) before parsing.
85
- const parts = String(modelId).toLowerCase().replace(/\[[^\]]*\]/g, '').split('-');
102
+ const parts = String(modelId || '').toLowerCase().replace(/\[[^\]]*\]/g, '').split('-');
103
+ const tierIdx = parts.findIndex((p) => TIERS.has(p));
104
+ if (tierIdx === -1) return { tier: null, major: null, minor: 0 };
105
+ let major = null;
106
+ let minor = 0;
107
+ if (isVer(parts[tierIdx + 1])) {
108
+ major = Number(parts[tierIdx + 1]);
109
+ if (isVer(parts[tierIdx + 2])) minor = Number(parts[tierIdx + 2]);
110
+ } else {
111
+ // Legacy order: claude-3-5-sonnet-… / claude-3-opus-…
112
+ const before = parts.slice(0, tierIdx).filter(isVer);
113
+ if (before.length) { major = Number(before[0]); minor = Number(before[1] || 0); }
114
+ }
115
+ return { tier: parts[tierIdx], major, minor };
116
+ }
86
117
 
87
- let tier = null;
88
- let tierIdx = -1;
89
- for (let i = 0; i < parts.length; i++) {
90
- if (TIERS.has(parts[i])) { tier = parts[i]; tierIdx = i; break; }
118
+ function resolvePricingKey(modelId) {
119
+ const { tier, major, minor } = parseModel(modelId);
120
+ if (!tier) return 'sonnet'; // unknown family — sonnet-class fallback
121
+ if (major === null) return tier; // tier named, no version — newest rates
122
+
123
+ const known = VERSIONS[tier];
124
+ let best = known[0];
125
+ for (const v of known) {
126
+ if (v.major < major || (v.major === major && v.minor <= minor)) best = v;
127
+ else break;
91
128
  }
92
- if (!tier) return 'sonnet'; // unknown family — sonnet-class fallback
93
-
94
- const major = parts[tierIdx + 1];
95
- const minor = parts[tierIdx + 2];
96
- if (major && /^\d+$/.test(major)) {
97
- if (minor && /^\d+$/.test(minor)) {
98
- const k = `${tier}-${major}-${minor}`;
99
- if (PRICING[k]) return k;
100
- }
101
- const km = `${tier}-${major}`;
102
- if (PRICING[km]) return km;
129
+ return best.key;
130
+ }
131
+
132
+ // The model's own identity as a `tier-major[-minor]` key — what stats are
133
+ // bucketed and labelled by. Unlike pricingKeyFor this never folds a model into
134
+ // a neighbour: a release newer than the table (fable-5-3) is priced like
135
+ // fable-5-2 but still shows up as "Fable 5.3". Ids with no readable version
136
+ // fall back to the pricing key. Any key this returns is itself a valid input
137
+ // to pricingKeyFor/ratesFor.
138
+ const modelKeyCache = new Map();
139
+ export function modelKeyFor(modelId) {
140
+ if (typeof modelId !== 'string') return pricingKeyFor(modelId);
141
+ let k = modelKeyCache.get(modelId);
142
+ if (k === undefined) {
143
+ const { tier, major, minor } = parseModel(modelId);
144
+ k = tier && major !== null ? `${tier}-${major}${minor ? `-${minor}` : ''}` : pricingKeyFor(modelId);
145
+ if (modelKeyCache.size >= 256) modelKeyCache.clear();
146
+ modelKeyCache.set(modelId, k);
103
147
  }
104
- return tier; // generic tier rates
148
+ return k;
105
149
  }
106
150
 
107
151
  export function ratesFor(modelId) {
package/src/scanner.js CHANGED
@@ -3,7 +3,7 @@ import { join, basename } from 'node:path';
3
3
  import { homedir } from 'node:os';
4
4
  import { CLAUDE_PROJECTS, SCAN_CACHE_PATH, AGGREGATE_PATH, DATA_DIR, EVENTS_LOG_PATH } from './paths.js';
5
5
  import { languageOf } from './languages.js';
6
- import { costFor, pricingKeyFor } from './pricing.js';
6
+ import { costFor, modelKeyFor } from './pricing.js';
7
7
  import { classifyShip } from './ships.js';
8
8
  import { renameSyncRetry } from './atomic-rename.js';
9
9
  import { localDateStamp } from './fmt.js';
@@ -17,7 +17,10 @@ import { localDateStamp } from './fmt.js';
17
17
  // full rescan that backfills model-mix history for already-scanned files.
18
18
  // v8: usage counted at each message's final values (usageDelta), not its first
19
19
  // line's — re-parse to correct output tokens/cost in existing history.
20
- const CACHE_VERSION = 8;
20
+ // v9: model buckets keyed by the model's real version (modelKeyFor) and the
21
+ // 2026-11 price table (Fable 5.2, Sonnet 5.5 cache reads) — re-parse so
22
+ // history stops showing e.g. Fable 5.2 as "Fable 5" at 5.0 rates.
23
+ const CACHE_VERSION = 9;
21
24
 
22
25
  // Cap counted gap between consecutive timestamps. Anything larger is treated
23
26
  // as the user walking away — we count only what's plausibly active time.
@@ -375,8 +378,9 @@ function parseChunkInto(text, summary, pstate) {
375
378
  const counted = usageDelta(pstate.recentIds, r.message?.id, r.message?.usage);
376
379
  const firstSeen = !!counted?.first;
377
380
  const u = r.message?.usage ? counted?.delta : null;
378
- // Per-model split bucket, keyed by pricing key so cost/tokens/turns align.
379
- const mkey = turnModel ? pricingKeyFor(turnModel) : null;
381
+ // Per-model split bucket, keyed by the model's own version (not its
382
+ // pricing row) so a release newer than the price table keeps its name.
383
+ const mkey = turnModel ? modelKeyFor(turnModel) : null;
380
384
  const mb = mkey ? (summary.byModel[mkey] ||= { turns: 0, tokens: 0, cost: 0 }) : null;
381
385
  // Per-day model split (day granularity only — week/hour stay lean).
382
386
  // Powers model-mix-over-time; the all-time byModel can't trend.
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.7.2';
14
+ const BAKED = '1.7.4';
15
15
 
16
16
  function readPkgVersion() {
17
17
  try {