context-doctor 0.44.0 → 0.46.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 (62) hide show
  1. package/README.md +5 -2
  2. package/dist/budget.d.ts +14 -1
  3. package/dist/budget.js +50 -28
  4. package/dist/cache.js +5 -4
  5. package/dist/cachemisses.js +6 -4
  6. package/dist/cacheplan.js +2 -2
  7. package/dist/cachettl.js +8 -5
  8. package/dist/ci.js +18 -2
  9. package/dist/cli.js +27 -6
  10. package/dist/codexcompact.js +14 -7
  11. package/dist/coldresume.d.ts +6 -0
  12. package/dist/coldresume.js +20 -11
  13. package/dist/compactwindow.js +14 -8
  14. package/dist/doctor.js +26 -2
  15. package/dist/extract.d.ts +2 -2
  16. package/dist/extract.js +14 -3
  17. package/dist/fanout.js +1 -1
  18. package/dist/fix.js +14 -10
  19. package/dist/hook.js +6 -2
  20. package/dist/httpguard.d.ts +9 -1
  21. package/dist/httpguard.js +5 -4
  22. package/dist/lens.js +7 -7
  23. package/dist/limits.d.ts +14 -5
  24. package/dist/limits.js +26 -17
  25. package/dist/mcp.js +62 -62
  26. package/dist/mcpschema.js +5 -3
  27. package/dist/mod/api.d.ts +129 -0
  28. package/dist/mod/api.js +12 -0
  29. package/dist/mod/logic.d.ts +146 -0
  30. package/dist/mod/logic.js +222 -0
  31. package/dist/mod/register.d.ts +58 -0
  32. package/dist/mod/register.js +237 -0
  33. package/dist/modelids.d.ts +23 -0
  34. package/dist/modelids.js +49 -0
  35. package/dist/modmeasure.d.ts +121 -0
  36. package/dist/modmeasure.js +298 -0
  37. package/dist/orgrates.d.ts +75 -0
  38. package/dist/orgrates.js +165 -0
  39. package/dist/overhead.js +11 -8
  40. package/dist/pack.js +95 -22
  41. package/dist/pricing.d.ts +123 -6
  42. package/dist/pricing.js +236 -62
  43. package/dist/proxy.d.ts +12 -1
  44. package/dist/proxy.js +13 -1
  45. package/dist/prune.js +55 -3
  46. package/dist/savings.js +19 -10
  47. package/dist/scan.d.ts +7 -1
  48. package/dist/scan.js +19 -1
  49. package/dist/sessionprice.d.ts +25 -2
  50. package/dist/sessionprice.js +60 -20
  51. package/dist/spend.d.ts +62 -10
  52. package/dist/spend.js +255 -29
  53. package/dist/statusline.d.ts +10 -2
  54. package/dist/statusline.js +18 -9
  55. package/dist/subagentmodel.d.ts +2 -2
  56. package/dist/subagentmodel.js +31 -24
  57. package/dist/subagentpay.d.ts +7 -1
  58. package/dist/subagentpay.js +51 -25
  59. package/dist/subagents.js +15 -10
  60. package/dist/tasks.js +9 -6
  61. package/dist/tooloutput.js +14 -5
  62. package/package.json +1 -1
package/dist/pack.js CHANGED
@@ -19,7 +19,7 @@ import { homedir } from "node:os";
19
19
  import { basename, extname, isAbsolute, join, relative, resolve, sep } from "node:path";
20
20
  import { estimateTokens, formatTokens } from "./tokens.js";
21
21
  import { EXTRACT_BUDGET_MS, EXTRACTABLE, extractText, extractTextAsync, monotonicNow } from "./extract.js";
22
- import { claudeDir } from "./claudedir.js";
22
+ import { claudeDir, claudeJsonPath } from "./claudedir.js";
23
23
  import { codexDir } from "./codexdir.js";
24
24
  const DEFAULT_BUDGET = 4000;
25
25
  const DEFAULT_CHUNK_TOKENS = 400;
@@ -360,10 +360,16 @@ export function renderPack(r, { outlineLimit = 60 } = {}) {
360
360
  }
361
361
  const SKIP_DIRS = new Set(["node_modules", ".git", "dist", "build", ".next", "target", "__pycache__", ".venv", "venv", "vendor"]);
362
362
  export const PACK_LIMITS = { files: 500, fileBytes: 5 * 1024 * 1024, totalBytes: 50 * 1024 * 1024 };
363
+ /**
364
+ * A folder's own .git/config can name a command for `git ls-files` to run
365
+ * (core.fsmonitor): an unpacked archive or a downloaded project brings its
366
+ * .git with it, and packing it must not run anything.
367
+ */
368
+ const SAFE_GIT = ["-c", "core.fsmonitor=false"];
363
369
  /** Files git would consider part of the repository under `dir` (relative to it), or undefined outside git. */
364
370
  function gitFiles(dir) {
365
371
  try {
366
- const r = spawnSync("git", ["-C", dir, "ls-files", "-z", "--cached", "--others", "--exclude-standard"], { encoding: "utf8", maxBuffer: 64 * 1024 * 1024, timeout: 30_000 });
372
+ const r = spawnSync("git", [...SAFE_GIT, "-C", dir, "ls-files", "-z", "--cached", "--others", "--exclude-standard"], { encoding: "utf8", maxBuffer: 64 * 1024 * 1024, timeout: 30_000 });
367
373
  if (r.status !== 0 || typeof r.stdout !== "string")
368
374
  return undefined;
369
375
  // --cached lists files deleted from the work tree too; only what exists is read.
@@ -376,7 +382,7 @@ function gitFiles(dir) {
376
382
  /** Git ignores something under `dir`: why a folder that has files can list none. */
377
383
  function gitIgnoresSome(dir) {
378
384
  // --directory names an ignored folder once instead of every file in it.
379
- const r = spawnSync("git", ["-C", dir, "ls-files", "-z", "--others", "--ignored", "--exclude-standard", "--directory"], { encoding: "utf8", maxBuffer: 64 * 1024 * 1024, timeout: 30_000 });
385
+ const r = spawnSync("git", [...SAFE_GIT, "-C", dir, "ls-files", "-z", "--others", "--ignored", "--exclude-standard", "--directory"], { encoding: "utf8", maxBuffer: 64 * 1024 * 1024, timeout: 30_000 });
380
386
  return r.status === 0 && typeof r.stdout === "string" && r.stdout.length > 0;
381
387
  }
382
388
  /** `inner` is `root` itself or somewhere under it. */
@@ -419,9 +425,9 @@ export function secretFileReason(path) {
419
425
  if (SECRET_EXT.has(extname(lower)))
420
426
  return `a key or certificate store (${extname(lower)})`;
421
427
  const parts = path.split(/[\\/]+/);
422
- if (lower === "credentials" && parts[parts.length - 2] === ".aws")
423
- return "AWS credentials";
424
428
  const parent = (parts[parts.length - 2] ?? "").toLowerCase();
429
+ if (lower === "credentials" && parent === ".aws")
430
+ return "AWS credentials";
425
431
  if (SECRET_IN_DIR.some(([dir, files]) => dir === parent && files.includes(lower)))
426
432
  return `a credentials file (${parent}/${name})`;
427
433
  return undefined;
@@ -440,19 +446,86 @@ function sensitiveDirs() {
440
446
  ];
441
447
  // Compared against real paths: /etc is /private/etc on macOS, and a home
442
448
  // under /var/folders is really /private/var/folders.
443
- const real = dirs.map((d) => {
449
+ return [...new Set([...dirs, ...dirs.map(realOf)])];
450
+ }
451
+ /**
452
+ * The agents' own MCP and settings files, in the home folder (and where
453
+ * CLAUDE_CONFIG_DIR, CODEX_HOME and COPILOT_HOME put them): each MCP server's
454
+ * `env` there commonly holds an API key, and settings.json an `env` of its
455
+ * own. Refused unless secrets are allowed (never over MCP). A project's own
456
+ * `.mcp.json` is not: it is read for good reasons, and it rides in the
457
+ * repository, where a key does not belong.
458
+ */
459
+ function agentConfigFiles() {
460
+ const home = homedir();
461
+ const files = [
462
+ claudeJsonPath(), join(home, ".claude.json"),
463
+ // Claude Code's copies of it: <config dir>/backups/.claude.json.backup.<ms> (2.1.321), and the older <file>.backup.
464
+ `${claudeJsonPath()}.backup`, join(home, ".claude.json.backup"), join(claudeDir(), "backups"), join(home, ".claude", "backups"),
465
+ ...[claudeDir(), join(home, ".claude")].flatMap((d) => [join(d, "settings.json"), join(d, "settings.local.json")]),
466
+ join(home, ".cursor", "mcp.json"),
467
+ join(codexDir(), "config.toml"), join(home, ".codex", "config.toml"),
468
+ join(home, ".gemini", "settings.json"),
469
+ // Antigravity: the shared config folder's file, and the app's own from before it.
470
+ join(home, ".gemini", "config", "mcp_config.json"), join(home, ".gemini", "antigravity", "mcp_config.json"),
471
+ // Claude Desktop on macOS, Windows and Linux.
472
+ join(home, "Library", "Application Support", "Claude", "claude_desktop_config.json"),
473
+ join(process.env.APPDATA || join(home, "AppData", "Roaming"), "Claude", "claude_desktop_config.json"),
474
+ join(home, ".config", "Claude", "claude_desktop_config.json"),
475
+ join(process.env.COPILOT_HOME || join(home, ".copilot"), "mcp-config.json"), join(home, ".copilot", "mcp-config.json"),
476
+ // Claude Desktop's extensions keep their settings, API keys among them, in a folder of their own.
477
+ ...appDataDirs().map((d) => join(d, "Claude", "Claude Extensions Settings")),
478
+ // VS Code's user MCP servers (stable and Insiders; a profile's own are vsCodeProfileDirs').
479
+ ...vsCodeUserDirs().map((d) => join(d, "mcp.json")),
480
+ // Windsurf, and Zed, whose MCP servers ("context_servers") are in its settings.
481
+ join(home, ".codeium", "windsurf", "mcp_config.json"),
482
+ // (%APPDATA%\Zed on Windows, whose disks ignore case: inSensitiveDir.)
483
+ ...appDataDirs().map((d) => join(d, "zed", "settings.json")),
484
+ ];
485
+ return [...new Set([...files, ...files.map(realOf)])];
486
+ }
487
+ /** Where apps keep their settings: macOS's Application Support, Windows' %APPDATA%, Linux's XDG config folder (every one, whatever the OS). */
488
+ function appDataDirs() {
489
+ const home = homedir();
490
+ return [...new Set([
491
+ join(home, "Library", "Application Support"),
492
+ process.env.APPDATA || join(home, "AppData", "Roaming"),
493
+ process.env.XDG_CONFIG_HOME || join(home, ".config"), join(home, ".config"),
494
+ ])];
495
+ }
496
+ /** VS Code's user folders, stable and Insiders. */
497
+ function vsCodeUserDirs() {
498
+ return appDataDirs().flatMap((d) => ["Code", "Code - Insiders"].map((app) => join(d, app, "User")));
499
+ }
500
+ /** The folders that hold VS Code's profiles, each with an mcp.json of its own (User/profiles/<id>/mcp.json). */
501
+ function vsCodeProfileDirs() {
502
+ const dirs = vsCodeUserDirs().map((d) => join(d, "profiles"));
503
+ return [...new Set([...dirs, ...dirs.map(realOf)])];
504
+ }
505
+ /**
506
+ * A path's real spelling: links resolved and, where the system can say,
507
+ * the case on disk and Windows' long names (`realpathSync.native`), so
508
+ * ~/.SSH and C:\Users\RUNNER~1 are the folders they name.
509
+ */
510
+ function realOf(p) {
511
+ for (const real of [realpathSync.native, realpathSync]) {
444
512
  try {
445
- return realpathSync(d);
513
+ return real(p);
446
514
  }
447
515
  catch {
448
- return d;
516
+ /* the next */
449
517
  }
450
- });
451
- return [...new Set([...dirs, ...real])];
518
+ }
519
+ return resolve(p);
452
520
  }
453
- /** The denylisted folder `path` (a real path) sits in, if any. */
521
+ /**
522
+ * The denylisted folder `path` (a real path) sits in, if any. macOS and
523
+ * Windows disks ignore case by default: ~/.AWS/credentials is
524
+ * ~/.aws/credentials there, whatever spelling the path arrived in.
525
+ */
454
526
  function inSensitiveDir(path, dirs) {
455
- return dirs.find((d) => within(d, path));
527
+ const fold = process.platform === "darwin" || process.platform === "win32" ? (s) => s.toLowerCase() : (s) => s;
528
+ return dirs.find((d) => within(fold(d), fold(path)));
456
529
  }
457
530
  /** A short reason for a filesystem error: EACCES reads as "permission denied", not a stack trace. */
458
531
  function fsReason(e) {
@@ -490,6 +563,8 @@ export function readSources(paths, cwdOrOptions = process.cwd()) {
490
563
  const includeSecrets = options.includeSecrets === true;
491
564
  const secretsHint = options.secretsHint ?? "";
492
565
  const denied = includeSecrets ? [] : sensitiveDirs();
566
+ const deniedConfigs = includeSecrets ? [] : agentConfigFiles();
567
+ const deniedProfiles = includeSecrets ? [] : vsCodeProfileDirs();
493
568
  const sources = [];
494
569
  const skipped = [];
495
570
  let bytes = 0;
@@ -502,14 +577,6 @@ export function readSources(paths, cwdOrOptions = process.cwd()) {
502
577
  let hidden = 0;
503
578
  // Whether the folder being walked was listed by git (hidden tracked files are source there).
504
579
  let insideGit = false;
505
- const realOf = (p) => {
506
- try {
507
- return realpathSync(p);
508
- }
509
- catch {
510
- return resolve(p);
511
- }
512
- };
513
580
  const visit = (p, top) => {
514
581
  if (sources.length >= PACK_LIMITS.files) {
515
582
  if (top || skipped.length < 20)
@@ -527,7 +594,7 @@ export function readSources(paths, cwdOrOptions = process.cwd()) {
527
594
  if (st.isSymbolicLink()) {
528
595
  let target;
529
596
  try {
530
- target = realpathSync(p);
597
+ target = realOf(realpathSync(p));
531
598
  }
532
599
  catch {
533
600
  return; // dangling: nothing to read
@@ -537,13 +604,19 @@ export function readSources(paths, cwdOrOptions = process.cwd()) {
537
604
  return;
538
605
  }
539
606
  if (denied.length > 0) {
540
- const dir = inSensitiveDir(realOf(p), denied);
607
+ const real = realOf(p);
608
+ const dir = inSensitiveDir(real, denied);
541
609
  if (dir) {
542
610
  // Once per named path: a folder of keys is one refusal, not one per key.
543
611
  if (top)
544
612
  skipped.push(`${p}: refused, ${dir} holds credentials${secretsHint}`);
545
613
  return;
546
614
  }
615
+ const config = inSensitiveDir(real, deniedConfigs) ?? (basename(real).toLowerCase() === "mcp.json" ? inSensitiveDir(real, deniedProfiles) : undefined);
616
+ if (config) {
617
+ skipped.push(`${p}: refused, ${config} can hold API keys (an MCP server's env)${secretsHint}`);
618
+ return;
619
+ }
547
620
  }
548
621
  if (st.isDirectory()) {
549
622
  const name = basename(p);
package/dist/pricing.d.ts CHANGED
@@ -3,9 +3,12 @@
3
3
  *
4
4
  * List rates of each provider's first-party API (standard tier, global
5
5
  * routing, no batch or fast mode), each family with the page it was read
6
- * from and the date. Prices drift, so all cost output is labeled as an
7
- * estimate. One table, one file, easy to update: PRs welcome when prices
8
- * change.
6
+ * from and the date. What a request recorded can bill it differently (fast
7
+ * mode, US-only inference, a long prompt's tier, web searches) and a row's
8
+ * price can end on a known day: requestCost applies all of it, per request,
9
+ * from the row's billing options. Prices drift, so all cost output is
10
+ * labeled as an estimate. One table, one file, easy to update: PRs welcome
11
+ * when prices change.
9
12
  *
10
13
  * A row names one model (a "known" price, see knownPricingFor) unless it is
11
14
  * listed in FALLBACKS: those price ids the table does not know by version,
@@ -19,7 +22,15 @@ export interface ModelPricing {
19
22
  outputPerM: number;
20
23
  /** USD per 1M cached input tokens read (2.5-10% of input, depending on the Claude model). */
21
24
  cacheReadPerM: number;
25
+ /**
26
+ * USD per 1M cache-write tokens, every lifetime alike: only an
27
+ * organization's contracted row has one (orgrates.ts). Without it a write
28
+ * is its TTL's multiple of input.
29
+ */
30
+ cacheWritePerM?: number;
22
31
  }
32
+ /** What a cache write costs per 1M tokens at `mult` times input (its TTL's), or the row's own write rate. */
33
+ export declare function writePerM(p: ModelPricing, mult: number): number;
23
34
  /** Anthropic cache writes, relative to the input price: 5-minute TTL and 1-hour TTL. */
24
35
  export declare const CACHE_WRITE_5M = 1.25;
25
36
  export declare const CACHE_WRITE_1H = 2;
@@ -32,6 +43,7 @@ export declare const CACHE_WRITE_1H = 2;
32
43
  */
33
44
  export declare const CACHE_WRITE_OPENAI_30M = 1.25;
34
45
  export declare const CACHE_WRITE_OPENAI_12H = 2.5;
46
+ /** A model's list row, as the page lists it today (no tier, mode or date applied). */
35
47
  export declare function pricingFor(model?: string): ModelPricing | undefined;
36
48
  /**
37
49
  * A model's price from a row for that model, not a family fallback: undefined
@@ -71,6 +83,16 @@ export interface RecordedUsage {
71
83
  ephemeral_1h_input_tokens?: unknown;
72
84
  ttl_12h_input_tokens?: unknown;
73
85
  } | null;
86
+ /** Anthropic: "fast" for a fast-mode request ("standard" otherwise). */
87
+ speed?: unknown;
88
+ /** Anthropic: "us" for US-only inference ("global", "", "not_available" otherwise). */
89
+ inference_geo?: unknown;
90
+ /** Anthropic: server-side tool uses billed per use. */
91
+ server_tool_use?: {
92
+ web_search_requests?: unknown;
93
+ web_fetch_requests?: unknown;
94
+ code_execution_requests?: unknown;
95
+ } | null;
74
96
  }
75
97
  export interface UsageCost {
76
98
  /** Uncached input. */
@@ -104,11 +126,106 @@ export declare function cacheWriteSplit(usage: RecordedUsage | undefined | null)
104
126
  */
105
127
  export declare function writeMultiplier(fiveMinute: number, oneHour: number, twelveHour?: number): number;
106
128
  /**
107
- * What one recorded request cost: uncached input, cache writes priced by
108
- * TTL, cache reads, output. The one place recorded usage is priced, so every
109
- * report agrees with the others and with the bill.
129
+ * Recorded usage at given rates: uncached input, cache writes priced by
130
+ * TTL, cache reads, output. The rates a request was billed at (its tier,
131
+ * fast mode, US-only, its date) are requestCost's to decide.
110
132
  */
111
133
  export declare function usageCost(usage: RecordedUsage | undefined | null, pricing: ModelPricing): UsageCost;
134
+ /** US-only inference on Claude 4.6 and later: 1.1x on every token category (Anthropic, "Data residency pricing", read 2026-11-08). */
135
+ export declare const US_ONLY_MULTIPLIER = 1.1;
136
+ /**
137
+ * Claude's web search tool: $10 per 1,000 searches, on top of its tokens
138
+ * (Anthropic, "Web search tool", read 2026-11-08). A token price, so not
139
+ * under the US-only multiplier. Web fetch has no charge beyond its tokens;
140
+ * code execution bills container time (1,550 free hours a month, then $0.05
141
+ * an hour), which usage does not record per request: not modelled.
142
+ */
143
+ export declare const WEB_SEARCH_USD: number;
144
+ /** The tokens a request's prompt holds: uncached input, cache reads and cache writes (what a long-prompt tier counts). */
145
+ export declare function promptTokens(usage: RecordedUsage | undefined | null): number;
146
+ /**
147
+ * The rates a model's requests bill at, from its row and what the request
148
+ * recorded: `rates` for a prompt up to `over` tokens, `longRates` beyond
149
+ * (no tier: `over` absent). Fast mode replaces the rates (its price holds
150
+ * across the full context window); US-only scales them. A request on or
151
+ * after the day its row's price changes (`changedOn`) is priced at the
152
+ * price the page said would follow, or the old one when it said none: an
153
+ * estimate either way (a scheduled price can be called off: Sonnet 5's was).
154
+ */
155
+ export interface RateCard {
156
+ rates: ModelPricing;
157
+ over?: number;
158
+ longRates?: ModelPricing;
159
+ /** The list row's own rates, before tier, fast mode and US-only: what the modifiers are measured from. */
160
+ list: ModelPricing;
161
+ /** Fast mode's rates applied. */
162
+ fast?: true;
163
+ /** US-only's 1.1x applied. */
164
+ geo?: true;
165
+ /** Priced by family or past its row's date: an estimate. */
166
+ estimated?: true;
167
+ /** "YYYY-MM-DD": the row's price changed on this day, before the request. */
168
+ changedOn?: string;
169
+ /** Web searches bill per use (Claude). */
170
+ webSearch?: true;
171
+ /**
172
+ * Priced at the organization's rates (Claude Code's managed `modelPricing`,
173
+ * orgrates.ts): its row for the model, or the list price times its
174
+ * multiplier. Every figure on the card is already scaled by `scale`.
175
+ */
176
+ org?: true;
177
+ /** The organization's multiplier, which also scales the web-search fee. */
178
+ scale?: number;
179
+ }
180
+ /** The rate card for one of `model`'s requests at time `at`, with the modifiers its usage records. Undefined for a model with no price. */
181
+ export declare function rateCard(model: string | undefined, usage?: RecordedUsage | null, at?: number): RateCard | undefined;
182
+ /** A card's rates for a prompt of `prompt` tokens: its long tier's past `over`. */
183
+ export declare function ratesAt(card: RateCard, prompt: number): ModelPricing;
184
+ /**
185
+ * What a request's billing modifiers added to its list-row price, in USD:
186
+ * fast mode, US-only inference, a long-prompt tier, and the web searches it
187
+ * ran (`webSearches` of them, `webSearchUsd`).
188
+ */
189
+ export interface Modifiers {
190
+ fastUsd: number;
191
+ geoUsd: number;
192
+ longUsd: number;
193
+ webSearchUsd: number;
194
+ webSearches: number;
195
+ }
196
+ export declare const NO_MODIFIERS: Readonly<Modifiers>;
197
+ export interface RequestCost extends UsageCost {
198
+ /** The rates its tokens were billed at (the parts above); `totalUsd` adds the web searches. */
199
+ rates: ModelPricing;
200
+ modifiers: Modifiers;
201
+ /** Priced by family, or past the day its row's price changed: an estimate. */
202
+ estimated?: true;
203
+ /** "YYYY-MM-DD": its row's price changed on this day, before the request. */
204
+ changedOn?: string;
205
+ /** Priced at the organization's rates (RateCard.org). */
206
+ org?: true;
207
+ }
208
+ /**
209
+ * What one recorded request cost, as billed: its model's row at the time it
210
+ * ran, its prompt's tier, fast mode, US-only inference, cache writes by TTL,
211
+ * and per-use tool fees. The one place a request's price is decided, so
212
+ * every report agrees with the others and with the bill. `at`: when it ran.
213
+ * Undefined for a model with no price.
214
+ */
215
+ export declare function requestCost(model: string | undefined, usage: RecordedUsage | undefined | null, at?: number): RequestCost | undefined;
216
+ /** `a` plus `b`, part by part. */
217
+ export declare function addModifiers(a: Modifiers, b: Readonly<Modifiers>): Modifiers;
218
+ /**
219
+ * When a model's price in the table stops being its list price: the day
220
+ * (YYYY-MM-DD) and, when the page said, the price from then. Undefined for
221
+ * a row with no end date. What `doctor` and the budget say once it has passed.
222
+ */
223
+ export declare function priceChange(model?: string): {
224
+ on: string;
225
+ then?: ModelPricing;
226
+ } | undefined;
227
+ /** "gemini-4-argon's price changed on 2026-12-01; a newer context-doctor knows the new one": said for each model priced past its row's date. */
228
+ export declare function priceChangedText(models: Array<[model: string, on: string]>): string;
112
229
  /**
113
230
  * OpenAI usage, in any of its shapes, as RecordedUsage: Responses
114
231
  * (`input_tokens`, `input_tokens_details.cached_tokens`, `cache_write_tokens`