context-doctor 0.46.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 (61) hide show
  1. package/README.md +7 -4
  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 +8 -2
  6. package/dist/budget.js +30 -7
  7. package/dist/ci.js +2 -1
  8. package/dist/claudeplugin.d.ts +97 -0
  9. package/dist/claudeplugin.js +142 -0
  10. package/dist/cli.js +109 -36
  11. package/dist/compactcost.d.ts +74 -0
  12. package/dist/compactcost.js +115 -0
  13. package/dist/cursor.js +2 -0
  14. package/dist/doctor.js +90 -18
  15. package/dist/extract.js +4 -3
  16. package/dist/fanout.d.ts +15 -0
  17. package/dist/fanout.js +30 -9
  18. package/dist/firstfix.d.ts +43 -0
  19. package/dist/firstfix.js +80 -0
  20. package/dist/fix.d.ts +46 -2
  21. package/dist/fix.js +95 -10
  22. package/dist/httpguard.d.ts +13 -0
  23. package/dist/httpguard.js +22 -0
  24. package/dist/install.d.ts +21 -9
  25. package/dist/install.js +211 -40
  26. package/dist/limits.d.ts +5 -0
  27. package/dist/limits.js +26 -2
  28. package/dist/mcp.js +60 -59
  29. package/dist/missledger.js +5 -3
  30. package/dist/mod/api.d.ts +8 -2
  31. package/dist/mod/api.js +2 -2
  32. package/dist/mod/logic.d.ts +13 -1
  33. package/dist/mod/logic.js +24 -2
  34. package/dist/mod/register.d.ts +2 -0
  35. package/dist/mod/register.js +19 -5
  36. package/dist/modelids.d.ts +4 -3
  37. package/dist/modelids.js +23 -7
  38. package/dist/modelswitch.js +8 -4
  39. package/dist/modmeasure.js +13 -1
  40. package/dist/orgrates.d.ts +18 -0
  41. package/dist/orgrates.js +51 -2
  42. package/dist/pack.d.ts +13 -0
  43. package/dist/pack.js +38 -2
  44. package/dist/preferences.js +2 -1
  45. package/dist/pricing.d.ts +8 -0
  46. package/dist/pricing.js +16 -0
  47. package/dist/progresssummaries.d.ts +148 -0
  48. package/dist/progresssummaries.js +248 -0
  49. package/dist/proxy.d.ts +1 -1
  50. package/dist/proxy.js +1 -1
  51. package/dist/prune.d.ts +8 -0
  52. package/dist/prune.js +11 -1
  53. package/dist/spend.d.ts +34 -0
  54. package/dist/spend.js +48 -4
  55. package/dist/subagentmodel.d.ts +12 -0
  56. package/dist/subagentmodel.js +17 -4
  57. package/dist/subagentpay.d.ts +8 -0
  58. package/dist/subagentpay.js +8 -1
  59. package/dist/toolcwd.d.ts +14 -0
  60. package/dist/toolcwd.js +17 -0
  61. package/package.json +1 -1
@@ -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);
@@ -11,9 +11,10 @@
11
11
  * `us.anthropic.claude-sonnet-4-5-20250929-v1:0`), the catalog's cleanest
12
12
  * list; first-party ids of the current naming (`claude-fable-5-2`); and
13
13
  * 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.
14
+ * them. First-party and display names of the known families count from
15
+ * major version 4 (the naming the table keys on): older aliases Claude Code
16
+ * still accepts (`claude-haiku-3-5`, `claude-sonnet-3-7`) are not ids
17
+ * anything bills. A family the table does not know counts from version 1.
17
18
  */
18
19
  /** Ids that have no price on purpose, with the reason. */
19
20
  export declare const UNPRICED_ON_PURPOSE: Record<string, string>;
package/dist/modelids.js CHANGED
@@ -11,12 +11,28 @@
11
11
  * `us.anthropic.claude-sonnet-4-5-20250929-v1:0`), the catalog's cleanest
12
12
  * list; first-party ids of the current naming (`claude-fable-5-2`); and
13
13
  * 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.
14
+ * them. First-party and display names of the known families count from
15
+ * major version 4 (the naming the table keys on): older aliases Claude Code
16
+ * still accepts (`claude-haiku-3-5`, `claude-sonnet-3-7`) are not ids
17
+ * anything bills. A family the table does not know counts from version 1.
17
18
  */
18
19
  import { hasKnownPrice } from "./pricing.js";
20
+ /** The families the table keys on: their ids and names count from major version 4. */
19
21
  const FAMILY = "opus|sonnet|haiku|fable|mythos";
22
+ /**
23
+ * Words that follow "claude-" or "Claude " with a number and are not a model
24
+ * family: products, plans, apps, test ids (`claude-eval-9` is in the 2.1.321
25
+ * binary). Any other word with a version is a model, a family new to the
26
+ * table included: Fable and Mythos were new families once, and an id of a
27
+ * family the table does not know has no price at all, not even a family's.
28
+ */
29
+ 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"]);
30
+ const family = (word, major) => {
31
+ const f = word.toLowerCase();
32
+ if (new RegExp(`^(?:${FAMILY})$`).test(f))
33
+ return Number(major) >= 4;
34
+ return !NOT_A_FAMILY.has(f) && Number(major) >= 1;
35
+ };
20
36
  /** Ids that have no price on purpose, with the reason. */
21
37
  export const UNPRICED_ON_PURPOSE = {
22
38
  "claude-mythos-preview": "no list price on the page; priced by the Fable/Mythos family row as an estimate",
@@ -31,13 +47,13 @@ export function claudeModelIds(text) {
31
47
  // A model's Bedrock id has a version number (com.anthropic.claude-code, an app id, has none).
32
48
  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
49
  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)
50
+ for (const m of text.matchAll(/(?<![\w.-])claude-([a-z]+)-(\d{1,2})(?:-(\d{1,2}))?(?:-\d{8})?(?![\w-])/g)) {
51
+ if (!family(m[1], m[2]))
36
52
  continue;
37
53
  out.add(`claude-${m[1]}-${m[2]}${m[3] && m[3] !== "0" ? `-${m[3]}` : ""}`);
38
54
  }
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)
55
+ for (const m of text.matchAll(/\bClaude ([A-Z][a-z]+) (\d{1,2})(?:\.(\d{1,2}))?(?![\w.]*\d)/g)) {
56
+ if (!family(m[1], m[2]))
41
57
  continue;
42
58
  out.add(`claude-${m[1].toLowerCase()}-${m[2]}${m[3] && m[3] !== "0" ? `-${m[3]}` : ""}`);
43
59
  }
@@ -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 {
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",
@@ -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
@@ -43,6 +43,14 @@ export declare const CACHE_WRITE_1H = 2;
43
43
  */
44
44
  export declare const CACHE_WRITE_OPENAI_30M = 1.25;
45
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;
46
54
  /** A model's list row, as the page lists it today (no tier, mode or date applied). */
47
55
  export declare function pricingFor(model?: string): ModelPricing | undefined;
48
56
  /**
package/dist/pricing.js CHANGED
@@ -15,6 +15,7 @@
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";
18
19
  import { orgApplies, orgRates, orgRowFor } from "./orgrates.js";
19
20
  /** What a cache write costs per 1M tokens at `mult` times input (its TTL's), or the row's own write rate. */
20
21
  export function writePerM(p, mult) {
@@ -219,6 +220,21 @@ const PRICING = [
219
220
  [/gemini.*flash/i, rate(0.1, 0.4, 0.025), FALLBACK],
220
221
  [/gemini.*pro/i, rate(1.25, 5, 0.31), FALLBACK],
221
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
+ }
222
238
  function row(model) {
223
239
  if (!model)
224
240
  return undefined;