context-doctor 0.45.0 → 0.47.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 (75) hide show
  1. package/README.md +8 -3
  2. package/dist/ab.js +3 -2
  3. package/dist/autopilot.js +9 -5
  4. package/dist/blob.js +66 -12
  5. package/dist/budget.d.ts +10 -1
  6. package/dist/budget.js +37 -8
  7. package/dist/cachemisses.js +5 -3
  8. package/dist/cacheplan.js +2 -2
  9. package/dist/cachettl.js +2 -1
  10. package/dist/ci.js +2 -1
  11. package/dist/claudeplugin.d.ts +97 -0
  12. package/dist/claudeplugin.js +142 -0
  13. package/dist/cli.js +126 -39
  14. package/dist/coldresume.d.ts +6 -0
  15. package/dist/coldresume.js +7 -6
  16. package/dist/compactcost.d.ts +74 -0
  17. package/dist/compactcost.js +115 -0
  18. package/dist/compactwindow.js +5 -4
  19. package/dist/cursor.js +2 -0
  20. package/dist/doctor.js +106 -17
  21. package/dist/extract.js +4 -3
  22. package/dist/fanout.d.ts +15 -0
  23. package/dist/fanout.js +31 -10
  24. package/dist/firstfix.d.ts +43 -0
  25. package/dist/firstfix.js +80 -0
  26. package/dist/fix.d.ts +46 -2
  27. package/dist/fix.js +109 -20
  28. package/dist/hook.js +6 -2
  29. package/dist/httpguard.d.ts +13 -0
  30. package/dist/httpguard.js +22 -0
  31. package/dist/install.d.ts +21 -9
  32. package/dist/install.js +211 -40
  33. package/dist/limits.d.ts +5 -0
  34. package/dist/limits.js +26 -2
  35. package/dist/mcp.js +63 -62
  36. package/dist/missledger.js +5 -3
  37. package/dist/mod/api.d.ts +135 -0
  38. package/dist/mod/api.js +12 -0
  39. package/dist/mod/logic.d.ts +158 -0
  40. package/dist/mod/logic.js +244 -0
  41. package/dist/mod/register.d.ts +60 -0
  42. package/dist/mod/register.js +251 -0
  43. package/dist/modelids.d.ts +24 -0
  44. package/dist/modelids.js +65 -0
  45. package/dist/modelswitch.js +8 -4
  46. package/dist/modmeasure.d.ts +121 -0
  47. package/dist/modmeasure.js +310 -0
  48. package/dist/orgrates.d.ts +93 -0
  49. package/dist/orgrates.js +214 -0
  50. package/dist/overhead.js +11 -8
  51. package/dist/pack.d.ts +13 -0
  52. package/dist/pack.js +68 -3
  53. package/dist/preferences.js +2 -1
  54. package/dist/pricing.d.ts +26 -0
  55. package/dist/pricing.js +61 -7
  56. package/dist/progresssummaries.d.ts +148 -0
  57. package/dist/progresssummaries.js +248 -0
  58. package/dist/proxy.d.ts +1 -1
  59. package/dist/proxy.js +1 -1
  60. package/dist/prune.d.ts +8 -0
  61. package/dist/prune.js +11 -1
  62. package/dist/savings.js +8 -6
  63. package/dist/sessionprice.d.ts +22 -0
  64. package/dist/sessionprice.js +46 -14
  65. package/dist/spend.d.ts +46 -3
  66. package/dist/spend.js +86 -10
  67. package/dist/statusline.js +2 -2
  68. package/dist/subagentmodel.d.ts +12 -0
  69. package/dist/subagentmodel.js +17 -4
  70. package/dist/subagentpay.d.ts +15 -1
  71. package/dist/subagentpay.js +58 -25
  72. package/dist/subagents.js +4 -0
  73. package/dist/toolcwd.d.ts +14 -0
  74. package/dist/toolcwd.js +17 -0
  75. package/package.json +1 -1
package/dist/overhead.js CHANGED
@@ -20,7 +20,8 @@ import { dirname, isAbsolute, join, relative, resolve } from "node:path";
20
20
  import { codexDir } from "./codexdir.js";
21
21
  import { forEachLine, listSessions, replyCounter, textOf } from "./session.js";
22
22
  import { estimateTokens, formatTokens, providerFor, realModel, tokensForLength } from "./tokens.js";
23
- import { cacheWriteSplit, formatUsd, pricingFor, writeMultiplier as ttlWriteMultiplier } from "./pricing.js";
23
+ import { cacheWriteSplit, formatUsd, rateCard, ratesAt, writeMultiplier as ttlWriteMultiplier, writePerM } from "./pricing.js";
24
+ import { priceBasis } from "./orgrates.js";
24
25
  import { isGeminiChat, readGeminiMessages } from "./gemini.js";
25
26
  import { claudeMcpConfigs, mcpUsage, measureServer, otherServerUses, serverUses } from "./mcpschema.js";
26
27
  import { claudeDir } from "./claudedir.js";
@@ -183,7 +184,7 @@ function claudeUsage(path, runRows) {
183
184
  const w = cacheWriteSplit(u);
184
185
  out.writes5m += w.fiveMinute;
185
186
  out.writes1h += w.oneHour;
186
- out.reqs.push({ at, model: realModel(e.message.model) });
187
+ out.reqs.push({ at, model: realModel(e.message.model), prompt, billing: { speed: u.speed, inference_geo: u.inference_geo } });
187
188
  });
188
189
  return out;
189
190
  }
@@ -275,7 +276,7 @@ function aggregate(agent, sessions, since, days) {
275
276
  const cold = prevAt === undefined || r.at - prevAt > TTL_MS;
276
277
  if (cold)
277
278
  coldStarts++;
278
- starts.push({ cold, model: r.model });
279
+ starts.push({ cold, model: r.model, at: r.at, prompt: r.prompt, billing: r.billing });
279
280
  if (r.model)
280
281
  models.set(r.model, (models.get(r.model) ?? 0) + 1);
281
282
  }
@@ -291,11 +292,13 @@ function aggregate(agent, sessions, since, days) {
291
292
  // at its own model's price: one month can mix a $4 and a $10 model.
292
293
  let usdPerK = 0, priced = 0;
293
294
  for (const r of starts) {
294
- const price = pricingFor(r.model ?? model);
295
- if (!price)
295
+ // At the rates that request billed (rateCard: its prompt's tier, fast mode, US-only, the day).
296
+ const card = rateCard(r.model ?? model, r.billing, r.at);
297
+ if (!card)
296
298
  continue;
299
+ const price = ratesAt(card, r.prompt ?? 0);
297
300
  priced++;
298
- usdPerK += (1000 * (r.cold ? writeMultiplier(r.model ?? model, writes5m, writes1h) * price.inputPerM : price.cacheReadPerM)) / 1e6;
301
+ usdPerK += (1000 * (r.cold ? writePerM(price, writeMultiplier(r.model ?? model, writes5m, writes1h)) : price.cacheReadPerM)) / 1e6;
299
302
  }
300
303
  const usdPerKPerMonth = priced > 0 ? usdPerK * (30 / days) : undefined;
301
304
  return {
@@ -470,7 +473,7 @@ export function renderOverhead(r, home = homedir()) {
470
473
  if (b) {
471
474
  out.push(`Claude Code, last ${b.days} days: ${sessionCount(b)} start at a median ~${formatTokens(b.median)} tokens (p90 ~${formatTokens(b.p90)}) before the first message.`, `Memory files loaded here are ~${formatTokens(claudeTokens)} of that; the rest is Claude Code's system prompt, tools, skills and MCP schemas.`);
472
475
  if (b.usdPerKPerMonth !== undefined) {
473
- out.push(`At your usage (${b.requests.toLocaleString("en-US")} requests, ${b.coldStarts.toLocaleString("en-US")} cold starts, ${b.model} list prices) every 1k tokens of it costs ~${formatUsd(b.usdPerKPerMonth)} a month;`, `the whole overhead ~${formatUsd((b.median / 1000) * b.usdPerKPerMonth)} a month.`);
476
+ out.push(`At your usage (${b.requests.toLocaleString("en-US")} requests, ${b.coldStarts.toLocaleString("en-US")} cold starts, ${b.model} ${priceBasis().replace(/^at /, "")}) every 1k tokens of it costs ~${formatUsd(b.usdPerKPerMonth)} a month;`, `the whole overhead ~${formatUsd((b.median / 1000) * b.usdPerKPerMonth)} a month.`);
474
477
  }
475
478
  }
476
479
  else {
@@ -480,7 +483,7 @@ export function renderOverhead(r, home = homedir()) {
480
483
  const tokens = r.files.filter((f) => f.agent === o.agent).reduce((s, f) => s + f.tokens, 0);
481
484
  out.push("", `${o.agent}, last ${o.days} days: ${sessionCount(o)} start at a median ~${formatTokens(o.median)} tokens (p90 ~${formatTokens(o.p90)}); ${tokens ? `memory files loaded here ~${formatTokens(tokens)} of it` : "no memory files of its own here"}.` +
482
485
  (o.usdPerKPerMonth !== undefined
483
- ? ` Each 1k tokens ~${formatUsd(o.usdPerKPerMonth)} a month (${o.requests.toLocaleString("en-US")} requests, ${o.coldStarts.toLocaleString("en-US")} cold starts, ${o.model} list prices).`
486
+ ? ` Each 1k tokens ~${formatUsd(o.usdPerKPerMonth)} a month (${o.requests.toLocaleString("en-US")} requests, ${o.coldStarts.toLocaleString("en-US")} cold starts, ${o.model} ${priceBasis().replace(/^at /, "")}).`
484
487
  : ""));
485
488
  }
486
489
  out.push(...renderMcp(r));
package/dist/pack.d.ts CHANGED
@@ -105,6 +105,19 @@ export declare const PACK_LIMITS: {
105
105
  fileBytes: number;
106
106
  totalBytes: number;
107
107
  };
108
+ /**
109
+ * Why the MCP server will not open a path a model names. A path the user
110
+ * types on the CLI is theirs to name.
111
+ * - Windows: a network share (\\host\share\…, \\?\UNC\…) or a device or
112
+ * pipe (\\.\…). Opening a share connects to that host over SMB and signs
113
+ * in as the user, handing whoever runs it the user's NTLM hash; a
114
+ * document can ask the model to "pack \\host\share\notes.md".
115
+ * - Windows: an alternate data stream (notes.md:hidden, .env::$DATA). A
116
+ * stream is the same file under a name no refusal here recognises.
117
+ * - macOS: /net/<host>/…, which the automounter mounts from that host on
118
+ * first access.
119
+ */
120
+ export declare function remotePathReason(path: string, platform?: NodeJS.Platform): string | undefined;
108
121
  /** Why `path` looks like a secrets file, or undefined when it does not. */
109
122
  export declare function secretFileReason(path: string): string | undefined;
110
123
  export interface ReadSourcesOptions {
package/dist/pack.js CHANGED
@@ -21,6 +21,7 @@ import { estimateTokens, formatTokens } from "./tokens.js";
21
21
  import { EXTRACT_BUDGET_MS, EXTRACTABLE, extractText, extractTextAsync, monotonicNow } from "./extract.js";
22
22
  import { claudeDir, claudeJsonPath } from "./claudedir.js";
23
23
  import { codexDir } from "./codexdir.js";
24
+ import { toolCwd } from "./toolcwd.js";
24
25
  const DEFAULT_BUDGET = 4000;
25
26
  const DEFAULT_CHUNK_TOKENS = 400;
26
27
  /** Claude's tokenizer produces the most tokens per char; a budget in its terms never overruns another's. */
@@ -369,7 +370,7 @@ const SAFE_GIT = ["-c", "core.fsmonitor=false"];
369
370
  /** Files git would consider part of the repository under `dir` (relative to it), or undefined outside git. */
370
371
  function gitFiles(dir) {
371
372
  try {
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 });
373
+ const r = spawnSync("git", [...SAFE_GIT, "-C", dir, "ls-files", "-z", "--cached", "--others", "--exclude-standard"], { cwd: toolCwd(), encoding: "utf8", maxBuffer: 64 * 1024 * 1024, timeout: 30_000 });
373
374
  if (r.status !== 0 || typeof r.stdout !== "string")
374
375
  return undefined;
375
376
  // --cached lists files deleted from the work tree too; only what exists is read.
@@ -382,7 +383,7 @@ function gitFiles(dir) {
382
383
  /** Git ignores something under `dir`: why a folder that has files can list none. */
383
384
  function gitIgnoresSome(dir) {
384
385
  // --directory names an ignored folder once instead of every file in it.
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 });
386
+ const r = spawnSync("git", [...SAFE_GIT, "-C", dir, "ls-files", "-z", "--others", "--ignored", "--exclude-standard", "--directory"], { cwd: toolCwd(), encoding: "utf8", maxBuffer: 64 * 1024 * 1024, timeout: 30_000 });
386
387
  return r.status === 0 && typeof r.stdout === "string" && r.stdout.length > 0;
387
388
  }
388
389
  /** `inner` is `root` itself or somewhere under it. */
@@ -404,6 +405,12 @@ const SECRET_NAMES = new Set([
404
405
  // Windows), Gemini CLI's, Terraform's.
405
406
  ".credentials.json", "oauth_creds.json", "credentials.tfrc.json",
406
407
  ]);
408
+ /**
409
+ * Shell histories: every command typed, `export TOKEN=…` and `curl -H
410
+ * "Authorization: …"` among them. Bash, zsh, fish (fish_history) and
411
+ * PowerShell (PSReadLine's ConsoleHost_history.txt).
412
+ */
413
+ const HISTORY_NAMES = new Set([".bash_history", ".zsh_history", ".zhistory", ".sh_history", "fish_history", "consolehost_history.txt"]);
407
414
  /** A file name that holds credentials inside one folder only: Codex's sign-in, Cargo's and RubyGems' tokens. */
408
415
  const SECRET_IN_DIR = [
409
416
  [".codex", ["auth.json"]],
@@ -411,6 +418,30 @@ const SECRET_IN_DIR = [
411
418
  [".gem", ["credentials"]],
412
419
  ];
413
420
  const SECRET_EXT = new Set([".pem", ".key", ".p12", ".pfx", ".keystore", ".jks"]);
421
+ /**
422
+ * Why the MCP server will not open a path a model names. A path the user
423
+ * types on the CLI is theirs to name.
424
+ * - Windows: a network share (\\host\share\…, \\?\UNC\…) or a device or
425
+ * pipe (\\.\…). Opening a share connects to that host over SMB and signs
426
+ * in as the user, handing whoever runs it the user's NTLM hash; a
427
+ * document can ask the model to "pack \\host\share\notes.md".
428
+ * - Windows: an alternate data stream (notes.md:hidden, .env::$DATA). A
429
+ * stream is the same file under a name no refusal here recognises.
430
+ * - macOS: /net/<host>/…, which the automounter mounts from that host on
431
+ * first access.
432
+ */
433
+ export function remotePathReason(path, platform = process.platform) {
434
+ const p = path.trim();
435
+ if (platform === "win32") {
436
+ if (/^[\\/]{2}/.test(p))
437
+ return "a network share or device path (\\\\host\\share, \\\\.\\…): pack_context reads this computer's own files only";
438
+ if (p.replace(/^[a-zA-Z]:/, "").includes(":"))
439
+ return "an alternate data stream (a name with \":\" after the drive): pack_context reads files by their own names";
440
+ }
441
+ if (platform === "darwin" && /^\/+net(\/|$)/i.test(p))
442
+ return "a /net path, which macOS mounts from another host on access: pack_context reads this computer's own files only";
443
+ return undefined;
444
+ }
414
445
  /** Why `path` looks like a secrets file, or undefined when it does not. */
415
446
  export function secretFileReason(path) {
416
447
  const name = basename(path);
@@ -419,6 +450,8 @@ export function secretFileReason(path) {
419
450
  return "an .env file";
420
451
  if (SECRET_NAMES.has(lower))
421
452
  return `a credentials file (${name})`;
453
+ if (HISTORY_NAMES.has(lower))
454
+ return `a shell history (${name})`;
422
455
  if (/^id_(rsa|dsa|ecdsa|ed25519)(_sk)?$/.test(lower) || (/^id_(rsa|dsa|ecdsa|ed25519)/.test(lower) && !lower.endsWith(".pub"))) {
423
456
  return "a private SSH key";
424
457
  }
@@ -440,6 +473,9 @@ function sensitiveDirs() {
440
473
  const home = homedir();
441
474
  const dirs = [
442
475
  ...[".ssh", ".aws", ".gnupg", ".kube", ".docker", ".azure", join(".config", "gcloud"), join(".config", "gh"), join(".config", "github-copilot"), join("Library", "Keychains"), ".password-store"].map((d) => join(home, d)),
476
+ // Package registries' sign-ins in the home folder: Yarn's npmAuthToken, Maven's server passwords.
477
+ // (A project's own .yarnrc.yml rides in the repository and is read.)
478
+ ...[".yarnrc.yml", join(".m2", "settings.xml"), join(".m2", "settings-security.xml")].map((f) => join(home, f)),
443
479
  // Where CLAUDE_CONFIG_DIR and CODEX_HOME put the agents' sign-ins.
444
480
  join(claudeDir(), ".credentials.json"), join(codexDir(), "auth.json"),
445
481
  "/etc/shadow", "/etc/gshadow", "/etc/sudoers", "/etc/master.passwd", "/etc/ssh",
@@ -460,6 +496,8 @@ function agentConfigFiles() {
460
496
  const home = homedir();
461
497
  const files = [
462
498
  claudeJsonPath(), join(home, ".claude.json"),
499
+ // Claude Code's copies of it: <config dir>/backups/.claude.json.backup.<ms> (2.1.321), and the older <file>.backup.
500
+ `${claudeJsonPath()}.backup`, join(home, ".claude.json.backup"), join(claudeDir(), "backups"), join(home, ".claude", "backups"),
463
501
  ...[claudeDir(), join(home, ".claude")].flatMap((d) => [join(d, "settings.json"), join(d, "settings.local.json")]),
464
502
  join(home, ".cursor", "mcp.json"),
465
503
  join(codexDir(), "config.toml"), join(home, ".codex", "config.toml"),
@@ -471,9 +509,35 @@ function agentConfigFiles() {
471
509
  join(process.env.APPDATA || join(home, "AppData", "Roaming"), "Claude", "claude_desktop_config.json"),
472
510
  join(home, ".config", "Claude", "claude_desktop_config.json"),
473
511
  join(process.env.COPILOT_HOME || join(home, ".copilot"), "mcp-config.json"), join(home, ".copilot", "mcp-config.json"),
512
+ // Claude Desktop's extensions keep their settings, API keys among them, in a folder of their own.
513
+ ...appDataDirs().map((d) => join(d, "Claude", "Claude Extensions Settings")),
514
+ // VS Code's user MCP servers (stable and Insiders; a profile's own are vsCodeProfileDirs').
515
+ ...vsCodeUserDirs().map((d) => join(d, "mcp.json")),
516
+ // Windsurf, and Zed, whose MCP servers ("context_servers") are in its settings.
517
+ join(home, ".codeium", "windsurf", "mcp_config.json"),
518
+ // (%APPDATA%\Zed on Windows, whose disks ignore case: inSensitiveDir.)
519
+ ...appDataDirs().map((d) => join(d, "zed", "settings.json")),
474
520
  ];
475
521
  return [...new Set([...files, ...files.map(realOf)])];
476
522
  }
523
+ /** Where apps keep their settings: macOS's Application Support, Windows' %APPDATA%, Linux's XDG config folder (every one, whatever the OS). */
524
+ function appDataDirs() {
525
+ const home = homedir();
526
+ return [...new Set([
527
+ join(home, "Library", "Application Support"),
528
+ process.env.APPDATA || join(home, "AppData", "Roaming"),
529
+ process.env.XDG_CONFIG_HOME || join(home, ".config"), join(home, ".config"),
530
+ ])];
531
+ }
532
+ /** VS Code's user folders, stable and Insiders. */
533
+ function vsCodeUserDirs() {
534
+ return appDataDirs().flatMap((d) => ["Code", "Code - Insiders"].map((app) => join(d, app, "User")));
535
+ }
536
+ /** The folders that hold VS Code's profiles, each with an mcp.json of its own (User/profiles/<id>/mcp.json). */
537
+ function vsCodeProfileDirs() {
538
+ const dirs = vsCodeUserDirs().map((d) => join(d, "profiles"));
539
+ return [...new Set([...dirs, ...dirs.map(realOf)])];
540
+ }
477
541
  /**
478
542
  * A path's real spelling: links resolved and, where the system can say,
479
543
  * the case on disk and Windows' long names (`realpathSync.native`), so
@@ -536,6 +600,7 @@ export function readSources(paths, cwdOrOptions = process.cwd()) {
536
600
  const secretsHint = options.secretsHint ?? "";
537
601
  const denied = includeSecrets ? [] : sensitiveDirs();
538
602
  const deniedConfigs = includeSecrets ? [] : agentConfigFiles();
603
+ const deniedProfiles = includeSecrets ? [] : vsCodeProfileDirs();
539
604
  const sources = [];
540
605
  const skipped = [];
541
606
  let bytes = 0;
@@ -583,7 +648,7 @@ export function readSources(paths, cwdOrOptions = process.cwd()) {
583
648
  skipped.push(`${p}: refused, ${dir} holds credentials${secretsHint}`);
584
649
  return;
585
650
  }
586
- const config = inSensitiveDir(real, deniedConfigs);
651
+ const config = inSensitiveDir(real, deniedConfigs) ?? (basename(real).toLowerCase() === "mcp.json" ? inSensitiveDir(real, deniedProfiles) : undefined);
587
652
  if (config) {
588
653
  skipped.push(`${p}: refused, ${config} can hold API keys (an MCP server's env)${secretsHint}`);
589
654
  return;
@@ -9,6 +9,7 @@
9
9
  * edited, so a long chat continues in a new one from a short brief.
10
10
  */
11
11
  import { spawnSync } from "node:child_process";
12
+ import { toolCwd } from "./toolcwd.js";
12
13
  export const CHAT_PREFERENCES = [
13
14
  "Context hygiene: summarize anything long I paste into the points you will use; refer to it by name, never re-quote it,",
14
15
  "never inline base64. When I ask about tokens, limits, cost or speed, and once past ~30 turns: if profile_context exists,",
@@ -27,7 +28,7 @@ export function copyToClipboard(text, platform = process.platform) {
27
28
  : platform === "win32" ? [["clip", []]]
28
29
  : [["wl-copy", []], ["xclip", ["-selection", "clipboard"]], ["xsel", ["--clipboard", "--input"]]];
29
30
  for (const [cmd, args] of candidates) {
30
- const r = spawnSync(cmd, args, { input: text, stdio: ["pipe", "ignore", "ignore"] });
31
+ const r = spawnSync(cmd, args, { cwd: toolCwd(), input: text, stdio: ["pipe", "ignore", "ignore"] });
31
32
  if (!r.error && r.status === 0)
32
33
  return true;
33
34
  }
package/dist/pricing.d.ts CHANGED
@@ -22,7 +22,15 @@ export interface ModelPricing {
22
22
  outputPerM: number;
23
23
  /** USD per 1M cached input tokens read (2.5-10% of input, depending on the Claude model). */
24
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;
25
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;
26
34
  /** Anthropic cache writes, relative to the input price: 5-minute TTL and 1-hour TTL. */
27
35
  export declare const CACHE_WRITE_5M = 1.25;
28
36
  export declare const CACHE_WRITE_1H = 2;
@@ -35,6 +43,14 @@ export declare const CACHE_WRITE_1H = 2;
35
43
  */
36
44
  export declare const CACHE_WRITE_OPENAI_30M = 1.25;
37
45
  export declare const CACHE_WRITE_OPENAI_12H = 2.5;
46
+ /**
47
+ * A fingerprint of this table and its billing constants. Dollars a ledger
48
+ * keeps per request (the budget's, a session's price) were priced by the
49
+ * table of the context-doctor that read them: under another table (an
50
+ * upgrade that corrected a price, as 0.46 did Fable 5.2's) they are stale
51
+ * and read again, not carried to the period's end.
52
+ */
53
+ export declare function priceTableKey(): string;
38
54
  /** A model's list row, as the page lists it today (no tier, mode or date applied). */
39
55
  export declare function pricingFor(model?: string): ModelPricing | undefined;
40
56
  /**
@@ -160,6 +176,14 @@ export interface RateCard {
160
176
  changedOn?: string;
161
177
  /** Web searches bill per use (Claude). */
162
178
  webSearch?: true;
179
+ /**
180
+ * Priced at the organization's rates (Claude Code's managed `modelPricing`,
181
+ * orgrates.ts): its row for the model, or the list price times its
182
+ * multiplier. Every figure on the card is already scaled by `scale`.
183
+ */
184
+ org?: true;
185
+ /** The organization's multiplier, which also scales the web-search fee. */
186
+ scale?: number;
163
187
  }
164
188
  /** 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
189
  export declare function rateCard(model: string | undefined, usage?: RecordedUsage | null, at?: number): RateCard | undefined;
@@ -186,6 +210,8 @@ export interface RequestCost extends UsageCost {
186
210
  estimated?: true;
187
211
  /** "YYYY-MM-DD": its row's price changed on this day, before the request. */
188
212
  changedOn?: string;
213
+ /** Priced at the organization's rates (RateCard.org). */
214
+ org?: true;
189
215
  }
190
216
  /**
191
217
  * What one recorded request cost, as billed: its model's row at the time it
package/dist/pricing.js CHANGED
@@ -15,6 +15,12 @@
15
15
  * at a family's price, so a new release still gets a number. A model a
16
16
  * provider prices only per minute, per image or not at all has no row.
17
17
  */
18
+ import { createHash } from "node:crypto";
19
+ import { orgApplies, orgRates, orgRowFor } from "./orgrates.js";
20
+ /** What a cache write costs per 1M tokens at `mult` times input (its TTL's), or the row's own write rate. */
21
+ export function writePerM(p, mult) {
22
+ return p.cacheWritePerM ?? mult * p.inputPerM;
23
+ }
18
24
  /** Anthropic cache writes, relative to the input price: 5-minute TTL and 1-hour TTL. */
19
25
  export const CACHE_WRITE_5M = 1.25;
20
26
  export const CACHE_WRITE_1H = 2;
@@ -79,16 +85,22 @@ const openaiLong = (inputPerM, outputPerM, cacheReadPerM) => {
79
85
  const PRICING = [
80
86
  // Anthropic: platform.claude.com/docs/en/about-claude/pricing ("Model
81
87
  // pricing"; 5-minute writes 1.25x, 1-hour writes 2x), read 2026-11-06,
82
- // its modifiers read 2026-11-08 (pricing.md):
88
+ // its modifiers read 2026-11-08 (pricing.md); read again 2026-11-10: Fable
89
+ // 5.2 and Mythos 5.2 added, every other row and modifier unchanged:
83
90
  // - "Data residency pricing": for Claude 4.6 and later, `inference_geo:
84
91
  // "us"` is 1.1x on input, output, cache writes and reads, and on Haiku
85
92
  // 5.5's over-100k prices too (GEO). Earlier models reject the parameter.
86
- // - "Fast mode pricing": Opus 5.5 $8 / $40, Opus 5 and Opus 4.8 $10 / $50,
93
+ // - "Fast mode pricing": Fable 5.2 and Mythos 5.2 $16 / $80 (read
94
+ // 2026-11-10), Opus 5.5 $8 / $40, Opus 5 and Opus 4.8 $10 / $50,
87
95
  // "across the full context window"; caching multipliers and data
88
96
  // residency apply on top (Opus 5.5's reads 0.05x: $0.40).
89
97
  // - "Long context pricing": only Haiku 5.5 is priced by prompt length.
90
98
  // Specific Claude versions first: the family rows below are only a
91
99
  // fallback for ids this table does not know yet.
100
+ // Fable 5.2 and Mythos 5.2 (read 2026-11-10): $8 / $40, writes $10 (5 min)
101
+ // and $16 (1 h), reads 0.025x ($0.20); fast mode $16 / $80 on the Claude
102
+ // API, reads $0.40 at that multiplier; US-only 1.1x (Claude 4.6 and later).
103
+ [claude("fable|mythos", 5, 2), rate(8, 40, 0.2), { geo: true, fast: rate(16, 80, 0.4) }],
92
104
  [claude("fable|mythos", 5, 1), rate(10, 50, 0.25), GEO],
93
105
  [claude("fable|mythos", 5), rate(10, 50, 1), GEO],
94
106
  [claude("opus", 5, 5), rate(4, 20, 0.2), { geo: true, fast: rate(8, 40, 0.4) }],
@@ -197,7 +209,7 @@ const PRICING = [
197
209
  // the same $0.30 / $2.50 / $0.03: no change to say.
198
210
  [gemini("gemini-3.1-pro"), rate(2, 12, 0.2), { long: { over: 200_000, rates: rate(4, 18, 0.4) } }],
199
211
  [gemini("gemini-3-flash"), rate(0.5, 3, 0.05)],
200
- [gemini("gemini-2.5-pro"), rate(1.25, 10, 0.125), { long: { over: 200_000, rates: rate(2.5, 15, 0.25) }, changes: "2026-12-01", then: rate(0.75, 3.75, 0.075) }],
212
+ [gemini("gemini-2.5-pro"), rate(1.25, 10, 0.125), { long: { over: 200_000, rates: rate(2.5, 15, 0.25) }, changes: "2026-12-01", then: rate(0.75, 3.75, 0.075), routes: "gemini-3.8-flash" }],
201
213
  [gemini("gemini-2.5-flash"), rate(0.3, 2.5, 0.03)],
202
214
  [gemini("gemini-2.5-flash-lite"), rate(0.1, 0.4, 0.01)],
203
215
  // Fallbacks for Gemini ids not on the page (gemini-3-pro, a new 3.x Flash,
@@ -208,6 +220,21 @@ const PRICING = [
208
220
  [/gemini.*flash/i, rate(0.1, 0.4, 0.025), FALLBACK],
209
221
  [/gemini.*pro/i, rate(1.25, 5, 0.31), FALLBACK],
210
222
  ];
223
+ let tableKey;
224
+ /**
225
+ * A fingerprint of this table and its billing constants. Dollars a ledger
226
+ * keeps per request (the budget's, a session's price) were priced by the
227
+ * table of the context-doctor that read them: under another table (an
228
+ * upgrade that corrected a price, as 0.46 did Fable 5.2's) they are stale
229
+ * and read again, not carried to the period's end.
230
+ */
231
+ export function priceTableKey() {
232
+ tableKey ??= createHash("sha1")
233
+ .update(JSON.stringify([PRICING.map(([re, p, b]) => [re.source, re.flags, p, b ?? null]), CACHE_WRITE_5M, CACHE_WRITE_1H, CACHE_WRITE_OPENAI_30M, CACHE_WRITE_OPENAI_12H, US_ONLY_MULTIPLIER, WEB_SEARCH_USD]))
234
+ .digest("hex")
235
+ .slice(0, 12);
236
+ return tableKey;
237
+ }
211
238
  function row(model) {
212
239
  if (!model)
213
240
  return undefined;
@@ -293,7 +320,9 @@ export function usageCost(usage, pricing) {
293
320
  const { fiveMinute, oneHour, twelveHour } = cacheWriteSplit(usage);
294
321
  const perM = (tokens, usd) => (tokens * usd) / 1_000_000;
295
322
  const inputUsd = perM(count(usage?.input_tokens), pricing.inputPerM);
296
- const writeUsd = perM(fiveMinute * CACHE_WRITE_5M + oneHour * CACHE_WRITE_1H + twelveHour * CACHE_WRITE_OPENAI_12H, pricing.inputPerM);
323
+ const writeUsd = pricing.cacheWritePerM !== undefined
324
+ ? perM(fiveMinute + oneHour + twelveHour, pricing.cacheWritePerM)
325
+ : perM(fiveMinute * CACHE_WRITE_5M + oneHour * CACHE_WRITE_1H + twelveHour * CACHE_WRITE_OPENAI_12H, pricing.inputPerM);
297
326
  const readUsd = perM(count(usage?.cache_read_input_tokens), pricing.cacheReadPerM);
298
327
  const outputUsd = perM(count(usage?.output_tokens), pricing.outputPerM);
299
328
  const promptUsd = inputUsd + writeUsd + readUsd;
@@ -315,14 +344,30 @@ export function promptTokens(usage) {
315
344
  }
316
345
  /** UTC midnight of a "YYYY-MM-DD" day. */
317
346
  const dayStart = (day) => Date.parse(`${day}T00:00:00Z`);
318
- const scaled = (p, k) => (k === 1 ? p : { inputPerM: p.inputPerM * k, outputPerM: p.outputPerM * k, cacheReadPerM: p.cacheReadPerM * k });
347
+ const scaled = (p, k) => (k === 1 ? p : { inputPerM: p.inputPerM * k, outputPerM: p.outputPerM * k, cacheReadPerM: p.cacheReadPerM * k, ...(p.cacheWritePerM !== undefined ? { cacheWritePerM: p.cacheWritePerM * k } : {}) });
319
348
  /** 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. */
320
349
  export function rateCard(model, usage, at = Date.now()) {
350
+ const org = model ? orgRates() : undefined;
351
+ const own = org && orgRowFor(org, model);
352
+ if (own) {
353
+ // A contracted row is charged as written: no tier, fast mode, US-only or date; then the multiplier.
354
+ const rates = scaled(own, org.multiplier);
355
+ return { rates, list: rates, org: true, ...(org.multiplier !== 1 ? { scale: org.multiplier } : {}), ...(/claude/i.test(model) ? { webSearch: true } : {}) };
356
+ }
321
357
  const r = row(model);
322
358
  if (!r)
323
359
  return undefined;
324
360
  const [, list, b = {}] = r;
361
+ // A request with no time of its own (a row without a timestamp) is priced as of now, the default:
362
+ // past a change that is the newer price, labelled an estimate with its day. NaN compared as never
363
+ // expired, so such a row got an ended price unlabelled in some reports and today's in others.
364
+ if (!Number.isFinite(at))
365
+ at = Date.now();
325
366
  const expired = b.changes !== undefined && at >= dayStart(b.changes);
367
+ // Routed to another model: its card, so a later change of that model's price follows (and is the day said).
368
+ const to = expired && b.routes ? rateCard(b.routes, usage, at) : undefined;
369
+ if (to)
370
+ return { ...to, estimated: true, changedOn: to.changedOn ?? b.changes };
326
371
  const base = expired && b.then ? b.then : list;
327
372
  const long = expired && b.then ? undefined : b.long;
328
373
  const fast = usage?.speed === "fast" && b.fast ? b.fast : undefined;
@@ -342,6 +387,15 @@ export function rateCard(model, usage, at = Date.now()) {
342
387
  card.changedOn = b.changes;
343
388
  if (/claude/i.test(model))
344
389
  card.webSearch = true;
390
+ if (org && orgApplies(org, model)) {
391
+ const k = org.multiplier;
392
+ card.rates = scaled(card.rates, k);
393
+ card.list = scaled(card.list, k);
394
+ if (card.longRates)
395
+ card.longRates = scaled(card.longRates, k);
396
+ card.org = true;
397
+ card.scale = k;
398
+ }
345
399
  return card;
346
400
  }
347
401
  /** A card's rates for a prompt of `prompt` tokens: its long tier's past `over`. */
@@ -364,7 +418,7 @@ export function requestCost(model, usage, at = Date.now()) {
364
418
  const rates = ratesAt(card, prompt);
365
419
  const c = usageCost(usage, rates);
366
420
  const searches = card.webSearch ? count(usage?.server_tool_use?.web_search_requests) : 0;
367
- const m = { ...NO_MODIFIERS, webSearches: searches, webSearchUsd: searches * WEB_SEARCH_USD };
421
+ const m = { ...NO_MODIFIERS, webSearches: searches, webSearchUsd: searches * WEB_SEARCH_USD * (card.scale ?? 1) };
368
422
  if (card.fast || card.geo || rates !== card.rates || card.over !== undefined) {
369
423
  // Each modifier measured from the step before it: list row, its tier, fast mode, US-only.
370
424
  const geo = card.geo ? US_ONLY_MULTIPLIER : 1;
@@ -375,7 +429,7 @@ export function requestCost(model, usage, at = Date.now()) {
375
429
  m.fastUsd = card.fast ? preGeo - tiered : 0;
376
430
  m.geoUsd = c.totalUsd - preGeo;
377
431
  }
378
- return { ...c, totalUsd: c.totalUsd + m.webSearchUsd, rates, modifiers: m, ...(card.estimated ? { estimated: true } : {}), ...(card.changedOn ? { changedOn: card.changedOn } : {}) };
432
+ return { ...c, totalUsd: c.totalUsd + m.webSearchUsd, rates, modifiers: m, ...(card.estimated ? { estimated: true } : {}), ...(card.changedOn ? { changedOn: card.changedOn } : {}), ...(card.org ? { org: true } : {}) };
379
433
  }
380
434
  /** `a` plus `b`, part by part. */
381
435
  export function addModifiers(a, b) {
@@ -0,0 +1,148 @@
1
+ /**
2
+ * Claude Code's subagent progress summaries, estimated: side requests no
3
+ * transcript records. The `progress-summaries` lever of `fix`.
4
+ *
5
+ * While a background subagent runs, Claude Code asks a model every 30
6
+ * seconds for a 3-5 word line about what it is doing (the text on its task
7
+ * row). The request is made with `skipTranscript`, so no transcript row
8
+ * carries it, and Claude Code bills it and counts it in its own cost
9
+ * (anthropics/claude-code#86879 measured 22.7% of one subagent-heavy
10
+ * session's requests). `CLAUDE_CODE_DISABLE_AGENT_PROGRESS_SUMMARIES=1`
11
+ * (2.1.318+, documented in 2.1.323) turns them off, and the requests with
12
+ * them. The summary never enters the agent's context: the work is the same.
13
+ *
14
+ * Read from the 2.1.321 binary (the Desktop app's bundled Claude Code, with
15
+ * `strings`; docs/spend.md has the details):
16
+ * - Who gets them. Only a subagent run in the background (the async
17
+ * runner), and there only when the host asked for them (the SDK's
18
+ * `agentProgressSummaries` option) or the session is interactive (a
19
+ * terminal, `entrypoint: "cli"`) and the fork gate is open (on unless
20
+ * CLAUDE_CODE_FORK_SUBAGENT=0) or coordinator mode is on. A fork launched
21
+ * in the background gets them in every mode. A foreground subagent gets
22
+ * them only when the host asked. Workflow agents never do. The Desktop
23
+ * app's Code tab runs Claude Code through the SDK, so its sessions are
24
+ * not interactive, and its bundle (5.11492) never sets the option: none.
25
+ * - How often. A timer every 30 s from the agent's start; a tick is skipped
26
+ * while the agent's transcript has fewer than 3 messages or has not
27
+ * changed since the last summary; it stops when the agent ends.
28
+ * - What each sends. Either the agent's whole conversation as a one-turn
29
+ * fork on the agent's own model (no cache write, so its prefix is read
30
+ * from the agent's cache), or ("short") at most ~1,500 tokens of notes
31
+ * about its recent steps, with prompt caching off and low effort, on the
32
+ * agent's own model (or Haiku). Which one is served per model from
33
+ * Anthropic's side and is not in any file here; Anthropic said on
34
+ * 2026-11-09 (#86879) that the summaries now "consume 99% less", which is
35
+ * the notes. So both are priced: the notes as the low figure, the whole
36
+ * context as the high one.
37
+ *
38
+ * Estimated per subagent from what its transcript does record: the time of
39
+ * each message (the ticks and whether the transcript changed), each reply's
40
+ * prompt size and model (the context a fork would read, the rates). Each
41
+ * summary's output is #86879's measured mean (65 tokens). Not counted: a
42
+ * tick held while the agent's own request waits on a cold cache (it fires
43
+ * later, not more often), and the thinking a summary may do.
44
+ */
45
+ import { type Extractor } from "./scan.js";
46
+ /** The variable the lever writes, and the value: Claude Code passes only "1" on to the sessions it starts in the background. */
47
+ export declare const PROGRESS_SUMMARIES_ENV = "CLAUDE_CODE_DISABLE_AGENT_PROGRESS_SUMMARIES";
48
+ export declare const PROGRESS_SUMMARIES_OFF = "1";
49
+ /** The first Claude Code that reads it (its CHANGELOG, 2.1.323: "available since 2.1.318"). */
50
+ export declare const PROGRESS_SUMMARIES_SINCE = "2.1.318";
51
+ /** The summary timer (the binary's default; #86879 and #105981 measured 30-32 s). */
52
+ export declare const SUMMARY_TICK_MS = 30000;
53
+ /** A short summary's prompt: notes capped at 2,000 - 500 tokens, plus its system prompt and instruction. */
54
+ export declare const NOTES_TOKENS = 1850;
55
+ /** A fork summary's own instruction, after the agent's context. */
56
+ export declare const FORK_PROMPT_TOKENS = 150;
57
+ /** Each summary's output: #86879's measured mean (21,966 tokens over 339 summaries). */
58
+ export declare const SUMMARY_OUTPUT_TOKENS = 65;
59
+ /** How Claude Code reads the variable (a boolean: "1", "true", "yes", "on"). */
60
+ export declare const disablesSummaries: (v: unknown) => boolean;
61
+ /**
62
+ * One subagent transcript's timeline: the first row's host and version, the
63
+ * time of each message, and each reply's prompt size and model (once per
64
+ * reply; its output is in the next prompt).
65
+ */
66
+ export declare const PROGRESS_ROWS: Extractor<{
67
+ head: boolean;
68
+ ids: Record<string, 1>;
69
+ }>;
70
+ /** What a subagent's `.meta.json` says about how it ran (2.1.266+ write requestShape). */
71
+ export interface AgentMeta {
72
+ agentType?: string;
73
+ requestShape?: string;
74
+ isFork?: boolean;
75
+ }
76
+ export declare function readAgentMeta(file: string): AgentMeta | undefined;
77
+ /** Why a subagent gets no summaries, or "yes". */
78
+ export type Eligibility = "yes" | "foreground" | "host" | "workflow" | "unknown" | "fork-gate-off" | "off" | "old";
79
+ /**
80
+ * Whether Claude Code (2.1.321's rules) wrote progress summaries for this
81
+ * agent. `interactive`: whether its host counts as interactive (default: a
82
+ * terminal session, entrypoint "cli").
83
+ */
84
+ export declare function eligibility(meta: AgentMeta | undefined, entrypoint: string | undefined, opts?: {
85
+ workflow?: boolean;
86
+ forkGateOff?: boolean;
87
+ interactive?: (entrypoint: string | undefined) => boolean;
88
+ }): Eligibility;
89
+ /** One subagent's summaries: how many, and their price both ways. */
90
+ export interface AgentSummaries {
91
+ calls: number;
92
+ notesUsd: number;
93
+ forkUsd: number;
94
+ }
95
+ type Rec = {
96
+ t: "h";
97
+ entrypoint?: string;
98
+ version?: string;
99
+ } | {
100
+ t: "m";
101
+ ts: number;
102
+ } | {
103
+ t: "r";
104
+ ts: number;
105
+ model?: string;
106
+ p: number;
107
+ speed?: string;
108
+ geo?: string;
109
+ };
110
+ /**
111
+ * The ticks a running agent's timer made and the summaries they sent, from
112
+ * its timeline: every 30 s from its first row to its last, a summary when
113
+ * it has 3+ messages and more than at the last summary. Only ticks in
114
+ * [since, until] are counted.
115
+ */
116
+ export declare function simulateAgent(recs: Rec[], since?: number, until?: number): AgentSummaries;
117
+ export interface ProgressSummaryEstimate {
118
+ /** Subagent transcripts read (workflow agents included). */
119
+ agents: number;
120
+ /** Agents Claude Code wrote summaries for in the window, by the rules above. */
121
+ summarized: number;
122
+ calls: number;
123
+ /** The summaries as short notes (what Anthropic serves since November 2026): the low figure. */
124
+ notesUsd: number;
125
+ /** As a fork of the whole context (before): the high figure. */
126
+ forkUsd: number;
127
+ /** Agents with none, by why. */
128
+ none: Partial<Record<Exclude<Eligibility, "yes">, number>>;
129
+ /** The hosts of the background agents that got none because their host is not interactive. */
130
+ hosts: string[];
131
+ }
132
+ export interface ProgressOptions {
133
+ since?: number;
134
+ until?: number;
135
+ /** CLAUDE_CODE_FORK_SUBAGENT is off: interactive sessions' ordinary background agents got none. */
136
+ forkGateOff?: boolean;
137
+ /** From this time, on Claude Code 2.1.318+, the variable was set (fix's record): none after it. */
138
+ offSince?: number;
139
+ /** Which hosts count as interactive (default: entrypoint "cli"); a measurement can ask "what if all were". */
140
+ interactive?: (entrypoint: string | undefined) => boolean;
141
+ /** Only agents on this Claude Code or newer (what the variable would have stopped: 2.1.318+). */
142
+ minVersion?: string;
143
+ }
144
+ /** The summaries of the subagents in `files` (their `.jsonl` transcripts), estimated. */
145
+ export declare function estimateProgressSummaries(files: string[], opts?: ProgressOptions): ProgressSummaryEstimate;
146
+ /** "the Desktop app", "the SDK or -p": a host as a person knows it. */
147
+ export declare function hostName(entrypoint: string): string;
148
+ export {};