context-doctor 0.48.0 → 0.49.1

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 (77) hide show
  1. package/README.md +16 -14
  2. package/dist/abclaude.js +1 -1
  3. package/dist/budget.d.ts +5 -2
  4. package/dist/budget.js +21 -7
  5. package/dist/cache.js +3 -3
  6. package/dist/cachemisses.d.ts +3 -0
  7. package/dist/cachemisses.js +8 -0
  8. package/dist/cachettl.js +6 -2
  9. package/dist/ccost.d.ts +195 -0
  10. package/dist/ccost.js +400 -0
  11. package/dist/cli.js +135 -32
  12. package/dist/cline.d.ts +41 -0
  13. package/dist/cline.js +174 -0
  14. package/dist/coldresume.d.ts +11 -0
  15. package/dist/coldresume.js +3 -3
  16. package/dist/coldreturns.d.ts +145 -0
  17. package/dist/coldreturns.js +282 -0
  18. package/dist/compactcost.d.ts +10 -4
  19. package/dist/compactcost.js +12 -7
  20. package/dist/compactwindow.js +2 -2
  21. package/dist/copilotusage.d.ts +78 -0
  22. package/dist/copilotusage.js +193 -0
  23. package/dist/doctor.d.ts +6 -0
  24. package/dist/doctor.js +17 -4
  25. package/dist/fix.d.ts +28 -2
  26. package/dist/fix.js +49 -5
  27. package/dist/install.js +1 -1
  28. package/dist/limits.d.ts +232 -14
  29. package/dist/limits.js +739 -33
  30. package/dist/mcp.js +19 -19
  31. package/dist/mcpdefer.d.ts +47 -0
  32. package/dist/mcpdefer.js +91 -0
  33. package/dist/mod/api.d.ts +72 -2
  34. package/dist/mod/api.js +5 -1
  35. package/dist/mod/logic.d.ts +289 -16
  36. package/dist/mod/logic.js +362 -38
  37. package/dist/mod/register.d.ts +37 -2
  38. package/dist/mod/register.js +290 -9
  39. package/dist/modmeasure.d.ts +6 -4
  40. package/dist/modmeasure.js +8 -4
  41. package/dist/opencode.d.ts +57 -0
  42. package/dist/opencode.js +234 -0
  43. package/dist/orgrates.d.ts +7 -0
  44. package/dist/orgrates.js +19 -0
  45. package/dist/overhead.d.ts +3 -0
  46. package/dist/overhead.js +5 -1
  47. package/dist/pricing.d.ts +59 -2
  48. package/dist/pricing.js +130 -10
  49. package/dist/proxy.d.ts +8 -1
  50. package/dist/proxy.js +13 -1
  51. package/dist/savings.d.ts +5 -1
  52. package/dist/savings.js +11 -5
  53. package/dist/scan.d.ts +3 -1
  54. package/dist/scan.js +8 -1
  55. package/dist/sessionprice.d.ts +5 -0
  56. package/dist/sessionprice.js +5 -1
  57. package/dist/sidecost.d.ts +65 -0
  58. package/dist/sidecost.js +117 -0
  59. package/dist/spend.d.ts +94 -3
  60. package/dist/spend.js +251 -23
  61. package/dist/spendplace.d.ts +40 -0
  62. package/dist/spendplace.js +93 -0
  63. package/dist/spendteam.d.ts +160 -0
  64. package/dist/spendteam.js +286 -0
  65. package/dist/starts.d.ts +106 -0
  66. package/dist/starts.js +406 -0
  67. package/dist/statusline.d.ts +2 -2
  68. package/dist/statusline.js +2 -2
  69. package/dist/subagentmodel.js +9 -7
  70. package/dist/subagentpay.d.ts +31 -2
  71. package/dist/subagentpay.js +232 -68
  72. package/dist/subagents.js +3 -3
  73. package/dist/tasks.js +3 -2
  74. package/dist/tooloutput.js +5 -5
  75. package/dist/usagepane.d.ts +77 -0
  76. package/dist/usagepane.js +287 -0
  77. package/package.json +1 -1
package/dist/mod/logic.js CHANGED
@@ -8,19 +8,7 @@
8
8
  * `fix --apply`, `fix undo`), the same code as in a terminal. The node test
9
9
  * suite exercises these functions directly.
10
10
  */
11
- /** The band shows within this long of the cache going cold... */
12
- export const WARN_BEFORE_MS = 5 * 60_000;
13
11
  const MIN = 60_000;
14
- /**
15
- * ...or within this share of the cache's life, when that is shorter: the last
16
- * minute of a 5-minute cache (WARN_BEFORE_MS would be all of it, the band
17
- * after every turn), the last five of the 1-hour cache.
18
- */
19
- export const WARN_SHARE = 1 / 5;
20
- /** How long before the cache goes cold the band warns, for a cache that lives `ttlMs`. */
21
- export function warnBeforeMs(ttlMs) {
22
- return Math.min(WARN_BEFORE_MS, ttlMs * WARN_SHARE);
23
- }
24
12
  /** The session price thresholds when the CLI cannot say them (no Node): the defaults, the environment's own, or none. */
25
13
  export const DEFAULT_THRESHOLDS = [25, 100, 500];
26
14
  /** CONTEXT_DOCTOR_SESSION_PRICE and CONTEXT_DOCTOR_NO_SESSION_PRICE read as sessionprice.ts reads them. */
@@ -79,56 +67,56 @@ export function priceText(d) {
79
67
  return `session ${money(d.ccUsd)} (Claude Code's figure)`;
80
68
  return undefined;
81
69
  }
70
+ /** "~$0.04", or "under $0.01" where `money` would say "<$0.01". */
71
+ function about(n) {
72
+ return n < 0.01 ? "under $0.01" : `~${money(n)}`;
73
+ }
82
74
  /**
83
- * The band above the prompt at `now`. Quiet unless it pays (the cache about
84
- * to go cold, or gone cold, on a context worth caring about; the session
85
- * past a price threshold), except with `always`. The terminal has the
86
- * status line for the clock and the price, so there the band shows only the
87
- * cold return, the one thing with a button. Nothing on mobile.
75
+ * The band above the prompt at `now`. Off by default: on a big session it came
76
+ * up after nearly every reply, and the every-prompt hook already has Claude
77
+ * offer to compact on a cold return. `cold` shows that return (back at a big
78
+ * session after its cache expired) with Compact first; `always` adds the cache
79
+ * clock, the expired notice and the session price. Nothing on mobile.
88
80
  */
89
81
  export function band(d, now, surface, opts = {}) {
90
- if (!d || surface === "mobile")
82
+ if (!d || surface === "mobile" || !(opts.cold || opts.always))
91
83
  return { kind: "none" };
92
84
  const hidden = opts.hidden ?? new Set();
93
85
  const show = (b) => (hidden.has(b.key) ? { kind: "none" } : b);
94
- const terminal = surface === "terminal";
86
+ // The terminal's status line already shows the clock and the price.
87
+ const extra = opts.always === true && surface !== "terminal";
95
88
  const price = priceText(d);
96
89
  const big = d.tokens !== undefined && d.tokens >= d.coldMinTokens;
97
90
  const known = d.tokens !== undefined && d.lastReplyAt !== undefined && d.ttlMs !== undefined;
98
91
  if (known) {
99
92
  const expiresAt = d.lastReplyAt + d.ttlMs;
100
93
  const coldAt = expiresAt + (d.coldMarginMs ?? 0);
101
- const rewrite = `${tokens(d.tokens)} tokens${d.rewriteUsd !== undefined ? ` (~${money(d.rewriteUsd)})` : ""}`;
102
- const tail = price && !terminal ? ` · ${price}` : "";
94
+ const cost = d.rewriteUsd !== undefined ? ` (~${money(d.rewriteUsd)})` : "";
103
95
  // The return the cold-resume offer is about: past the cache's life by the margin, big enough, and not about to be compacted by Claude Code anyway.
104
96
  if (now >= coldAt && big && d.tokens < (d.autoCompactAt ?? Infinity)) {
105
- const each = d.perMessageUsd !== undefined && d.afterCompactPerMessageUsd !== undefined
106
- ? `each later message re-reads ~${money(d.perMessageUsd)} of context now, ~${money(d.afterCompactPerMessageUsd)} after`
107
- : `each later message re-reads ${tokens(d.tokens)} tokens now, far fewer after`;
97
+ const after = d.perMessageUsd !== undefined && d.afterCompactPerMessageUsd !== undefined
98
+ ? `each message after that costs ${about(d.afterCompactPerMessageUsd)} instead of ${about(d.perMessageUsd)}`
99
+ : `each message after that re-reads far fewer than ${tokens(d.tokens)} tokens`;
108
100
  return show({
109
101
  kind: "cold",
110
102
  key: `cold:${d.lastReplyAt}`,
111
- text: `context-doctor: idle ${duration(now - d.lastReplyAt)}, the cache expired: your next message re-writes ${rewrite}${tail}`,
112
- compact: `Compact first: ${each}`,
103
+ text: `context-doctor: you were away ${duration(now - d.lastReplyAt)}, so the cache expired. Your next message re-sends this ${tokens(d.tokens)}-token chat at full price${cost}.`,
104
+ compact: `Compact first to shrink it: ${after}.`,
113
105
  });
114
106
  }
115
- if (terminal)
107
+ if (!extra)
116
108
  return { kind: "none" };
117
- if (now >= expiresAt && (big || opts.always)) {
109
+ const tail = price ? ` · ${price}` : "";
110
+ const rewrite = `${tokens(d.tokens)} tokens${cost}`;
111
+ if (now >= expiresAt) {
118
112
  return show({ kind: "expired", key: `expired:${d.lastReplyAt}`, text: `context-doctor: the cache expired, so your next message re-writes ${rewrite}${tail}` });
119
113
  }
120
- if (now < expiresAt && (opts.always || (big && expiresAt - now <= warnBeforeMs(d.ttlMs)))) {
121
- return show({ kind: "warm", key: `warm:${d.lastReplyAt}`, text: `context-doctor: cache warm for ${duration(expiresAt - now)}, then your next message re-writes ${rewrite}${tail}` });
122
- }
114
+ return show({ kind: "warm", key: `warm:${d.lastReplyAt}`, text: `context-doctor: cache warm for ${duration(expiresAt - now)}, then your next message re-writes ${rewrite}${tail}` });
123
115
  }
124
- if (terminal)
116
+ if (!extra || !price)
125
117
  return { kind: "none" };
126
- const usd = d.usd ?? d.ccUsd;
127
- const t = passedThreshold(usd, d.thresholds);
128
- if (price && (t !== undefined || opts.always)) {
129
- return show({ kind: "price", key: `price:${t ?? 0}`, text: `context-doctor: ${price}` });
130
- }
131
- return { kind: "none" };
118
+ const t = passedThreshold(d.usd ?? d.ccUsd, d.thresholds);
119
+ return show({ kind: "price", key: `price:${t ?? 0}`, text: `context-doctor: ${price}` });
132
120
  }
133
121
  /** The lever that changes which model runs: never applied by `--apply all`, and marked as such here. */
134
122
  export const MODEL_CHANGE = "subagent-model";
@@ -242,3 +230,339 @@ export function outcome(stdout, stderr, exitCode) {
242
230
  const err = stderr.split("\n").map((l) => l.trim()).filter(Boolean);
243
231
  return { ok: exitCode === 0, lines: [...lines, ...(exitCode === 0 ? [] : err.slice(-3))].slice(0, 8) };
244
232
  }
233
+ // -- Keeping the cache warm while away -------------------------------------------------
234
+ /**
235
+ * `/context-doctor-keep-warm <hours> [$cap]`: while the person is away, a
236
+ * cache read of the session's whole context every 55 minutes (4.5 on a
237
+ * 5-minute cache), through Claude Code's `$.model.fork`: the main thread's
238
+ * last request again with one short message after it, the reply kept out of
239
+ * the transcript, so the return reads the context instead of writing it
240
+ * again. Only on that command (the yes), capped in hours and dollars, never
241
+ * armed by itself or again after it stops.
242
+ *
243
+ * On the author's 30 days (2026-11-15) a 2-hour cap would have sent 918
244
+ * pings ($87) and kept 56 of 183 cold returns warm ($275 of re-writes): $188
245
+ * net. `cache-misses` prices it on your own history.
246
+ */
247
+ export const KEEP_WARM_COMMAND = "context-doctor-keep-warm";
248
+ export const KEEP_WARM_MAX_HOURS = 8;
249
+ export const KEEP_WARM_DEFAULT_CAP_USD = 2;
250
+ export const KEEP_WARM_MAX_CAP_USD = 20;
251
+ /** A ping every this long keeps a 1-hour cache warm, and a 5-minute one (coldreturns.ts prices the same). */
252
+ export const PING_EVERY_1H_MS = 55 * MIN;
253
+ export const PING_EVERY_5M_MS = 270_000;
254
+ /** The band's clock ticks this often: a ping goes out within one tick before its time, never after it. */
255
+ export const KEEP_WARM_TICK_MS = 30_000;
256
+ /** Asks for haste in the prompt, not with `effort`: a level other than the session's could write the whole context again. */
257
+ export const PING_PROMPT = "context-doctor keep-warm: an automated cache refresh while the person is away, not a request. Reply with the single word ok, straight away, with no tools and without thinking it over.";
258
+ /** The command's arguments: `2h`, `90m`, `2h $5`, `off`. None is a question, not a yes. */
259
+ export function parseKeepWarm(args) {
260
+ const words = (args ?? "").trim().toLowerCase().split(/\s+/).filter(Boolean);
261
+ if (!words.length)
262
+ return { kind: "status" };
263
+ if (words.length === 1 && /^(off|stop)$/.test(words[0]))
264
+ return { kind: "off" };
265
+ let hours, capUsd;
266
+ for (const w of words) {
267
+ const h = /^(\d+(?:\.\d+)?)h$/.exec(w), m = /^(\d+)(?:m|min)$/.exec(w), usd = /^\$(\d+(?:\.\d+)?)$/.exec(w);
268
+ if (h && hours === undefined)
269
+ hours = Number(h[1]);
270
+ else if (m && hours === undefined)
271
+ hours = Number(m[1]) / 60;
272
+ else if (usd && capUsd === undefined)
273
+ capUsd = Number(usd[1]);
274
+ else
275
+ return { kind: "error", text: `"${w}" is not a duration (2h, 90m) or a dollar limit ($5).` };
276
+ }
277
+ if (hours === undefined)
278
+ return { kind: "error", text: `Say for how long: 2h, 90m (at most ${KEEP_WARM_MAX_HOURS}h).` };
279
+ if (!(hours > 0) || hours > KEEP_WARM_MAX_HOURS)
280
+ return { kind: "error", text: `At most ${KEEP_WARM_MAX_HOURS}h: past that, a cold return costs less than the pings.` };
281
+ capUsd ??= KEEP_WARM_DEFAULT_CAP_USD;
282
+ if (!(capUsd > 0) || capUsd > KEEP_WARM_MAX_CAP_USD)
283
+ return { kind: "error", text: `A dollar limit from $0.01 to $${KEEP_WARM_MAX_CAP_USD}.` };
284
+ return { kind: "arm", hours, capUsd };
285
+ }
286
+ /**
287
+ * CONTEXT_DOCTOR_KEEP_WARM_PING_MS: a ping every this many ms (1 s to 5 min)
288
+ * and the clock ticking at least that often, for the canary alone, which
289
+ * cannot wait 55 minutes to see a ping reach its mock API. Unset, the real
290
+ * intervals.
291
+ */
292
+ export function keepWarmTestEvery(raw) {
293
+ const n = Number(raw);
294
+ return raw && Number.isFinite(n) && n >= 1000 && n <= 300_000 ? Math.round(n) : undefined;
295
+ }
296
+ export const pingEvery = (ttlMs) => (ttlMs >= 60 * MIN ? PING_EVERY_1H_MS : PING_EVERY_5M_MS);
297
+ const everyText = (ttlMs) => (pingEvery(ttlMs) >= 60 * MIN - 5 * MIN ? "55 minutes" : "4.5 minutes");
298
+ /** What a ping should cost: one read of the context (the band's per-message figure), and a little more for the prompt and reply. */
299
+ export function pingEstimateUsd(d) {
300
+ return d.perMessageUsd !== undefined ? d.perMessageUsd * 1.05 : undefined;
301
+ }
302
+ /** Why keeping warm cannot start now, or undefined when it can. */
303
+ export function keepWarmRefusal(d, now) {
304
+ if (!d || d.tokens === undefined || d.lastReplyAt === undefined || d.ttlMs === undefined)
305
+ return "nothing measured in this session yet: send a message first, then run it as you leave.";
306
+ if (now - d.lastReplyAt >= d.ttlMs)
307
+ return `the cache already expired (idle ${duration(now - d.lastReplyAt)}): a ping now would write the whole context again. Run it before you step away.`;
308
+ if (pingEstimateUsd(d) === undefined)
309
+ return "this session's model has no known price, so the dollar limit could not be kept.";
310
+ return undefined;
311
+ }
312
+ /**
313
+ * What the timer does at `now`: wait, ping, or stop for good. A ping is due
314
+ * a tick before its interval is up after the last request or ping, so it
315
+ * lands inside the cache's life; a cache that lapsed anyway (Claude Code
316
+ * closed, the machine asleep) is not pinged, since that ping would write the
317
+ * whole context.
318
+ */
319
+ export function keepWarmStep(kw, d, now, everyMs) {
320
+ if (!kw || kw.stopped)
321
+ return { do: "wait" };
322
+ if (now >= kw.until)
323
+ return { do: "stop", why: `its ${duration(kw.until - kw.armedAt)} are up` };
324
+ if (!d || d.lastReplyAt === undefined || d.ttlMs === undefined)
325
+ return { do: "wait" };
326
+ const last = Math.max(d.lastReplyAt, kw.lastPingAt ?? 0);
327
+ if (now - last >= d.ttlMs)
328
+ return { do: "stop", why: "the cache expired before a ping could go out (Claude Code closed, or the machine asleep)" };
329
+ if (now - last < (everyMs ?? pingEvery(d.ttlMs) - KEEP_WARM_TICK_MS))
330
+ return { do: "wait" };
331
+ const est = pingEstimateUsd(d) ?? Infinity;
332
+ if (kw.spentUsd + est > kw.capUsd)
333
+ return { do: "stop", why: `the next ping (~${money(est)}) would pass its ${money(kw.capUsd)} limit` };
334
+ return { do: "ping" };
335
+ }
336
+ /**
337
+ * What a ping read and cost. Warm: it read the context and wrote little
338
+ * (the fork's own tail is never cached). Priced from the band's figures: a
339
+ * read at the per-message rate, a write at the session's re-write rate,
340
+ * uncached input at that over the TTL's multiple (2x for 1 hour, 1.25x for
341
+ * 5 minutes), output at 5x input (every current Claude model). An estimate.
342
+ */
343
+ export function pingOutcome(u, d) {
344
+ const t = d.tokens && d.tokens > 0 ? d.tokens : 1;
345
+ const read = (d.perMessageUsd ?? 0) / t, write = (d.rewriteUsd ?? 0) / t;
346
+ const input = write / ((d.ttlMs ?? 0) >= 60 * MIN ? 2 : 1.25);
347
+ const n = (x) => (typeof x === "number" && Number.isFinite(x) && x > 0 ? x : 0);
348
+ const usd = n(u.cache_read_input_tokens) * read + n(u.cache_creation_input_tokens) * write + n(u.input_tokens) * input + n(u.output_tokens) * input * 5;
349
+ return { warm: n(u.cache_read_input_tokens) > 0 && n(u.cache_creation_input_tokens) < 0.1 * n(u.cache_read_input_tokens), usd };
350
+ }
351
+ /** The band while keeping warm: for how long more, what it has spent, against its limit. */
352
+ export function keepWarmText(kw, now) {
353
+ return `context-doctor: keeping the cache warm for ${duration(Math.max(0, kw.until - now))} more: ${kw.pings} ping${kw.pings === 1 ? "" : "s"}, ~${money(kw.spentUsd)} of ${money(kw.capUsd)}`;
354
+ }
355
+ /** What the command says when it arms. */
356
+ export function keepWarmArmedText(kw, d) {
357
+ const est = pingEstimateUsd(d);
358
+ return [
359
+ `Keeping this session's prompt cache warm for up to ${duration(kw.until - kw.armedAt)} or ${money(kw.capUsd)}, whichever comes first:`,
360
+ `a cache read of the ~${tokens(d.tokens ?? 0)}-token context every ${everyText(d.ttlMs ?? 60 * MIN)} while you are away${est !== undefined ? ` (~${money(est)} each at list price)` : ""},`,
361
+ "so your next message reads the context instead of writing it again. The pings bill to your plan or key (on a subscription they use your limit).",
362
+ `It stops at either limit, at /clear, or with /${KEEP_WARM_COMMAND} off, and never starts again by itself.`,
363
+ ].join(" ");
364
+ }
365
+ /** The command with no arguments: the price of a yes, or how the one in force stands. Arms nothing. */
366
+ export function keepWarmStatusText(kw, d, now) {
367
+ if (kw && !kw.stopped)
368
+ return `${keepWarmText(kw, now).replace(/^context-doctor: /, "")}. /${KEEP_WARM_COMMAND} off stops it.`;
369
+ const last = kw?.stopped ? `Last time it stopped: ${kw.stopped} (${kw.pings} ping${kw.pings === 1 ? "" : "s"}, ~${money(kw.spentUsd)}). ` : "";
370
+ const est = d ? pingEstimateUsd(d) : undefined;
371
+ const each = d?.tokens !== undefined && est !== undefined ? `Here a ping reads ~${tokens(d.tokens)} tokens, ~${money(est)} at list price, every ${everyText(d.ttlMs ?? 60 * MIN)} while you are away. ` : "";
372
+ return `${last}${each}To keep the cache warm while you step away: /${KEEP_WARM_COMMAND} 2h (at most ${KEEP_WARM_MAX_HOURS}h), with a dollar limit such as $5 (default ${money(KEEP_WARM_DEFAULT_CAP_USD)}). context-doctor cache-misses shows what it would have saved on your history.`;
373
+ }
374
+ /** The agent statuses that count as running: started and not settled. */
375
+ export const RUNNING = new Set(["pending", "running", "waiting"]);
376
+ /** "claude-opus-5-5" → "Opus 5.5", "claude-haiku-4-5-20251001" → "Haiku 4.5"; anything else as it is. */
377
+ export function shortModel(id) {
378
+ if (!id)
379
+ return "unknown model";
380
+ const m = /^claude-([a-z]+)-(\d+)(?:-(\d{1,2}))?(?:-\d{8})?(\[1m\])?$/.exec(id);
381
+ if (!m)
382
+ return id;
383
+ return `${m[1][0].toUpperCase()}${m[1].slice(1)} ${m[2]}${m[3] !== undefined ? `.${m[3]}` : ""}${m[4] ? " (1M)" : ""}`;
384
+ }
385
+ /** A bar of `width` cells, filled to `pct`: "██████░░░░". */
386
+ export function bar(pct, width = 16) {
387
+ const w = Math.max(4, Math.min(40, Math.round(width)));
388
+ const p = Math.max(0, Math.min(100, Number.isFinite(pct) ? pct : 0));
389
+ const full = Math.round((p / 100) * w);
390
+ return "█".repeat(full) + "░".repeat(w - full);
391
+ }
392
+ /** "41%", "0.4%", "100%". */
393
+ export function pctText(pct) {
394
+ if (!Number.isFinite(pct))
395
+ return "?%";
396
+ return pct > 0 && pct < 1 ? `${pct.toFixed(1)}%` : `${Math.round(pct)}%`;
397
+ }
398
+ /** The context ring, for the surfaces that draw `Svg`: a circle filled to `pct`, the percent in its middle. */
399
+ export function ringSvg(pct, size = 64) {
400
+ const p = Math.max(0, Math.min(100, Number.isFinite(pct) ? pct : 0));
401
+ const r = 26, c = 2 * Math.PI * r;
402
+ const dash = ((p / 100) * c).toFixed(2);
403
+ // Near the window's end Claude Code compacts soon: amber past 80%, red past 95%.
404
+ const color = p >= 95 ? "#d64545" : p >= 80 ? "#d99a1e" : "#4a7bd0";
405
+ return `<svg xmlns="http://www.w3.org/2000/svg" width="${size}" height="${size}" viewBox="0 0 64 64">`
406
+ + `<circle cx="32" cy="32" r="${r}" fill="none" stroke="#8884" stroke-width="7"/>`
407
+ + `<circle cx="32" cy="32" r="${r}" fill="none" stroke="${color}" stroke-width="7" stroke-linecap="round" stroke-dasharray="${dash} ${c.toFixed(2)}" transform="rotate(-90 32 32)"/>`
408
+ + `<text x="32" y="37" text-anchor="middle" font-family="system-ui, sans-serif" font-size="15" fill="currentColor">${pctText(p)}</text>`
409
+ + `</svg>`;
410
+ }
411
+ /** The limit windows to show: the ledger's, each overlaid by Claude Code's own newer reading; a window only Claude Code has, from it alone. */
412
+ export function mergeLimits(ledger, live) {
413
+ const out = ledger.map((w) => ({ ...w }));
414
+ for (const r of live?.rateLimits ?? []) {
415
+ if ((r.kind !== "five_hour" && r.kind !== "seven_day") || typeof r.percentUsed !== "number" || !Number.isFinite(r.percentUsed))
416
+ continue;
417
+ const reset = typeof r.resetsAt === "string" ? Date.parse(r.resetsAt) : NaN;
418
+ const w = out.find((x) => x.window === r.kind);
419
+ if (w) {
420
+ if (live.at >= w.at) {
421
+ w.pct = r.percentUsed;
422
+ w.at = live.at;
423
+ if (Number.isFinite(reset))
424
+ w.resetsAt = reset;
425
+ w.resetSince = false;
426
+ w.stale = false;
427
+ }
428
+ }
429
+ else {
430
+ out.push({ window: r.kind, label: r.kind === "five_hour" ? "5-hour" : "Weekly", pct: r.percentUsed, at: live.at, resetSince: false, ...(Number.isFinite(reset) ? { resetsAt: reset } : {}) });
431
+ }
432
+ }
433
+ return out.sort((a, b) => (a.window === "five_hour" ? 0 : 1) - (b.window === "five_hour" ? 0 : 1));
434
+ }
435
+ const per = (n) => (n >= 10 ? Math.round(n).toString() : n.toFixed(1));
436
+ /** Everything the usage pane says, as words; register.ts lays it out. */
437
+ export function usageView(v) {
438
+ const { data, live, now } = v;
439
+ // The context ring: Claude Code's own figure.
440
+ const ctx = live?.context;
441
+ const pct = ctx?.tokens !== undefined && ctx.window > 0 ? (ctx.percent ?? (ctx.tokens / ctx.window) * 100) : undefined;
442
+ const context = pct !== undefined
443
+ ? { pct, text: `${tokens(ctx.tokens)} of ${tokens(ctx.window)} tokens (${pctText(pct)})${live?.model ? ` · ${shortModel(live.model)}` : ""}` }
444
+ : { text: "Measured after the session's first reply." };
445
+ const limits = mergeLimits(data?.limits ?? [], live).map((w) => {
446
+ if (w.resetSince)
447
+ return { key: w.window, label: w.label, pct: 0, text: `reset since the last reading (${pctText(w.pct)} then)` };
448
+ const parts = [];
449
+ if (w.resetsAt !== undefined && w.resetsAt > now)
450
+ parts.push(`resets in ${duration(w.resetsAt - now)}`);
451
+ if (w.stale)
452
+ parts.push(`read ${duration(now - w.at)} ago, no pace from it`);
453
+ else if (w.perHour !== undefined && w.perHour > 0) {
454
+ const outIn = w.runsOutAt !== undefined && w.runsOutAt > now ? `, runs out in ${duration(w.runsOutAt - now)}${w.beforeReset ? " (before the reset)" : ""}` : "";
455
+ parts.push(`+${per(w.perHour)} points an hour lately${outIn}`);
456
+ }
457
+ const subs = [];
458
+ if (w.usdPerPct !== undefined)
459
+ subs.push(`≈ ${money(w.usdPerPct)} of list-price use per 1%${w.relSe !== undefined ? ` (±${Math.round(w.relSe * 100)}%)` : ""}, ${w.fitFromEarlier ? "in the last window with enough readings" : "this window"}`);
460
+ const mv = data?.history?.limitMove;
461
+ if (mv && mv.window === w.window && mv.at <= now)
462
+ subs.push(`1% moved from ${money(mv.before)} to ${money(mv.after)} ${duration(now - mv.at)} ago (${mv.factor < 1 ? `${per(1 / mv.factor)}x less use per 1%` : `${per(mv.factor)}x more use per 1%`})`);
463
+ return { key: w.window, label: w.label, pct: w.pct, text: `${pctText(w.pct)}${parts.length ? ` · ${parts.join(" · ")}` : ""}`, ...(subs.length ? { sub: subs.join("; ") } : {}) };
464
+ });
465
+ // A plan with no 5-hour window (Ultra): `limits` says so from the ledger (F4); with no history yet, the windows Claude Code reported say it.
466
+ const noFive = data?.history?.noFiveHour ?? (limits.length > 0 && !limits.some((l) => l.key === "five_hour"));
467
+ const limitsNote = limits.length
468
+ ? noFive && !limits.some((l) => l.key === "five_hour") ? "No 5-hour window on this plan (Ultra has none): the weekly limit only." : undefined
469
+ : data || live ? "No limit readings yet: Claude Code reports the windows on a Pro, Max or Ultra sign-in, after the first reply." : undefined;
470
+ const hist = data?.history;
471
+ const periods = (hist?.periods ?? []).map((p) => ({ key: p.key, text: `${p.label} ${money(p.usd)} · ${tokens(p.tokens)} tokens` }));
472
+ const chosen = hist?.periods.find((p) => p.key === (v.period ?? "today")) ?? hist?.periods[0];
473
+ const period = chosen
474
+ ? {
475
+ key: chosen.key,
476
+ label: chosen.label,
477
+ rows: chosen.models.length
478
+ ? chosen.models.map((m) => ({ model: /^\d+ other models?$/.test(m.model) ? m.model : shortModel(m.model), text: `${money(m.usd)} · ${tokens(m.tokens)} tokens · ${m.requests.toLocaleString("en-US")} request${m.requests === 1 ? "" : "s"}` }))
479
+ : [{ model: "", text: "Nothing in Claude Code in this period." }],
480
+ }
481
+ : undefined;
482
+ const historyNote = hist?.unpriced ? `${hist.unpriced} request${hist.unpriced === 1 ? "" : "s"} on a model with no list price, counted at $0.` : undefined;
483
+ const running = v.agents?.filter((a) => !a.status || RUNNING.has(a.status));
484
+ const byId = new Map((data?.agents ?? []).map((a) => [a.id, a]));
485
+ const agents = (running ?? []).map((a) => {
486
+ const u = byId.get(a.id);
487
+ const bits = [];
488
+ if (u?.model)
489
+ bits.push(shortModel(u.model));
490
+ if (u?.contextTokens !== undefined)
491
+ bits.push(`context ${tokens(u.contextTokens)}${u.window ? ` of ${tokens(u.window)}` : ""}`);
492
+ if (u?.usd !== undefined)
493
+ bits.push(`${money(u.usd)} so far`);
494
+ if (!u)
495
+ bits.push("measuring…");
496
+ else if (!bits.length)
497
+ bits.push("no request yet");
498
+ const what = (a.description ?? a.name ?? "").trim();
499
+ return { key: a.id, head: `${a.type ?? "agent"}${what ? `: ${what.length > 60 ? what.slice(0, 59) + "…" : what}` : ""}${a.status && a.status !== "running" ? ` (${a.status})` : ""}`, text: bits.join(" · ") };
500
+ });
501
+ const agentsNote = v.agents === undefined ? "This Claude Code does not list subagents to mods." : agents.length ? undefined : "No subagents running.";
502
+ const today = hist?.periods.find((p) => p.key === "today");
503
+ const week = limits.find((l) => l.key === "seven_day");
504
+ const glance = [pct !== undefined ? `context ${pctText(pct)}` : "", today ? `today ${money(today.usd)}` : "", week ? `weekly ${pctText(week.pct)}` : "", agents.length ? `${agents.length} subagent${agents.length === 1 ? "" : "s"}` : ""].filter(Boolean).join(" · ") || "context-doctor usage";
505
+ const footer = v.error
506
+ ? v.error
507
+ : v.loading && !hist
508
+ ? "Measuring your last 30 days…"
509
+ : hist
510
+ ? `Dollars at list price, as context-doctor spend prices them; measured ${now - hist.at < MIN ? "just now" : `${duration(now - hist.at)} ago`}${v.loading ? ", measuring again…" : ""}.`
511
+ : "";
512
+ return { context, limits, ...(limitsNote ? { limitsNote } : {}), periods, ...(period ? { period } : {}), ...(historyNote ? { historyNote } : {}), agents, ...(agentsNote ? { agentsNote } : {}), glance, footer };
513
+ }
514
+ /** The pane as lines of text: the command's answer where no surface draws the pane (`claude -p`, a headless host). */
515
+ export function usageText(view) {
516
+ const lines = [`context-doctor usage: ${view.glance}`, `Context: ${view.context.text}`];
517
+ for (const l of view.limits)
518
+ lines.push(`${l.label} limit: ${l.text}${l.sub ? ` (${l.sub})` : ""}`);
519
+ if (view.limitsNote)
520
+ lines.push(view.limitsNote);
521
+ if (view.periods.length)
522
+ lines.push(`Claude Code: ${view.periods.map((p) => p.text).join(" · ")}`);
523
+ for (const r of view.period?.rows ?? [])
524
+ lines.push(` ${view.period.label}, ${r.model ? `${r.model}: ` : ""}${r.text}`);
525
+ for (const a of view.agents)
526
+ lines.push(`Subagent ${a.head}: ${a.text}`);
527
+ if (view.agentsNote)
528
+ lines.push(view.agentsNote);
529
+ if (view.footer)
530
+ lines.push(view.footer);
531
+ return lines.join("\n");
532
+ }
533
+ /** How often the pane asks `mod usage` again: the history (cached by the CLI for as long) and the subagents while any runs. */
534
+ export const USAGE_HISTORY_EVERY_MS = 5 * MIN;
535
+ export const USAGE_AGENTS_EVERY_MS = 30_000;
536
+ /**
537
+ * Whether the pane asks `mod usage` now, and for what. Never while closed or
538
+ * while a run is in flight; the history at most every 5 minutes; the
539
+ * subagents and the limits every 30 s while a subagent runs or after a turn
540
+ * moved them. Nothing on a draw: drawing only reads.
541
+ */
542
+ export function usageDue(s, now) {
543
+ if (!s.open || s.loading)
544
+ return false;
545
+ if (s.lastAt === undefined || s.historyAt === undefined || now - s.historyAt >= USAGE_HISTORY_EVERY_MS)
546
+ return { history: true };
547
+ if (now - s.lastAt < USAGE_AGENTS_EVERY_MS)
548
+ return false;
549
+ if (s.agentsRunning > 0 || (s.measuredAt !== undefined && s.measuredAt > s.lastAt))
550
+ return { history: false };
551
+ return false;
552
+ }
553
+ /** The command the pane runs: the CLI's own. */
554
+ export function usageArgv(node, cli) {
555
+ return [node, cli, "mod", "usage"];
556
+ }
557
+ /** Parse `mod usage`'s output; undefined when it is not one. */
558
+ export function parseUsage(stdout) {
559
+ try {
560
+ const j = JSON.parse(stdout);
561
+ if (!j || typeof j !== "object" || typeof j.at !== "number" || !Array.isArray(j.limits) || !Array.isArray(j.agents))
562
+ return undefined;
563
+ return j;
564
+ }
565
+ catch {
566
+ return undefined;
567
+ }
568
+ }
@@ -19,8 +19,20 @@
19
19
  * - `/context-doctor-fix` opens a pane with `fix`'s plan and an Apply / Undo
20
20
  * button per lever. Each press runs the CLI's own `fix --apply <id>` /
21
21
  * `fix undo <id>`: the same lock, backup and record as in a terminal.
22
+ * - `/context-doctor-keep-warm 2h [$5]` keeps the prompt cache warm while
23
+ * the person is away: `$.model.fork` (a cache read of the main thread's
24
+ * last request, nothing in the transcript) a tick before every 55 minutes
25
+ * idle (4.5 on a 5-minute cache), until the hours or the dollars run out,
26
+ * a ping finds the cache cold, the session ends, or Stop. Never armed but
27
+ * by that command, never again by itself; the band shows it while it runs.
28
+ * - `/context-doctor-usage` opens the usage view the Desktop app dropped:
29
+ * the context ring and the limit windows from Claude Code's own figures,
30
+ * tokens and dollars by model for today, 7 and 30 days, and the running
31
+ * subagents with their model, context and cost so far. Drawing only reads
32
+ * what the mod holds; `context-doctor mod usage` refreshes it on the
33
+ * timer, only while the pane is open (usageDue).
22
34
  *
23
- * Nothing happens without a press: no auto-compaction, no auto-apply. The
35
+ * Nothing happens without a press or a command: no auto-compaction, no auto-apply, no ping. The
24
36
  * mod writes no file itself; the CLI writes ours. Off: CONTEXT_DOCTOR_NO_MOD=1.
25
37
  *
26
38
  * The mods runtime has no Node, so this file imports only ./logic.js (no
@@ -28,13 +40,17 @@
28
40
  * reads which calls a module makes from its source: `$` is passed only to
29
41
  * functions declared at the top of this file.
30
42
  */
31
- import { type BandData, type PlanJson } from "./logic.js";
43
+ import { type AgentLike, type BandData, type KeepWarm, type LiveUsage, type PeriodUse, type PlanJson, type UsagePaneData } from "./logic.js";
32
44
  import type { On } from "./api.js";
33
45
  export declare const COMMAND = "context-doctor-fix";
34
46
  export declare const PANE = "context-doctor-fix";
47
+ export declare const USAGE_COMMAND = "context-doctor-usage";
48
+ export declare const USAGE_PANE = "context-doctor-usage";
35
49
  /** The mod's state for this load (a reload starts it over; the next turn measures again). */
36
50
  interface State {
37
51
  off: boolean;
52
+ /** CONTEXT_DOCTOR_MOD_BAND: the band is off unless it says `cold` or `always`. */
53
+ cold: boolean;
38
54
  always: boolean;
39
55
  /** The session price thresholds in force, for when the CLI cannot say them (no Node). */
40
56
  thresholds: number[];
@@ -53,6 +69,25 @@ interface State {
53
69
  lines: string[];
54
70
  };
55
71
  presses: Map<string, "applied" | "undone">;
72
+ /** The one keep-warm yes in force (or the last, stopped): never armed but by the command. */
73
+ kw?: KeepWarm;
74
+ /** A ping in flight: never two at once. */
75
+ pinging: boolean;
76
+ /** CONTEXT_DOCTOR_KEEP_WARM_PING_MS (the canary's): a ping this often instead of every 55 minutes. */
77
+ pingEveryMs?: number;
78
+ /** The usage pane: what `mod usage` said last, and when it is asked again. */
79
+ usage?: UsagePaneData;
80
+ usageOpen: boolean;
81
+ usageLoading: boolean;
82
+ usageError?: string;
83
+ usageLastAt?: number;
84
+ /** Claude Code's own figures from the last `session.measure`: the context ring and the windows. */
85
+ live?: LiveUsage;
86
+ /** `$.agent.list()`'s rows; undefined on a Claude Code without it. */
87
+ agents?: AgentLike[];
88
+ period: PeriodUse["key"];
89
+ /** What the pane last said, so the timer redraws only when its words change. */
90
+ usageDrawn: string;
56
91
  }
57
92
  /** For tests: the state the hooks share. */
58
93
  export declare const state: () => State;