context-doctor 0.48.0 → 0.49.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (74) hide show
  1. package/README.md +15 -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 +160 -0
  10. package/dist/ccost.js +304 -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/limits.d.ts +222 -14
  28. package/dist/limits.js +684 -33
  29. package/dist/mcp.js +1 -1
  30. package/dist/mcpdefer.d.ts +47 -0
  31. package/dist/mcpdefer.js +91 -0
  32. package/dist/mod/api.d.ts +72 -2
  33. package/dist/mod/api.js +5 -1
  34. package/dist/mod/logic.d.ts +281 -0
  35. package/dist/mod/logic.js +336 -0
  36. package/dist/mod/register.d.ts +35 -2
  37. package/dist/mod/register.js +283 -6
  38. package/dist/modmeasure.d.ts +6 -4
  39. package/dist/modmeasure.js +8 -4
  40. package/dist/opencode.d.ts +57 -0
  41. package/dist/opencode.js +234 -0
  42. package/dist/orgrates.d.ts +7 -0
  43. package/dist/orgrates.js +19 -0
  44. package/dist/overhead.d.ts +3 -0
  45. package/dist/overhead.js +5 -1
  46. package/dist/pricing.d.ts +59 -2
  47. package/dist/pricing.js +125 -10
  48. package/dist/proxy.d.ts +8 -1
  49. package/dist/proxy.js +13 -1
  50. package/dist/savings.d.ts +5 -1
  51. package/dist/savings.js +11 -5
  52. package/dist/scan.d.ts +3 -1
  53. package/dist/scan.js +8 -1
  54. package/dist/sessionprice.d.ts +5 -0
  55. package/dist/sessionprice.js +5 -1
  56. package/dist/spend.d.ts +86 -3
  57. package/dist/spend.js +240 -23
  58. package/dist/spendplace.d.ts +40 -0
  59. package/dist/spendplace.js +93 -0
  60. package/dist/spendteam.d.ts +160 -0
  61. package/dist/spendteam.js +286 -0
  62. package/dist/starts.d.ts +106 -0
  63. package/dist/starts.js +406 -0
  64. package/dist/statusline.d.ts +2 -2
  65. package/dist/statusline.js +2 -2
  66. package/dist/subagentmodel.js +9 -7
  67. package/dist/subagentpay.d.ts +31 -2
  68. package/dist/subagentpay.js +232 -68
  69. package/dist/subagents.js +3 -3
  70. package/dist/tasks.js +3 -2
  71. package/dist/tooloutput.js +5 -5
  72. package/dist/usagepane.d.ts +77 -0
  73. package/dist/usagepane.js +287 -0
  74. package/package.json +1 -1
package/dist/mod/logic.js CHANGED
@@ -242,3 +242,339 @@ export function outcome(stdout, stderr, exitCode) {
242
242
  const err = stderr.split("\n").map((l) => l.trim()).filter(Boolean);
243
243
  return { ok: exitCode === 0, lines: [...lines, ...(exitCode === 0 ? [] : err.slice(-3))].slice(0, 8) };
244
244
  }
245
+ // -- Keeping the cache warm while away -------------------------------------------------
246
+ /**
247
+ * `/context-doctor-keep-warm <hours> [$cap]`: while the person is away, a
248
+ * cache read of the session's whole context every 55 minutes (4.5 on a
249
+ * 5-minute cache), through Claude Code's `$.model.fork`: the main thread's
250
+ * last request again with one short message after it, the reply kept out of
251
+ * the transcript, so the return reads the context instead of writing it
252
+ * again. Only on that command (the yes), capped in hours and dollars, never
253
+ * armed by itself or again after it stops.
254
+ *
255
+ * On the author's 30 days (2026-11-15) a 2-hour cap would have sent 918
256
+ * pings ($87) and kept 56 of 183 cold returns warm ($275 of re-writes): $188
257
+ * net. `cache-misses` prices it on your own history.
258
+ */
259
+ export const KEEP_WARM_COMMAND = "context-doctor-keep-warm";
260
+ export const KEEP_WARM_MAX_HOURS = 8;
261
+ export const KEEP_WARM_DEFAULT_CAP_USD = 2;
262
+ export const KEEP_WARM_MAX_CAP_USD = 20;
263
+ /** A ping every this long keeps a 1-hour cache warm, and a 5-minute one (coldreturns.ts prices the same). */
264
+ export const PING_EVERY_1H_MS = 55 * MIN;
265
+ export const PING_EVERY_5M_MS = 270_000;
266
+ /** The band's clock ticks this often: a ping goes out within one tick before its time, never after it. */
267
+ export const KEEP_WARM_TICK_MS = 30_000;
268
+ /** Asks for haste in the prompt, not with `effort`: a level other than the session's could write the whole context again. */
269
+ 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.";
270
+ /** The command's arguments: `2h`, `90m`, `2h $5`, `off`. None is a question, not a yes. */
271
+ export function parseKeepWarm(args) {
272
+ const words = (args ?? "").trim().toLowerCase().split(/\s+/).filter(Boolean);
273
+ if (!words.length)
274
+ return { kind: "status" };
275
+ if (words.length === 1 && /^(off|stop)$/.test(words[0]))
276
+ return { kind: "off" };
277
+ let hours, capUsd;
278
+ for (const w of words) {
279
+ const h = /^(\d+(?:\.\d+)?)h$/.exec(w), m = /^(\d+)(?:m|min)$/.exec(w), usd = /^\$(\d+(?:\.\d+)?)$/.exec(w);
280
+ if (h && hours === undefined)
281
+ hours = Number(h[1]);
282
+ else if (m && hours === undefined)
283
+ hours = Number(m[1]) / 60;
284
+ else if (usd && capUsd === undefined)
285
+ capUsd = Number(usd[1]);
286
+ else
287
+ return { kind: "error", text: `"${w}" is not a duration (2h, 90m) or a dollar limit ($5).` };
288
+ }
289
+ if (hours === undefined)
290
+ return { kind: "error", text: `Say for how long: 2h, 90m (at most ${KEEP_WARM_MAX_HOURS}h).` };
291
+ if (!(hours > 0) || hours > KEEP_WARM_MAX_HOURS)
292
+ return { kind: "error", text: `At most ${KEEP_WARM_MAX_HOURS}h: past that, a cold return costs less than the pings.` };
293
+ capUsd ??= KEEP_WARM_DEFAULT_CAP_USD;
294
+ if (!(capUsd > 0) || capUsd > KEEP_WARM_MAX_CAP_USD)
295
+ return { kind: "error", text: `A dollar limit from $0.01 to $${KEEP_WARM_MAX_CAP_USD}.` };
296
+ return { kind: "arm", hours, capUsd };
297
+ }
298
+ /**
299
+ * CONTEXT_DOCTOR_KEEP_WARM_PING_MS: a ping every this many ms (1 s to 5 min)
300
+ * and the clock ticking at least that often, for the canary alone, which
301
+ * cannot wait 55 minutes to see a ping reach its mock API. Unset, the real
302
+ * intervals.
303
+ */
304
+ export function keepWarmTestEvery(raw) {
305
+ const n = Number(raw);
306
+ return raw && Number.isFinite(n) && n >= 1000 && n <= 300_000 ? Math.round(n) : undefined;
307
+ }
308
+ export const pingEvery = (ttlMs) => (ttlMs >= 60 * MIN ? PING_EVERY_1H_MS : PING_EVERY_5M_MS);
309
+ const everyText = (ttlMs) => (pingEvery(ttlMs) >= 60 * MIN - 5 * MIN ? "55 minutes" : "4.5 minutes");
310
+ /** 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. */
311
+ export function pingEstimateUsd(d) {
312
+ return d.perMessageUsd !== undefined ? d.perMessageUsd * 1.05 : undefined;
313
+ }
314
+ /** Why keeping warm cannot start now, or undefined when it can. */
315
+ export function keepWarmRefusal(d, now) {
316
+ if (!d || d.tokens === undefined || d.lastReplyAt === undefined || d.ttlMs === undefined)
317
+ return "nothing measured in this session yet: send a message first, then run it as you leave.";
318
+ if (now - d.lastReplyAt >= d.ttlMs)
319
+ 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.`;
320
+ if (pingEstimateUsd(d) === undefined)
321
+ return "this session's model has no known price, so the dollar limit could not be kept.";
322
+ return undefined;
323
+ }
324
+ /**
325
+ * What the timer does at `now`: wait, ping, or stop for good. A ping is due
326
+ * a tick before its interval is up after the last request or ping, so it
327
+ * lands inside the cache's life; a cache that lapsed anyway (Claude Code
328
+ * closed, the machine asleep) is not pinged, since that ping would write the
329
+ * whole context.
330
+ */
331
+ export function keepWarmStep(kw, d, now, everyMs) {
332
+ if (!kw || kw.stopped)
333
+ return { do: "wait" };
334
+ if (now >= kw.until)
335
+ return { do: "stop", why: `its ${duration(kw.until - kw.armedAt)} are up` };
336
+ if (!d || d.lastReplyAt === undefined || d.ttlMs === undefined)
337
+ return { do: "wait" };
338
+ const last = Math.max(d.lastReplyAt, kw.lastPingAt ?? 0);
339
+ if (now - last >= d.ttlMs)
340
+ return { do: "stop", why: "the cache expired before a ping could go out (Claude Code closed, or the machine asleep)" };
341
+ if (now - last < (everyMs ?? pingEvery(d.ttlMs) - KEEP_WARM_TICK_MS))
342
+ return { do: "wait" };
343
+ const est = pingEstimateUsd(d) ?? Infinity;
344
+ if (kw.spentUsd + est > kw.capUsd)
345
+ return { do: "stop", why: `the next ping (~${money(est)}) would pass its ${money(kw.capUsd)} limit` };
346
+ return { do: "ping" };
347
+ }
348
+ /**
349
+ * What a ping read and cost. Warm: it read the context and wrote little
350
+ * (the fork's own tail is never cached). Priced from the band's figures: a
351
+ * read at the per-message rate, a write at the session's re-write rate,
352
+ * uncached input at that over the TTL's multiple (2x for 1 hour, 1.25x for
353
+ * 5 minutes), output at 5x input (every current Claude model). An estimate.
354
+ */
355
+ export function pingOutcome(u, d) {
356
+ const t = d.tokens && d.tokens > 0 ? d.tokens : 1;
357
+ const read = (d.perMessageUsd ?? 0) / t, write = (d.rewriteUsd ?? 0) / t;
358
+ const input = write / ((d.ttlMs ?? 0) >= 60 * MIN ? 2 : 1.25);
359
+ const n = (x) => (typeof x === "number" && Number.isFinite(x) && x > 0 ? x : 0);
360
+ 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;
361
+ return { warm: n(u.cache_read_input_tokens) > 0 && n(u.cache_creation_input_tokens) < 0.1 * n(u.cache_read_input_tokens), usd };
362
+ }
363
+ /** The band while keeping warm: for how long more, what it has spent, against its limit. */
364
+ export function keepWarmText(kw, now) {
365
+ 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)}`;
366
+ }
367
+ /** What the command says when it arms. */
368
+ export function keepWarmArmedText(kw, d) {
369
+ const est = pingEstimateUsd(d);
370
+ return [
371
+ `Keeping this session's prompt cache warm for up to ${duration(kw.until - kw.armedAt)} or ${money(kw.capUsd)}, whichever comes first:`,
372
+ `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)` : ""},`,
373
+ "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).",
374
+ `It stops at either limit, at /clear, or with /${KEEP_WARM_COMMAND} off, and never starts again by itself.`,
375
+ ].join(" ");
376
+ }
377
+ /** The command with no arguments: the price of a yes, or how the one in force stands. Arms nothing. */
378
+ export function keepWarmStatusText(kw, d, now) {
379
+ if (kw && !kw.stopped)
380
+ return `${keepWarmText(kw, now).replace(/^context-doctor: /, "")}. /${KEEP_WARM_COMMAND} off stops it.`;
381
+ const last = kw?.stopped ? `Last time it stopped: ${kw.stopped} (${kw.pings} ping${kw.pings === 1 ? "" : "s"}, ~${money(kw.spentUsd)}). ` : "";
382
+ const est = d ? pingEstimateUsd(d) : undefined;
383
+ 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. ` : "";
384
+ 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.`;
385
+ }
386
+ /** The agent statuses that count as running: started and not settled. */
387
+ export const RUNNING = new Set(["pending", "running", "waiting"]);
388
+ /** "claude-opus-5-5" → "Opus 5.5", "claude-haiku-4-5-20251001" → "Haiku 4.5"; anything else as it is. */
389
+ export function shortModel(id) {
390
+ if (!id)
391
+ return "unknown model";
392
+ const m = /^claude-([a-z]+)-(\d+)(?:-(\d{1,2}))?(?:-\d{8})?(\[1m\])?$/.exec(id);
393
+ if (!m)
394
+ return id;
395
+ return `${m[1][0].toUpperCase()}${m[1].slice(1)} ${m[2]}${m[3] !== undefined ? `.${m[3]}` : ""}${m[4] ? " (1M)" : ""}`;
396
+ }
397
+ /** A bar of `width` cells, filled to `pct`: "██████░░░░". */
398
+ export function bar(pct, width = 16) {
399
+ const w = Math.max(4, Math.min(40, Math.round(width)));
400
+ const p = Math.max(0, Math.min(100, Number.isFinite(pct) ? pct : 0));
401
+ const full = Math.round((p / 100) * w);
402
+ return "█".repeat(full) + "░".repeat(w - full);
403
+ }
404
+ /** "41%", "0.4%", "100%". */
405
+ export function pctText(pct) {
406
+ if (!Number.isFinite(pct))
407
+ return "?%";
408
+ return pct > 0 && pct < 1 ? `${pct.toFixed(1)}%` : `${Math.round(pct)}%`;
409
+ }
410
+ /** The context ring, for the surfaces that draw `Svg`: a circle filled to `pct`, the percent in its middle. */
411
+ export function ringSvg(pct, size = 64) {
412
+ const p = Math.max(0, Math.min(100, Number.isFinite(pct) ? pct : 0));
413
+ const r = 26, c = 2 * Math.PI * r;
414
+ const dash = ((p / 100) * c).toFixed(2);
415
+ // Near the window's end Claude Code compacts soon: amber past 80%, red past 95%.
416
+ const color = p >= 95 ? "#d64545" : p >= 80 ? "#d99a1e" : "#4a7bd0";
417
+ return `<svg xmlns="http://www.w3.org/2000/svg" width="${size}" height="${size}" viewBox="0 0 64 64">`
418
+ + `<circle cx="32" cy="32" r="${r}" fill="none" stroke="#8884" stroke-width="7"/>`
419
+ + `<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)"/>`
420
+ + `<text x="32" y="37" text-anchor="middle" font-family="system-ui, sans-serif" font-size="15" fill="currentColor">${pctText(p)}</text>`
421
+ + `</svg>`;
422
+ }
423
+ /** 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. */
424
+ export function mergeLimits(ledger, live) {
425
+ const out = ledger.map((w) => ({ ...w }));
426
+ for (const r of live?.rateLimits ?? []) {
427
+ if ((r.kind !== "five_hour" && r.kind !== "seven_day") || typeof r.percentUsed !== "number" || !Number.isFinite(r.percentUsed))
428
+ continue;
429
+ const reset = typeof r.resetsAt === "string" ? Date.parse(r.resetsAt) : NaN;
430
+ const w = out.find((x) => x.window === r.kind);
431
+ if (w) {
432
+ if (live.at >= w.at) {
433
+ w.pct = r.percentUsed;
434
+ w.at = live.at;
435
+ if (Number.isFinite(reset))
436
+ w.resetsAt = reset;
437
+ w.resetSince = false;
438
+ w.stale = false;
439
+ }
440
+ }
441
+ else {
442
+ 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 } : {}) });
443
+ }
444
+ }
445
+ return out.sort((a, b) => (a.window === "five_hour" ? 0 : 1) - (b.window === "five_hour" ? 0 : 1));
446
+ }
447
+ const per = (n) => (n >= 10 ? Math.round(n).toString() : n.toFixed(1));
448
+ /** Everything the usage pane says, as words; register.ts lays it out. */
449
+ export function usageView(v) {
450
+ const { data, live, now } = v;
451
+ // The context ring: Claude Code's own figure.
452
+ const ctx = live?.context;
453
+ const pct = ctx?.tokens !== undefined && ctx.window > 0 ? (ctx.percent ?? (ctx.tokens / ctx.window) * 100) : undefined;
454
+ const context = pct !== undefined
455
+ ? { pct, text: `${tokens(ctx.tokens)} of ${tokens(ctx.window)} tokens (${pctText(pct)})${live?.model ? ` · ${shortModel(live.model)}` : ""}` }
456
+ : { text: "Measured after the session's first reply." };
457
+ const limits = mergeLimits(data?.limits ?? [], live).map((w) => {
458
+ if (w.resetSince)
459
+ return { key: w.window, label: w.label, pct: 0, text: `reset since the last reading (${pctText(w.pct)} then)` };
460
+ const parts = [];
461
+ if (w.resetsAt !== undefined && w.resetsAt > now)
462
+ parts.push(`resets in ${duration(w.resetsAt - now)}`);
463
+ if (w.stale)
464
+ parts.push(`read ${duration(now - w.at)} ago, no pace from it`);
465
+ else if (w.perHour !== undefined && w.perHour > 0) {
466
+ const outIn = w.runsOutAt !== undefined && w.runsOutAt > now ? `, runs out in ${duration(w.runsOutAt - now)}${w.beforeReset ? " (before the reset)" : ""}` : "";
467
+ parts.push(`+${per(w.perHour)} points an hour lately${outIn}`);
468
+ }
469
+ const subs = [];
470
+ if (w.usdPerPct !== undefined)
471
+ 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"}`);
472
+ const mv = data?.history?.limitMove;
473
+ if (mv && mv.window === w.window && mv.at <= now)
474
+ 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%`})`);
475
+ return { key: w.window, label: w.label, pct: w.pct, text: `${pctText(w.pct)}${parts.length ? ` · ${parts.join(" · ")}` : ""}`, ...(subs.length ? { sub: subs.join("; ") } : {}) };
476
+ });
477
+ // 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.
478
+ const noFive = data?.history?.noFiveHour ?? (limits.length > 0 && !limits.some((l) => l.key === "five_hour"));
479
+ const limitsNote = limits.length
480
+ ? noFive && !limits.some((l) => l.key === "five_hour") ? "No 5-hour window on this plan (Ultra has none): the weekly limit only." : undefined
481
+ : data || live ? "No limit readings yet: Claude Code reports the windows on a Pro, Max or Ultra sign-in, after the first reply." : undefined;
482
+ const hist = data?.history;
483
+ const periods = (hist?.periods ?? []).map((p) => ({ key: p.key, text: `${p.label} ${money(p.usd)} · ${tokens(p.tokens)} tokens` }));
484
+ const chosen = hist?.periods.find((p) => p.key === (v.period ?? "today")) ?? hist?.periods[0];
485
+ const period = chosen
486
+ ? {
487
+ key: chosen.key,
488
+ label: chosen.label,
489
+ rows: chosen.models.length
490
+ ? 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"}` }))
491
+ : [{ model: "", text: "Nothing in Claude Code in this period." }],
492
+ }
493
+ : undefined;
494
+ const historyNote = hist?.unpriced ? `${hist.unpriced} request${hist.unpriced === 1 ? "" : "s"} on a model with no list price, counted at $0.` : undefined;
495
+ const running = v.agents?.filter((a) => !a.status || RUNNING.has(a.status));
496
+ const byId = new Map((data?.agents ?? []).map((a) => [a.id, a]));
497
+ const agents = (running ?? []).map((a) => {
498
+ const u = byId.get(a.id);
499
+ const bits = [];
500
+ if (u?.model)
501
+ bits.push(shortModel(u.model));
502
+ if (u?.contextTokens !== undefined)
503
+ bits.push(`context ${tokens(u.contextTokens)}${u.window ? ` of ${tokens(u.window)}` : ""}`);
504
+ if (u?.usd !== undefined)
505
+ bits.push(`${money(u.usd)} so far`);
506
+ if (!u)
507
+ bits.push("measuring…");
508
+ else if (!bits.length)
509
+ bits.push("no request yet");
510
+ const what = (a.description ?? a.name ?? "").trim();
511
+ 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(" · ") };
512
+ });
513
+ const agentsNote = v.agents === undefined ? "This Claude Code does not list subagents to mods." : agents.length ? undefined : "No subagents running.";
514
+ const today = hist?.periods.find((p) => p.key === "today");
515
+ const week = limits.find((l) => l.key === "seven_day");
516
+ 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";
517
+ const footer = v.error
518
+ ? v.error
519
+ : v.loading && !hist
520
+ ? "Measuring your last 30 days…"
521
+ : hist
522
+ ? `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…" : ""}.`
523
+ : "";
524
+ return { context, limits, ...(limitsNote ? { limitsNote } : {}), periods, ...(period ? { period } : {}), ...(historyNote ? { historyNote } : {}), agents, ...(agentsNote ? { agentsNote } : {}), glance, footer };
525
+ }
526
+ /** The pane as lines of text: the command's answer where no surface draws the pane (`claude -p`, a headless host). */
527
+ export function usageText(view) {
528
+ const lines = [`context-doctor usage: ${view.glance}`, `Context: ${view.context.text}`];
529
+ for (const l of view.limits)
530
+ lines.push(`${l.label} limit: ${l.text}${l.sub ? ` (${l.sub})` : ""}`);
531
+ if (view.limitsNote)
532
+ lines.push(view.limitsNote);
533
+ if (view.periods.length)
534
+ lines.push(`Claude Code: ${view.periods.map((p) => p.text).join(" · ")}`);
535
+ for (const r of view.period?.rows ?? [])
536
+ lines.push(` ${view.period.label}, ${r.model ? `${r.model}: ` : ""}${r.text}`);
537
+ for (const a of view.agents)
538
+ lines.push(`Subagent ${a.head}: ${a.text}`);
539
+ if (view.agentsNote)
540
+ lines.push(view.agentsNote);
541
+ if (view.footer)
542
+ lines.push(view.footer);
543
+ return lines.join("\n");
544
+ }
545
+ /** How often the pane asks `mod usage` again: the history (cached by the CLI for as long) and the subagents while any runs. */
546
+ export const USAGE_HISTORY_EVERY_MS = 5 * MIN;
547
+ export const USAGE_AGENTS_EVERY_MS = 30_000;
548
+ /**
549
+ * Whether the pane asks `mod usage` now, and for what. Never while closed or
550
+ * while a run is in flight; the history at most every 5 minutes; the
551
+ * subagents and the limits every 30 s while a subagent runs or after a turn
552
+ * moved them. Nothing on a draw: drawing only reads.
553
+ */
554
+ export function usageDue(s, now) {
555
+ if (!s.open || s.loading)
556
+ return false;
557
+ if (s.lastAt === undefined || s.historyAt === undefined || now - s.historyAt >= USAGE_HISTORY_EVERY_MS)
558
+ return { history: true };
559
+ if (now - s.lastAt < USAGE_AGENTS_EVERY_MS)
560
+ return false;
561
+ if (s.agentsRunning > 0 || (s.measuredAt !== undefined && s.measuredAt > s.lastAt))
562
+ return { history: false };
563
+ return false;
564
+ }
565
+ /** The command the pane runs: the CLI's own. */
566
+ export function usageArgv(node, cli) {
567
+ return [node, cli, "mod", "usage"];
568
+ }
569
+ /** Parse `mod usage`'s output; undefined when it is not one. */
570
+ export function parseUsage(stdout) {
571
+ try {
572
+ const j = JSON.parse(stdout);
573
+ if (!j || typeof j !== "object" || typeof j.at !== "number" || !Array.isArray(j.limits) || !Array.isArray(j.agents))
574
+ return undefined;
575
+ return j;
576
+ }
577
+ catch {
578
+ return undefined;
579
+ }
580
+ }
@@ -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,10 +40,12 @@
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;
@@ -53,6 +67,25 @@ interface State {
53
67
  lines: string[];
54
68
  };
55
69
  presses: Map<string, "applied" | "undone">;
70
+ /** The one keep-warm yes in force (or the last, stopped): never armed but by the command. */
71
+ kw?: KeepWarm;
72
+ /** A ping in flight: never two at once. */
73
+ pinging: boolean;
74
+ /** CONTEXT_DOCTOR_KEEP_WARM_PING_MS (the canary's): a ping this often instead of every 55 minutes. */
75
+ pingEveryMs?: number;
76
+ /** The usage pane: what `mod usage` said last, and when it is asked again. */
77
+ usage?: UsagePaneData;
78
+ usageOpen: boolean;
79
+ usageLoading: boolean;
80
+ usageError?: string;
81
+ usageLastAt?: number;
82
+ /** Claude Code's own figures from the last `session.measure`: the context ring and the windows. */
83
+ live?: LiveUsage;
84
+ /** `$.agent.list()`'s rows; undefined on a Claude Code without it. */
85
+ agents?: AgentLike[];
86
+ period: PeriodUse["key"];
87
+ /** What the pane last said, so the timer redraws only when its words change. */
88
+ usageDrawn: string;
56
89
  }
57
90
  /** For tests: the state the hooks share. */
58
91
  export declare const state: () => State;