context-doctor 0.46.0 → 0.48.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 (68) hide show
  1. package/README.md +9 -4
  2. package/dist/ab.d.ts +51 -3
  3. package/dist/ab.js +71 -28
  4. package/dist/abclaude.d.ts +167 -0
  5. package/dist/abclaude.js +511 -0
  6. package/dist/abstore.d.ts +46 -0
  7. package/dist/abstore.js +58 -0
  8. package/dist/autopilot.js +9 -5
  9. package/dist/blob.js +66 -12
  10. package/dist/budget.d.ts +8 -2
  11. package/dist/budget.js +30 -7
  12. package/dist/ci.js +2 -1
  13. package/dist/claudeplugin.d.ts +97 -0
  14. package/dist/claudeplugin.js +142 -0
  15. package/dist/cli.js +128 -36
  16. package/dist/compactcost.d.ts +74 -0
  17. package/dist/compactcost.js +115 -0
  18. package/dist/cursor.js +2 -0
  19. package/dist/doctor.js +90 -18
  20. package/dist/extract.js +4 -3
  21. package/dist/fanout.d.ts +15 -0
  22. package/dist/fanout.js +30 -9
  23. package/dist/firstfix.d.ts +43 -0
  24. package/dist/firstfix.js +80 -0
  25. package/dist/fix.d.ts +53 -4
  26. package/dist/fix.js +101 -13
  27. package/dist/httpguard.d.ts +13 -0
  28. package/dist/httpguard.js +22 -0
  29. package/dist/install.d.ts +21 -9
  30. package/dist/install.js +213 -40
  31. package/dist/limits.d.ts +5 -0
  32. package/dist/limits.js +26 -2
  33. package/dist/mcp.d.ts +4 -0
  34. package/dist/mcp.js +142 -97
  35. package/dist/mcpclient.js +73 -42
  36. package/dist/missledger.js +5 -3
  37. package/dist/mod/api.d.ts +8 -2
  38. package/dist/mod/api.js +2 -2
  39. package/dist/mod/logic.d.ts +13 -1
  40. package/dist/mod/logic.js +24 -2
  41. package/dist/mod/register.d.ts +2 -0
  42. package/dist/mod/register.js +19 -5
  43. package/dist/modelids.d.ts +62 -3
  44. package/dist/modelids.js +156 -8
  45. package/dist/modelswitch.js +8 -4
  46. package/dist/modmeasure.js +13 -1
  47. package/dist/orgrates.d.ts +18 -0
  48. package/dist/orgrates.js +51 -2
  49. package/dist/pack.d.ts +13 -0
  50. package/dist/pack.js +38 -2
  51. package/dist/preferences.js +2 -1
  52. package/dist/pricing.d.ts +8 -0
  53. package/dist/pricing.js +30 -2
  54. package/dist/progresssummaries.d.ts +148 -0
  55. package/dist/progresssummaries.js +248 -0
  56. package/dist/proxy.d.ts +1 -1
  57. package/dist/proxy.js +1 -1
  58. package/dist/prune.d.ts +8 -0
  59. package/dist/prune.js +11 -1
  60. package/dist/spend.d.ts +34 -0
  61. package/dist/spend.js +48 -4
  62. package/dist/subagentmodel.d.ts +12 -0
  63. package/dist/subagentmodel.js +17 -4
  64. package/dist/subagentpay.d.ts +8 -0
  65. package/dist/subagentpay.js +8 -1
  66. package/dist/toolcwd.d.ts +14 -0
  67. package/dist/toolcwd.js +17 -0
  68. package/package.json +6 -3
@@ -18,7 +18,7 @@
18
18
  import { appendFileSync, closeSync, existsSync, mkdirSync, openSync, readFileSync, readSync, statSync, writeFileSync } from "node:fs";
19
19
  import { dirname, join } from "node:path";
20
20
  import { statePath } from "./ledger.js";
21
- import { CACHE_WRITE_1H, CACHE_WRITE_5M, pricingFor } from "./pricing.js";
21
+ import { CACHE_WRITE_1H, CACHE_WRITE_5M, rateCard, writePerM } from "./pricing.js";
22
22
  /** Beside the limits log: ~/.claude/.context-doctor-misses.jsonl. */
23
23
  export function missLogPath() {
24
24
  return join(dirname(statePath()), ".context-doctor-misses.jsonl");
@@ -174,9 +174,11 @@ export function diagnosedMisses(since = 0, path = missLogPath()) {
174
174
  // status line runs, the line names the cause of the last one only, so
175
175
  // its share of the tokens goes to that cause and the rest to "unseen".
176
176
  const k = Math.max(1, prev && l.n >= prev.n ? l.n - prev.n : l.n);
177
- const price = pricingFor(l.m);
177
+ // At the rates the rest of the report prices with (rateCard, as requestCost): the
178
+ // organization's when set (its own cache-write rate), the price of the miss's day.
179
+ const price = rateCard(l.m, undefined, l.at * 1000)?.rates;
178
180
  // No ttl recorded: Claude Code's default, 5 minutes (as the status line prices it).
179
- const perToken = price ? (price.inputPerM * (l.ttl === "1h" ? CACHE_WRITE_1H : CACHE_WRITE_5M) - price.cacheReadPerM) / 1e6 : 0;
181
+ const perToken = price ? (writePerM(price, l.ttl === "1h" ? CACHE_WRITE_1H : CACHE_WRITE_5M) - price.cacheReadPerM) / 1e6 : 0;
180
182
  misses += k;
181
183
  tokens += tok;
182
184
  extraUsd += tok * perToken;
package/dist/mod/api.d.ts CHANGED
@@ -6,8 +6,8 @@
6
6
  * declarations Claude Code 2.1.321 writes (`claude-code.d.ts`): `$.process.run`,
7
7
  * `$.session.{id,model,compact}`, `$.ui.{open,resolve,invalidate,toast}`,
8
8
  * `$.command.register`, `$.clock.{now,every}`, `$.env.get`, `$.plugin.root`,
9
- * and the events `session.start`, `session.measure`, `command.run`,
10
- * `ui.render`. A subset, structurally compatible: no runtime code.
9
+ * and the events `session.start`, `session.measure`, `session.end`,
10
+ * `command.run`, `ui.render`. A subset, structurally compatible: no runtime code.
11
11
  */
12
12
  export type Surface = "terminal" | "desktop" | "vscode" | "mobile";
13
13
  export interface RateLimit {
@@ -114,6 +114,12 @@ export interface On {
114
114
  (event: "session.measure", hook: Hook<MeasureEvent, {
115
115
  changed: string[];
116
116
  }>): unknown;
117
+ (event: "session.end", hook: Hook<{
118
+ reason: string;
119
+ sessionId: string;
120
+ }, {
121
+ sessionId: string;
122
+ }>): unknown;
117
123
  (event: "command.run", matcher: {
118
124
  command: string;
119
125
  }, hook: Hook<{
package/dist/mod/api.js CHANGED
@@ -6,7 +6,7 @@
6
6
  * declarations Claude Code 2.1.321 writes (`claude-code.d.ts`): `$.process.run`,
7
7
  * `$.session.{id,model,compact}`, `$.ui.{open,resolve,invalidate,toast}`,
8
8
  * `$.command.register`, `$.clock.{now,every}`, `$.env.get`, `$.plugin.root`,
9
- * and the events `session.start`, `session.measure`, `command.run`,
10
- * `ui.render`. A subset, structurally compatible: no runtime code.
9
+ * and the events `session.start`, `session.measure`, `session.end`,
10
+ * `command.run`, `ui.render`. A subset, structurally compatible: no runtime code.
11
11
  */
12
12
  export {};
@@ -50,8 +50,20 @@ export type Band = {
50
50
  text: string;
51
51
  compact: string;
52
52
  };
53
- /** The band shows within this long of the cache going cold. */
53
+ /** The band shows within this long of the cache going cold... */
54
54
  export declare const WARN_BEFORE_MS: number;
55
+ /**
56
+ * ...or within this share of the cache's life, when that is shorter: the last
57
+ * minute of a 5-minute cache (WARN_BEFORE_MS would be all of it, the band
58
+ * after every turn), the last five of the 1-hour cache.
59
+ */
60
+ export declare const WARN_SHARE: number;
61
+ /** How long before the cache goes cold the band warns, for a cache that lives `ttlMs`. */
62
+ export declare function warnBeforeMs(ttlMs: number): number;
63
+ /** The session price thresholds when the CLI cannot say them (no Node): the defaults, the environment's own, or none. */
64
+ export declare const DEFAULT_THRESHOLDS: number[];
65
+ /** CONTEXT_DOCTOR_SESSION_PRICE and CONTEXT_DOCTOR_NO_SESSION_PRICE read as sessionprice.ts reads them. */
66
+ export declare function thresholdsFrom(raw: string | undefined, off: string | undefined): number[];
55
67
  /** "$0.42", "$3.10", "$112", "$1,240". */
56
68
  export declare function money(n: number): string;
57
69
  /** "820", "45k", "520k", "1.2M". */
package/dist/mod/logic.js CHANGED
@@ -8,9 +8,31 @@
8
8
  * `fix --apply`, `fix undo`), the same code as in a terminal. The node test
9
9
  * suite exercises these functions directly.
10
10
  */
11
- /** The band shows within this long of the cache going cold. */
11
+ /** The band shows within this long of the cache going cold... */
12
12
  export const WARN_BEFORE_MS = 5 * 60_000;
13
13
  const MIN = 60_000;
14
+ /**
15
+ * ...or within this share of the cache's life, when that is shorter: the last
16
+ * minute of a 5-minute cache (WARN_BEFORE_MS would be all of it, the band
17
+ * after every turn), the last five of the 1-hour cache.
18
+ */
19
+ export const WARN_SHARE = 1 / 5;
20
+ /** How long before the cache goes cold the band warns, for a cache that lives `ttlMs`. */
21
+ export function warnBeforeMs(ttlMs) {
22
+ return Math.min(WARN_BEFORE_MS, ttlMs * WARN_SHARE);
23
+ }
24
+ /** The session price thresholds when the CLI cannot say them (no Node): the defaults, the environment's own, or none. */
25
+ export const DEFAULT_THRESHOLDS = [25, 100, 500];
26
+ /** CONTEXT_DOCTOR_SESSION_PRICE and CONTEXT_DOCTOR_NO_SESSION_PRICE read as sessionprice.ts reads them. */
27
+ export function thresholdsFrom(raw, off) {
28
+ if (off === "1")
29
+ return [];
30
+ const text = raw?.trim();
31
+ if (!text)
32
+ return DEFAULT_THRESHOLDS;
33
+ const set = text.split(/[\s,]+/).map((v) => Number(v.replace(/^\$/, ""))).filter((v) => Number.isFinite(v) && v > 0);
34
+ return set.length ? [...new Set(set)].sort((a, b) => a - b) : DEFAULT_THRESHOLDS;
35
+ }
14
36
  /** "$0.42", "$3.10", "$112", "$1,240". */
15
37
  export function money(n) {
16
38
  if (!Number.isFinite(n))
@@ -95,7 +117,7 @@ export function band(d, now, surface, opts = {}) {
95
117
  if (now >= expiresAt && (big || opts.always)) {
96
118
  return show({ kind: "expired", key: `expired:${d.lastReplyAt}`, text: `context-doctor: the cache expired, so your next message re-writes ${rewrite}${tail}` });
97
119
  }
98
- if (now < expiresAt && (opts.always || (big && expiresAt - now <= WARN_BEFORE_MS))) {
120
+ if (now < expiresAt && (opts.always || (big && expiresAt - now <= warnBeforeMs(d.ttlMs)))) {
99
121
  return show({ kind: "warm", key: `warm:${d.lastReplyAt}`, text: `context-doctor: cache warm for ${duration(expiresAt - now)}, then your next message re-writes ${rewrite}${tail}` });
100
122
  }
101
123
  }
@@ -36,6 +36,8 @@ export declare const PANE = "context-doctor-fix";
36
36
  interface State {
37
37
  off: boolean;
38
38
  always: boolean;
39
+ /** The session price thresholds in force, for when the CLI cannot say them (no Node). */
40
+ thresholds: number[];
39
41
  data?: BandData;
40
42
  hidden: Set<string>;
41
43
  drawn: string;
@@ -28,7 +28,7 @@
28
28
  * reads which calls a module makes from its source: `$` is passed only to
29
29
  * functions declared at the top of this file.
30
30
  */
31
- import { applyOutcome, band, fixArgv, MODEL_CHANGE, outcome, paneRows, parsePlan, withPresses } from "./logic.js";
31
+ import { applyOutcome, band, DEFAULT_THRESHOLDS, fixArgv, MODEL_CHANGE, outcome, paneRows, parsePlan, thresholdsFrom, withPresses } from "./logic.js";
32
32
  export const COMMAND = "context-doctor-fix";
33
33
  export const PANE = "context-doctor-fix";
34
34
  /** How often the band checks whether its text changed (a countdown in minutes). */
@@ -36,7 +36,7 @@ const TICK_MS = 30_000;
36
36
  /** `fix` measures 30 days of history: give it time. */
37
37
  const FIX_TIMEOUT_MS = 10 * 60_000;
38
38
  const MEASURE_TIMEOUT_MS = 30_000;
39
- const fresh = () => ({ off: false, always: false, hidden: new Set(), drawn: "", compacting: false, loading: false, presses: new Map() });
39
+ const fresh = () => ({ off: false, always: false, thresholds: DEFAULT_THRESHOLDS, hidden: new Set(), drawn: "", compacting: false, loading: false, presses: new Map() });
40
40
  let S = fresh();
41
41
  /** For tests: the state the hooks share. */
42
42
  export const state = () => S;
@@ -54,7 +54,7 @@ function bandKey(now, surface) {
54
54
  }
55
55
  /** Hand the reading to the CLI; with no CLI (no node on PATH), keep what Claude Code said. */
56
56
  async function measure($, e) {
57
- const fallback = { at: await $.clock.now(), coldMinTokens: 150_000, thresholds: [25, 100, 500], ...(e.cost ? { ccUsd: e.cost.usd } : {}) };
57
+ const fallback = { at: await $.clock.now(), coldMinTokens: 150_000, thresholds: S.thresholds, ...(e.cost ? { ccUsd: e.cost.usd } : {}) };
58
58
  try {
59
59
  const sessionId = await $.session.id();
60
60
  const cwd = await $.session.cwd();
@@ -94,8 +94,10 @@ async function compact($) {
94
94
  catch { /* the count is a nicety */ }
95
95
  }
96
96
  }
97
- catch {
98
- $.ui.toast("context-doctor: Claude Code is busy; compact once the turn ends.");
97
+ catch (err) {
98
+ // Claude Code rejects a compaction while a turn runs, and for its own reasons (nothing to compact, a failed summary): say which.
99
+ const why = err instanceof Error && err.message.trim() ? err.message.trim() : typeof err === "string" && err.trim() ? err.trim() : "";
100
+ $.ui.toast(why ? `context-doctor: not compacted: ${why}` : "context-doctor: not compacted; Claude Code may be busy: compact once the turn ends.");
99
101
  }
100
102
  finally {
101
103
  S.compacting = false;
@@ -166,6 +168,7 @@ export function register(on) {
166
168
  try {
167
169
  S.off = (await $.env.get("CONTEXT_DOCTOR_NO_MOD")) === "1";
168
170
  S.always = (await $.env.get("CONTEXT_DOCTOR_MOD_BAND")) === "always";
171
+ S.thresholds = thresholdsFrom(await $.env.get("CONTEXT_DOCTOR_SESSION_PRICE"), await $.env.get("CONTEXT_DOCTOR_NO_SESSION_PRICE"));
169
172
  if (!S.off) {
170
173
  await $.command.register({ name: "context-doctor-fix", description: "context-doctor: the fix plan, with an Apply and an Undo button per lever (nothing applies without a press)" });
171
174
  $.clock.every(TICK_MS, () => void tick($));
@@ -184,6 +187,17 @@ export function register(on) {
184
187
  $.ui.invalidate("ui.render");
185
188
  return r;
186
189
  });
190
+ // A `/clear` or a resume ends this session and the process goes on under another, with no
191
+ // session.start for it: the band's figures were the old session's, and its Compact first button
192
+ // would compact the new one on them. Nothing is shown until the next turn measures the new one.
193
+ on("session.end", async ($, e, next) => {
194
+ S.data = undefined;
195
+ try {
196
+ $.ui.invalidate("ui.render");
197
+ }
198
+ catch { /* ending anyway */ }
199
+ return next(e);
200
+ });
187
201
  on("ui.render", { component: "AbovePrompt" }, async ($, e, next) => {
188
202
  if (S.off || e.props.hasSurvey)
189
203
  return next(e);
@@ -1,4 +1,9 @@
1
1
  /**
2
+ * The models a source names, to check each has a price of its own. Claude's
3
+ * below; OpenAI's and Google's price pages, Codex's model catalog and Gemini
4
+ * CLI's model list after them (openaiPageIds...), and the table's own dated
5
+ * rows (datedRows, dueRows). All read by scripts/check-models.mjs.
6
+ *
2
7
  * The Claude models a text names, to check each has a price of its own
3
8
  * (pricing.ts hasKnownPrice) before a user runs it: Claude Code ships a
4
9
  * model days before a context-doctor release (2.1.322 made Fable 5.2 the
@@ -11,9 +16,10 @@
11
16
  * `us.anthropic.claude-sonnet-4-5-20250929-v1:0`), the catalog's cleanest
12
17
  * list; first-party ids of the current naming (`claude-fable-5-2`); and
13
18
  * display names (`Claude Fable 5.2`), which is how the price page names
14
- * them. First-party and display names count from major version 4 (the
15
- * naming the table keys on): older aliases Claude Code still accepts
16
- * (`claude-haiku-3-5`, `claude-sonnet-3-7`) are not ids anything bills.
19
+ * them. First-party and display names of the known families count from
20
+ * major version 4 (the naming the table keys on): older aliases Claude Code
21
+ * still accepts (`claude-haiku-3-5`, `claude-sonnet-3-7`) are not ids
22
+ * anything bills. A family the table does not know counts from version 1.
17
23
  */
18
24
  /** Ids that have no price on purpose, with the reason. */
19
25
  export declare const UNPRICED_ON_PURPOSE: Record<string, string>;
@@ -21,3 +27,56 @@ export declare const UNPRICED_ON_PURPOSE: Record<string, string>;
21
27
  export declare function claudeModelIds(text: string): string[];
22
28
  /** The Claude models `text` names that have no price of their own and no reason to lack one. */
23
29
  export declare function unpricedClaudeIds(text: string): string[];
30
+ /** The ids in `ids` that have no price of their own and no reason to lack one. */
31
+ export declare function unpriced(ids: string[]): string[];
32
+ /**
33
+ * The models OpenAI's price page (developers.openai.com/api/docs/pricing,
34
+ * its .md) lists in its text tables: each table row's model cell (the first,
35
+ * or the second where the first is a category), the context-length notes
36
+ * dropped. Tables with a Modality or Use case column (images, audio,
37
+ * transcription) and the tools table are not models priced by the token.
38
+ */
39
+ export declare function openaiPageIds(markdown: string): string[];
40
+ /**
41
+ * The models Google's price page (ai.google.dev/gemini-api/docs/pricing, its
42
+ * .md.txt) prices: each section's model id line (`*[\`gemini-4-argon\`](...)*`),
43
+ * the text models only.
44
+ */
45
+ export declare function googlePageIds(markdown: string): string[];
46
+ /**
47
+ * The models Codex offers (its models catalog, codex-rs/models-manager/
48
+ * models.json): `listed` are the ones its picker shows, `hidden` the rest
49
+ * (internal and trusted-access ids, which the price page may not name).
50
+ */
51
+ export declare function codexModelIds(json: string): {
52
+ listed: string[];
53
+ hidden: string[];
54
+ };
55
+ /**
56
+ * The Gemini models Gemini CLI names (packages/core/src/config/models.ts):
57
+ * every quoted full model id (a version and a Pro/Flash/Flash-Lite name),
58
+ * not family prefixes like 'gemini-3' or the embedding model.
59
+ */
60
+ export declare function geminiCliIds(source: string): string[];
61
+ /** A dated pricing.ts row: the model it prices, the day its price changes, and whether the page gave what follows. */
62
+ export interface DatedRow {
63
+ id: string;
64
+ changes: string;
65
+ successor: boolean;
66
+ }
67
+ /**
68
+ * The rows of pricing.ts's table (its source, `src/pricing.ts`) whose price
69
+ * ends on a known day (`changes`), each with whether the page said what
70
+ * follows (`then`, or `routes`: billed as another model from that day).
71
+ * Throws on a dated row it cannot name, so the check cannot pass by missing one.
72
+ */
73
+ export declare function datedRows(pricingSource: string): DatedRow[];
74
+ /**
75
+ * The dated rows with no successor price whose last day at that price (the
76
+ * day before `changes`) is at most `days` days after `today`, or already
77
+ * past: from then, every install prices that model as an estimate, so the
78
+ * page needs reading again (and the successor price adding, once published).
79
+ */
80
+ export declare function dueRows(rows: DatedRow[], today: string, days?: number): Array<DatedRow & {
81
+ daysLeft: number;
82
+ }>;
package/dist/modelids.js CHANGED
@@ -1,4 +1,9 @@
1
1
  /**
2
+ * The models a source names, to check each has a price of its own. Claude's
3
+ * below; OpenAI's and Google's price pages, Codex's model catalog and Gemini
4
+ * CLI's model list after them (openaiPageIds...), and the table's own dated
5
+ * rows (datedRows, dueRows). All read by scripts/check-models.mjs.
6
+ *
2
7
  * The Claude models a text names, to check each has a price of its own
3
8
  * (pricing.ts hasKnownPrice) before a user runs it: Claude Code ships a
4
9
  * model days before a context-doctor release (2.1.322 made Fable 5.2 the
@@ -11,15 +16,35 @@
11
16
  * `us.anthropic.claude-sonnet-4-5-20250929-v1:0`), the catalog's cleanest
12
17
  * list; first-party ids of the current naming (`claude-fable-5-2`); and
13
18
  * display names (`Claude Fable 5.2`), which is how the price page names
14
- * them. First-party and display names count from major version 4 (the
15
- * naming the table keys on): older aliases Claude Code still accepts
16
- * (`claude-haiku-3-5`, `claude-sonnet-3-7`) are not ids anything bills.
19
+ * them. First-party and display names of the known families count from
20
+ * major version 4 (the naming the table keys on): older aliases Claude Code
21
+ * still accepts (`claude-haiku-3-5`, `claude-sonnet-3-7`) are not ids
22
+ * anything bills. A family the table does not know counts from version 1.
17
23
  */
18
24
  import { hasKnownPrice } from "./pricing.js";
25
+ /** The families the table keys on: their ids and names count from major version 4. */
19
26
  const FAMILY = "opus|sonnet|haiku|fable|mythos";
27
+ /**
28
+ * Words that follow "claude-" or "Claude " with a number and are not a model
29
+ * family: products, plans, apps, test ids (`claude-eval-9` is in the 2.1.321
30
+ * binary). Any other word with a version is a model, a family new to the
31
+ * table included: Fable and Mythos were new families once, and an id of a
32
+ * family the table does not know has no price at all, not even a family's.
33
+ */
34
+ const NOT_A_FAMILY = new Set(["code", "eval", "agent", "agents", "desktop", "app", "apps", "api", "cli", "sdk", "tag", "chrome", "max", "pro", "team", "enterprise", "gov", "console", "platform", "models", "cowork", "design", "for", "in", "on", "and", "is", "the"]);
35
+ const family = (word, major) => {
36
+ const f = word.toLowerCase();
37
+ if (new RegExp(`^(?:${FAMILY})$`).test(f))
38
+ return Number(major) >= 4;
39
+ return !NOT_A_FAMILY.has(f) && Number(major) >= 1;
40
+ };
20
41
  /** Ids that have no price on purpose, with the reason. */
21
42
  export const UNPRICED_ON_PURPOSE = {
22
43
  "claude-mythos-preview": "no list price on the page; priced by the Fable/Mythos family row as an estimate",
44
+ // Gemini CLI names these (packages/core/src/config/models.ts, read
45
+ // 2026-11-14); Google's price page does not, so there is no price to copy.
46
+ "gemini-3-pro-preview": "Gemini CLI's preview model, not on Google's price page (2026-11-14); the 3.x Pro fallback prices it at 3.1 Pro's rates, an estimate",
47
+ "gemini-3.5-flash": "Gemini CLI's base Flash, not on Google's price page (2026-11-14; Gemini CLI rewrites it to gemini-3.8-flash once that is GA); the 3.x Flash fallback prices it at 3.8 Flash's rates, an estimate",
23
48
  };
24
49
  /** The model a Bedrock id names, as a first-party id: region prefix, `-v1:0` and the date dropped. */
25
50
  function fromBedrock(id) {
@@ -31,13 +56,13 @@ export function claudeModelIds(text) {
31
56
  // A model's Bedrock id has a version number (com.anthropic.claude-code, an app id, has none).
32
57
  for (const m of text.matchAll(/(?<![\w.-])(?:(?:us|eu|apac|global|au|jp|ca|us-gov)\.)?anthropic\.(claude-[a-z0-9-]*?\d[a-z0-9-]*?)(?:-v\d+(?::\d+)?)?(?![\w.-]*\w)/g))
33
58
  out.add(fromBedrock(m[1]));
34
- for (const m of text.matchAll(new RegExp(`(?<![\\w.-])claude-(${FAMILY})-(\\d{1,2})(?:-(\\d{1,2}))?(?:-\\d{8})?(?![\\w-])`, "g"))) {
35
- if (Number(m[2]) < 4)
59
+ for (const m of text.matchAll(/(?<![\w.-])claude-([a-z]+)-(\d{1,2})(?:-(\d{1,2}))?(?:-\d{8})?(?![\w-])/g)) {
60
+ if (!family(m[1], m[2]))
36
61
  continue;
37
62
  out.add(`claude-${m[1]}-${m[2]}${m[3] && m[3] !== "0" ? `-${m[3]}` : ""}`);
38
63
  }
39
- for (const m of text.matchAll(new RegExp(`\\bClaude (${FAMILY.replace(/\b\w/g, (c) => c.toUpperCase())}) (\\d{1,2})(?:\\.(\\d{1,2}))?(?![\\w.]*\\d)`, "g"))) {
40
- if (Number(m[2]) < 4)
64
+ for (const m of text.matchAll(/\bClaude ([A-Z][a-z]+) (\d{1,2})(?:\.(\d{1,2}))?(?![\w.]*\d)/g)) {
65
+ if (!family(m[1], m[2]))
41
66
  continue;
42
67
  out.add(`claude-${m[1].toLowerCase()}-${m[2]}${m[3] && m[3] !== "0" ? `-${m[3]}` : ""}`);
43
68
  }
@@ -45,5 +70,128 @@ export function claudeModelIds(text) {
45
70
  }
46
71
  /** The Claude models `text` names that have no price of their own and no reason to lack one. */
47
72
  export function unpricedClaudeIds(text) {
48
- return claudeModelIds(text).filter((id) => !hasKnownPrice(id) && !(id in UNPRICED_ON_PURPOSE));
73
+ return unpriced(claudeModelIds(text));
74
+ }
75
+ /** The ids in `ids` that have no price of their own and no reason to lack one. */
76
+ export function unpriced(ids) {
77
+ return ids.filter((id) => !hasKnownPrice(id) && !(id in UNPRICED_ON_PURPOSE));
78
+ }
79
+ /**
80
+ * Models priced per image, per minute or per character, or not by the token
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
83
+ * on the free tier only): the table has no row for them on purpose
84
+ * (pricing.ts header). Matched anywhere in the id.
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;
87
+ /**
88
+ * The models OpenAI's price page (developers.openai.com/api/docs/pricing,
89
+ * its .md) lists in its text tables: each table row's model cell (the first,
90
+ * or the second where the first is a category), the context-length notes
91
+ * dropped. Tables with a Modality or Use case column (images, audio,
92
+ * transcription) and the tools table are not models priced by the token.
93
+ */
94
+ export function openaiPageIds(markdown) {
95
+ const out = new Set();
96
+ let header;
97
+ for (const line of markdown.split("\n")) {
98
+ if (!line.startsWith("|")) {
99
+ header = undefined;
100
+ continue;
101
+ }
102
+ const cells = line.split("|").slice(1, -1).map((c) => c.trim());
103
+ if (!header) {
104
+ header = cells.map((c) => c.toLowerCase());
105
+ continue;
106
+ }
107
+ if (cells.every((c) => /^-+$/.test(c)))
108
+ continue;
109
+ if (header.includes("modality") || header.includes("use case") || header[0] === "tool")
110
+ continue;
111
+ const at = header.indexOf("model");
112
+ if (at === -1)
113
+ continue;
114
+ const name = cells[at]?.replace(/\s*\(.*\)\s*$/, "").replace(/<[^>]*>/g, "").trim();
115
+ if (name && /^[a-z][a-z0-9.-]*$/.test(name) && !NOT_A_TEXT_MODEL.test(name))
116
+ out.add(name);
117
+ }
118
+ return [...out].sort();
119
+ }
120
+ /**
121
+ * The models Google's price page (ai.google.dev/gemini-api/docs/pricing, its
122
+ * .md.txt) prices: each section's model id line (`*[\`gemini-4-argon\`](...)*`),
123
+ * the text models only.
124
+ */
125
+ export function googlePageIds(markdown) {
126
+ const out = new Set();
127
+ for (const m of markdown.matchAll(/^\s*\*\[`([a-z][a-z0-9.-]*)`\]/gm))
128
+ if (!NOT_A_TEXT_MODEL.test(m[1]))
129
+ out.add(m[1]);
130
+ return [...out].sort();
131
+ }
132
+ /**
133
+ * The models Codex offers (its models catalog, codex-rs/models-manager/
134
+ * models.json): `listed` are the ones its picker shows, `hidden` the rest
135
+ * (internal and trusted-access ids, which the price page may not name).
136
+ */
137
+ export function codexModelIds(json) {
138
+ const models = JSON.parse(json).models ?? [];
139
+ const listed = new Set();
140
+ const hidden = new Set();
141
+ for (const m of models)
142
+ if (typeof m.slug === "string")
143
+ (m.visibility === "list" ? listed : hidden).add(m.slug);
144
+ return { listed: [...listed].sort(), hidden: [...hidden].sort() };
145
+ }
146
+ /**
147
+ * The Gemini models Gemini CLI names (packages/core/src/config/models.ts):
148
+ * every quoted full model id (a version and a Pro/Flash/Flash-Lite name),
149
+ * not family prefixes like 'gemini-3' or the embedding model.
150
+ */
151
+ export function geminiCliIds(source) {
152
+ const out = new Set();
153
+ for (const m of source.matchAll(/['"`](gemini-\d[\d.]*-(?:pro|flash)[a-z0-9.-]*)['"`]/g))
154
+ if (!NOT_A_TEXT_MODEL.test(m[1]))
155
+ out.add(m[1]);
156
+ return [...out].sort();
157
+ }
158
+ /** One way of naming a pricing.ts row, as a model id the row prices. */
159
+ function rowId(line) {
160
+ const named = /\[(?:openai|gemini)\("([^"]+)"\)/.exec(line);
161
+ if (named)
162
+ return named[1];
163
+ const c = /\[claude\("([a-z]+)[^"]*",\s*(\d+)(?:,\s*(\d+))?\)/.exec(line);
164
+ return c ? `claude-${c[1]}-${c[2]}${c[3] ? `-${c[3]}` : ""}` : undefined;
165
+ }
166
+ /**
167
+ * The rows of pricing.ts's table (its source, `src/pricing.ts`) whose price
168
+ * ends on a known day (`changes`), each with whether the page said what
169
+ * follows (`then`, or `routes`: billed as another model from that day).
170
+ * Throws on a dated row it cannot name, so the check cannot pass by missing one.
171
+ */
172
+ export function datedRows(pricingSource) {
173
+ const out = [];
174
+ for (const line of pricingSource.split("\n")) {
175
+ const day = /\bchanges:\s*"(\d{4}-\d{2}-\d{2})"/.exec(line);
176
+ if (!day || /^\s*(?:\/\/|\*)/.test(line))
177
+ continue;
178
+ const id = rowId(line);
179
+ if (!id)
180
+ throw new Error(`a dated row with no model name this check can read: ${line.trim()}`);
181
+ out.push({ id, changes: day[1], successor: /\bthen:|\broutes:/.test(line) });
182
+ }
183
+ return out;
184
+ }
185
+ /**
186
+ * The dated rows with no successor price whose last day at that price (the
187
+ * day before `changes`) is at most `days` days after `today`, or already
188
+ * past: from then, every install prices that model as an estimate, so the
189
+ * page needs reading again (and the successor price adding, once published).
190
+ */
191
+ export function dueRows(rows, today, days = 14) {
192
+ const t = Date.parse(`${today}T00:00:00Z`);
193
+ return rows
194
+ .filter((r) => !r.successor)
195
+ .map((r) => ({ ...r, daysLeft: Math.round((Date.parse(`${r.changes}T00:00:00Z`) - 864e5 - t) / 864e5) }))
196
+ .filter((r) => r.daysLeft <= days);
49
197
  }
@@ -34,7 +34,7 @@ import { spawnSync } from "node:child_process";
34
34
  import { existsSync, readdirSync, readFileSync, realpathSync, statSync } from "node:fs";
35
35
  import { homedir } from "node:os";
36
36
  import { delimiter, dirname, join } from "node:path";
37
- import { CACHE_WRITE_1H, CACHE_WRITE_5M, formatUsd, pricingFor } from "./pricing.js";
37
+ import { CACHE_WRITE_1H, CACHE_WRITE_5M, formatUsd, rateCard, ratesAt, writePerM } from "./pricing.js";
38
38
  import { formatTokens } from "./tokens.js";
39
39
  import { tailUsage } from "./statusline.js";
40
40
  /** The first Claude Code that runs PreModelSwitch hooks (hooks docs). */
@@ -63,13 +63,17 @@ export function modelSwitchMessage(input) {
63
63
  return undefined;
64
64
  const oneHour = input.cache_ttl === "1h";
65
65
  const writeMult = oneHour ? CACHE_WRITE_1H : CACHE_WRITE_5M;
66
- const toPrice = pricingFor(bare(to));
67
- const fromPrice = from ? pricingFor(bare(from)) : undefined;
66
+ // Each model's rates as the next request bills this context (rateCard, as every report prices):
67
+ // its prompt's tier (Haiku 5.5 over 100k), fast mode and US-only as the last request recorded,
68
+ // the organization's rates where set, the price of today.
69
+ const at = (model) => { const c = rateCard(bare(model), live?.billing); return c && ratesAt(c, tokens); };
70
+ const toPrice = at(to);
71
+ const fromPrice = from ? at(from) : undefined;
68
72
  const size = `~${formatTokens(tokens)}-token`;
69
73
  if (!toPrice) {
70
74
  return `context-doctor: switching to ${to} writes this session's ${size} context into its own cache once (no known price for ${to}); the next request on ${from ?? "the current model"} would read it from cache instead.`;
71
75
  }
72
- const writeUsd = (tokens / 1e6) * toPrice.inputPerM * writeMult;
76
+ const writeUsd = (tokens / 1e6) * writePerM(toPrice, writeMult);
73
77
  const stay = fromPrice ? `, where the next request on ${from} would read it for ${formatUsd((tokens / 1e6) * fromPrice.cacheReadPerM)}` : "";
74
78
  return (`context-doctor: switching to ${to} re-writes this session's ${size} context into its cache: ` +
75
79
  `about ${formatUsd(writeUsd)} once at the ${oneHour ? "1-hour" : "5-minute"} cache-write rate${stay}. ` +
@@ -195,6 +195,18 @@ export function costGaps(lines) {
195
195
  .filter((l) => l.cc >= MIN_COMPARE_USD)
196
196
  .map((l) => ({ sid: l.sid, ts: l.ts, cc: l.cc, cd: l.cd, gap: (l.cd - l.cc) / l.cc, ...(l.model ? { model: l.model } : {}), ...(l.unpriced ? { unpriced: l.unpriced } : {}) }));
197
197
  }
198
+ /**
199
+ * What a gap can come from, by its sign. Ours below Claude Code's: requests
200
+ * the transcript keeps no usage for, which Claude Code's ledger holds as
201
+ * billed and context-doctor estimates (a compaction's own request:
202
+ * compactcost.ts) or leaves out (subagent progress summaries:
203
+ * progresssummaries.ts), a model with no price, rates from MDM or server-managed
204
+ * settings.
205
+ * Ours above: a price in context-doctor's table, or contracted rates it
206
+ * does not read.
207
+ */
208
+ const UNDER = "Claude Code's figure holds as billed what the transcript keeps no usage for and context-doctor only estimates (a compaction's own request: its thinking, its instruction) or leaves out (a background subagent's progress summaries in a terminal session, which context-doctor spend estimates beside its total); a model with no price, or contracted rates set by an MDM profile or server-managed settings (context-doctor reads modelPricing from the managed settings files only), show up here too";
209
+ const OVER = "A price in context-doctor's table that is off, or contracted rates set by an MDM profile or server-managed settings (context-doctor reads modelPricing from the managed settings files only), show up here";
198
210
  const pct = (x) => `${x >= 0 ? "+" : ""}${(x * 100).toFixed(Math.abs(x) < 0.1 ? 1 : 0)}%`;
199
211
  /**
200
212
  * `doctor`'s line: how close our session price is to Claude Code's own cost,
@@ -213,7 +225,7 @@ export function costCheck(days = 30, now = Date.now(), path = costLogPath()) {
213
225
  if (within === n)
214
226
  return { label, status: "ok", detail: `${head} (largest gap ${pct(worst.gap)})` };
215
227
  const why = worst.unpriced ? `, ${worst.unpriced} request${worst.unpriced === 1 ? "" : "s"} with no list price` : "";
216
- return { label, status: "warn", detail: `${head}; the largest gap is ${pct(worst.gap)} ($${worst.cd.toFixed(2)} against $${worst.cc.toFixed(2)}${worst.model ? `, on ${worst.model}` : ""}${why}). A price missing from context-doctor's table, or contracted rates Claude Code applies (modelPricing), show up here` };
228
+ return { label, status: "warn", detail: `${head}; the largest gap is ${pct(worst.gap)} ($${worst.cd.toFixed(2)} against $${worst.cc.toFixed(2)}${worst.model ? `, on ${worst.model}` : ""}${why}). ${worst.gap < 0 ? UNDER : OVER}` };
217
229
  }
218
230
  // -- The measure itself ---------------------------------------------------------------
219
231
  const num = (v) => (typeof v === "number" && Number.isFinite(v) && v >= 0 ? v : undefined);
@@ -73,3 +73,21 @@ export declare function priceBasis(plural?: boolean, env?: NodeJS.ProcessEnv): s
73
73
  * which files set them and what they are. Undefined at list prices.
74
74
  */
75
75
  export declare function orgRatesLine(env?: NodeJS.ProcessEnv): string | undefined;
76
+ /**
77
+ * The managed sources Claude Code reads before the managed settings files,
78
+ * found on this machine. Read from the 2.1.321 binary: the policy origin is
79
+ * server-managed settings when present, else an MDM profile (a macOS
80
+ * managed-preferences plist, the Windows HKLM policy key), else the files,
81
+ * and by default only the first source found counts ("first-wins"): with
82
+ * either of the others present, Claude Code prices at their modelPricing,
83
+ * or at list, never at the files'. context-doctor reads neither (the
84
+ * server-managed copy, `remote-settings.json` in Claude Code's folder, is an
85
+ * undocumented, signed cache); this only says that one is there. The
86
+ * Windows key is not looked up (it needs reg.exe).
87
+ */
88
+ export declare function managedSourcesAhead(env?: NodeJS.ProcessEnv, home?: string, prefs?: string): string[];
89
+ /**
90
+ * The line a report adds when Claude Code may take its rates from a source
91
+ * context-doctor does not read: undefined when none is on this machine.
92
+ */
93
+ export declare function managedSourcesLine(env?: NodeJS.ProcessEnv, home?: string, prefs?: string): string | undefined;
package/dist/orgrates.js CHANGED
@@ -24,8 +24,10 @@
24
24
  * order, nested blocks merged key by key). MDM profiles and
25
25
  * server-managed settings are not read.
26
26
  */
27
- import { readFileSync } from "node:fs";
28
- import { basename } from "node:path";
27
+ import { existsSync, readFileSync } from "node:fs";
28
+ import { userInfo } from "node:os";
29
+ import { basename, join } from "node:path";
30
+ import { claudeDir } from "./claudedir.js";
29
31
  import { managedSettingsPaths } from "./effective.js";
30
32
  const isObject = (v) => Boolean(v) && typeof v === "object" && !Array.isArray(v);
31
33
  /** Nested blocks merged key by key, the later value winning (Claude Code's rule for managed-settings.d). */
@@ -163,3 +165,50 @@ export function orgRatesLine(env = process.env) {
163
165
  ];
164
166
  return `Claude requests priced at your organization's rates (Claude Code's managed modelPricing: ${parts.join("; ")}; in ${r.sources.map((s) => basename(s)).join(", ")}), as Claude Code's own cost figures are; other providers at list prices.`;
165
167
  }
168
+ /**
169
+ * The managed sources Claude Code reads before the managed settings files,
170
+ * found on this machine. Read from the 2.1.321 binary: the policy origin is
171
+ * server-managed settings when present, else an MDM profile (a macOS
172
+ * managed-preferences plist, the Windows HKLM policy key), else the files,
173
+ * and by default only the first source found counts ("first-wins"): with
174
+ * either of the others present, Claude Code prices at their modelPricing,
175
+ * or at list, never at the files'. context-doctor reads neither (the
176
+ * server-managed copy, `remote-settings.json` in Claude Code's folder, is an
177
+ * undocumented, signed cache); this only says that one is there. The
178
+ * Windows key is not looked up (it needs reg.exe).
179
+ */
180
+ export function managedSourcesAhead(env = process.env, home, prefs = "/Library/Managed Preferences") {
181
+ if (env.CONTEXT_DOCTOR_NO_MANAGED_SETTINGS)
182
+ return [];
183
+ const out = [];
184
+ try {
185
+ const remote = join(claudeDir(home, env), "remote-settings.json");
186
+ if (existsSync(remote))
187
+ out.push(`server-managed settings (Claude Code's copy: ${remote})`);
188
+ }
189
+ catch { /* no config folder */ }
190
+ if (process.platform === "darwin") {
191
+ let user = "";
192
+ try {
193
+ user = userInfo().username;
194
+ }
195
+ catch { /* none */ }
196
+ for (const p of [...(user ? [join(prefs, user, "com.anthropic.claudecode.plist")] : []), join(prefs, "com.anthropic.claudecode.plist")]) {
197
+ if (existsSync(p)) {
198
+ out.push(`an MDM profile (${p})`);
199
+ break;
200
+ }
201
+ }
202
+ }
203
+ return out;
204
+ }
205
+ /**
206
+ * The line a report adds when Claude Code may take its rates from a source
207
+ * context-doctor does not read: undefined when none is on this machine.
208
+ */
209
+ export function managedSourcesLine(env = process.env, home, prefs) {
210
+ const ahead = managedSourcesAhead(env, home, prefs);
211
+ if (!ahead.length)
212
+ return undefined;
213
+ return `Claude Code takes its managed settings from ${ahead.join(" and ")} before the managed settings files, and only from the first it finds: its own cost figures may use contracted rates (modelPricing) set there, which context-doctor does not read; these reports price ${orgRates(env) ? "at the files' rates" : "at list rates"}.`;
214
+ }
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 {