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
@@ -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,15 +40,19 @@
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 { applyOutcome, band, DEFAULT_THRESHOLDS, fixArgv, MODEL_CHANGE, outcome, paneRows, parsePlan, thresholdsFrom, withPresses } from "./logic.js";
43
+ import { applyOutcome, band, bar, DEFAULT_THRESHOLDS, fixArgv, KEEP_WARM_COMMAND, keepWarmTestEvery, keepWarmArmedText, keepWarmRefusal, keepWarmStatusText, keepWarmStep, keepWarmText, MODEL_CHANGE, money, outcome, paneRows, parseKeepWarm, parsePlan, parseUsage, pctText, PING_PROMPT, pingOutcome, ringSvg, RUNNING, thresholdsFrom, usageArgv, usageDue, usageText, usageView, withPresses } from "./logic.js";
32
44
  export const COMMAND = "context-doctor-fix";
33
45
  export const PANE = "context-doctor-fix";
46
+ export const USAGE_COMMAND = "context-doctor-usage";
47
+ export const USAGE_PANE = "context-doctor-usage";
34
48
  /** How often the band checks whether its text changed (a countdown in minutes). */
35
49
  const TICK_MS = 30_000;
36
50
  /** `fix` measures 30 days of history: give it time. */
37
51
  const FIX_TIMEOUT_MS = 10 * 60_000;
38
52
  const MEASURE_TIMEOUT_MS = 30_000;
39
- const fresh = () => ({ off: false, always: false, thresholds: DEFAULT_THRESHOLDS, hidden: new Set(), drawn: "", compacting: false, loading: false, presses: new Map() });
53
+ /** `mod usage` measures 30 days the first time (~3 s cold on 22,000 requests); later runs read its 5-minute cache. */
54
+ const USAGE_TIMEOUT_MS = 2 * 60_000;
55
+ const fresh = () => ({ off: false, always: false, thresholds: DEFAULT_THRESHOLDS, hidden: new Set(), drawn: "", compacting: false, loading: false, presses: new Map(), pinging: false, usageOpen: false, usageLoading: false, period: "today", usageDrawn: "" });
40
56
  let S = fresh();
41
57
  /** For tests: the state the hooks share. */
42
58
  export const state = () => S;
@@ -63,6 +79,8 @@ async function measure($, e) {
63
79
  model = await $.session.model();
64
80
  }
65
81
  catch { /* measured without it */ }
82
+ if (S.live)
83
+ S.live.model = model;
66
84
  const run = await $.process.run(["node", cliOf($), "mod", "measure"], { stdin: JSON.stringify({ sessionId, cwd, model, rateLimits: e.rateLimits, cost: e.cost, context: e.context }), timeoutMs: MEASURE_TIMEOUT_MS });
67
85
  const got = JSON.parse(run.stdout || "{}");
68
86
  S.data = got && typeof got.at === "number" ? got : fallback;
@@ -153,14 +171,177 @@ function refresh($) {
153
171
  if (!S.loading)
154
172
  void loadPlan($);
155
173
  }
174
+ /** A line in the session-cost ledger (the CLI writes it): keep-warm's yes, each ping, its stop. */
175
+ async function note($, ev, tokens) {
176
+ try {
177
+ const sessionId = await $.session.id();
178
+ await $.process.run(["node", cliOf($), "mod", "event"], { stdin: JSON.stringify({ sessionId, ev, tokens }), timeoutMs: MEASURE_TIMEOUT_MS });
179
+ }
180
+ catch { /* the record is a nicety */ }
181
+ }
182
+ /** Stop for good: this yes is spent. A new one takes the command again. */
183
+ function stopKeepWarm($, why) {
184
+ const kw = S.kw;
185
+ if (!kw || kw.stopped)
186
+ return;
187
+ kw.stopped = why;
188
+ $.ui.toast(`context-doctor: stopped keeping the cache warm: ${why} (${kw.pings} ping${kw.pings === 1 ? "" : "s"}, ~${money(kw.spentUsd)}).`);
189
+ $.ui.invalidate("ui.render");
190
+ void note($, "keep-warm-off");
191
+ }
192
+ /** One ping when one is due: `$.model.fork`, checked to have read the cache, priced against the limit. */
193
+ async function keepWarm($, now) {
194
+ if (S.pinging)
195
+ return;
196
+ const step = keepWarmStep(S.kw, S.data, now, S.pingEveryMs);
197
+ if (step.do === "stop")
198
+ return stopKeepWarm($, step.why);
199
+ if (step.do !== "ping" || !S.kw || !S.data)
200
+ return;
201
+ // No presence check: `claude plugin validate` refuses `$.model` read as a value (a module spells
202
+ // `$` only as `$.noun.call(...)`), so an engine without the call is found by calling it.
203
+ S.pinging = true;
204
+ const kw = S.kw, d = S.data;
205
+ try {
206
+ const r = await $.model.fork({ prompt: PING_PROMPT });
207
+ if (kw.stopped)
208
+ return;
209
+ const u = r.usage;
210
+ const cost = u ? pingOutcome(u, d) : undefined;
211
+ if (cost)
212
+ kw.spentUsd += cost.usd;
213
+ if (!r.isAnswered && r.reason === "nothing-to-fork")
214
+ return stopKeepWarm($, "Claude Code holds no request to repeat (restarted, or /clear)");
215
+ if (!r.isAnswered && !u)
216
+ return stopKeepWarm($, `the ping failed (${r.reason}${r.status ? ` ${r.status}` : ""})`);
217
+ kw.pings++;
218
+ kw.lastPingAt = now;
219
+ void note($, "keep-warm-ping", u?.cache_read_input_tokens);
220
+ // A ping that wrote the context found it gone: the next would too.
221
+ if (cost && !cost.warm)
222
+ return stopKeepWarm($, `a ping found the cache cold (read ${u.cache_read_input_tokens}, wrote ${u.cache_creation_input_tokens} tokens)`);
223
+ if (kw.spentUsd >= kw.capUsd)
224
+ return stopKeepWarm($, `it reached its ${money(kw.capUsd)} limit`);
225
+ $.ui.invalidate("ui.render");
226
+ }
227
+ catch (err) {
228
+ stopKeepWarm($, err instanceof TypeError ? "this Claude Code has no $.model.fork" : `the ping could not be sent: ${err instanceof Error ? err.message : String(err)}`);
229
+ }
230
+ finally {
231
+ S.pinging = false;
232
+ }
233
+ }
234
+ /** The command: a status with no arguments, `off`, or the yes (hours and a dollar limit). */
235
+ async function keepWarmCommand($, args) {
236
+ const req = parseKeepWarm(args);
237
+ const now = await $.clock.now();
238
+ if (req.kind === "error")
239
+ return { text: `${req.text} Nothing was started.` };
240
+ if (req.kind === "status")
241
+ return { text: keepWarmStatusText(S.kw, S.data, now) };
242
+ if (req.kind === "off") {
243
+ if (!S.kw || S.kw.stopped)
244
+ return { text: "Nothing to stop: the cache is not being kept warm." };
245
+ stopKeepWarm($, "you stopped it");
246
+ return { text: `Stopped keeping the cache warm (${S.kw.pings} ping${S.kw.pings === 1 ? "" : "s"}, ~${money(S.kw.spentUsd)}).` };
247
+ }
248
+ const refusal = keepWarmRefusal(S.data, now);
249
+ if (refusal)
250
+ return { text: `Not started: ${refusal}` };
251
+ // A new yes replaces one in force, with what it spent counted from zero.
252
+ if (S.kw && !S.kw.stopped)
253
+ S.kw.stopped = "replaced by a new one";
254
+ S.kw = { armedAt: now, until: now + req.hours * 3_600_000, capUsd: req.capUsd, spentUsd: 0, pings: 0 };
255
+ void note($, "keep-warm-on", S.data.tokens);
256
+ $.ui.invalidate("ui.render");
257
+ return { text: keepWarmArmedText(S.kw, S.data) };
258
+ }
259
+ function refreshUsage($) {
260
+ void loadUsage($, true, true);
261
+ }
262
+ function choosePeriod($, key) {
263
+ S.period = key;
264
+ $.ui.invalidate("ui.render");
265
+ }
266
+ /** The subagents Claude Code is running: one call, no file read. */
267
+ async function listAgents($) {
268
+ try {
269
+ const all = await $.agent.list();
270
+ S.agents = Array.isArray(all) ? all.map((a) => ({ id: a.id, type: a.type, description: a.description, status: a.status, ...(a.name ? { name: a.name } : {}) })) : undefined;
271
+ }
272
+ catch {
273
+ S.agents = undefined;
274
+ }
275
+ }
276
+ const runningIds = () => (S.agents ?? []).filter((a) => !a.status || RUNNING.has(a.status)).map((a) => a.id);
277
+ /** `mod usage`: the history (from its 5-minute cache, or measured), the limits ledger, the running subagents. Off the draw, never two at once. */
278
+ async function loadUsage($, history, again = false) {
279
+ if (S.usageLoading)
280
+ return;
281
+ S.usageLoading = true;
282
+ S.usageError = undefined;
283
+ if (S.usageOpen)
284
+ $.ui.invalidate("ui.render");
285
+ try {
286
+ await listAgents($);
287
+ const sessionId = await $.session.id();
288
+ const cwd = await $.session.cwd();
289
+ const run = await $.process.run(usageArgv("node", cliOf($)), { stdin: JSON.stringify({ sessionId, cwd, agents: runningIds(), history, fresh: again }), timeoutMs: USAGE_TIMEOUT_MS });
290
+ const got = parseUsage(run.stdout);
291
+ if (got)
292
+ S.usage = { ...got, history: got.history ?? S.usage?.history };
293
+ else
294
+ S.usageError = `context-doctor mod usage did not answer (exit ${run.exitCode}): ${(run.stderr || run.stdout).trim().split("\n").slice(-1)[0] ?? ""}`;
295
+ }
296
+ catch (err) {
297
+ S.usageError = `context-doctor could not run: ${err instanceof Error ? err.message : String(err)}. It needs Node.js on the PATH Claude Code starts with.`;
298
+ }
299
+ S.usageLastAt = await $.clock.now();
300
+ S.usageLoading = false;
301
+ if (S.usageOpen)
302
+ $.ui.invalidate("ui.render");
303
+ }
304
+ /** Claude Code's figures at the moment the pane opens, before any turn measured them. */
305
+ async function liveNow($) {
306
+ if (S.live)
307
+ return;
308
+ try {
309
+ const u = await $.session.usage();
310
+ S.live = { at: await $.clock.now(), context: u.context, rateLimits: u.rateLimits };
311
+ try {
312
+ S.live.model = await $.session.model();
313
+ }
314
+ catch { /* without it */ }
315
+ }
316
+ catch { /* the next turn measures */ }
317
+ }
318
+ function viewAt(now) {
319
+ return usageView({ data: S.usage, live: S.live, agents: S.agents, period: S.period, loading: S.usageLoading, error: S.usageError, now });
320
+ }
321
+ /** While the pane is open: the subagents (one call), `mod usage` when it is due, and a redraw only when the words change. */
322
+ async function usageTick($, now) {
323
+ if (!S.usageOpen)
324
+ return;
325
+ await listAgents($);
326
+ const due = usageDue({ open: S.usageOpen, loading: S.usageLoading, lastAt: S.usageLastAt, historyAt: S.usage?.history?.at, measuredAt: S.live?.at, agentsRunning: runningIds().length }, now);
327
+ if (due)
328
+ void loadUsage($, due.history);
329
+ const k = JSON.stringify(viewAt(now));
330
+ if (k !== S.usageDrawn) {
331
+ S.usageDrawn = k;
332
+ $.ui.invalidate("ui.render");
333
+ }
334
+ }
156
335
  /** The countdown is in minutes: redraw only when the band's words change. */
157
336
  async function tick($) {
158
337
  const now = await $.clock.now();
159
- const k = bandKey(now, "desktop") + bandKey(now, "terminal");
338
+ await keepWarm($, now);
339
+ const k = bandKey(now, "desktop") + bandKey(now, "terminal") + (S.kw && !S.kw.stopped ? keepWarmText(S.kw, now) : "");
160
340
  if (k !== S.drawn) {
161
341
  S.drawn = k;
162
342
  $.ui.invalidate("ui.render");
163
343
  }
344
+ await usageTick($, now);
164
345
  }
165
346
  export function register(on) {
166
347
  S = fresh();
@@ -169,9 +350,13 @@ export function register(on) {
169
350
  S.off = (await $.env.get("CONTEXT_DOCTOR_NO_MOD")) === "1";
170
351
  S.always = (await $.env.get("CONTEXT_DOCTOR_MOD_BAND")) === "always";
171
352
  S.thresholds = thresholdsFrom(await $.env.get("CONTEXT_DOCTOR_SESSION_PRICE"), await $.env.get("CONTEXT_DOCTOR_NO_SESSION_PRICE"));
353
+ S.pingEveryMs = keepWarmTestEvery(await $.env.get("CONTEXT_DOCTOR_KEEP_WARM_PING_MS"));
172
354
  if (!S.off) {
173
355
  await $.command.register({ name: "context-doctor-fix", description: "context-doctor: the fix plan, with an Apply and an Undo button per lever (nothing applies without a press)" });
174
- $.clock.every(TICK_MS, () => void tick($));
356
+ await $.command.register({ name: "context-doctor-usage", description: "context-doctor: the context ring, your limit windows, tokens and dollars by model (today, 7 and 30 days) and the running subagents" });
357
+ $.clock.every(Math.min(TICK_MS, S.pingEveryMs ?? TICK_MS), () => void tick($));
358
+ // Last: an engine that refuses it keeps the rest.
359
+ await $.command.register({ name: KEEP_WARM_COMMAND, description: "context-doctor: keep the prompt cache warm while you step away, for up to the hours and dollars you give (the pings bill to your plan or key); off stops it", argumentHint: "<2h> [$5] | off" });
175
360
  }
176
361
  }
177
362
  catch {
@@ -183,6 +368,8 @@ export function register(on) {
183
368
  const r = await next(e);
184
369
  if (S.off)
185
370
  return r;
371
+ // The usage pane's ring and windows: Claude Code's own figures, kept as they came.
372
+ S.live = { at: await $.clock.now(), context: e.context, rateLimits: e.rateLimits, ...(S.live?.model ? { model: S.live.model } : {}) };
186
373
  await measure($, e);
187
374
  $.ui.invalidate("ui.render");
188
375
  return r;
@@ -191,7 +378,18 @@ export function register(on) {
191
378
  // session.start for it: the band's figures were the old session's, and its Compact first button
192
379
  // would compact the new one on them. Nothing is shown until the next turn measures the new one.
193
380
  on("session.end", async ($, e, next) => {
381
+ // The yes was for that conversation: a ping now would keep the new one's cache warm unasked.
382
+ try {
383
+ stopKeepWarm($, "the session ended");
384
+ }
385
+ catch { /* ending anyway */ }
194
386
  S.data = undefined;
387
+ // The next session's ring and subagents are its own; the history (every session's) stays.
388
+ S.live = undefined;
389
+ if (S.agents)
390
+ S.agents = [];
391
+ if (S.usage)
392
+ S.usage = { ...S.usage, agents: [] };
195
393
  try {
196
394
  $.ui.invalidate("ui.render");
197
395
  }
@@ -201,7 +399,13 @@ export function register(on) {
201
399
  on("ui.render", { component: "AbovePrompt" }, async ($, e, next) => {
202
400
  if (S.off || e.props.hasSurvey)
203
401
  return next(e);
204
- const b = band(S.data, await $.clock.now(), e.surface, { hidden: S.hidden, always: S.always });
402
+ const now = await $.clock.now();
403
+ // Keeping warm spends money: while it runs, the band says so, with Stop, wherever it can draw.
404
+ if (S.kw && !S.kw.stopped && e.surface !== "mobile") {
405
+ const { Box, Text, Button } = $.ui.resolve(e);
406
+ return h(Box, { flexDirection: "row", flexWrap: "wrap", columnGap: 1 }, h(Text, { dimColor: true }, keepWarmText(S.kw, now)), h(Button, { key: "cd-keep-warm-stop", label: "Stop", onPress: () => stopKeepWarm($, "you stopped it") }));
407
+ }
408
+ const b = band(S.data, now, e.surface, { hidden: S.hidden, always: S.always });
205
409
  // A compaction only runs between turns: no button while one runs.
206
410
  if (b.kind === "none" || (b.kind === "cold" && e.props.isWorking))
207
411
  return next(e);
@@ -211,6 +415,74 @@ export function register(on) {
211
415
  return h(Box, { flexDirection: "row", flexWrap: "wrap", columnGap: 1 }, h(Text, { dimColor: true }, b.text), hideButton);
212
416
  return h(Box, { flexDirection: "column" }, h(Text, { dimColor: true }, b.text), h(Box, { flexDirection: "row", flexWrap: "wrap", columnGap: 1 }, h(Button, { key: "cd-compact", label: S.compacting ? "Compacting…" : "Compact first", variant: "primary", onPress: () => compact($) }), h(Text, { dimColor: true }, b.compact), hideButton));
213
417
  });
418
+ on("command.run", { command: "context-doctor-usage" }, async ($) => {
419
+ if (S.off)
420
+ return { text: "context-doctor's mod is off (CONTEXT_DOCTOR_NO_MOD=1)." };
421
+ S.usageOpen = true;
422
+ await liveNow($);
423
+ const { isPlaced } = await $.ui.open({ id: USAGE_PANE, title: "context-doctor usage" });
424
+ if (isPlaced) {
425
+ void loadUsage($, true);
426
+ return { text: "Opened context-doctor's usage pane." };
427
+ }
428
+ // Nothing draws the pane here (`claude -p`, a headless host): the same figures, as text.
429
+ S.usageOpen = false;
430
+ await loadUsage($, true);
431
+ return { text: usageText(viewAt(await $.clock.now())) };
432
+ });
433
+ // An engine that does not know the event (the pane's timer then stops at the next session) keeps the rest of the mod.
434
+ try {
435
+ on("ui.close", async ($, e, next) => {
436
+ if (e.id === USAGE_PANE)
437
+ S.usageOpen = false;
438
+ return next(e);
439
+ });
440
+ }
441
+ catch { /* no ui.close here */ }
442
+ on("ui.render", { component: "Pane", requestId: USAGE_PANE }, async ($, e) => {
443
+ // Drawn with nothing held (after a reload): one look now; the timer keeps it from there.
444
+ if (!S.usageOpen)
445
+ S.usageOpen = true;
446
+ if (!S.usage && !S.usageLoading && !S.usageError)
447
+ void loadUsage($, true);
448
+ const v = viewAt(await $.clock.now());
449
+ const { Box, Text, Button, Svg } = $.ui.resolve(e);
450
+ if (e.props.placement === "widget")
451
+ return h(Box, { flexDirection: "column" }, h(Text, null, v.glance));
452
+ const cols = typeof e.props.bodyColumns === "number" ? e.props.bodyColumns : 60;
453
+ const barWidth = Math.max(8, Math.min(24, cols - 44));
454
+ const ring = e.surface !== "terminal" ? Svg : undefined;
455
+ const head = (t) => h(Text, { bold: true }, t);
456
+ const dim = (t) => h(Text, { dimColor: true }, t);
457
+ const body = [];
458
+ body.push(head("Context"));
459
+ if (v.context.pct !== undefined) {
460
+ body.push(h(Box, { flexDirection: "row", columnGap: 1, alignItems: "center" }, ring ? h(ring, { source: ringSvg(v.context.pct), alt: `Context ${pctText(v.context.pct)} used`, width: 64, height: 64 }) : h(Text, null, bar(v.context.pct, barWidth)), h(Text, null, v.context.text)));
461
+ }
462
+ else
463
+ body.push(dim(v.context.text));
464
+ body.push(h(Box, { marginTop: 1 }, head("Limits")));
465
+ for (const l of v.limits) {
466
+ body.push(h(Box, { key: `limit:${l.key}`, flexDirection: "column" }, h(Box, { flexDirection: "row", columnGap: 1 }, h(Box, { width: 8 }, h(Text, null, l.label)), h(Text, null, bar(l.pct, barWidth)), h(Text, null, l.text)), ...(l.sub ? [dim(l.sub)] : [])));
467
+ }
468
+ if (v.limitsNote)
469
+ body.push(dim(v.limitsNote));
470
+ body.push(h(Box, { marginTop: 1 }, head("Claude Code: tokens and dollars by model")));
471
+ if (v.periods.length) {
472
+ body.push(h(Box, { flexDirection: "row", flexWrap: "wrap", columnGap: 1 }, ...v.periods.map((p) => h(Button, { key: `period:${p.key}`, label: p.text, ...(v.period?.key === p.key ? { variant: "primary" } : {}), onPress: () => choosePeriod($, p.key) }))));
473
+ for (const r of v.period?.rows ?? [])
474
+ body.push(h(Box, { flexDirection: "row", columnGap: 1 }, h(Box, { width: 14 }, h(Text, null, r.model)), dim(r.text)));
475
+ }
476
+ if (v.historyNote)
477
+ body.push(dim(v.historyNote));
478
+ body.push(h(Box, { marginTop: 1 }, head(`Subagents running${v.agents.length ? ` (${v.agents.length})` : ""}`)));
479
+ for (const a of v.agents)
480
+ body.push(h(Box, { key: `agent:${a.key}`, flexDirection: "column" }, h(Text, null, a.head), dim(` ${a.text}`)));
481
+ if (v.agentsNote)
482
+ body.push(dim(v.agentsNote));
483
+ body.push(h(Box, { flexDirection: "row", columnGap: 1, marginTop: 1, flexWrap: "wrap" }, h(Button, { key: "usage-refresh", label: S.usageLoading ? "Measuring…" : "Refresh", onPress: () => refreshUsage($) }), ...(v.footer ? [dim(v.footer)] : [])));
484
+ return h(Box, { flexDirection: "column" }, ...body);
485
+ });
214
486
  on("command.run", { command: "context-doctor-fix" }, async ($) => {
215
487
  if (S.off)
216
488
  return { text: "context-doctor's mod is off (CONTEXT_DOCTOR_NO_MOD=1)." };
@@ -219,6 +491,11 @@ export function register(on) {
219
491
  void loadPlan($);
220
492
  return { text: "Opened context-doctor's fix plan. Nothing is applied until you press Apply." };
221
493
  });
494
+ on("command.run", { command: KEEP_WARM_COMMAND }, async ($, e) => {
495
+ if (S.off)
496
+ return { text: "context-doctor's mod is off (CONTEXT_DOCTOR_NO_MOD=1)." };
497
+ return keepWarmCommand($, e.args);
498
+ });
222
499
  on("ui.render", { component: "Pane", requestId: PANE }, async ($, e) => {
223
500
  const { Box, Text, Button } = $.ui.resolve(e);
224
501
  const body = [h(Text, { bold: true }, "context-doctor fix: each lever, by what it would have saved you")];
@@ -47,7 +47,8 @@ export interface ModMeasureInput {
47
47
  /**
48
48
  * The mod's windows in the status line's shape, `{ five_hour: { used_percentage,
49
49
  * resets_at } }`, resets in epoch seconds: the one shape recordLimits reads.
50
- * A gateway's `spend_limit` has no place in the ledger and is left out.
50
+ * A gateway's `spend_limit` has no place in the ledger and is left out; a
51
+ * plan with no 5-hour window (Ultra) sends only `seven_day`, and only that is kept.
51
52
  */
52
53
  export declare function statusLineRateLimits(list: unknown): Record<string, {
53
54
  used_percentage: number;
@@ -115,7 +116,8 @@ export declare function costCheck(days?: number, now?: number, path?: string): {
115
116
  export declare function modMeasure(input: ModMeasureInput, now?: number, env?: NodeJS.ProcessEnv): Partial<BandData> & Pick<BandData, "at" | "coldMinTokens" | "thresholds">;
116
117
  /**
117
118
  * The CLI side: `mod measure` keeps the reading and prints the band's
118
- * figures; `mod event` records a press (`{ sessionId, ev, tokens }`). Both
119
- * print JSON and exit 0 whatever happens, as the status line does.
119
+ * figures; `mod event` records a press (`{ sessionId, ev, tokens }`); `mod
120
+ * usage` prints the usage pane's figures (usagepane.ts). Each prints JSON
121
+ * and exits 0 whatever happens, as the status line does.
120
122
  */
121
- export declare function runMod(sub: "measure" | "event"): Promise<void>;
123
+ export declare function runMod(sub: "measure" | "event" | "usage"): Promise<void>;
@@ -37,7 +37,8 @@ import { rateCard, ratesAt } from "./pricing.js";
37
37
  /**
38
38
  * The mod's windows in the status line's shape, `{ five_hour: { used_percentage,
39
39
  * resets_at } }`, resets in epoch seconds: the one shape recordLimits reads.
40
- * A gateway's `spend_limit` has no place in the ledger and is left out.
40
+ * A gateway's `spend_limit` has no place in the ledger and is left out; a
41
+ * plan with no 5-hour window (Ultra) sends only `seven_day`, and only that is kept.
41
42
  */
42
43
  export function statusLineRateLimits(list) {
43
44
  if (!Array.isArray(list))
@@ -237,7 +238,7 @@ export function modMeasure(input, now = Date.now(), env = process.env) {
237
238
  const out = { at: now, coldMinTokens: COLD_MIN_TOKENS, thresholds: sessionPriceThresholds(env) };
238
239
  try {
239
240
  if (env.CONTEXT_DOCTOR_NO_LIMITS_LOG !== "1")
240
- recordLimits(statusLineRateLimits(input?.rateLimits), now);
241
+ recordLimits(statusLineRateLimits(input?.rateLimits), now, undefined, "mod");
241
242
  }
242
243
  catch { /* the rest still runs */ }
243
244
  const ccUsd = num(input?.cost?.usd);
@@ -291,8 +292,9 @@ async function readStdin() {
291
292
  }
292
293
  /**
293
294
  * The CLI side: `mod measure` keeps the reading and prints the band's
294
- * figures; `mod event` records a press (`{ sessionId, ev, tokens }`). Both
295
- * print JSON and exit 0 whatever happens, as the status line does.
295
+ * figures; `mod event` records a press (`{ sessionId, ev, tokens }`); `mod
296
+ * usage` prints the usage pane's figures (usagepane.ts). Each prints JSON
297
+ * and exits 0 whatever happens, as the status line does.
296
298
  */
297
299
  export async function runMod(sub) {
298
300
  let out = {};
@@ -300,6 +302,8 @@ export async function runMod(sub) {
300
302
  const input = JSON.parse((await readStdin()) || "{}");
301
303
  if (sub === "measure")
302
304
  out = modMeasure(input);
305
+ else if (sub === "usage")
306
+ out = (await import("./usagepane.js")).usagePane(input);
303
307
  else
304
308
  out = { ok: recordModEvent(String(input?.sessionId ?? ""), String(input?.ev ?? ""), num(input?.tokens)) };
305
309
  }
@@ -0,0 +1,57 @@
1
+ /**
2
+ * OpenCode's record of what it sent: each assistant message's `tokens`.
3
+ * Checked 2026-11-15 against ccusage's OpenCode loader (rust/adapters/opencode)
4
+ * and its docs. OpenCode keeps its data in `${XDG_DATA_HOME:-~/.local/share}/opencode`
5
+ * (`OPENCODE_DATA_DIR`, a comma list, instead), in one of three places:
6
+ *
7
+ * - `storage/message/<sessionID>/<messageID>.json` (before its SQLite store):
8
+ * `{id, sessionID, role, modelID, providerID, time: {created}, tokens:
9
+ * {input, output, reasoning, cache: {read, write}, total}, path: {cwd, root}}`.
10
+ * - `opencode.db`, table `message`: the same object in `data`.
11
+ * - `opencode.db`, table `session_message` (its v2 store): rows of `type`
12
+ * "assistant" or "compaction" (a compaction is billed apart; only a
13
+ * "completed" one), the model as `model: {id, providerID}`. A forked
14
+ * session starts with a copy of its parent's rows, new ids and the same
15
+ * `seq`; `session_v2.fork_boundary` says up to which (its "through" or
16
+ * "before" a parent message): those copies are not counted again.
17
+ *
18
+ * `tokens.input` is the uncached input; reasoning bills as output, and a
19
+ * `total` above the parts is output too (as ccusage counts it). A message
20
+ * on OpenCode's `claude-agent` provider ran inside Claude Code, whose own
21
+ * transcript `spend` already reads: not counted here. The same message in
22
+ * the JSON files and the database (a store that was migrated) is counted once.
23
+ */
24
+ /** One OpenCode model call. */
25
+ export interface OpenCodeCall {
26
+ id: string;
27
+ ts: number;
28
+ session: string;
29
+ model?: string;
30
+ provider?: string;
31
+ input: number;
32
+ read: number;
33
+ write: number;
34
+ output: number;
35
+ /** The folder it ran in (`path.cwd`, else the session's `directory`), and the project's root (`path.root`). */
36
+ cwd?: string;
37
+ root?: string;
38
+ compaction?: boolean;
39
+ }
40
+ /** OpenCode's data folders: $OPENCODE_DATA_DIR's (when `home` is this user's), else <XDG data>/opencode. */
41
+ export declare function opencodeDataDirs(home?: string): string[];
42
+ /** The counts of one message's `tokens`, as billed: reasoning, and a total above the parts, as output. */
43
+ export declare function opencodeTokens(t: any): {
44
+ input: number;
45
+ read: number;
46
+ write: number;
47
+ output: number;
48
+ } | undefined;
49
+ /**
50
+ * Every OpenCode model call between `since` and `until`, each once, less
51
+ * those on the claude-agent provider. `sqlite`: false when an opencode.db
52
+ * was there and this runtime cannot read SQLite.
53
+ */
54
+ export declare function opencodeCalls(since: number, until?: number, home?: string): {
55
+ calls: OpenCodeCall[];
56
+ sqlite: boolean;
57
+ };