context-doctor 0.44.0 → 0.45.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/mcpschema.js CHANGED
@@ -95,20 +95,22 @@ export function claudeMcpConfigs(cwd = process.cwd(), home = homedir()) {
95
95
  out.set(name, { name, scope, command: c.command, args: c.args, env: c.env, url: c.url, type: c.type });
96
96
  }
97
97
  };
98
+ let cfg;
98
99
  try {
99
- const cfg = JSON.parse(readFileSync(claudeJsonPath(home), "utf8"));
100
- addAll(cfg.mcpServers, "user");
101
- addAll(cfg.projects?.[resolve(cwd)]?.mcpServers, "project");
100
+ cfg = JSON.parse(readFileSync(claudeJsonPath(home), "utf8"));
102
101
  }
103
102
  catch {
104
103
  /* absent */
105
104
  }
105
+ // A name in several scopes is Claude Code's local one, then the .mcp.json one, then the user's.
106
+ addAll(cfg?.mcpServers, "user");
106
107
  try {
107
108
  addAll(JSON.parse(readFileSync(join(cwd, ".mcp.json"), "utf8")).mcpServers, ".mcp.json");
108
109
  }
109
110
  catch {
110
111
  /* absent */
111
112
  }
113
+ addAll(cfg?.projects?.[resolve(cwd)]?.mcpServers, "project");
112
114
  return [...out.values()].sort((a, b) => a.name.localeCompare(b.name));
113
115
  }
114
116
  export const MCP_ROWS = {
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,58 @@ 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
+ ...[claudeDir(), join(home, ".claude")].flatMap((d) => [join(d, "settings.json"), join(d, "settings.local.json")]),
464
+ join(home, ".cursor", "mcp.json"),
465
+ join(codexDir(), "config.toml"), join(home, ".codex", "config.toml"),
466
+ join(home, ".gemini", "settings.json"),
467
+ // Antigravity: the shared config folder's file, and the app's own from before it.
468
+ join(home, ".gemini", "config", "mcp_config.json"), join(home, ".gemini", "antigravity", "mcp_config.json"),
469
+ // Claude Desktop on macOS, Windows and Linux.
470
+ join(home, "Library", "Application Support", "Claude", "claude_desktop_config.json"),
471
+ join(process.env.APPDATA || join(home, "AppData", "Roaming"), "Claude", "claude_desktop_config.json"),
472
+ join(home, ".config", "Claude", "claude_desktop_config.json"),
473
+ join(process.env.COPILOT_HOME || join(home, ".copilot"), "mcp-config.json"), join(home, ".copilot", "mcp-config.json"),
474
+ ];
475
+ return [...new Set([...files, ...files.map(realOf)])];
476
+ }
477
+ /**
478
+ * A path's real spelling: links resolved and, where the system can say,
479
+ * the case on disk and Windows' long names (`realpathSync.native`), so
480
+ * ~/.SSH and C:\Users\RUNNER~1 are the folders they name.
481
+ */
482
+ function realOf(p) {
483
+ for (const real of [realpathSync.native, realpathSync]) {
444
484
  try {
445
- return realpathSync(d);
485
+ return real(p);
446
486
  }
447
487
  catch {
448
- return d;
488
+ /* the next */
449
489
  }
450
- });
451
- return [...new Set([...dirs, ...real])];
490
+ }
491
+ return resolve(p);
452
492
  }
453
- /** The denylisted folder `path` (a real path) sits in, if any. */
493
+ /**
494
+ * The denylisted folder `path` (a real path) sits in, if any. macOS and
495
+ * Windows disks ignore case by default: ~/.AWS/credentials is
496
+ * ~/.aws/credentials there, whatever spelling the path arrived in.
497
+ */
454
498
  function inSensitiveDir(path, dirs) {
455
- return dirs.find((d) => within(d, path));
499
+ const fold = process.platform === "darwin" || process.platform === "win32" ? (s) => s.toLowerCase() : (s) => s;
500
+ return dirs.find((d) => within(fold(d), fold(path)));
456
501
  }
457
502
  /** A short reason for a filesystem error: EACCES reads as "permission denied", not a stack trace. */
458
503
  function fsReason(e) {
@@ -490,6 +535,7 @@ export function readSources(paths, cwdOrOptions = process.cwd()) {
490
535
  const includeSecrets = options.includeSecrets === true;
491
536
  const secretsHint = options.secretsHint ?? "";
492
537
  const denied = includeSecrets ? [] : sensitiveDirs();
538
+ const deniedConfigs = includeSecrets ? [] : agentConfigFiles();
493
539
  const sources = [];
494
540
  const skipped = [];
495
541
  let bytes = 0;
@@ -502,14 +548,6 @@ export function readSources(paths, cwdOrOptions = process.cwd()) {
502
548
  let hidden = 0;
503
549
  // Whether the folder being walked was listed by git (hidden tracked files are source there).
504
550
  let insideGit = false;
505
- const realOf = (p) => {
506
- try {
507
- return realpathSync(p);
508
- }
509
- catch {
510
- return resolve(p);
511
- }
512
- };
513
551
  const visit = (p, top) => {
514
552
  if (sources.length >= PACK_LIMITS.files) {
515
553
  if (top || skipped.length < 20)
@@ -527,7 +565,7 @@ export function readSources(paths, cwdOrOptions = process.cwd()) {
527
565
  if (st.isSymbolicLink()) {
528
566
  let target;
529
567
  try {
530
- target = realpathSync(p);
568
+ target = realOf(realpathSync(p));
531
569
  }
532
570
  catch {
533
571
  return; // dangling: nothing to read
@@ -537,13 +575,19 @@ export function readSources(paths, cwdOrOptions = process.cwd()) {
537
575
  return;
538
576
  }
539
577
  if (denied.length > 0) {
540
- const dir = inSensitiveDir(realOf(p), denied);
578
+ const real = realOf(p);
579
+ const dir = inSensitiveDir(real, denied);
541
580
  if (dir) {
542
581
  // Once per named path: a folder of keys is one refusal, not one per key.
543
582
  if (top)
544
583
  skipped.push(`${p}: refused, ${dir} holds credentials${secretsHint}`);
545
584
  return;
546
585
  }
586
+ const config = inSensitiveDir(real, deniedConfigs);
587
+ if (config) {
588
+ skipped.push(`${p}: refused, ${config} can hold API keys (an MCP server's env)${secretsHint}`);
589
+ return;
590
+ }
547
591
  }
548
592
  if (st.isDirectory()) {
549
593
  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,
@@ -32,6 +35,7 @@ export declare const CACHE_WRITE_1H = 2;
32
35
  */
33
36
  export declare const CACHE_WRITE_OPENAI_30M = 1.25;
34
37
  export declare const CACHE_WRITE_OPENAI_12H = 2.5;
38
+ /** A model's list row, as the page lists it today (no tier, mode or date applied). */
35
39
  export declare function pricingFor(model?: string): ModelPricing | undefined;
36
40
  /**
37
41
  * A model's price from a row for that model, not a family fallback: undefined
@@ -71,6 +75,16 @@ export interface RecordedUsage {
71
75
  ephemeral_1h_input_tokens?: unknown;
72
76
  ttl_12h_input_tokens?: unknown;
73
77
  } | null;
78
+ /** Anthropic: "fast" for a fast-mode request ("standard" otherwise). */
79
+ speed?: unknown;
80
+ /** Anthropic: "us" for US-only inference ("global", "", "not_available" otherwise). */
81
+ inference_geo?: unknown;
82
+ /** Anthropic: server-side tool uses billed per use. */
83
+ server_tool_use?: {
84
+ web_search_requests?: unknown;
85
+ web_fetch_requests?: unknown;
86
+ code_execution_requests?: unknown;
87
+ } | null;
74
88
  }
75
89
  export interface UsageCost {
76
90
  /** Uncached input. */
@@ -104,11 +118,96 @@ export declare function cacheWriteSplit(usage: RecordedUsage | undefined | null)
104
118
  */
105
119
  export declare function writeMultiplier(fiveMinute: number, oneHour: number, twelveHour?: number): number;
106
120
  /**
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.
121
+ * Recorded usage at given rates: uncached input, cache writes priced by
122
+ * TTL, cache reads, output. The rates a request was billed at (its tier,
123
+ * fast mode, US-only, its date) are requestCost's to decide.
110
124
  */
111
125
  export declare function usageCost(usage: RecordedUsage | undefined | null, pricing: ModelPricing): UsageCost;
126
+ /** US-only inference on Claude 4.6 and later: 1.1x on every token category (Anthropic, "Data residency pricing", read 2026-11-08). */
127
+ export declare const US_ONLY_MULTIPLIER = 1.1;
128
+ /**
129
+ * Claude's web search tool: $10 per 1,000 searches, on top of its tokens
130
+ * (Anthropic, "Web search tool", read 2026-11-08). A token price, so not
131
+ * under the US-only multiplier. Web fetch has no charge beyond its tokens;
132
+ * code execution bills container time (1,550 free hours a month, then $0.05
133
+ * an hour), which usage does not record per request: not modelled.
134
+ */
135
+ export declare const WEB_SEARCH_USD: number;
136
+ /** The tokens a request's prompt holds: uncached input, cache reads and cache writes (what a long-prompt tier counts). */
137
+ export declare function promptTokens(usage: RecordedUsage | undefined | null): number;
138
+ /**
139
+ * The rates a model's requests bill at, from its row and what the request
140
+ * recorded: `rates` for a prompt up to `over` tokens, `longRates` beyond
141
+ * (no tier: `over` absent). Fast mode replaces the rates (its price holds
142
+ * across the full context window); US-only scales them. A request on or
143
+ * after the day its row's price changes (`changedOn`) is priced at the
144
+ * price the page said would follow, or the old one when it said none: an
145
+ * estimate either way (a scheduled price can be called off: Sonnet 5's was).
146
+ */
147
+ export interface RateCard {
148
+ rates: ModelPricing;
149
+ over?: number;
150
+ longRates?: ModelPricing;
151
+ /** The list row's own rates, before tier, fast mode and US-only: what the modifiers are measured from. */
152
+ list: ModelPricing;
153
+ /** Fast mode's rates applied. */
154
+ fast?: true;
155
+ /** US-only's 1.1x applied. */
156
+ geo?: true;
157
+ /** Priced by family or past its row's date: an estimate. */
158
+ estimated?: true;
159
+ /** "YYYY-MM-DD": the row's price changed on this day, before the request. */
160
+ changedOn?: string;
161
+ /** Web searches bill per use (Claude). */
162
+ webSearch?: true;
163
+ }
164
+ /** 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. */
165
+ export declare function rateCard(model: string | undefined, usage?: RecordedUsage | null, at?: number): RateCard | undefined;
166
+ /** A card's rates for a prompt of `prompt` tokens: its long tier's past `over`. */
167
+ export declare function ratesAt(card: RateCard, prompt: number): ModelPricing;
168
+ /**
169
+ * What a request's billing modifiers added to its list-row price, in USD:
170
+ * fast mode, US-only inference, a long-prompt tier, and the web searches it
171
+ * ran (`webSearches` of them, `webSearchUsd`).
172
+ */
173
+ export interface Modifiers {
174
+ fastUsd: number;
175
+ geoUsd: number;
176
+ longUsd: number;
177
+ webSearchUsd: number;
178
+ webSearches: number;
179
+ }
180
+ export declare const NO_MODIFIERS: Readonly<Modifiers>;
181
+ export interface RequestCost extends UsageCost {
182
+ /** The rates its tokens were billed at (the parts above); `totalUsd` adds the web searches. */
183
+ rates: ModelPricing;
184
+ modifiers: Modifiers;
185
+ /** Priced by family, or past the day its row's price changed: an estimate. */
186
+ estimated?: true;
187
+ /** "YYYY-MM-DD": its row's price changed on this day, before the request. */
188
+ changedOn?: string;
189
+ }
190
+ /**
191
+ * What one recorded request cost, as billed: its model's row at the time it
192
+ * ran, its prompt's tier, fast mode, US-only inference, cache writes by TTL,
193
+ * and per-use tool fees. The one place a request's price is decided, so
194
+ * every report agrees with the others and with the bill. `at`: when it ran.
195
+ * Undefined for a model with no price.
196
+ */
197
+ export declare function requestCost(model: string | undefined, usage: RecordedUsage | undefined | null, at?: number): RequestCost | undefined;
198
+ /** `a` plus `b`, part by part. */
199
+ export declare function addModifiers(a: Modifiers, b: Readonly<Modifiers>): Modifiers;
200
+ /**
201
+ * When a model's price in the table stops being its list price: the day
202
+ * (YYYY-MM-DD) and, when the page said, the price from then. Undefined for
203
+ * a row with no end date. What `doctor` and the budget say once it has passed.
204
+ */
205
+ export declare function priceChange(model?: string): {
206
+ on: string;
207
+ then?: ModelPricing;
208
+ } | undefined;
209
+ /** "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. */
210
+ export declare function priceChangedText(models: Array<[model: string, on: string]>): string;
112
211
  /**
113
212
  * OpenAI usage, in any of its shapes, as RecordedUsage: Responses
114
213
  * (`input_tokens`, `input_tokens_details.cached_tokens`, `cache_write_tokens`