context-doctor 0.49.1 → 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 (46) hide show
  1. package/README.md +15 -14
  2. package/dist/appwindow.d.ts +69 -0
  3. package/dist/appwindow.js +147 -0
  4. package/dist/ccost.js +8 -4
  5. package/dist/claudedir.d.ts +15 -0
  6. package/dist/claudedir.js +19 -1
  7. package/dist/cli.js +59 -23
  8. package/dist/clihelp.d.ts +5 -1
  9. package/dist/clihelp.js +9 -1
  10. package/dist/codexstatusline.d.ts +176 -0
  11. package/dist/codexstatusline.js +353 -0
  12. package/dist/compactwindow.d.ts +14 -2
  13. package/dist/compactwindow.js +30 -5
  14. package/dist/credits.d.ts +130 -0
  15. package/dist/credits.js +265 -0
  16. package/dist/doctor.d.ts +6 -0
  17. package/dist/doctor.js +15 -1
  18. package/dist/fanout.d.ts +2 -0
  19. package/dist/fanout.js +12 -2
  20. package/dist/fix.d.ts +37 -1
  21. package/dist/fix.js +67 -9
  22. package/dist/limits.d.ts +45 -1
  23. package/dist/limits.js +121 -9
  24. package/dist/mcp.d.ts +1 -0
  25. package/dist/mcp.js +106 -100
  26. package/dist/mod/api.d.ts +27 -1
  27. package/dist/mod/api.js +2 -1
  28. package/dist/mod/logic.d.ts +39 -0
  29. package/dist/mod/logic.js +42 -1
  30. package/dist/mod/register.d.ts +4 -0
  31. package/dist/mod/register.js +25 -1
  32. package/dist/modelids.js +2 -2
  33. package/dist/orgrates.d.ts +4 -2
  34. package/dist/orgrates.js +21 -3
  35. package/dist/overhead.js +2 -1
  36. package/dist/pricing.js +7 -0
  37. package/dist/progresssummaries.d.ts +20 -1
  38. package/dist/progresssummaries.js +33 -3
  39. package/dist/proxy.d.ts +1 -1
  40. package/dist/proxy.js +9 -4
  41. package/dist/savings.js +3 -1
  42. package/dist/spend.d.ts +28 -1
  43. package/dist/spend.js +38 -5
  44. package/dist/starts.d.ts +27 -1
  45. package/dist/starts.js +81 -18
  46. 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 {};
@@ -429,3 +429,42 @@ export declare function usageDue(s: {
429
429
  export declare function usageArgv(node: string, cli: string): string[];
430
430
  /** Parse `mod usage`'s output; undefined when it is not one. */
431
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
@@ -452,7 +452,7 @@ export function usageView(v) {
452
452
  parts.push(`read ${duration(now - w.at)} ago, no pace from it`);
453
453
  else if (w.perHour !== undefined && w.perHour > 0) {
454
454
  const outIn = w.runsOutAt !== undefined && w.runsOutAt > now ? `, runs out in ${duration(w.runsOutAt - now)}${w.beforeReset ? " (before the reset)" : ""}` : "";
455
- parts.push(`+${per(w.perHour)} points an hour lately${outIn}`);
455
+ parts.push(`+${per(w.perHour)}% an hour lately${outIn}`);
456
456
  }
457
457
  const subs = [];
458
458
  if (w.usdPerPct !== undefined)
@@ -566,3 +566,44 @@ export function parseUsage(stdout) {
566
566
  return undefined;
567
567
  }
568
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.
@@ -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";
@@ -434,6 +438,26 @@ export function register(on) {
434
438
  await loadUsage($, true);
435
439
  return { text: usageText(viewAt(await $.clock.now())) };
436
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 */ }
437
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.
438
462
  try {
439
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
@@ -214,6 +214,10 @@ const PRICING = [
214
214
  [gemini("gemini-4-carbon"), rate(2, 10, 0.1), { changes: "2026-12-01", then: rate(4, 20, 0.2) }],
215
215
  [gemini("gemini-4-argon"), rate(2, 10, 0.1), { changes: "2026-12-01", then: rate(4, 20, 0.2) }],
216
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)],
217
221
  // 3.6 and 3.8 Flash double "starting January 1, 2027" ($1.50 / $7.50 / $0.15).
218
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) }],
219
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) }],
@@ -632,6 +636,9 @@ export function formatUsd(amount) {
632
636
  // Same reasoning as formatTokens: "$NaN" is worse than "$0.00".
633
637
  if (!Number.isFinite(amount))
634
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 })}`;
635
642
  if (amount >= 1)
636
643
  return `$${amount.toFixed(2)}`;
637
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. */
@@ -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
@@ -57,6 +69,11 @@ export const PROGRESS_SUMMARIES_SINCE = "2.1.318";
57
69
  export const SUMMARY_TICK_MS = 30_000;
58
70
  /** A short summary's prompt: notes capped at 2,000 - 500 tokens, plus its system prompt and instruction. */
59
71
  export const NOTES_TOKENS = 1_850;
72
+ /** The first Claude Code that writes every summary from notes on the small fast model (its CHANGELOG). */
73
+ export const SMALL_NOTES_SINCE = "2.1.328";
74
+ /** The small fast model those run on: the 2.1.329 catalog's Haiku on the Anthropic API. */
75
+ export const SMALL_FAST_MODEL = "claude-haiku-5-5";
76
+ export const SMALL_FAST_MODEL_NAME = "Haiku 5.5";
60
77
  /** A fork summary's own instruction, after the agent's context. */
61
78
  export const FORK_PROMPT_TOKENS = 150;
62
79
  /** Each summary's output: #86879's measured mean (21,966 tokens over 339 summaries). */
@@ -147,7 +164,7 @@ export function eligibility(meta, entrypoint, opts = {}) {
147
164
  * it has 3+ messages and more than at the last summary. Only ticks in
148
165
  * [since, until] are counted.
149
166
  */
150
- export function simulateAgent(recs, since = -Infinity, until = Infinity) {
167
+ export function simulateAgent(recs, since = -Infinity, until = Infinity, smallNotes = false) {
151
168
  const msgs = recs.filter((r) => r.t === "m").map((r) => r.ts).sort((a, b) => a - b);
152
169
  const replies = recs.filter((r) => r.t === "r").sort((a, b) => a.ts - b.ts);
153
170
  const out = { calls: 0, notesUsd: 0, forkUsd: 0 };
@@ -177,6 +194,16 @@ export function simulateAgent(recs, since = -Infinity, until = Infinity) {
177
194
  const read = cur ? cur.p : 0;
178
195
  const fresh = (next ? Math.max(0, next.p - read) : 0) + FORK_PROMPT_TOKENS;
179
196
  const b = { ...(ref.speed ? { speed: ref.speed } : {}), ...(ref.geo ? { inference_geo: ref.geo } : {}) };
197
+ if (smallNotes) {
198
+ // 2.1.328+: the notes on the small fast model, the one way it sends them (the agent's fast mode is not the writer's).
199
+ const small = requestCost(SMALL_FAST_MODEL, { input_tokens: NOTES_TOKENS, cache_read_input_tokens: 0, cache_creation_input_tokens: 0, output_tokens: SUMMARY_OUTPUT_TOKENS, ...(ref.geo ? { inference_geo: ref.geo } : {}) }, at);
200
+ if (!small)
201
+ continue;
202
+ out.calls++;
203
+ out.forkUsd += small.totalUsd;
204
+ out.notesUsd += small.totalUsd;
205
+ continue;
206
+ }
180
207
  const fork = requestCost(model, { input_tokens: fresh, cache_read_input_tokens: read, cache_creation_input_tokens: 0, output_tokens: SUMMARY_OUTPUT_TOKENS, ...b }, at);
181
208
  const notes = requestCost(model, { input_tokens: NOTES_TOKENS, cache_read_input_tokens: 0, cache_creation_input_tokens: 0, output_tokens: SUMMARY_OUTPUT_TOKENS, ...b }, at);
182
209
  if (!fork || !notes)
@@ -189,7 +216,7 @@ export function simulateAgent(recs, since = -Infinity, until = Infinity) {
189
216
  }
190
217
  /** The summaries of the subagents in `files` (their `.jsonl` transcripts), estimated. */
191
218
  export function estimateProgressSummaries(files, opts = {}) {
192
- const r = { agents: 0, summarized: 0, calls: 0, notesUsd: 0, forkUsd: 0, none: {}, hosts: [] };
219
+ const r = { agents: 0, summarized: 0, calls: 0, smallCalls: 0, notesUsd: 0, forkUsd: 0, none: {}, hosts: [] };
193
220
  const hosts = new Set();
194
221
  for (const file of files) {
195
222
  let recs;
@@ -217,11 +244,14 @@ export function estimateProgressSummaries(files, opts = {}) {
217
244
  if (first > until)
218
245
  why = "off";
219
246
  else {
220
- const s = simulateAgent(recs, opts.since, until);
247
+ const small = !!head?.version && compareVersions(head.version, SMALL_NOTES_SINCE) >= 0;
248
+ const s = simulateAgent(recs, opts.since, until, small);
221
249
  // One that ran under 30 s, or outside the window, sent none.
222
250
  if (s.calls)
223
251
  r.summarized++;
224
252
  r.calls += s.calls;
253
+ if (small)
254
+ r.smallCalls += s.calls;
225
255
  r.notesUsd += s.notesUsd;
226
256
  r.forkUsd += s.forkUsd;
227
257
  continue;
package/dist/proxy.d.ts CHANGED
@@ -83,7 +83,7 @@ export interface ProxyOptions extends OptimizeOptions {
83
83
  /** Default request body cap: far above any real request (a 1M-token context is ~4 MB of JSON, images aside). */
84
84
  export declare const DEFAULT_MAX_BODY_BYTES: number;
85
85
  /** Reported by /health so `autopilot status` can tell an outdated service from a current one. */
86
- export declare const PROXY_VERSION = "0.49.1";
86
+ export declare const PROXY_VERSION = "0.50.0";
87
87
  /**
88
88
  * Remove a leading `/t/<token>` from a request path, or return undefined when
89
89
  * the prefix is absent or the token differs. The comparison is constant time
package/dist/proxy.js CHANGED
@@ -25,9 +25,11 @@ import { makeGuard, refusal } from "./httpguard.js";
25
25
  /** Default request body cap: far above any real request (a 1M-token context is ~4 MB of JSON, images aside). */
26
26
  export const DEFAULT_MAX_BODY_BYTES = 100 * 1024 * 1024;
27
27
  /** Reported by /health so `autopilot status` can tell an outdated service from a current one. */
28
- export const PROXY_VERSION = "0.49.1";
28
+ export const PROXY_VERSION = "0.50.0";
29
29
  /** Connection-level headers that must not be forwarded. */
30
30
  const SKIP_REQUEST_HEADERS = new Set(["host", "content-length", "connection", "transfer-encoding", "accept-encoding", "expect"]);
31
+ /** A reply carrying any of these has something for the limits ledger: a plan window, or the usage-credits state. */
32
+ const LIMIT_HEADERS = ["7d-utilization", "5h-utilization", "overage-status", "overage-in-use"].map((h) => `anthropic-ratelimit-unified-${h}`);
31
33
  const SKIP_RESPONSE_HEADERS = new Set(["content-length", "content-encoding", "transfer-encoding", "connection"]);
32
34
  /**
33
35
  * Remove a leading `/t/<token>` from a request path, or return undefined when
@@ -566,16 +568,19 @@ export function startProxy(opts = {}) {
566
568
  upstream = new Response(text, { status: upstream.status, statusText: upstream.statusText, headers: upstream.headers });
567
569
  }
568
570
  }
569
- // The plan's windows, as Claude Code reads them from the same headers:
571
+ // The plan's windows, as Claude Code reads them from the same headers,
572
+ // and whether usage credits are paying past them (the overage headers):
570
573
  // into the limits ledger, after the reply is on its way (recordLimits
571
- // writes only a change, at most once a minute, and never throws).
572
- if (upstreamBase === (opts.anthropicUpstream ?? "https://api.anthropic.com") && process.env.CONTEXT_DOCTOR_NO_LIMITS_LOG !== "1" && (upstream.headers.has("anthropic-ratelimit-unified-7d-utilization") || upstream.headers.has("anthropic-ratelimit-unified-5h-utilization"))) {
574
+ // and recordOverage write only a change, at most once a minute, and
575
+ // never throw).
576
+ if (upstreamBase === (opts.anthropicUpstream ?? "https://api.anthropic.com") && process.env.CONTEXT_DOCTOR_NO_LIMITS_LOG !== "1" && LIMIT_HEADERS.some((h) => upstream.headers.has(h))) {
573
577
  const got = upstream.headers;
574
578
  // Loaded on first use: limits.ts reads transcripts and imports this module's version.
575
579
  void import("./limits.js").then((m) => {
576
580
  const rl = m.rateLimitsFromHeaders((n) => got.get(n));
577
581
  if (rl)
578
582
  m.recordLimits(rl, Date.now(), opts.limitsLogPath, "proxy");
583
+ m.recordOverage(m.overageFromHeaders((n) => got.get(n)), Date.now(), opts.limitsLogPath, "proxy");
579
584
  }).catch(() => undefined);
580
585
  }
581
586
  console.error(`[context-doctor] ${req.method} ${logUrl(url)} → ${upstream.status} in ${Date.now() - upstreamStart}ms | ${note}` +
package/dist/savings.js CHANGED
@@ -369,7 +369,9 @@ export function renderSavings(r, autopilotOn = false, cw, missLines, limitLines,
369
369
  // The same count, said the same way, as compact-window's.
370
370
  lines.push(`Last ${r.days} days, ${sessionsLabel(n, r.transcripts ?? n)}, ${priceBasis()}`);
371
371
  lines.push("─".repeat(60));
372
- lines.push(`Input you were billed for ${usd(r.billedUsd).padStart(9)} from your transcripts' usage`);
372
+ lines.push(`Input in your main conversations ${usd(r.billedUsd).padStart(9)} from your transcripts' usage`);
373
+ // spend's total is larger: it adds output and the subagents. Said here, so the two do not look like they disagree.
374
+ lines.push(" Not in it: output and subagents (context-doctor spend has the whole bill).");
373
375
  lines.push("");
374
376
  lines.push(`1. Compact when you come back ${usd(Math.max(0, r.coldResumeNetUsd)).padStart(9)}${pct(Math.max(0, r.coldResumeNetUsd))}`);
375
377
  lines.push(` ${r.coldResumes} return${r.coldResumes === 1 ? "" : "s"} to a session over 150k tokens after the prompt cache`);
package/dist/spend.d.ts CHANGED
@@ -32,7 +32,8 @@
32
32
  * Not in the total: Claude Code's subagent progress summaries, side requests
33
33
  * no transcript records (progresssummaries.ts). They are estimated per
34
34
  * background subagent and shown beside the total as a range, the two ways
35
- * Anthropic may serve them (short notes, or the whole context).
35
+ * Anthropic may serve them (short notes, or the whole context); a subagent
36
+ * on Claude Code 2.1.328+ once, as notes on the small fast model.
36
37
  *
37
38
  * `savings` bills a narrower slice of the same Claude Code requests: the main
38
39
  * conversation's input (cache writes and reads included, output not), in
@@ -42,6 +43,7 @@
42
43
  import { type ProgressOptions } from "./progresssummaries.js";
43
44
  import { type Modifiers } from "./pricing.js";
44
45
  import { type SessionGap } from "./ccost.js";
46
+ import type { ExtraUsage } from "./claudedir.js";
45
47
  /**
46
48
  * What spend's dollars are: each request as it was billed (its tier, fast mode,
47
49
  * US-only, web searches) at list rates, or at the organization's rates.
@@ -295,12 +297,14 @@ export interface SpendReport {
295
297
  /**
296
298
  * Claude Code's subagent progress summaries, estimated (no transcript records them): NOT in `usd`.
297
299
  * `notesUsd` as short notes (served since November 2026), `forkUsd` as the whole context (before).
300
+ * `smallCalls`: of `calls`, those on Claude Code 2.1.328+, notes on the small fast model in both figures (absent when none).
298
301
  * `set`: CLAUDE_CODE_DISABLE_AGENT_PROGRESS_SUMMARIES is set there, since when unknown: not estimated.
299
302
  * Absent when no subagent got any.
300
303
  */
301
304
  progressSummaries?: {
302
305
  agents: number;
303
306
  calls: number;
307
+ smallCalls?: number;
304
308
  notesUsd: number;
305
309
  forkUsd: number;
306
310
  } | {
@@ -316,6 +320,20 @@ export interface SpendReport {
316
320
  first: number;
317
321
  last: number;
318
322
  }>;
323
+ /**
324
+ * Claude Code past the plan's limit, paid from usage credits (credits.ts):
325
+ * its dollars and requests (`fromHeaders` as the API's replies said,
326
+ * `inferred` from a window at 100%), `claudeUsd` all of Claude Code's,
327
+ * `since` when the first such limit ran out. Inside `usd`; absent when none.
328
+ */
329
+ credits?: {
330
+ usd: number;
331
+ requests: number;
332
+ claudeUsd: number;
333
+ fromHeaders: number;
334
+ inferred: number;
335
+ since: number;
336
+ };
319
337
  /** A tool that could not be read (Cursor without SQLite), and why. */
320
338
  skipped: Array<{
321
339
  tool: Tool;
@@ -341,6 +359,10 @@ export interface SpendOptions {
341
359
  progress?: false | (Pick<ProgressOptions, "forkGateOff" | "offSince"> & {
342
360
  set?: string;
343
361
  });
362
+ /** The limits ledger to read for requests past the plan's limit (tests); default ~/.claude's. */
363
+ limitsLogPath?: string;
364
+ /** `~/.claude.json`'s extra-usage word (tests); null: none. Default read from `home`. */
365
+ extraUsage?: ExtraUsage | null;
344
366
  }
345
367
  /**
346
368
  * The longest window: ten years, older than any history these tools keep.
@@ -373,6 +395,11 @@ export declare function spendReport(days?: number, opts?: SpendOptions): SpendRe
373
395
  export declare const usd: (n: number) => string;
374
396
  /** "fast mode +$4.10, US-only +$0.93, web searches $0.12 (12), long-prompt tier +$0.40": what each billing modifier added, the ones that added anything. */
375
397
  export declare function modifiersText(m: Modifiers): string;
398
+ /**
399
+ * Claude Code's dollars split at the plan's limit: what ran past it on usage
400
+ * credits, and the rest, inside the plan.
401
+ */
402
+ export declare function creditsSplitLines(c: NonNullable<SpendReport["credits"]>, now: number): string[];
376
403
  /** The full report, kept within 80 columns. `top`: rows per list. Grouped by repository or branch instead of project when the report has them (`--by`). */
377
404
  export declare function renderSpend(r: SpendReport, top?: number): string;
378
405
  /**