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
@@ -0,0 +1,251 @@
1
+ /**
2
+ * context-doctor's mod: the status line's measurements and `fix`'s plan where
3
+ * the status line never runs (Claude Code's Desktop app, the VS Code
4
+ * extension), and in the terminal too.
5
+ *
6
+ * Shipped inside the plugin: hooks/hooks.json names this file under
7
+ * `modules`. Claude Code runs mods from 2.1.287 (terminal), 2.1.286 (the
8
+ * Desktop app's Code tab) and 2.1.299 (VS Code); an older one never loads
9
+ * it and keeps the rest of the plugin.
10
+ *
11
+ * - After each turn (`session.measure`) it runs `context-doctor mod measure`
12
+ * with Claude Code's rate-limit windows and session cost: the CLI keeps
13
+ * them (the limits ledger; Claude Code's cost beside ours) and answers
14
+ * with the band's figures.
15
+ * - A band above the prompt, only when it pays: the cache about to go cold
16
+ * or gone cold on a big context (with the re-write's price), the session
17
+ * past a price threshold. On a cold return a "Compact first" button calls
18
+ * `$.session.compact()`, between turns, on the press alone.
19
+ * - `/context-doctor-fix` opens a pane with `fix`'s plan and an Apply / Undo
20
+ * button per lever. Each press runs the CLI's own `fix --apply <id>` /
21
+ * `fix undo <id>`: the same lock, backup and record as in a terminal.
22
+ *
23
+ * Nothing happens without a press: no auto-compaction, no auto-apply. The
24
+ * mod writes no file itself; the CLI writes ours. Off: CONTEXT_DOCTOR_NO_MOD=1.
25
+ *
26
+ * The mods runtime has no Node, so this file imports only ./logic.js (no
27
+ * imports of its own) and reaches everything else through `$`. Claude Code
28
+ * reads which calls a module makes from its source: `$` is passed only to
29
+ * functions declared at the top of this file.
30
+ */
31
+ import { applyOutcome, band, DEFAULT_THRESHOLDS, fixArgv, MODEL_CHANGE, outcome, paneRows, parsePlan, thresholdsFrom, withPresses } from "./logic.js";
32
+ export const COMMAND = "context-doctor-fix";
33
+ export const PANE = "context-doctor-fix";
34
+ /** How often the band checks whether its text changed (a countdown in minutes). */
35
+ const TICK_MS = 30_000;
36
+ /** `fix` measures 30 days of history: give it time. */
37
+ const FIX_TIMEOUT_MS = 10 * 60_000;
38
+ const MEASURE_TIMEOUT_MS = 30_000;
39
+ const fresh = () => ({ off: false, always: false, thresholds: DEFAULT_THRESHOLDS, hidden: new Set(), drawn: "", compacting: false, loading: false, presses: new Map() });
40
+ let S = fresh();
41
+ /** For tests: the state the hooks share. */
42
+ export const state = () => S;
43
+ /** The CLI beside this module, in the same plugin: dist/mod/register.js → dist/cli.js. */
44
+ function cliOf($) {
45
+ // The module may import nothing but ./logic.js (no node:path): join with the
46
+ // separator the root already uses, so Windows gets D:\…\dist\cli.js.
47
+ const root = $.plugin.root;
48
+ const sep = root.includes("\\") && !root.includes("/") ? "\\" : "/";
49
+ return `${root}${sep}dist${sep}cli.js`;
50
+ }
51
+ function bandKey(now, surface) {
52
+ const b = band(S.data, now, surface, { hidden: S.hidden, always: S.always });
53
+ return b.kind === "none" ? "" : `${b.key}|${b.text}`;
54
+ }
55
+ /** Hand the reading to the CLI; with no CLI (no node on PATH), keep what Claude Code said. */
56
+ async function measure($, e) {
57
+ const fallback = { at: await $.clock.now(), coldMinTokens: 150_000, thresholds: S.thresholds, ...(e.cost ? { ccUsd: e.cost.usd } : {}) };
58
+ try {
59
+ const sessionId = await $.session.id();
60
+ const cwd = await $.session.cwd();
61
+ let model;
62
+ try {
63
+ model = await $.session.model();
64
+ }
65
+ catch { /* measured without it */ }
66
+ const run = await $.process.run(["node", cliOf($), "mod", "measure"], { stdin: JSON.stringify({ sessionId, cwd, model, rateLimits: e.rateLimits, cost: e.cost, context: e.context }), timeoutMs: MEASURE_TIMEOUT_MS });
67
+ const got = JSON.parse(run.stdout || "{}");
68
+ S.data = got && typeof got.at === "number" ? got : fallback;
69
+ }
70
+ catch {
71
+ S.data = fallback;
72
+ }
73
+ }
74
+ /** The press is the consent: one compaction, between turns, and a line in the ledger that it was taken. */
75
+ async function compact($) {
76
+ if (S.compacting)
77
+ return;
78
+ S.compacting = true;
79
+ $.ui.invalidate("ui.render");
80
+ const tokens = S.data?.tokens;
81
+ try {
82
+ const r = await $.session.compact();
83
+ if (r && typeof r.skip === "string") {
84
+ $.ui.toast(`context-doctor: not compacted: ${r.skip}`);
85
+ }
86
+ else {
87
+ // The old context's figures no longer hold: the next turn measures the new one.
88
+ if (S.data)
89
+ S.data = { ...S.data, tokens: undefined, lastReplyAt: undefined, rewriteUsd: undefined };
90
+ try {
91
+ const sessionId = await $.session.id();
92
+ await $.process.run(["node", cliOf($), "mod", "event"], { stdin: JSON.stringify({ sessionId, ev: "compact", tokens }), timeoutMs: MEASURE_TIMEOUT_MS });
93
+ }
94
+ catch { /* the count is a nicety */ }
95
+ }
96
+ }
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.");
101
+ }
102
+ finally {
103
+ S.compacting = false;
104
+ $.ui.invalidate("ui.render");
105
+ }
106
+ }
107
+ /** `fix --json`: the plan, measured on the history (it takes a while on a long one). */
108
+ async function loadPlan($) {
109
+ S.loading = true;
110
+ S.planError = undefined;
111
+ $.ui.invalidate("ui.render");
112
+ try {
113
+ const run = await $.process.run(fixArgv("node", cliOf($), "plan"), { timeoutMs: FIX_TIMEOUT_MS });
114
+ const p = parsePlan(run.stdout);
115
+ if (p) {
116
+ S.plan = p;
117
+ S.presses.clear();
118
+ }
119
+ else {
120
+ S.planError = `context-doctor fix did not answer with a plan (exit ${run.exitCode}): ${(run.stderr || run.stdout).trim().split("\n").slice(-2).join(" ")}`;
121
+ }
122
+ }
123
+ catch (err) {
124
+ S.planError = `context-doctor could not run: ${err instanceof Error ? err.message : String(err)}. It needs Node.js on the PATH Claude Code starts with.`;
125
+ }
126
+ S.loading = false;
127
+ $.ui.invalidate("ui.render");
128
+ }
129
+ /** One press, one CLI run: `fix --apply <id>` or `fix undo <id>`. */
130
+ async function press($, op, id) {
131
+ if (S.busy)
132
+ return;
133
+ S.busy = `${op}:${id}`;
134
+ $.ui.invalidate("ui.render");
135
+ try {
136
+ const run = await $.process.run(fixArgv("node", cliOf($), op, id), { timeoutMs: FIX_TIMEOUT_MS });
137
+ const r = op === "apply" ? applyOutcome(run.stdout, run.stderr, run.exitCode) : outcome(run.stdout, run.stderr, run.exitCode);
138
+ S.last = { id, ...r };
139
+ if (r.ok)
140
+ S.presses.set(id, op === "apply" ? "applied" : "undone");
141
+ }
142
+ catch (err) {
143
+ S.last = { id, ok: false, lines: [`could not run context-doctor: ${err instanceof Error ? err.message : String(err)}`] };
144
+ }
145
+ S.busy = undefined;
146
+ $.ui.invalidate("ui.render");
147
+ }
148
+ function hide($, key) {
149
+ S.hidden.add(key);
150
+ $.ui.invalidate("ui.render");
151
+ }
152
+ function refresh($) {
153
+ if (!S.loading)
154
+ void loadPlan($);
155
+ }
156
+ /** The countdown is in minutes: redraw only when the band's words change. */
157
+ async function tick($) {
158
+ const now = await $.clock.now();
159
+ const k = bandKey(now, "desktop") + bandKey(now, "terminal");
160
+ if (k !== S.drawn) {
161
+ S.drawn = k;
162
+ $.ui.invalidate("ui.render");
163
+ }
164
+ }
165
+ export function register(on) {
166
+ S = fresh();
167
+ on("session.start", async ($, e, next) => {
168
+ try {
169
+ S.off = (await $.env.get("CONTEXT_DOCTOR_NO_MOD")) === "1";
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"));
172
+ if (!S.off) {
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)" });
174
+ $.clock.every(TICK_MS, () => void tick($));
175
+ }
176
+ }
177
+ catch {
178
+ /* an engine without one of these: the mod stays quiet */
179
+ }
180
+ return next(e);
181
+ });
182
+ on("session.measure", async ($, e, next) => {
183
+ const r = await next(e);
184
+ if (S.off)
185
+ return r;
186
+ await measure($, e);
187
+ $.ui.invalidate("ui.render");
188
+ return r;
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
+ });
201
+ on("ui.render", { component: "AbovePrompt" }, async ($, e, next) => {
202
+ if (S.off || e.props.hasSurvey)
203
+ return next(e);
204
+ const b = band(S.data, await $.clock.now(), e.surface, { hidden: S.hidden, always: S.always });
205
+ // A compaction only runs between turns: no button while one runs.
206
+ if (b.kind === "none" || (b.kind === "cold" && e.props.isWorking))
207
+ return next(e);
208
+ const { Box, Text, Button } = $.ui.resolve(e);
209
+ const hideButton = h(Button, { key: "cd-hide", label: "Hide", onPress: () => hide($, b.key) });
210
+ if (b.kind !== "cold")
211
+ return h(Box, { flexDirection: "row", flexWrap: "wrap", columnGap: 1 }, h(Text, { dimColor: true }, b.text), hideButton);
212
+ return h(Box, { flexDirection: "column" }, h(Text, { dimColor: true }, b.text), h(Box, { flexDirection: "row", flexWrap: "wrap", columnGap: 1 }, h(Button, { key: "cd-compact", label: S.compacting ? "Compacting…" : "Compact first", variant: "primary", onPress: () => compact($) }), h(Text, { dimColor: true }, b.compact), hideButton));
213
+ });
214
+ on("command.run", { command: "context-doctor-fix" }, async ($) => {
215
+ if (S.off)
216
+ return { text: "context-doctor's mod is off (CONTEXT_DOCTOR_NO_MOD=1)." };
217
+ await $.ui.open({ id: PANE, title: "context-doctor fix" });
218
+ if (!S.plan && !S.loading)
219
+ void loadPlan($);
220
+ return { text: "Opened context-doctor's fix plan. Nothing is applied until you press Apply." };
221
+ });
222
+ on("ui.render", { component: "Pane", requestId: PANE }, async ($, e) => {
223
+ const { Box, Text, Button } = $.ui.resolve(e);
224
+ const body = [h(Text, { bold: true }, "context-doctor fix: each lever, by what it would have saved you")];
225
+ if (S.loading)
226
+ body.push(h(Text, { dimColor: true }, "Measuring your history (30 days)…"));
227
+ if (S.planError)
228
+ body.push(h(Text, null, S.planError));
229
+ const last = S.last;
230
+ if (last)
231
+ body.push(h(Box, { flexDirection: "column", marginTop: 1 }, ...[`${last.ok ? "Done" : "Not done"}: ${last.id}`, ...last.lines].map((l) => h(Text, { dimColor: last.ok }, l))));
232
+ if (S.plan) {
233
+ if (S.plan.recordProblem)
234
+ body.push(h(Text, null, `⚠ ${S.plan.recordProblem}`));
235
+ const rows = withPresses(paneRows(S.plan), S.presses);
236
+ if (!rows.length)
237
+ body.push(h(Text, { dimColor: true }, "Nothing to fix here."));
238
+ for (const row of rows) {
239
+ const buttons = [];
240
+ if (row.apply)
241
+ buttons.push(h(Button, { key: `apply:${row.id}`, label: S.busy === `apply:${row.id}` ? "Applying…" : row.apply, ...(row.id === MODEL_CHANGE ? {} : { variant: "primary" }), onPress: () => press($, "apply", row.id) }));
242
+ if (row.undo)
243
+ buttons.push(h(Button, { key: `undo:${row.id}`, label: S.busy === `undo:${row.id}` ? "Undoing…" : row.undo, onPress: () => press($, "undo", row.id) }));
244
+ body.push(h(Box, { key: `row:${row.id}`, flexDirection: "column", marginTop: 1 }, h(Text, { bold: true }, row.head), ...row.lines.map((l) => h(Text, { dimColor: !(row.modelChange && l.startsWith("Model change")) }, l)), ...(buttons.length ? [h(Box, { flexDirection: "row", columnGap: 1 }, ...buttons)] : [])));
245
+ }
246
+ body.push(h(Text, { dimColor: true }, "Each figure is measured alone; the levers overlap, so together they save less. Undo puts back exactly what was there."));
247
+ }
248
+ body.push(h(Box, { flexDirection: "row", marginTop: 1 }, h(Button, { key: "refresh", label: S.loading ? "Measuring…" : "Refresh", onPress: () => refresh($) })));
249
+ return h(Box, { flexDirection: "column" }, ...body);
250
+ });
251
+ }
@@ -0,0 +1,24 @@
1
+ /**
2
+ * The Claude models a text names, to check each has a price of its own
3
+ * (pricing.ts hasKnownPrice) before a user runs it: Claude Code ships a
4
+ * model days before a context-doctor release (2.1.322 made Fable 5.2 the
5
+ * default the day its price changed), and an id the table does not know is
6
+ * priced by its family's row, an estimate that was five times too high on
7
+ * Fable 5.2's cache reads. Read from Claude Code's binary (its model
8
+ * catalog), its CHANGELOG and the price page by scripts/check-models.mjs.
9
+ *
10
+ * Three spellings: Bedrock ids (`anthropic.claude-opus-5-5`,
11
+ * `us.anthropic.claude-sonnet-4-5-20250929-v1:0`), the catalog's cleanest
12
+ * list; first-party ids of the current naming (`claude-fable-5-2`); and
13
+ * display names (`Claude Fable 5.2`), which is how the price page names
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.
18
+ */
19
+ /** Ids that have no price on purpose, with the reason. */
20
+ export declare const UNPRICED_ON_PURPOSE: Record<string, string>;
21
+ /** Every Claude model id `text` names, each once, sorted. */
22
+ export declare function claudeModelIds(text: string): string[];
23
+ /** The Claude models `text` names that have no price of their own and no reason to lack one. */
24
+ export declare function unpricedClaudeIds(text: string): string[];
@@ -0,0 +1,65 @@
1
+ /**
2
+ * The Claude models a text names, to check each has a price of its own
3
+ * (pricing.ts hasKnownPrice) before a user runs it: Claude Code ships a
4
+ * model days before a context-doctor release (2.1.322 made Fable 5.2 the
5
+ * default the day its price changed), and an id the table does not know is
6
+ * priced by its family's row, an estimate that was five times too high on
7
+ * Fable 5.2's cache reads. Read from Claude Code's binary (its model
8
+ * catalog), its CHANGELOG and the price page by scripts/check-models.mjs.
9
+ *
10
+ * Three spellings: Bedrock ids (`anthropic.claude-opus-5-5`,
11
+ * `us.anthropic.claude-sonnet-4-5-20250929-v1:0`), the catalog's cleanest
12
+ * list; first-party ids of the current naming (`claude-fable-5-2`); and
13
+ * display names (`Claude Fable 5.2`), which is how the price page names
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.
18
+ */
19
+ import { hasKnownPrice } from "./pricing.js";
20
+ /** The families the table keys on: their ids and names count from major version 4. */
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
+ };
36
+ /** Ids that have no price on purpose, with the reason. */
37
+ export const UNPRICED_ON_PURPOSE = {
38
+ "claude-mythos-preview": "no list price on the page; priced by the Fable/Mythos family row as an estimate",
39
+ };
40
+ /** The model a Bedrock id names, as a first-party id: region prefix, `-v1:0` and the date dropped. */
41
+ function fromBedrock(id) {
42
+ return id.replace(/^(?:[a-z]{2,6}\.)?anthropic\./, "").replace(/-v\d+(?::\d+)?$/, "").replace(/-\d{8}$/, "");
43
+ }
44
+ /** Every Claude model id `text` names, each once, sorted. */
45
+ export function claudeModelIds(text) {
46
+ const out = new Set();
47
+ // A model's Bedrock id has a version number (com.anthropic.claude-code, an app id, has none).
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))
49
+ out.add(fromBedrock(m[1]));
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]))
52
+ continue;
53
+ out.add(`claude-${m[1]}-${m[2]}${m[3] && m[3] !== "0" ? `-${m[3]}` : ""}`);
54
+ }
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]))
57
+ continue;
58
+ out.add(`claude-${m[1].toLowerCase()}-${m[2]}${m[3] && m[3] !== "0" ? `-${m[3]}` : ""}`);
59
+ }
60
+ return [...out].sort();
61
+ }
62
+ /** The Claude models `text` names that have no price of their own and no reason to lack one. */
63
+ export function unpricedClaudeIds(text) {
64
+ return claudeModelIds(text).filter((id) => !hasKnownPrice(id) && !(id in UNPRICED_ON_PURPOSE));
65
+ }
@@ -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}. ` +
@@ -0,0 +1,121 @@
1
+ /**
2
+ * `context-doctor mod measure`: what the plugin's mod hands over after each
3
+ * turn, kept the way the status line keeps it.
4
+ *
5
+ * The status line never runs in the Desktop app's Code tab or the VS Code
6
+ * extension, so there the limit ledger stayed empty and Claude Code's own
7
+ * cost was never compared with ours (ROADMAP K2). A mod runs there: after
8
+ * each main-thread turn Claude Code raises `session.measure` with the
9
+ * rate-limit windows (`kind`, `percentUsed`, `resetsAt` as ISO 8601) and the
10
+ * session's cost (`cost.usd`, as /cost totals it). The mod has no file
11
+ * access of its own worth trusting with our formats, so it runs this command
12
+ * with that reading on stdin, and this:
13
+ *
14
+ * - appends the windows to the limits ledger in the status line's own
15
+ * format and with its rules (recordLimits: changes only, at most once a
16
+ * minute, never a lower figure of the same window from a parallel
17
+ * session), so `context-doctor limits` reads Desktop's readings too;
18
+ * - appends Claude Code's cost beside our own price of the same session
19
+ * (sessionTotal: the transcript and its subagents, as the every-prompt
20
+ * hook prices it) to a small capped ledger, for `doctor`'s comparison;
21
+ * - prints what the band needs, as JSON: the cache clock read from the
22
+ * transcript's tail (coldresume.ts), the re-write's price, the price.
23
+ *
24
+ * Silent like the status line: anything unreadable prints `{}` and exits 0.
25
+ * Off: CONTEXT_DOCTOR_NO_LIMITS_LOG=1 (the limits), CONTEXT_DOCTOR_NO_COST_LOG=1
26
+ * (the cost ledger).
27
+ */
28
+ import type { BandData } from "./mod/logic.js";
29
+ /** What the mod sends: `session.measure`'s input, and who the session is. All optional. */
30
+ export interface ModMeasureInput {
31
+ sessionId?: string;
32
+ cwd?: string;
33
+ model?: string;
34
+ rateLimits?: Array<{
35
+ kind?: unknown;
36
+ percentUsed?: unknown;
37
+ resetsAt?: unknown;
38
+ }>;
39
+ cost?: {
40
+ usd?: unknown;
41
+ };
42
+ context?: {
43
+ tokens?: unknown;
44
+ window?: unknown;
45
+ };
46
+ }
47
+ /**
48
+ * The mod's windows in the status line's shape, `{ five_hour: { used_percentage,
49
+ * resets_at } }`, resets in epoch seconds: the one shape recordLimits reads.
50
+ * A gateway's `spend_limit` has no place in the ledger and is left out.
51
+ */
52
+ export declare function statusLineRateLimits(list: unknown): Record<string, {
53
+ used_percentage: number;
54
+ resets_at?: number;
55
+ }> | undefined;
56
+ /** A Claude Code session's transcript: in its folder's project, else wherever a project holds the id (a session that moved folders). */
57
+ export declare function findTranscript(sessionId: string | undefined, cwd: string | undefined, home?: string): string | undefined;
58
+ /** One line: Claude Code's cost of a session and ours, at one moment; or a press of the mod's Compact button. */
59
+ export interface CostLine {
60
+ ts: number;
61
+ sid: string;
62
+ /** Claude Code's figure, USD. */
63
+ cc?: number;
64
+ /** context-doctor's, USD. */
65
+ cd?: number;
66
+ model?: string;
67
+ /** Requests with no list price, left out of `cd`. */
68
+ unpriced?: number;
69
+ /** The part of `cd` priced at its family's row. */
70
+ est?: number;
71
+ /** "compact": the mod's Compact first button was pressed (`tokens`: the context it compacted). */
72
+ ev?: string;
73
+ tokens?: number;
74
+ }
75
+ export declare function costLogPath(): string;
76
+ /**
77
+ * Append a session's two figures, unless neither moved since its last line
78
+ * (a second measure of the same turn, a parallel window of the same session).
79
+ * Never throws. True when a line was written.
80
+ */
81
+ export declare function recordSessionCost(line: Omit<CostLine, "ev">, path?: string): boolean;
82
+ /** A press of one of the mod's buttons that changes nothing on disk (the Compact button), for the follow-through count. */
83
+ export declare function recordModEvent(sid: string, ev: string, tokens?: number, now?: number, path?: string): boolean;
84
+ /** Every line of the ledger since `since`. */
85
+ export declare function readCostLines(since?: number, path?: string): CostLine[];
86
+ /** A session's last pair of figures, and how far ours is from Claude Code's. */
87
+ export interface CostGap {
88
+ sid: string;
89
+ ts: number;
90
+ cc: number;
91
+ cd: number;
92
+ /** (cd - cc) / cc. */
93
+ gap: number;
94
+ model?: string;
95
+ unpriced?: number;
96
+ }
97
+ /** The target: within this of Claude Code's figure wherever every model is priced (ROADMAP K2). */
98
+ export declare const COST_GAP_TARGET = 0.02;
99
+ /** Each session's last pair, where both figures are there and Claude Code's is worth comparing. */
100
+ export declare function costGaps(lines: CostLine[]): CostGap[];
101
+ /**
102
+ * `doctor`'s line: how close our session price is to Claude Code's own cost,
103
+ * on the sessions the mod measured in the last `days`. Undefined when it
104
+ * measured none (no mod, or no session above $0.50 yet).
105
+ */
106
+ export declare function costCheck(days?: number, now?: number, path?: string): {
107
+ label: string;
108
+ status: "ok" | "warn";
109
+ detail: string;
110
+ } | undefined;
111
+ /**
112
+ * Keep what the mod measured and work out the band's inputs. Never throws;
113
+ * what it cannot read is left out of the answer.
114
+ */
115
+ export declare function modMeasure(input: ModMeasureInput, now?: number, env?: NodeJS.ProcessEnv): Partial<BandData> & Pick<BandData, "at" | "coldMinTokens" | "thresholds">;
116
+ /**
117
+ * The CLI side: `mod measure` keeps the reading and prints the band's
118
+ * figures; `mod event` records a press (`{ sessionId, ev, tokens }`). Both
119
+ * print JSON and exit 0 whatever happens, as the status line does.
120
+ */
121
+ export declare function runMod(sub: "measure" | "event"): Promise<void>;