context-doctor 0.49.0 → 0.50.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 (50) hide show
  1. package/README.md +16 -14
  2. package/dist/appwindow.d.ts +69 -0
  3. package/dist/appwindow.js +147 -0
  4. package/dist/ccost.d.ts +35 -0
  5. package/dist/ccost.js +105 -5
  6. package/dist/claudedir.d.ts +15 -0
  7. package/dist/claudedir.js +19 -1
  8. package/dist/cli.js +59 -23
  9. package/dist/clihelp.d.ts +5 -1
  10. package/dist/clihelp.js +9 -1
  11. package/dist/codexstatusline.d.ts +176 -0
  12. package/dist/codexstatusline.js +353 -0
  13. package/dist/compactwindow.d.ts +14 -2
  14. package/dist/compactwindow.js +30 -5
  15. package/dist/credits.d.ts +130 -0
  16. package/dist/credits.js +265 -0
  17. package/dist/doctor.d.ts +6 -0
  18. package/dist/doctor.js +15 -1
  19. package/dist/fanout.d.ts +2 -0
  20. package/dist/fanout.js +12 -2
  21. package/dist/fix.d.ts +37 -1
  22. package/dist/fix.js +67 -9
  23. package/dist/install.js +1 -1
  24. package/dist/limits.d.ts +56 -2
  25. package/dist/limits.js +181 -14
  26. package/dist/mcp.d.ts +1 -0
  27. package/dist/mcp.js +106 -100
  28. package/dist/mod/api.d.ts +27 -1
  29. package/dist/mod/api.js +2 -1
  30. package/dist/mod/logic.d.ts +47 -16
  31. package/dist/mod/logic.js +68 -39
  32. package/dist/mod/register.d.ts +6 -0
  33. package/dist/mod/register.js +34 -6
  34. package/dist/modelids.js +2 -2
  35. package/dist/orgrates.d.ts +4 -2
  36. package/dist/orgrates.js +21 -3
  37. package/dist/overhead.js +2 -1
  38. package/dist/pricing.js +12 -0
  39. package/dist/progresssummaries.d.ts +20 -1
  40. package/dist/progresssummaries.js +33 -3
  41. package/dist/proxy.d.ts +1 -1
  42. package/dist/proxy.js +9 -4
  43. package/dist/savings.js +3 -1
  44. package/dist/sidecost.d.ts +65 -0
  45. package/dist/sidecost.js +117 -0
  46. package/dist/spend.d.ts +36 -1
  47. package/dist/spend.js +49 -5
  48. package/dist/starts.d.ts +27 -1
  49. package/dist/starts.js +81 -18
  50. package/package.json +1 -1
package/dist/mod/api.d.ts CHANGED
@@ -10,7 +10,8 @@
10
10
  * and the events `session.start`, `session.measure`, `session.end`,
11
11
  * `command.run`, `ui.render`; from 2.1.325's, for the usage pane,
12
12
  * `$.agent.list`, `$.session.usage`, the `Svg` element, a pane's `placement`
13
- * and `bodyColumns`, and `ui.close`. A subset, structurally compatible: no
13
+ * and `bodyColumns`, and `ui.close`; from 2.1.329's, `tool.describe` with
14
+ * its `mcpServer` and an answer's `isDeferred`. A subset, structurally compatible: no
14
15
  * runtime code.
15
16
  */
16
17
  export type Surface = "terminal" | "desktop" | "vscode" | "mobile";
@@ -202,4 +203,29 @@ export interface On {
202
203
  kind: string;
203
204
  };
204
205
  }, unknown>): unknown;
206
+ (event: "tool.describe", hook: Hook<ToolDescribeInput, ToolDescribeResult>): unknown;
207
+ }
208
+ /**
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
211
+ * time the engine renders its schema in a session. `isDeferred: true` on the
212
+ * answer puts the tool behind ToolSearch from the next new thread or `/clear`;
213
+ * `breakPromptCache` would send it at the next turn by re-writing the whole
214
+ * prompt cache, which the mod never asks for.
215
+ */
216
+ export interface ToolDescribeInput {
217
+ tool: string;
218
+ description: string;
219
+ isDeferred?: true;
220
+ provider?: unknown;
221
+ mcpServer?: {
222
+ type: "stdio" | "http" | "sse" | "ws" | "sdk" | "sse-ide" | "ws-ide" | "claudeai-proxy" | string;
223
+ origin?: string;
224
+ connectorId?: string;
225
+ };
226
+ }
227
+ export interface ToolDescribeResult {
228
+ description: string;
229
+ isDeferred?: boolean;
230
+ breakPromptCache?: boolean;
205
231
  }
package/dist/mod/api.js CHANGED
@@ -10,7 +10,8 @@
10
10
  * and the events `session.start`, `session.measure`, `session.end`,
11
11
  * `command.run`, `ui.render`; from 2.1.325's, for the usage pane,
12
12
  * `$.agent.list`, `$.session.usage`, the `Svg` element, a pane's `placement`
13
- * and `bodyColumns`, and `ui.close`. A subset, structurally compatible: no
13
+ * and `bodyColumns`, and `ui.close`; from 2.1.329's, `tool.describe` with
14
+ * its `mcpServer` and an answer's `isDeferred`. A subset, structurally compatible: no
14
15
  * runtime code.
15
16
  */
16
17
  export {};
@@ -50,16 +50,6 @@ export type Band = {
50
50
  text: string;
51
51
  compact: string;
52
52
  };
53
- /** The band shows within this long of the cache going cold... */
54
- export declare const WARN_BEFORE_MS: number;
55
- /**
56
- * ...or within this share of the cache's life, when that is shorter: the last
57
- * minute of a 5-minute cache (WARN_BEFORE_MS would be all of it, the band
58
- * after every turn), the last five of the 1-hour cache.
59
- */
60
- export declare const WARN_SHARE: number;
61
- /** How long before the cache goes cold the band warns, for a cache that lives `ttlMs`. */
62
- export declare function warnBeforeMs(ttlMs: number): number;
63
53
  /** The session price thresholds when the CLI cannot say them (no Node): the defaults, the environment's own, or none. */
64
54
  export declare const DEFAULT_THRESHOLDS: number[];
65
55
  /** CONTEXT_DOCTOR_SESSION_PRICE and CONTEXT_DOCTOR_NO_SESSION_PRICE read as sessionprice.ts reads them. */
@@ -77,15 +67,17 @@ export declare function priceText(d: Pick<BandData, "usd" | "ccUsd">): string |
77
67
  export interface BandOptions {
78
68
  /** Keys the person hid this session. */
79
69
  hidden?: ReadonlySet<string>;
80
- /** CONTEXT_DOCTOR_MOD_BAND=always: show the cache clock and the price at all times, not only when they pay. */
70
+ /** CONTEXT_DOCTOR_MOD_BAND=cold: show the cold-return offer (Compact first). */
71
+ cold?: boolean;
72
+ /** CONTEXT_DOCTOR_MOD_BAND=always: the cold return, and the cache clock and the price at all times. */
81
73
  always?: boolean;
82
74
  }
83
75
  /**
84
- * The band above the prompt at `now`. Quiet unless it pays (the cache about
85
- * to go cold, or gone cold, on a context worth caring about; the session
86
- * past a price threshold), except with `always`. The terminal has the
87
- * status line for the clock and the price, so there the band shows only the
88
- * cold return, the one thing with a button. Nothing on mobile.
76
+ * The band above the prompt at `now`. Off by default: on a big session it came
77
+ * up after nearly every reply, and the every-prompt hook already has Claude
78
+ * offer to compact on a cold return. `cold` shows that return (back at a big
79
+ * session after its cache expired) with Compact first; `always` adds the cache
80
+ * clock, the expired notice and the session price. Nothing on mobile.
89
81
  */
90
82
  export declare function band(d: BandData | undefined, now: number, surface: Surface, opts?: BandOptions): Band;
91
83
  /** A lever as `context-doctor fix --json` prints it (the fields the pane reads). */
@@ -437,3 +429,42 @@ export declare function usageDue(s: {
437
429
  export declare function usageArgv(node: string, cli: string): string[];
438
430
  /** Parse `mod usage`'s output; undefined when it is not one. */
439
431
  export declare function parseUsage(stdout: string): UsagePaneData | undefined;
432
+ /**
433
+ * The variable `fix --apply desktop-tools-defer` writes to ~/.claude/settings.json's
434
+ * `env`: the MCP servers whose tools the mod answers `isDeferred: true` for at
435
+ * `tool.describe`. Unset (the default, and after `fix undo`), the mod moves nothing.
436
+ * register.ts spells the name again as a literal: Claude Code reads the
437
+ * variables a module reads off its source.
438
+ */
439
+ export declare const DEFER_APP_TOOLS_ENV = "CONTEXT_DOCTOR_DEFER_MCP";
440
+ /**
441
+ * The Desktop app's own servers `fix` offers to defer: in-process (`sdk`)
442
+ * servers no MCP setting reaches, whose tools go whole into every Desktop
443
+ * session and subagent start. On the author's 30 days (ROADMAP, Research
444
+ * 2026-11-20) they cost $88.63 of starts, and most sessions never called them.
445
+ */
446
+ export declare const APP_TOOL_SERVERS: readonly string[];
447
+ /** Kept in front whatever the variable says: the app's turn tool, called in most sessions (31 of 61 on the author's). */
448
+ export declare const KEEP_APP_SERVERS: readonly string[];
449
+ /** The servers the variable names (comma or space separated), less the ones always kept, each once. */
450
+ export declare function deferredServers(raw: string | undefined): string[];
451
+ /** What `tool.describe` hands a hook (Claude Code 2.1.326+'s declarations: ToolDescribeInput, ToolMcpServer). */
452
+ export interface DescribeInput {
453
+ tool: string;
454
+ description: string;
455
+ isDeferred?: true;
456
+ mcpServer?: {
457
+ type: string;
458
+ origin?: string;
459
+ connectorId?: string;
460
+ };
461
+ }
462
+ /**
463
+ * Whether the mod moves this tool behind ToolSearch: an MCP tool
464
+ * (`mcp__<server>__<tool>`) of a server the variable names, that the engine
465
+ * would send whole. Never on an engine without `mcpServer` on the input
466
+ * (older than 2.1.326, which cannot place a tool from a hook either), never
467
+ * a tool already behind ToolSearch (its second, loaded description among
468
+ * them), never one of the servers always kept.
469
+ */
470
+ export declare function shouldDefer(e: DescribeInput, servers: readonly string[]): boolean;
package/dist/mod/logic.js CHANGED
@@ -8,19 +8,7 @@
8
8
  * `fix --apply`, `fix undo`), the same code as in a terminal. The node test
9
9
  * suite exercises these functions directly.
10
10
  */
11
- /** The band shows within this long of the cache going cold... */
12
- export const WARN_BEFORE_MS = 5 * 60_000;
13
11
  const MIN = 60_000;
14
- /**
15
- * ...or within this share of the cache's life, when that is shorter: the last
16
- * minute of a 5-minute cache (WARN_BEFORE_MS would be all of it, the band
17
- * after every turn), the last five of the 1-hour cache.
18
- */
19
- export const WARN_SHARE = 1 / 5;
20
- /** How long before the cache goes cold the band warns, for a cache that lives `ttlMs`. */
21
- export function warnBeforeMs(ttlMs) {
22
- return Math.min(WARN_BEFORE_MS, ttlMs * WARN_SHARE);
23
- }
24
12
  /** The session price thresholds when the CLI cannot say them (no Node): the defaults, the environment's own, or none. */
25
13
  export const DEFAULT_THRESHOLDS = [25, 100, 500];
26
14
  /** CONTEXT_DOCTOR_SESSION_PRICE and CONTEXT_DOCTOR_NO_SESSION_PRICE read as sessionprice.ts reads them. */
@@ -79,56 +67,56 @@ export function priceText(d) {
79
67
  return `session ${money(d.ccUsd)} (Claude Code's figure)`;
80
68
  return undefined;
81
69
  }
70
+ /** "~$0.04", or "under $0.01" where `money` would say "<$0.01". */
71
+ function about(n) {
72
+ return n < 0.01 ? "under $0.01" : `~${money(n)}`;
73
+ }
82
74
  /**
83
- * The band above the prompt at `now`. Quiet unless it pays (the cache about
84
- * to go cold, or gone cold, on a context worth caring about; the session
85
- * past a price threshold), except with `always`. The terminal has the
86
- * status line for the clock and the price, so there the band shows only the
87
- * cold return, the one thing with a button. Nothing on mobile.
75
+ * The band above the prompt at `now`. Off by default: on a big session it came
76
+ * up after nearly every reply, and the every-prompt hook already has Claude
77
+ * offer to compact on a cold return. `cold` shows that return (back at a big
78
+ * session after its cache expired) with Compact first; `always` adds the cache
79
+ * clock, the expired notice and the session price. Nothing on mobile.
88
80
  */
89
81
  export function band(d, now, surface, opts = {}) {
90
- if (!d || surface === "mobile")
82
+ if (!d || surface === "mobile" || !(opts.cold || opts.always))
91
83
  return { kind: "none" };
92
84
  const hidden = opts.hidden ?? new Set();
93
85
  const show = (b) => (hidden.has(b.key) ? { kind: "none" } : b);
94
- const terminal = surface === "terminal";
86
+ // The terminal's status line already shows the clock and the price.
87
+ const extra = opts.always === true && surface !== "terminal";
95
88
  const price = priceText(d);
96
89
  const big = d.tokens !== undefined && d.tokens >= d.coldMinTokens;
97
90
  const known = d.tokens !== undefined && d.lastReplyAt !== undefined && d.ttlMs !== undefined;
98
91
  if (known) {
99
92
  const expiresAt = d.lastReplyAt + d.ttlMs;
100
93
  const coldAt = expiresAt + (d.coldMarginMs ?? 0);
101
- const rewrite = `${tokens(d.tokens)} tokens${d.rewriteUsd !== undefined ? ` (~${money(d.rewriteUsd)})` : ""}`;
102
- const tail = price && !terminal ? ` · ${price}` : "";
94
+ const cost = d.rewriteUsd !== undefined ? ` (~${money(d.rewriteUsd)})` : "";
103
95
  // The return the cold-resume offer is about: past the cache's life by the margin, big enough, and not about to be compacted by Claude Code anyway.
104
96
  if (now >= coldAt && big && d.tokens < (d.autoCompactAt ?? Infinity)) {
105
- const each = d.perMessageUsd !== undefined && d.afterCompactPerMessageUsd !== undefined
106
- ? `each later message re-reads ~${money(d.perMessageUsd)} of context now, ~${money(d.afterCompactPerMessageUsd)} after`
107
- : `each later message re-reads ${tokens(d.tokens)} tokens now, far fewer after`;
97
+ const after = d.perMessageUsd !== undefined && d.afterCompactPerMessageUsd !== undefined
98
+ ? `each message after that costs ${about(d.afterCompactPerMessageUsd)} instead of ${about(d.perMessageUsd)}`
99
+ : `each message after that re-reads far fewer than ${tokens(d.tokens)} tokens`;
108
100
  return show({
109
101
  kind: "cold",
110
102
  key: `cold:${d.lastReplyAt}`,
111
- text: `context-doctor: idle ${duration(now - d.lastReplyAt)}, the cache expired: your next message re-writes ${rewrite}${tail}`,
112
- compact: `Compact first: ${each}`,
103
+ text: `context-doctor: you were away ${duration(now - d.lastReplyAt)}, so the cache expired. Your next message re-sends this ${tokens(d.tokens)}-token chat at full price${cost}.`,
104
+ compact: `Compact first to shrink it: ${after}.`,
113
105
  });
114
106
  }
115
- if (terminal)
107
+ if (!extra)
116
108
  return { kind: "none" };
117
- if (now >= expiresAt && (big || opts.always)) {
109
+ const tail = price ? ` · ${price}` : "";
110
+ const rewrite = `${tokens(d.tokens)} tokens${cost}`;
111
+ if (now >= expiresAt) {
118
112
  return show({ kind: "expired", key: `expired:${d.lastReplyAt}`, text: `context-doctor: the cache expired, so your next message re-writes ${rewrite}${tail}` });
119
113
  }
120
- if (now < expiresAt && (opts.always || (big && expiresAt - now <= warnBeforeMs(d.ttlMs)))) {
121
- return show({ kind: "warm", key: `warm:${d.lastReplyAt}`, text: `context-doctor: cache warm for ${duration(expiresAt - now)}, then your next message re-writes ${rewrite}${tail}` });
122
- }
114
+ return show({ kind: "warm", key: `warm:${d.lastReplyAt}`, text: `context-doctor: cache warm for ${duration(expiresAt - now)}, then your next message re-writes ${rewrite}${tail}` });
123
115
  }
124
- if (terminal)
116
+ if (!extra || !price)
125
117
  return { kind: "none" };
126
- const usd = d.usd ?? d.ccUsd;
127
- const t = passedThreshold(usd, d.thresholds);
128
- if (price && (t !== undefined || opts.always)) {
129
- return show({ kind: "price", key: `price:${t ?? 0}`, text: `context-doctor: ${price}` });
130
- }
131
- return { kind: "none" };
118
+ const t = passedThreshold(d.usd ?? d.ccUsd, d.thresholds);
119
+ return show({ kind: "price", key: `price:${t ?? 0}`, text: `context-doctor: ${price}` });
132
120
  }
133
121
  /** The lever that changes which model runs: never applied by `--apply all`, and marked as such here. */
134
122
  export const MODEL_CHANGE = "subagent-model";
@@ -464,7 +452,7 @@ export function usageView(v) {
464
452
  parts.push(`read ${duration(now - w.at)} ago, no pace from it`);
465
453
  else if (w.perHour !== undefined && w.perHour > 0) {
466
454
  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}`);
455
+ parts.push(`+${per(w.perHour)}% an hour lately${outIn}`);
468
456
  }
469
457
  const subs = [];
470
458
  if (w.usdPerPct !== undefined)
@@ -578,3 +566,44 @@ export function parseUsage(stdout) {
578
566
  return undefined;
579
567
  }
580
568
  }
569
+ // -- The Desktop app's own MCP tools behind tool search (fix's desktop-tools-defer) ------
570
+ /**
571
+ * The variable `fix --apply desktop-tools-defer` writes to ~/.claude/settings.json's
572
+ * `env`: the MCP servers whose tools the mod answers `isDeferred: true` for at
573
+ * `tool.describe`. Unset (the default, and after `fix undo`), the mod moves nothing.
574
+ * register.ts spells the name again as a literal: Claude Code reads the
575
+ * variables a module reads off its source.
576
+ */
577
+ export const DEFER_APP_TOOLS_ENV = "CONTEXT_DOCTOR_DEFER_MCP";
578
+ /**
579
+ * The Desktop app's own servers `fix` offers to defer: in-process (`sdk`)
580
+ * servers no MCP setting reaches, whose tools go whole into every Desktop
581
+ * session and subagent start. On the author's 30 days (ROADMAP, Research
582
+ * 2026-11-20) they cost $88.63 of starts, and most sessions never called them.
583
+ */
584
+ export const APP_TOOL_SERVERS = ["Claude_Browser", "ccd_session", "visualize", "terminal"];
585
+ /** Kept in front whatever the variable says: the app's turn tool, called in most sessions (31 of 61 on the author's). */
586
+ export const KEEP_APP_SERVERS = ["ccd_turn"];
587
+ /** The servers the variable names (comma or space separated), less the ones always kept, each once. */
588
+ export function deferredServers(raw) {
589
+ const out = [];
590
+ for (const n of (raw ?? "").split(/[\s,]+/)) {
591
+ if (!/^[A-Za-z0-9_.-]{1,80}$/.test(n) || KEEP_APP_SERVERS.includes(n) || out.includes(n))
592
+ continue;
593
+ out.push(n);
594
+ }
595
+ return out;
596
+ }
597
+ /**
598
+ * Whether the mod moves this tool behind ToolSearch: an MCP tool
599
+ * (`mcp__<server>__<tool>`) of a server the variable names, that the engine
600
+ * would send whole. Never on an engine without `mcpServer` on the input
601
+ * (older than 2.1.326, which cannot place a tool from a hook either), never
602
+ * a tool already behind ToolSearch (its second, loaded description among
603
+ * them), never one of the servers always kept.
604
+ */
605
+ export function shouldDefer(e, servers) {
606
+ if (!e || typeof e.tool !== "string" || !e.mcpServer || typeof e.mcpServer !== "object" || e.isDeferred === true)
607
+ return false;
608
+ return servers.some((n) => !KEEP_APP_SERVERS.includes(n) && e.tool.startsWith(`mcp__${n}__`));
609
+ }
@@ -31,6 +31,10 @@
31
31
  * subagents with their model, context and cost so far. Drawing only reads
32
32
  * what the mod holds; `context-doctor mod usage` refreshes it on the
33
33
  * timer, only while the pane is open (usageDue).
34
+ * - `tool.describe` (2.1.326+): once `fix --apply desktop-tools-defer`
35
+ * named the Desktop app's own MCP servers in CONTEXT_DOCTOR_DEFER_MCP,
36
+ * their tools go behind tool search from the next new conversation; never
37
+ * ccd_turn, never with `breakPromptCache`. Unset, nothing moves.
34
38
  *
35
39
  * Nothing happens without a press or a command: no auto-compaction, no auto-apply, no ping. The
36
40
  * mod writes no file itself; the CLI writes ours. Off: CONTEXT_DOCTOR_NO_MOD=1.
@@ -49,6 +53,8 @@ export declare const USAGE_PANE = "context-doctor-usage";
49
53
  /** The mod's state for this load (a reload starts it over; the next turn measures again). */
50
54
  interface State {
51
55
  off: boolean;
56
+ /** CONTEXT_DOCTOR_MOD_BAND: the band is off unless it says `cold` or `always`. */
57
+ cold: boolean;
52
58
  always: boolean;
53
59
  /** The session price thresholds in force, for when the CLI cannot say them (no Node). */
54
60
  thresholds: number[];
@@ -31,6 +31,10 @@
31
31
  * subagents with their model, context and cost so far. Drawing only reads
32
32
  * what the mod holds; `context-doctor mod usage` refreshes it on the
33
33
  * timer, only while the pane is open (usageDue).
34
+ * - `tool.describe` (2.1.326+): once `fix --apply desktop-tools-defer`
35
+ * named the Desktop app's own MCP servers in CONTEXT_DOCTOR_DEFER_MCP,
36
+ * their tools go behind tool search from the next new conversation; never
37
+ * ccd_turn, never with `breakPromptCache`. Unset, nothing moves.
34
38
  *
35
39
  * Nothing happens without a press or a command: no auto-compaction, no auto-apply, no ping. The
36
40
  * mod writes no file itself; the CLI writes ours. Off: CONTEXT_DOCTOR_NO_MOD=1.
@@ -40,7 +44,7 @@
40
44
  * reads which calls a module makes from its source: `$` is passed only to
41
45
  * functions declared at the top of this file.
42
46
  */
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";
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";
44
48
  export const COMMAND = "context-doctor-fix";
45
49
  export const PANE = "context-doctor-fix";
46
50
  export const USAGE_COMMAND = "context-doctor-usage";
@@ -52,7 +56,7 @@ const FIX_TIMEOUT_MS = 10 * 60_000;
52
56
  const MEASURE_TIMEOUT_MS = 30_000;
53
57
  /** `mod usage` measures 30 days the first time (~3 s cold on 22,000 requests); later runs read its 5-minute cache. */
54
58
  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: "" });
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: "" });
56
60
  let S = fresh();
57
61
  /** For tests: the state the hooks share. */
58
62
  export const state = () => S;
@@ -65,7 +69,7 @@ function cliOf($) {
65
69
  return `${root}${sep}dist${sep}cli.js`;
66
70
  }
67
71
  function bandKey(now, surface) {
68
- const b = band(S.data, now, surface, { hidden: S.hidden, always: S.always });
72
+ const b = band(S.data, now, surface, { hidden: S.hidden, cold: S.cold, always: S.always });
69
73
  return b.kind === "none" ? "" : `${b.key}|${b.text}`;
70
74
  }
71
75
  /** Hand the reading to the CLI; with no CLI (no node on PATH), keep what Claude Code said. */
@@ -348,7 +352,9 @@ export function register(on) {
348
352
  on("session.start", async ($, e, next) => {
349
353
  try {
350
354
  S.off = (await $.env.get("CONTEXT_DOCTOR_NO_MOD")) === "1";
351
- S.always = (await $.env.get("CONTEXT_DOCTOR_MOD_BAND")) === "always";
355
+ const bandMode = (await $.env.get("CONTEXT_DOCTOR_MOD_BAND"))?.trim().toLowerCase();
356
+ S.cold = bandMode === "cold";
357
+ S.always = bandMode === "always";
352
358
  S.thresholds = thresholdsFrom(await $.env.get("CONTEXT_DOCTOR_SESSION_PRICE"), await $.env.get("CONTEXT_DOCTOR_NO_SESSION_PRICE"));
353
359
  S.pingEveryMs = keepWarmTestEvery(await $.env.get("CONTEXT_DOCTOR_KEEP_WARM_PING_MS"));
354
360
  if (!S.off) {
@@ -405,7 +411,7 @@ export function register(on) {
405
411
  const { Box, Text, Button } = $.ui.resolve(e);
406
412
  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
413
  }
408
- const b = band(S.data, now, e.surface, { hidden: S.hidden, always: S.always });
414
+ const b = band(S.data, now, e.surface, { hidden: S.hidden, cold: S.cold, always: S.always });
409
415
  // A compaction only runs between turns: no button while one runs.
410
416
  if (b.kind === "none" || (b.kind === "cold" && e.props.isWorking))
411
417
  return next(e);
@@ -413,7 +419,9 @@ export function register(on) {
413
419
  const hideButton = h(Button, { key: "cd-hide", label: "Hide", onPress: () => hide($, b.key) });
414
420
  if (b.kind !== "cold")
415
421
  return h(Box, { flexDirection: "row", flexWrap: "wrap", columnGap: 1 }, h(Text, { dimColor: true }, b.text), hideButton);
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));
422
+ return h(Box, { flexDirection: "column" }, h(Text, { dimColor: true }, b.text), h(Text, { dimColor: true }, b.compact),
423
+ // The buttons on a row of their own: between lines of wrapped text they read as part of it.
424
+ h(Box, { flexDirection: "row", columnGap: 1 }, h(Button, { key: "cd-compact", label: S.compacting ? "Compacting…" : "Compact first", variant: "primary", onPress: () => compact($) }), hideButton));
417
425
  });
418
426
  on("command.run", { command: "context-doctor-usage" }, async ($) => {
419
427
  if (S.off)
@@ -430,6 +438,26 @@ export function register(on) {
430
438
  await loadUsage($, true);
431
439
  return { text: usageText(viewAt(await $.clock.now())) };
432
440
  });
441
+ // The Desktop app's own MCP tools behind tool search, only once `fix --apply desktop-tools-defer`
442
+ // named their servers in CONTEXT_DOCTOR_DEFER_MCP (settings.json env). Read at each describe,
443
+ // which the engine asks once per tool and session. The answer moves the tool for the next new
444
+ // thread or /clear; no breakPromptCache, so a running conversation's cache is never re-written.
445
+ // An engine older than 2.1.326 (no `mcpServer` on the input) gets its own answer back untouched.
446
+ try {
447
+ on("tool.describe", async ($, e, next) => {
448
+ if (!e?.mcpServer || e.isDeferred === true)
449
+ return next(e);
450
+ let servers = [];
451
+ try {
452
+ if ((await $.env.get("CONTEXT_DOCTOR_NO_MOD")) !== "1")
453
+ servers = deferredServers(await $.env.get("CONTEXT_DOCTOR_DEFER_MCP"));
454
+ }
455
+ catch { /* no variable: nothing moves */ }
456
+ const r = await next(e);
457
+ return shouldDefer(e, servers) && r && typeof r === "object" ? { ...r, isDeferred: true } : r;
458
+ });
459
+ }
460
+ catch { /* an engine without tool.describe: nothing to defer */ }
433
461
  // 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
462
  try {
435
463
  on("ui.close", async ($, e, next) => {
package/dist/modelids.js CHANGED
@@ -79,11 +79,11 @@ export function unpriced(ids) {
79
79
  /**
80
80
  * Models priced per image, per minute or per character, or not by the token
81
81
  * at all (embeddings, moderation), and Google's endpoints that are not
82
- * models a coding agent runs (video, music, robots, the Decisions API, Gemma
82
+ * models a coding agent runs (video, music, world generation, robots, the Decisions API, Gemma
83
83
  * on the free tier only): the table has no row for them on purpose
84
84
  * (pricing.ts header). Matched anywhere in the id.
85
85
  */
86
- const NOT_A_TEXT_MODEL = /image|realtime|audio|tts|transcribe|whisper|translate|(?:^|-)live(?:-|$)|embedding|moderation|omni|robotics|decision|lyria|veo|imagen|gemma|nano-banana|sora/i;
86
+ const NOT_A_TEXT_MODEL = /image|realtime|audio|tts|transcribe|whisper|translate|(?:^|-)live(?:-|$)|embedding|moderation|omni|robotics|decision|lyria|veo|imagen|gemma|nano-banana|sora|genie/i;
87
87
  /**
88
88
  * The models OpenAI's price page (developers.openai.com/api/docs/pricing,
89
89
  * its .md) lists in its text tables: each table row's model cell (the first,
@@ -87,9 +87,11 @@ export declare function orgRatesLine(env?: NodeJS.ProcessEnv): string | undefine
87
87
  * managed-preferences plist, the Windows HKLM policy key), else the files,
88
88
  * and by default only the first source found counts ("first-wins"): with
89
89
  * either of the others present, Claude Code prices at their modelPricing,
90
- * or at list, never at the files'. context-doctor reads neither (the
90
+ * or at list, never at the files'. context-doctor reads neither's rates (the
91
91
  * server-managed copy, `remote-settings.json` in Claude Code's folder, is an
92
- * undocumented, signed cache); this only says that one is there. The
92
+ * undocumented, signed cache); this only says that one is there, and leaves
93
+ * out a copy that parses and never names modelPricing while the files set
94
+ * none either (both price at list then). The
93
95
  * Windows key is not looked up (it needs reg.exe).
94
96
  */
95
97
  export declare function managedSourcesAhead(env?: NodeJS.ProcessEnv, home?: string, prefs?: string): string[];
package/dist/orgrates.js CHANGED
@@ -191,9 +191,11 @@ export function orgRatesLine(env = process.env) {
191
191
  * managed-preferences plist, the Windows HKLM policy key), else the files,
192
192
  * and by default only the first source found counts ("first-wins"): with
193
193
  * either of the others present, Claude Code prices at their modelPricing,
194
- * or at list, never at the files'. context-doctor reads neither (the
194
+ * or at list, never at the files'. context-doctor reads neither's rates (the
195
195
  * server-managed copy, `remote-settings.json` in Claude Code's folder, is an
196
- * undocumented, signed cache); this only says that one is there. The
196
+ * undocumented, signed cache); this only says that one is there, and leaves
197
+ * out a copy that parses and never names modelPricing while the files set
198
+ * none either (both price at list then). The
197
199
  * Windows key is not looked up (it needs reg.exe).
198
200
  */
199
201
  export function managedSourcesAhead(env = process.env, home, prefs = "/Library/Managed Preferences") {
@@ -202,7 +204,12 @@ export function managedSourcesAhead(env = process.env, home, prefs = "/Library/M
202
204
  const out = [];
203
205
  try {
204
206
  const remote = join(claudeDir(home, env), "remote-settings.json");
205
- if (existsSync(remote))
207
+ // Only whether it can set rates is looked at: a copy that parses and never
208
+ // names modelPricing prices at list, as these reports do, unless the files
209
+ // set rates (then it still matters: Claude Code reads it and not them).
210
+ // Every claude.ai sign-in can have one ({"channelsEnabled": …}): saying
211
+ // "its figures may use contracted rates" on each report there was noise.
212
+ if (existsSync(remote) && (mayPrice(remote) || orgRates(env)))
206
213
  out.push(`server-managed settings (Claude Code's copy: ${remote})`);
207
214
  }
208
215
  catch { /* no config folder */ }
@@ -221,6 +228,17 @@ export function managedSourcesAhead(env = process.env, home, prefs = "/Library/M
221
228
  }
222
229
  return out;
223
230
  }
231
+ /** False only for a file that parses as JSON and has no `modelPricing` key anywhere: unread or unparsed, it may. */
232
+ function mayPrice(path) {
233
+ try {
234
+ const text = readFileSync(path, "utf8");
235
+ JSON.parse(text);
236
+ return text.includes("modelPricing");
237
+ }
238
+ catch {
239
+ return true;
240
+ }
241
+ }
224
242
  /**
225
243
  * The line a report adds when Claude Code may take its rates from a source
226
244
  * context-doctor does not read: undefined when none is on this machine.
package/dist/overhead.js CHANGED
@@ -29,6 +29,7 @@ import { mcpjsonServerApproved } from "./prune.js";
29
29
  import { REQUEST_ROWS } from "./coldresume.js";
30
30
  import { rowsOf } from "./scan.js";
31
31
  import { measureStarts, renderStarts } from "./starts.js";
32
+ import { readFixRecords } from "./fix.js";
32
33
  const TTL_MS = 3_600_000;
33
34
  const CLAUDE = "claude-opus-5"; // Claude's tokenizer ratios; the model only picks the provider here.
34
35
  function readText(path) {
@@ -489,7 +490,7 @@ export function renderOverhead(r, home = homedir()) {
489
490
  : ""));
490
491
  }
491
492
  if (r.starts)
492
- out.push(...renderStarts(r.starts));
493
+ out.push(...renderStarts(r.starts, new Set(readFixRecords(home).map((f) => f.id))));
493
494
  out.push(...renderMcp(r));
494
495
  out.push("", "Memory files loaded in this directory", "─".repeat(56));
495
496
  if (r.files.length === 0)
package/dist/pricing.js CHANGED
@@ -144,6 +144,11 @@ const PRICING = [
144
144
  // no cached-input price (the -pro ones) read at full input. Not modelled:
145
145
  // Fast mode (priority processing; Codex records only its thread's
146
146
  // `service_tier`, not each request's) and the 10% regional uplift.
147
+ // GPT-6.2 Astra and Sol, read 2026-11-18. Astra for Law's price is
148
+ // promotional "at least through December 31, 2026": no end date yet.
149
+ [openai("gpt-6.2-astra"), ...openaiLong(8, 40, 0.4)],
150
+ [openai("gpt-6.2-astra-law"), ...openaiLong(8, 40, 0.4)],
151
+ [openai("gpt-6.2-sol"), ...openaiLong(2, 10, 0.1)],
147
152
  [openai("gpt-6-astra"), ...openaiLong(10, 50, 1)],
148
153
  // GPT-6 Astra for Law's price is promotional "at least through December
149
154
  // 31, 2026" (read 2026-11-14): no end date to record yet.
@@ -209,6 +214,10 @@ const PRICING = [
209
214
  [gemini("gemini-4-carbon"), rate(2, 10, 0.1), { changes: "2026-12-01", then: rate(4, 20, 0.2) }],
210
215
  [gemini("gemini-4-argon"), rate(2, 10, 0.1), { changes: "2026-12-01", then: rate(4, 20, 0.2) }],
211
216
  [gemini("gemini-4-hydrogen"), rate(1.5, 7.5, 0.075)],
217
+ // Gemini 4 Neon, read 2026-11-20: $3 / $15 / $0.15 (implicit caching
218
+ // only), no date, no long-prompt tier. Genie 4 (world generation, billed
219
+ // by video tokens) is not a text model: modelids.ts NOT_A_TEXT_MODEL.
220
+ [gemini("gemini-4-neon"), rate(3, 15, 0.15)],
212
221
  // 3.6 and 3.8 Flash double "starting January 1, 2027" ($1.50 / $7.50 / $0.15).
213
222
  [gemini("gemini-3.8-flash"), rate(0.75, 3.75, 0.075), { changes: "2027-01-01", then: rate(1.5, 7.5, 0.15) }],
214
223
  [gemini("gemini-3.6-flash"), rate(0.75, 3.75, 0.075), { changes: "2027-01-01", then: rate(1.5, 7.5, 0.15) }],
@@ -627,6 +636,9 @@ export function formatUsd(amount) {
627
636
  // Same reasoning as formatTokens: "$NaN" is worse than "$0.00".
628
637
  if (!Number.isFinite(amount))
629
638
  return "$0.00";
639
+ // Thousands grouped, as the reports' money() does: "$1442.13" beside "$1,436" read as two kinds of number.
640
+ if (amount >= 1000)
641
+ return `$${amount.toLocaleString("en-US", { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`;
630
642
  if (amount >= 1)
631
643
  return `$${amount.toFixed(2)}`;
632
644
  if (amount >= 0.01)
@@ -35,6 +35,18 @@
35
35
  * the notes. So both are priced: the notes as the low figure, the whole
36
36
  * context as the high one.
37
37
  *
38
+ * From 2.1.328 (its CHANGELOG: "written by the default small fast model
39
+ * from short notes ... using far fewer tokens", terminal sessions on the
40
+ * Anthropic API; 2.1.327 moved Bedrock, Vertex and Foundry to notes on the
41
+ * agent's own model) there is one way: the notes, on the small fast model.
42
+ * The 2.1.329 binary agrees: the writer is ANTHROPIC_SMALL_FAST_MODEL's
43
+ * default, the catalog's Haiku (`claude-haiku-5-5` on the Anthropic API),
44
+ * and the notes are cut to 2,000 - 500 tokens less the label lines, by its
45
+ * own count of about 3 characters a token, under a ~100-token system prompt
46
+ * and a ~250-token instruction: NOTES_TOKENS stays the ceiling. So a
47
+ * subagent whose transcript says `version` 2.1.328 or later is priced once,
48
+ * at Haiku 5.5's rates (low and high the same); an older one as before.
49
+ *
38
50
  * Estimated per subagent from what its transcript does record: the time of
39
51
  * each message (the ticks and whether the transcript changed), each reply's
40
52
  * prompt size and model (the context a fork would read, the rates). Each
@@ -52,6 +64,11 @@ export declare const PROGRESS_SUMMARIES_SINCE = "2.1.318";
52
64
  export declare const SUMMARY_TICK_MS = 30000;
53
65
  /** A short summary's prompt: notes capped at 2,000 - 500 tokens, plus its system prompt and instruction. */
54
66
  export declare const NOTES_TOKENS = 1850;
67
+ /** The first Claude Code that writes every summary from notes on the small fast model (its CHANGELOG). */
68
+ export declare const SMALL_NOTES_SINCE = "2.1.328";
69
+ /** The small fast model those run on: the 2.1.329 catalog's Haiku on the Anthropic API. */
70
+ export declare const SMALL_FAST_MODEL = "claude-haiku-5-5";
71
+ export declare const SMALL_FAST_MODEL_NAME = "Haiku 5.5";
55
72
  /** A fork summary's own instruction, after the agent's context. */
56
73
  export declare const FORK_PROMPT_TOKENS = 150;
57
74
  /** Each summary's output: #86879's measured mean (21,966 tokens over 339 summaries). */
@@ -113,13 +130,15 @@ type Rec = {
113
130
  * it has 3+ messages and more than at the last summary. Only ticks in
114
131
  * [since, until] are counted.
115
132
  */
116
- export declare function simulateAgent(recs: Rec[], since?: number, until?: number): AgentSummaries;
133
+ export declare function simulateAgent(recs: Rec[], since?: number, until?: number, smallNotes?: boolean): AgentSummaries;
117
134
  export interface ProgressSummaryEstimate {
118
135
  /** Subagent transcripts read (workflow agents included). */
119
136
  agents: number;
120
137
  /** Agents Claude Code wrote summaries for in the window, by the rules above. */
121
138
  summarized: number;
122
139
  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. */
141
+ smallCalls: number;
123
142
  /** The summaries as short notes (what Anthropic serves since November 2026): the low figure. */
124
143
  notesUsd: number;
125
144
  /** As a fork of the whole context (before): the high figure. */