context-doctor 0.50.0 → 0.52.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.
package/dist/mod/api.d.ts CHANGED
@@ -207,7 +207,7 @@ export interface On {
207
207
  }
208
208
  /**
209
209
  * `tool.describe` (2.1.323+; `mcpServer` and an answer's `isDeferred` from
210
- * 2.1.326, read in 2.1.329's declarations): one tool's description the first
210
+ * 2.1.326, read in 2.1.329's declarations and again in 2.1.331's, unchanged): one tool's description the first
211
211
  * time the engine renders its schema in a session. `isDeferred: true` on the
212
212
  * answer puts the tool behind ToolSearch from the next new thread or `/clear`;
213
213
  * `breakPromptCache` would send it at the next turn by re-writing the whole
@@ -274,13 +274,15 @@ export interface HistoryUse {
274
274
  current: boolean;
275
275
  resetsAt: number;
276
276
  }>>;
277
- /** The latest move in that figure: before and after, after / before, when. */
277
+ /** The latest move in that figure: before and after, after / before, when; `cause` "mix" when the model mix explains it (`model`: the one that grew), "both" when the limit moved beyond the mix. */
278
278
  limitMove?: {
279
279
  window: string;
280
280
  at: number;
281
281
  before: number;
282
282
  after: number;
283
283
  factor: number;
284
+ cause?: "limit" | "mix" | "both" | "unclear";
285
+ model?: string;
284
286
  };
285
287
  /** Weekly readings and no 5-hour ones: a plan without that window (Ultra). */
286
288
  noFiveHour?: boolean;
@@ -356,6 +358,8 @@ export interface UsageView {
356
358
  pct?: number;
357
359
  text: string;
358
360
  };
361
+ /** How long the prompt cache stays warm, and the next message's price now and after (cacheLine). */
362
+ cache?: string;
359
363
  limits: Array<{
360
364
  key: string;
361
365
  label: string;
@@ -399,7 +403,22 @@ export interface UsageViewInput {
399
403
  loading?: boolean;
400
404
  error?: string;
401
405
  now: number;
406
+ /** `mod measure`'s figures after the last turn (the cache clock, the re-write's price), and keep-warm's last ping. */
407
+ band?: BandData;
408
+ lastPingAt?: number;
402
409
  }
410
+ /**
411
+ * The usage pane's cache line (ROADMAP H5): how long the prompt cache stays
412
+ * warm and what the next message costs if sent now against after it
413
+ * expires. The clock is the transcript's last reply (`lastReplyAt`), or
414
+ * keep-warm's last ping when later, plus the lifetime that reply wrote
415
+ * (`ttlMs`: an hour when its `usage.cache_creation.ephemeral_1h_input_tokens`
416
+ * is above 0, else 5 minutes; coldresume.ts). The prices are `mod measure`'s
417
+ * (a cache read of the context now, a write of it after), scaled to Claude
418
+ * Code's own context figure when it has one. Shown only in the pane, which
419
+ * the person opens: never the band.
420
+ */
421
+ export declare function cacheLine(d: BandData | undefined, live: LiveUsage | undefined, now: number, lastPingAt?: number): string | undefined;
403
422
  /** 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. */
404
423
  export declare function mergeLimits(ledger: LimitWindow[], live: LiveUsage | undefined): LimitWindow[];
405
424
  /** Everything the usage pane says, as words; register.ts lays it out. */
@@ -468,3 +487,29 @@ export interface DescribeInput {
468
487
  * them), never one of the servers always kept.
469
488
  */
470
489
  export declare function shouldDefer(e: DescribeInput, servers: readonly string[]): boolean;
490
+ /** `mcp__<server>__<tool>`'s server, or undefined for any other name. */
491
+ export declare function mcpServerOf(tool: string): string | undefined;
492
+ /** One server's tools as `tool.describe` showed them this session: each tool once, at its first description. */
493
+ export interface SeenServer {
494
+ type: string;
495
+ tools: Set<string>;
496
+ deferred: number;
497
+ moved: number;
498
+ }
499
+ /** What `mod measure` keeps per server (apptools.ts reads the same shape). */
500
+ export interface SeenServerLine {
501
+ server: string;
502
+ type: string;
503
+ tools: number;
504
+ deferredByHost: boolean;
505
+ movedByUs: boolean;
506
+ }
507
+ /**
508
+ * Note one description: its server, its transport, whether the engine
509
+ * already had it behind tool search and whether the mod moved it. Only an
510
+ * MCP tool with `mcpServer` (2.1.326+) counts; a tool seen again (its
511
+ * loaded description, after tool search found it) is not counted twice.
512
+ */
513
+ export declare function noteDescribe(seen: Map<string, SeenServer>, e: DescribeInput, moved: boolean): void;
514
+ /** The servers as `mod measure` takes them, sorted by name: what changes the ledger line. */
515
+ export declare function seenServers(seen: Map<string, SeenServer>): SeenServerLine[];
package/dist/mod/logic.js CHANGED
@@ -408,6 +408,34 @@ export function ringSvg(pct, size = 64) {
408
408
  + `<text x="32" y="37" text-anchor="middle" font-family="system-ui, sans-serif" font-size="15" fill="currentColor">${pctText(p)}</text>`
409
409
  + `</svg>`;
410
410
  }
411
+ /**
412
+ * The usage pane's cache line (ROADMAP H5): how long the prompt cache stays
413
+ * warm and what the next message costs if sent now against after it
414
+ * expires. The clock is the transcript's last reply (`lastReplyAt`), or
415
+ * keep-warm's last ping when later, plus the lifetime that reply wrote
416
+ * (`ttlMs`: an hour when its `usage.cache_creation.ephemeral_1h_input_tokens`
417
+ * is above 0, else 5 minutes; coldresume.ts). The prices are `mod measure`'s
418
+ * (a cache read of the context now, a write of it after), scaled to Claude
419
+ * Code's own context figure when it has one. Shown only in the pane, which
420
+ * the person opens: never the band.
421
+ */
422
+ export function cacheLine(d, live, now, lastPingAt) {
423
+ if (!d || d.lastReplyAt === undefined || d.ttlMs === undefined || d.tokens === undefined || !(d.tokens > 0))
424
+ return undefined;
425
+ const ctx = live?.context?.tokens;
426
+ const t = ctx !== undefined && Number.isFinite(ctx) && ctx > 0 ? ctx : d.tokens;
427
+ const scale = t / d.tokens;
428
+ const nowUsd = d.perMessageUsd !== undefined ? d.perMessageUsd * scale : undefined;
429
+ const coldUsd = d.rewriteUsd !== undefined ? d.rewriteUsd * scale : undefined;
430
+ const expiresAt = Math.max(d.lastReplyAt, lastPingAt ?? 0) + d.ttlMs;
431
+ if (now < expiresAt) {
432
+ const left = duration(expiresAt - now);
433
+ return nowUsd !== undefined && coldUsd !== undefined
434
+ ? `Cache warm for ${left}. Your next message: ${about(nowUsd)} now, ${about(coldUsd)} after it expires.`
435
+ : `Cache warm for ${left}. After that, your next message re-sends the ${tokens(t)}-token chat at full price.`;
436
+ }
437
+ return `Cache expired ${duration(now - expiresAt)} ago. Your next message re-sends the ${tokens(t)}-token chat at full price${coldUsd !== undefined ? `: ${about(coldUsd)}` : ""}.`;
438
+ }
411
439
  /** 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
440
  export function mergeLimits(ledger, live) {
413
441
  const out = ledger.map((w) => ({ ...w }));
@@ -458,8 +486,10 @@ export function usageView(v) {
458
486
  if (w.usdPerPct !== undefined)
459
487
  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
488
  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%`})`);
489
+ if (mv && mv.window === w.window && mv.at <= now) {
490
+ const why = mv.cause === "mix" ? `: your model mix (more ${shortModel(mv.model)}), not the limit` : mv.cause === "both" ? `, partly your model mix (more ${shortModel(mv.model)})` : "";
491
+ 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%`}${why})`);
492
+ }
463
493
  return { key: w.window, label: w.label, pct: w.pct, text: `${pctText(w.pct)}${parts.length ? ` · ${parts.join(" · ")}` : ""}`, ...(subs.length ? { sub: subs.join("; ") } : {}) };
464
494
  });
465
495
  // 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.
@@ -509,11 +539,12 @@ export function usageView(v) {
509
539
  : hist
510
540
  ? `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
541
  : "";
512
- return { context, limits, ...(limitsNote ? { limitsNote } : {}), periods, ...(period ? { period } : {}), ...(historyNote ? { historyNote } : {}), agents, ...(agentsNote ? { agentsNote } : {}), glance, footer };
542
+ const cache = cacheLine(v.band, live, now, v.lastPingAt);
543
+ return { context, ...(cache ? { cache } : {}), limits, ...(limitsNote ? { limitsNote } : {}), periods, ...(period ? { period } : {}), ...(historyNote ? { historyNote } : {}), agents, ...(agentsNote ? { agentsNote } : {}), glance, footer };
513
544
  }
514
545
  /** The pane as lines of text: the command's answer where no surface draws the pane (`claude -p`, a headless host). */
515
546
  export function usageText(view) {
516
- const lines = [`context-doctor usage: ${view.glance}`, `Context: ${view.context.text}`];
547
+ const lines = [`context-doctor usage: ${view.glance}`, `Context: ${view.context.text}`, ...(view.cache ? [view.cache] : [])];
517
548
  for (const l of view.limits)
518
549
  lines.push(`${l.label} limit: ${l.text}${l.sub ? ` (${l.sub})` : ""}`);
519
550
  if (view.limitsNote)
@@ -607,3 +638,44 @@ export function shouldDefer(e, servers) {
607
638
  return false;
608
639
  return servers.some((n) => !KEEP_APP_SERVERS.includes(n) && e.tool.startsWith(`mcp__${n}__`));
609
640
  }
641
+ // -- Which servers the engine hands the mod (H3: the tools ledger) -----------------------
642
+ /** `mcp__<server>__<tool>`'s server, or undefined for any other name. */
643
+ export function mcpServerOf(tool) {
644
+ const m = /^mcp__(.+?)__./.exec(typeof tool === "string" ? tool : "");
645
+ return m && /^[A-Za-z0-9_.-]{1,80}$/.test(m[1]) ? m[1] : undefined;
646
+ }
647
+ /**
648
+ * Note one description: its server, its transport, whether the engine
649
+ * already had it behind tool search and whether the mod moved it. Only an
650
+ * MCP tool with `mcpServer` (2.1.326+) counts; a tool seen again (its
651
+ * loaded description, after tool search found it) is not counted twice.
652
+ */
653
+ export function noteDescribe(seen, e, moved) {
654
+ if (!e || !e.mcpServer || typeof e.mcpServer !== "object")
655
+ return;
656
+ const server = mcpServerOf(e.tool);
657
+ if (!server)
658
+ return;
659
+ const type = typeof e.mcpServer.type === "string" && /^[a-z-]{1,20}$/.test(e.mcpServer.type) ? e.mcpServer.type : "unknown";
660
+ let s = seen.get(server);
661
+ if (!s) {
662
+ // A runaway list (hundreds of servers) is not worth keeping whole.
663
+ if (seen.size >= 60)
664
+ return;
665
+ s = { type, tools: new Set(), deferred: 0, moved: 0 };
666
+ seen.set(server, s);
667
+ }
668
+ if (s.tools.has(e.tool))
669
+ return;
670
+ s.tools.add(e.tool);
671
+ if (e.isDeferred === true)
672
+ s.deferred++;
673
+ if (moved)
674
+ s.moved++;
675
+ }
676
+ /** The servers as `mod measure` takes them, sorted by name: what changes the ledger line. */
677
+ export function seenServers(seen) {
678
+ return [...seen.entries()]
679
+ .map(([server, s]) => ({ server, type: s.type, tools: s.tools.size, deferredByHost: s.tools.size > 0 && s.deferred === s.tools.size, movedByUs: s.moved > 0 }))
680
+ .sort((a, b) => (a.server < b.server ? -1 : a.server > b.server ? 1 : 0));
681
+ }
@@ -28,13 +28,18 @@
28
28
  * - `/context-doctor-usage` opens the usage view the Desktop app dropped:
29
29
  * the context ring and the limit windows from Claude Code's own figures,
30
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
31
+ * subagents with their model, context and cost so far, and under Context
32
+ * how long the prompt cache stays warm with the next message's price now
33
+ * and after it expires (the $.clock tick redraws it). Drawing only reads
32
34
  * what the mod holds; `context-doctor mod usage` refreshes it on the
33
35
  * timer, only while the pane is open (usageDue).
34
36
  * - `tool.describe` (2.1.326+): once `fix --apply desktop-tools-defer`
35
37
  * named the Desktop app's own MCP servers in CONTEXT_DOCTOR_DEFER_MCP,
36
38
  * their tools go behind tool search from the next new conversation; never
37
- * ccd_turn, never with `breakPromptCache`. Unset, nothing moves.
39
+ * ccd_turn, never with `breakPromptCache`. Unset, nothing moves. Set or
40
+ * not, it notes each MCP server's transport, tool count and placement,
41
+ * and the next `mod measure` keeps them (changes only) for `fix` and
42
+ * `doctor`: proof the lever reaches the app before anyone applies it.
38
43
  *
39
44
  * Nothing happens without a press or a command: no auto-compaction, no auto-apply, no ping. The
40
45
  * mod writes no file itself; the CLI writes ours. Off: CONTEXT_DOCTOR_NO_MOD=1.
@@ -44,7 +49,7 @@
44
49
  * reads which calls a module makes from its source: `$` is passed only to
45
50
  * functions declared at the top of this file.
46
51
  */
47
- import { type AgentLike, type BandData, type KeepWarm, type LiveUsage, type PeriodUse, type PlanJson, type UsagePaneData } from "./logic.js";
52
+ import { type AgentLike, type BandData, type KeepWarm, type LiveUsage, type PeriodUse, type PlanJson, type SeenServer, type UsagePaneData } from "./logic.js";
48
53
  import type { On } from "./api.js";
49
54
  export declare const COMMAND = "context-doctor-fix";
50
55
  export declare const PANE = "context-doctor-fix";
@@ -92,6 +97,11 @@ interface State {
92
97
  period: PeriodUse["key"];
93
98
  /** What the pane last said, so the timer redraws only when its words change. */
94
99
  usageDrawn: string;
100
+ /** `session.start`'s surface, for the tools ledger. */
101
+ surface?: string;
102
+ /** The MCP servers `tool.describe` showed this session, and what `mod measure` was last handed of them. */
103
+ tools: Map<string, SeenServer>;
104
+ toolsSent: string;
95
105
  }
96
106
  /** For tests: the state the hooks share. */
97
107
  export declare const state: () => State;
@@ -28,13 +28,18 @@
28
28
  * - `/context-doctor-usage` opens the usage view the Desktop app dropped:
29
29
  * the context ring and the limit windows from Claude Code's own figures,
30
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
31
+ * subagents with their model, context and cost so far, and under Context
32
+ * how long the prompt cache stays warm with the next message's price now
33
+ * and after it expires (the $.clock tick redraws it). Drawing only reads
32
34
  * what the mod holds; `context-doctor mod usage` refreshes it on the
33
35
  * timer, only while the pane is open (usageDue).
34
36
  * - `tool.describe` (2.1.326+): once `fix --apply desktop-tools-defer`
35
37
  * named the Desktop app's own MCP servers in CONTEXT_DOCTOR_DEFER_MCP,
36
38
  * their tools go behind tool search from the next new conversation; never
37
- * ccd_turn, never with `breakPromptCache`. Unset, nothing moves.
39
+ * ccd_turn, never with `breakPromptCache`. Unset, nothing moves. Set or
40
+ * not, it notes each MCP server's transport, tool count and placement,
41
+ * and the next `mod measure` keeps them (changes only) for `fix` and
42
+ * `doctor`: proof the lever reaches the app before anyone applies it.
38
43
  *
39
44
  * Nothing happens without a press or a command: no auto-compaction, no auto-apply, no ping. The
40
45
  * mod writes no file itself; the CLI writes ours. Off: CONTEXT_DOCTOR_NO_MOD=1.
@@ -44,7 +49,7 @@
44
49
  * reads which calls a module makes from its source: `$` is passed only to
45
50
  * functions declared at the top of this file.
46
51
  */
47
- import { applyOutcome, band, bar, DEFAULT_THRESHOLDS, deferredServers, fixArgv, KEEP_WARM_COMMAND, keepWarmTestEvery, keepWarmArmedText, keepWarmRefusal, keepWarmStatusText, keepWarmStep, keepWarmText, MODEL_CHANGE, money, outcome, paneRows, parseKeepWarm, parsePlan, parseUsage, pctText, PING_PROMPT, pingOutcome, ringSvg, RUNNING, shouldDefer, thresholdsFrom, usageArgv, usageDue, usageText, usageView, withPresses } from "./logic.js";
52
+ import { applyOutcome, band, bar, DEFAULT_THRESHOLDS, deferredServers, fixArgv, noteDescribe, seenServers, KEEP_WARM_COMMAND, keepWarmTestEvery, keepWarmArmedText, keepWarmRefusal, keepWarmStatusText, keepWarmStep, keepWarmText, MODEL_CHANGE, money, outcome, paneRows, parseKeepWarm, parsePlan, parseUsage, pctText, PING_PROMPT, pingOutcome, ringSvg, RUNNING, shouldDefer, thresholdsFrom, usageArgv, usageDue, usageText, usageView, withPresses } from "./logic.js";
48
53
  export const COMMAND = "context-doctor-fix";
49
54
  export const PANE = "context-doctor-fix";
50
55
  export const USAGE_COMMAND = "context-doctor-usage";
@@ -56,7 +61,7 @@ const FIX_TIMEOUT_MS = 10 * 60_000;
56
61
  const MEASURE_TIMEOUT_MS = 30_000;
57
62
  /** `mod usage` measures 30 days the first time (~3 s cold on 22,000 requests); later runs read its 5-minute cache. */
58
63
  const USAGE_TIMEOUT_MS = 2 * 60_000;
59
- const fresh = () => ({ off: false, cold: 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: "" });
64
+ const fresh = () => ({ off: false, cold: 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: "", tools: new Map(), toolsSent: "" });
60
65
  let S = fresh();
61
66
  /** For tests: the state the hooks share. */
62
67
  export const state = () => S;
@@ -85,7 +90,13 @@ async function measure($, e) {
85
90
  catch { /* measured without it */ }
86
91
  if (S.live)
87
92
  S.live.model = model;
88
- 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 });
93
+ // The servers the app handed over this session, only when they changed since the last measure (the CLI keeps them: apptools.ts).
94
+ const tools = seenServers(S.tools);
95
+ const toolsKey = tools.length ? JSON.stringify(tools) : "";
96
+ const send = toolsKey !== "" && toolsKey !== S.toolsSent;
97
+ const run = await $.process.run(["node", cliOf($), "mod", "measure"], { stdin: JSON.stringify({ sessionId, cwd, model, rateLimits: e.rateLimits, cost: e.cost, context: e.context, ...(send ? { tools, ...(S.surface ? { surface: S.surface } : {}) } : {}) }), timeoutMs: MEASURE_TIMEOUT_MS });
98
+ if (send && run.exitCode === 0)
99
+ S.toolsSent = toolsKey;
89
100
  const got = JSON.parse(run.stdout || "{}");
90
101
  S.data = got && typeof got.at === "number" ? got : fallback;
91
102
  }
@@ -320,7 +331,7 @@ async function liveNow($) {
320
331
  catch { /* the next turn measures */ }
321
332
  }
322
333
  function viewAt(now) {
323
- return usageView({ data: S.usage, live: S.live, agents: S.agents, period: S.period, loading: S.usageLoading, error: S.usageError, now });
334
+ return usageView({ data: S.usage, live: S.live, agents: S.agents, period: S.period, loading: S.usageLoading, error: S.usageError, now, band: S.data, lastPingAt: S.kw?.lastPingAt });
324
335
  }
325
336
  /** While the pane is open: the subagents (one call), `mod usage` when it is due, and a redraw only when the words change. */
326
337
  async function usageTick($, now) {
@@ -352,6 +363,7 @@ export function register(on) {
352
363
  on("session.start", async ($, e, next) => {
353
364
  try {
354
365
  S.off = (await $.env.get("CONTEXT_DOCTOR_NO_MOD")) === "1";
366
+ S.surface = typeof e?.surface === "string" ? e.surface : undefined;
355
367
  const bandMode = (await $.env.get("CONTEXT_DOCTOR_MOD_BAND"))?.trim().toLowerCase();
356
368
  S.cold = bandMode === "cold";
357
369
  S.always = bandMode === "always";
@@ -390,6 +402,9 @@ export function register(on) {
390
402
  }
391
403
  catch { /* ending anyway */ }
392
404
  S.data = undefined;
405
+ // The next session's tools are described again, and recorded as its own.
406
+ S.tools = new Map();
407
+ S.toolsSent = "";
393
408
  // The next session's ring and subagents are its own; the history (every session's) stays.
394
409
  S.live = undefined;
395
410
  if (S.agents)
@@ -443,18 +458,30 @@ export function register(on) {
443
458
  // which the engine asks once per tool and session. The answer moves the tool for the next new
444
459
  // thread or /clear; no breakPromptCache, so a running conversation's cache is never re-written.
445
460
  // An engine older than 2.1.326 (no `mcpServer` on the input) gets its own answer back untouched.
461
+ // Set or not, each MCP tool's server, transport and placement is noted in memory (no file, no
462
+ // process: the next session.measure hands them to the CLI), so `fix` and `doctor` can say
463
+ // whether the lever reaches the app's servers before anyone applies it.
446
464
  try {
447
465
  on("tool.describe", async ($, e, next) => {
448
- if (!e?.mcpServer || e.isDeferred === true)
466
+ if (!e?.mcpServer)
449
467
  return next(e);
468
+ let off = false;
450
469
  let servers = [];
451
470
  try {
452
- if ((await $.env.get("CONTEXT_DOCTOR_NO_MOD")) !== "1")
471
+ off = (await $.env.get("CONTEXT_DOCTOR_NO_MOD")) === "1";
472
+ if (!off && e.isDeferred !== true)
453
473
  servers = deferredServers(await $.env.get("CONTEXT_DOCTOR_DEFER_MCP"));
454
474
  }
455
475
  catch { /* no variable: nothing moves */ }
456
476
  const r = await next(e);
457
- return shouldDefer(e, servers) && r && typeof r === "object" ? { ...r, isDeferred: true } : r;
477
+ const move = shouldDefer(e, servers) && !!r && typeof r === "object";
478
+ if (!off) {
479
+ try {
480
+ noteDescribe(S.tools, e, move);
481
+ }
482
+ catch { /* a note is a nicety */ }
483
+ }
484
+ return move ? { ...r, isDeferred: true } : r;
458
485
  });
459
486
  }
460
487
  catch { /* an engine without tool.describe: nothing to defer */ }
@@ -489,6 +516,9 @@ export function register(on) {
489
516
  }
490
517
  else
491
518
  body.push(dim(v.context.text));
519
+ // The cache clock and the next message's price, now and after it expires: here only, never the band.
520
+ if (v.cache)
521
+ body.push(h(Text, null, v.cache));
492
522
  body.push(h(Box, { marginTop: 1 }, head("Limits")));
493
523
  for (const l of v.limits) {
494
524
  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)] : [])));
@@ -43,6 +43,21 @@ export declare function openaiPageIds(markdown: string): string[];
43
43
  * the text models only.
44
44
  */
45
45
  export declare function googlePageIds(markdown: string): string[];
46
+ /**
47
+ * The models Claude Code's signed model catalog offers
48
+ * (downloads.claude.ai/model-catalog/v1/catalog.json, read from 2.1.331 on;
49
+ * `modelCatalogUrl` can point elsewhere): every
50
+ * `surfaces.<surface>.model_selector_config[].models[].id`, across the
51
+ * terminal (`cc`), the Desktop app's Code tab (`ccd`) and the rest. It
52
+ * changes between Claude Code releases (version 5883 was issued 2026-11-24
53
+ * and expires a week later), so a model can reach the picker before any
54
+ * binary or CHANGELOG names it. `about` says which catalog was read.
55
+ * Throws on a catalog in another shape.
56
+ */
57
+ export declare function catalogModelIds(json: string): {
58
+ ids: string[];
59
+ about: string;
60
+ };
46
61
  /**
47
62
  * The models Codex offers (its models catalog, codex-rs/models-manager/
48
63
  * models.json): `listed` are the ones its picker shows, `hidden` the rest
package/dist/modelids.js CHANGED
@@ -129,6 +129,39 @@ export function googlePageIds(markdown) {
129
129
  out.add(m[1]);
130
130
  return [...out].sort();
131
131
  }
132
+ /**
133
+ * The models Claude Code's signed model catalog offers
134
+ * (downloads.claude.ai/model-catalog/v1/catalog.json, read from 2.1.331 on;
135
+ * `modelCatalogUrl` can point elsewhere): every
136
+ * `surfaces.<surface>.model_selector_config[].models[].id`, across the
137
+ * terminal (`cc`), the Desktop app's Code tab (`ccd`) and the rest. It
138
+ * changes between Claude Code releases (version 5883 was issued 2026-11-24
139
+ * and expires a week later), so a model can reach the picker before any
140
+ * binary or CHANGELOG names it. `about` says which catalog was read.
141
+ * Throws on a catalog in another shape.
142
+ */
143
+ export function catalogModelIds(json) {
144
+ const catalog = JSON.parse(json);
145
+ const surfaces = catalog?.surfaces;
146
+ if (!surfaces || typeof surfaces !== "object" || Array.isArray(surfaces))
147
+ throw new Error("no surfaces object");
148
+ const out = new Set();
149
+ for (const surface of Object.values(surfaces)) {
150
+ const configs = surface?.model_selector_config;
151
+ if (!Array.isArray(configs))
152
+ continue;
153
+ for (const config of configs) {
154
+ if (!Array.isArray(config?.models))
155
+ continue;
156
+ for (const m of config.models)
157
+ if (typeof m?.id === "string" && m.id)
158
+ out.add(m.id);
159
+ }
160
+ }
161
+ const version = catalog.version !== undefined ? `version ${catalog.version}` : "no version";
162
+ const dates = [catalog.issued_at && `issued ${String(catalog.issued_at).slice(0, 10)}`, catalog.expires_at && `expires ${String(catalog.expires_at).slice(0, 10)}`].filter(Boolean).join(", ");
163
+ return { ids: [...out].sort(), about: `catalog ${version}${dates ? `, ${dates}` : ""}; surfaces ${Object.keys(surfaces).join(", ")}` };
164
+ }
132
165
  /**
133
166
  * The models Codex offers (its models catalog, codex-rs/models-manager/
134
167
  * models.json): `listed` are the ones its picker shows, `hidden` the rest
@@ -18,6 +18,9 @@
18
18
  * - appends Claude Code's cost beside our own price of the same session
19
19
  * (sessionTotal: the transcript and its subagents, as the every-prompt
20
20
  * hook prices it) to a small capped ledger, for `doctor`'s comparison;
21
+ * - appends the MCP servers the mod's `tool.describe` saw this session
22
+ * (their type, tool count, whether already behind tool search), when
23
+ * they changed, to the tools ledger (apptools.ts), for `fix` and `doctor`;
21
24
  * - prints what the band needs, as JSON: the cache clock read from the
22
25
  * transcript's tail (coldresume.ts), the re-write's price, the price.
23
26
  *
@@ -43,6 +46,10 @@ export interface ModMeasureInput {
43
46
  tokens?: unknown;
44
47
  window?: unknown;
45
48
  };
49
+ /** `session.start`'s surface (desktop, terminal, vscode), for the tools ledger. */
50
+ surface?: unknown;
51
+ /** The MCP servers `tool.describe` showed the mod this session, when they changed since it last sent them (apptools.ts). */
52
+ tools?: unknown;
46
53
  }
47
54
  /**
48
55
  * The mod's windows in the status line's shape, `{ five_hour: { used_percentage,
@@ -18,6 +18,9 @@
18
18
  * - appends Claude Code's cost beside our own price of the same session
19
19
  * (sessionTotal: the transcript and its subagents, as the every-prompt
20
20
  * hook prices it) to a small capped ledger, for `doctor`'s comparison;
21
+ * - appends the MCP servers the mod's `tool.describe` saw this session
22
+ * (their type, tool count, whether already behind tool search), when
23
+ * they changed, to the tools ledger (apptools.ts), for `fix` and `doctor`;
21
24
  * - prints what the band needs, as JSON: the cache clock read from the
22
25
  * transcript's tail (coldresume.ts), the re-write's price, the price.
23
26
  *
@@ -34,6 +37,7 @@ import { claudeDir } from "./claudedir.js";
34
37
  import { saveIfWorthIt, sessionPriceThresholds, sessionTotal } from "./sessionprice.js";
35
38
  import { AFTER_COMPACT_TOKENS, autoCompactsAt, COLD_MARGIN_MS, COLD_MIN_TOKENS, detectColdResume } from "./coldresume.js";
36
39
  import { rateCard, ratesAt } from "./pricing.js";
40
+ import { recordToolServers } from "./apptools.js";
37
41
  /**
38
42
  * The mod's windows in the status line's shape, `{ five_hour: { used_percentage,
39
43
  * resets_at } }`, resets in epoch seconds: the one shape recordLimits reads.
@@ -245,6 +249,11 @@ export function modMeasure(input, now = Date.now(), env = process.env) {
245
249
  if (ccUsd !== undefined)
246
250
  out.ccUsd = ccUsd;
247
251
  const sid = typeof input?.sessionId === "string" ? input.sessionId : undefined;
252
+ try {
253
+ if (sid && input?.tools !== undefined && env.CONTEXT_DOCTOR_NO_COST_LOG !== "1")
254
+ recordToolServers({ ts: now, sid, ...(typeof input.surface === "string" ? { surface: input.surface } : {}), servers: input.tools });
255
+ }
256
+ catch { /* the rest still runs */ }
248
257
  const transcript = findTranscript(sid, typeof input?.cwd === "string" ? input.cwd : undefined);
249
258
  if (!sid || !transcript)
250
259
  return out;
package/dist/overhead.js CHANGED
@@ -28,7 +28,7 @@ import { claudeDir } from "./claudedir.js";
28
28
  import { mcpjsonServerApproved } from "./prune.js";
29
29
  import { REQUEST_ROWS } from "./coldresume.js";
30
30
  import { rowsOf } from "./scan.js";
31
- import { measureStarts, renderStarts } from "./starts.js";
31
+ import { measureStarts, renderStarts, startsTotal } from "./starts.js";
32
32
  import { readFixRecords } from "./fix.js";
33
33
  const TTL_MS = 3_600_000;
34
34
  const CLAUDE = "claude-opus-5"; // Claude's tokenizer ratios; the model only picks the provider here.
@@ -473,10 +473,16 @@ export function renderOverhead(r, home = homedir()) {
473
473
  out.push("FIXED OVERHEAD: what every request re-reads before your message", "═".repeat(56));
474
474
  const b = r.baseline;
475
475
  const claudeTokens = r.files.filter((f) => f.agent === "Claude Code").reduce((s, f) => s + f.tokens, 0);
476
+ const st = r.starts && r.starts.groups.length ? startsTotal(r.starts) : undefined;
476
477
  if (b) {
477
478
  out.push(`Claude Code, last ${b.days} days: ${sessionCount(b)} start at a median ~${formatTokens(b.median)} tokens (p90 ~${formatTokens(b.p90)}) before the first message.`, `Memory files loaded here are ~${formatTokens(claudeTokens)} of that; the rest is Claude Code's system prompt, tools, skills and MCP schemas.`);
478
479
  if (b.usdPerKPerMonth !== undefined) {
479
- out.push(`At your usage (${b.requests.toLocaleString("en-US")} requests, ${b.coldStarts.toLocaleString("en-US")} cold starts, ${b.model} ${priceBasis().replace(/^at /, "")}) every 1k tokens of it costs ~${formatUsd(b.usdPerKPerMonth)} a month;`, `the whole overhead ~${formatUsd((b.median / 1000) * b.usdPerKPerMonth)} a month.`);
480
+ out.push(`At your usage (${b.requests.toLocaleString("en-US")} requests, ${b.coldStarts.toLocaleString("en-US")} cold starts, ${b.model} ${priceBasis().replace(/^at /, "")}) every 1k tokens added to it costs ~${formatUsd(b.usdPerKPerMonth)} a month (what the memory files below are priced at).`,
481
+ // One figure for the whole: the starts below, each start as billed with subagents in, when measured. The
482
+ // median at the rate above leaves subagents and sessions begun before the period out, and read as a second total.
483
+ ...(st && st.usd > 0
484
+ ? [`The whole of it, every session and subagent start as billed: ${formatUsd(st.usd)}${st.unpriced ? "+" : ""} over the last ${r.starts.days} days${st.subagents ? ` (subagents ${formatUsd(st.subagentUsd)})` : ""}, itemised below.`]
485
+ : [`The whole of it ~${formatUsd((b.median / 1000) * b.usdPerKPerMonth)} a month: the median start at that rate, an estimate.`]));
480
486
  }
481
487
  }
482
488
  else {
@@ -47,6 +47,30 @@
47
47
  * subagent whose transcript says `version` 2.1.328 or later is priced once,
48
48
  * at Haiku 5.5's rates (low and high the same); an older one as before.
49
49
  *
50
+ * Read again from the 2.1.330 binary: that is a terminal session on the
51
+ * Anthropic API's only. Per subagent, Claude Code reads its provider (from
52
+ * CLAUDE_CODE_USE_*: the Claude Code gateway, Bedrock, Foundry, Anthropic on
53
+ * AWS or Google Cloud, Mantle, Vertex, else the Anthropic API):
54
+ * - Bedrock, Vertex, Foundry or the gateway (CLAUDE_CODE_USE_GATEWAY): the
55
+ * notes, written by the subagent's OWN model ("release" mode).
56
+ * - Any other: a served flag (notes unless it says otherwise), and the
57
+ * writer is the small fast model only when ANTHROPIC_SMALL_FAST_MODEL and
58
+ * ANTHROPIC_DEFAULT_HAIKU_MODEL are both unset, the provider is the
59
+ * Anthropic API, and the API counts as Anthropic's: ANTHROPIC_BASE_URL
60
+ * unset or api.anthropic.com (or _CLAUDE_CODE_ASSUME_FIRST_PARTY_BASE_URL),
61
+ * or the key is an Anthropic API key (sk-ant-api..., not
62
+ * ANTHROPIC_AUTH_TOKEN, a claude.ai sign-in or /login's managed key).
63
+ * With no writer, the summary is the whole context on the agent's own
64
+ * model, the pre-2.1.328 form. A plain ANTHROPIC_BASE_URL is not the
65
+ * "gateway": a proxy on 127.0.0.1 (context-doctor's autopilot) leaves the
66
+ * provider the Anthropic API and fails the base-URL test, so on a Claude
67
+ * sign-in it gets the whole context.
68
+ * Which applied is told from the transcript where it can be (Bedrock and
69
+ * Vertex model and message ids), else from the settings and environment
70
+ * now (summaryRoute), autopilot's proxy counted from when autopilot was
71
+ * turned on. Where neither tells (an API key that may or may not be used
72
+ * behind a proxy), a range: Haiku notes low, the whole context high.
73
+ *
50
74
  * Estimated per subagent from what its transcript does record: the time of
51
75
  * each message (the ticks and whether the transcript changed), each reply's
52
76
  * prompt size and model (the context a fork would read, the rates). Each
@@ -55,6 +79,7 @@
55
79
  * later, not more often), and the thinking a summary may do.
56
80
  */
57
81
  import { type Extractor } from "./scan.js";
82
+ import { type SettingsSource } from "./effective.js";
58
83
  /** The variable the lever writes, and the value: Claude Code passes only "1" on to the sessions it starts in the background. */
59
84
  export declare const PROGRESS_SUMMARIES_ENV = "CLAUDE_CODE_DISABLE_AGENT_PROGRESS_SUMMARIES";
60
85
  export declare const PROGRESS_SUMMARIES_OFF = "1";
@@ -73,6 +98,36 @@ export declare const SMALL_FAST_MODEL_NAME = "Haiku 5.5";
73
98
  export declare const FORK_PROMPT_TOKENS = 150;
74
99
  /** Each summary's output: #86879's measured mean (21,966 tokens over 339 summaries). */
75
100
  export declare const SUMMARY_OUTPUT_TOKENS = 65;
101
+ /**
102
+ * How a terminal subagent's summaries were written on Claude Code 2.1.328+:
103
+ * notes by Haiku ("haiku"), notes by the subagent's own model ("own-notes"),
104
+ * its whole context on its own model ("whole"), or one of the first and
105
+ * the last, which could not be told ("range").
106
+ */
107
+ export type SummaryForm = "haiku" | "own-notes" | "whole" | "range";
108
+ /** The form, why in plain words, and (autopilot's proxy) from when: before `since`, `before`. */
109
+ export interface SummaryRoute {
110
+ form: SummaryForm;
111
+ why: string;
112
+ since?: number;
113
+ before?: SummaryRoute;
114
+ }
115
+ /** Nothing set: the Anthropic API, notes by Haiku. */
116
+ export declare const ANTHROPIC_API_ROUTE: SummaryRoute;
117
+ /** The cloud a reply's ids name: Bedrock's (`anthropic.`, region-prefixed, an ARN; `msg_bdrk_`), Vertex's (`@date`; `msg_vrtx_`). */
118
+ export declare function replyCloud(model: unknown, id: unknown): "bedrock" | "vertex" | undefined;
119
+ /**
120
+ * Which form Claude Code 2.1.330 uses for a terminal subagent on a
121
+ * first-party model id, from the settings and environment as they are now
122
+ * (read only). Autopilot's proxy counts from when autopilot was turned on
123
+ * (its config file, written then); before it, the address it replaced.
124
+ */
125
+ export declare function summaryRoute(deps?: {
126
+ home?: string;
127
+ cwd?: string;
128
+ env?: NodeJS.ProcessEnv;
129
+ sources?: SettingsSource[];
130
+ }): SummaryRoute;
76
131
  /** How Claude Code reads the variable (a boolean: "1", "true", "yes", "on"). */
77
132
  export declare const disablesSummaries: (v: unknown) => boolean;
78
133
  /**
@@ -123,22 +178,46 @@ type Rec = {
123
178
  p: number;
124
179
  speed?: string;
125
180
  geo?: string;
181
+ cloud?: "bedrock" | "vertex";
126
182
  };
183
+ /** How one agent's summaries were written: its transcript's cloud, else the route at its start. */
184
+ export declare function agentRoute(recs: Rec[], route?: SummaryRoute): SummaryRoute;
185
+ /** Priced how: "old" (before 2.1.328: notes low, whole context high) or a 2.1.328+ form. */
186
+ export type PriceMode = "old" | SummaryForm;
127
187
  /**
128
188
  * The ticks a running agent's timer made and the summaries they sent, from
129
189
  * its timeline: every 30 s from its first row to its last, a summary when
130
190
  * it has 3+ messages and more than at the last summary. Only ticks in
131
191
  * [since, until] are counted.
132
192
  */
133
- export declare function simulateAgent(recs: Rec[], since?: number, until?: number, smallNotes?: boolean): AgentSummaries;
193
+ export declare function simulateAgent(recs: Rec[], since?: number, until?: number, mode?: boolean | PriceMode): AgentSummaries;
134
194
  export interface ProgressSummaryEstimate {
135
195
  /** Subagent transcripts read (workflow agents included). */
136
196
  agents: number;
137
197
  /** Agents Claude Code wrote summaries for in the window, by the rules above. */
138
198
  summarized: number;
139
199
  calls: number;
140
- /** Of `calls`, those by agents on Claude Code 2.1.328+: notes on the small fast model, the same in both figures. */
200
+ /** Of `calls`, those by agents on Claude Code 2.1.328+ on the Anthropic API: notes on the small fast model, the same in both figures. */
141
201
  smallCalls: number;
202
+ /**
203
+ * The other 2.1.328+ summaries, by form and why (summaryRoute, agentRoute):
204
+ * notes on the agent's own model, its whole context, or a range. Absent
205
+ * or empty when all were on the Anthropic API.
206
+ */
207
+ routes?: Array<{
208
+ form: Exclude<SummaryForm, "haiku">;
209
+ why: string;
210
+ calls: number;
211
+ agents: number;
212
+ lowUsd: number;
213
+ highUsd: number;
214
+ }>;
215
+ /**
216
+ * What turning them off saves, for fix: before 2.1.328 the notes (the low
217
+ * figure, as before), from it the form's figure, a range at its high end
218
+ * (what could not be told is not counted at the cheapest).
219
+ */
220
+ valueUsd?: number;
142
221
  /** The summaries as short notes (what Anthropic serves since November 2026): the low figure. */
143
222
  notesUsd: number;
144
223
  /** As a fork of the whole context (before): the high figure. */
@@ -159,9 +238,13 @@ export interface ProgressOptions {
159
238
  interactive?: (entrypoint: string | undefined) => boolean;
160
239
  /** Only agents on this Claude Code or newer (what the variable would have stopped: 2.1.318+). */
161
240
  minVersion?: string;
241
+ /** How 2.1.328+ agents on a first-party model id were served (summaryRoute); default the Anthropic API. */
242
+ route?: SummaryRoute;
162
243
  }
163
244
  /** The summaries of the subagents in `files` (their `.jsonl` transcripts), estimated. */
164
245
  export declare function estimateProgressSummaries(files: string[], opts?: ProgressOptions): ProgressSummaryEstimate;
246
+ /** A 2.1.328+ form in words: what each summary sent, and on what. */
247
+ export declare function formWords(form: SummaryForm): string;
165
248
  /** "the Desktop app", "the SDK or -p": a host as a person knows it. */
166
249
  export declare function hostName(entrypoint: string): string;
167
250
  export {};