context-doctor 0.52.0 → 0.53.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.
@@ -37,6 +37,50 @@ export declare function unpriced(ids: string[]): string[];
37
37
  * transcription) and the tools table are not models priced by the token.
38
38
  */
39
39
  export declare function openaiPageIds(markdown: string): string[];
40
+ /** One model's per-1M rates as OpenAI's price page states them: short context, and the long tier where it has one. */
41
+ export interface PagePrice {
42
+ model: string;
43
+ short: {
44
+ input: number;
45
+ output: number;
46
+ cached?: number;
47
+ };
48
+ long?: {
49
+ input: number;
50
+ output: number;
51
+ cached?: number;
52
+ };
53
+ }
54
+ /**
55
+ * The prices in OpenAI's price page's Standard tables (not Batch, Flex, Fast
56
+ * or Ultrafast): the main table's "Short context …" and "Long context …"
57
+ * columns, and the specialized tables' "(short context)" / "(long context)"
58
+ * row pairs. A "-" cell is no price (no cached rate, or no long tier). So
59
+ * the weekly check can compare what we charge with what the page says, not
60
+ * only that a model has some price.
61
+ */
62
+ export declare function openaiPagePrices(markdown: string): PagePrice[];
63
+ /**
64
+ * The prices in Anthropic's price page's model table (platform.claude.com
65
+ * pricing.md, "Model | Base input tokens | … | Cache hits and refreshes |
66
+ * Output tokens"): each "Claude Opus 5.5" row as `claude-opus-5-5`, notes in
67
+ * parentheses and footnote marks dropped. A model priced in two rows by
68
+ * prompt size (Haiku 5.5's "for prompts over 100,000 tokens") gets the
69
+ * second as its long tier. Cache writes are not read: they are 1.25x and 2x
70
+ * input by rule, which pricing.ts applies.
71
+ */
72
+ export declare function anthropicPagePrices(markdown: string): PagePrice[];
73
+ /**
74
+ * The prices in Google's price page (ai.google.dev/gemini-api/docs/pricing,
75
+ * its .md.txt): in each model's section, the Standard tab's paid-tier cells
76
+ * for input, output and context caching. A cell's first price is today's
77
+ * (a later "$4.00 starting December 1" line is the dated row's `then`, which
78
+ * the dated check covers); "prompts <= 200k" / "prompts > 200k" lines split
79
+ * a short and a long tier; per-hour storage lines and audio rates after a
80
+ * text rate are not read. A section whose cells do not read this way is
81
+ * left out rather than guessed.
82
+ */
83
+ export declare function googlePagePrices(markdown: string): PagePrice[];
40
84
  /**
41
85
  * The models Google's price page (ai.google.dev/gemini-api/docs/pricing, its
42
86
  * .md.txt) prices: each section's model id line (`*[\`gemini-4-argon\`](...)*`),
package/dist/modelids.js CHANGED
@@ -117,6 +117,180 @@ export function openaiPageIds(markdown) {
117
117
  }
118
118
  return [...out].sort();
119
119
  }
120
+ /**
121
+ * The prices in OpenAI's price page's Standard tables (not Batch, Flex, Fast
122
+ * or Ultrafast): the main table's "Short context …" and "Long context …"
123
+ * columns, and the specialized tables' "(short context)" / "(long context)"
124
+ * row pairs. A "-" cell is no price (no cached rate, or no long tier). So
125
+ * the weekly check can compare what we charge with what the page says, not
126
+ * only that a model has some price.
127
+ */
128
+ export function openaiPagePrices(markdown) {
129
+ const out = new Map();
130
+ const usd = (c) => {
131
+ const m = c?.match(/^\$([0-9]+(?:\.[0-9]+)?)$/);
132
+ return m ? Number(m[1]) : undefined;
133
+ };
134
+ let speed = "";
135
+ let header;
136
+ for (const raw of markdown.split("\n")) {
137
+ const line = raw.trim();
138
+ if (/^(Standard|Batch|Flex|Fast|Ultrafast|Priority)$/.test(line))
139
+ speed = line;
140
+ if (!line.startsWith("|")) {
141
+ header = undefined;
142
+ continue;
143
+ }
144
+ const cells = line.split("|").slice(1, -1).map((c) => c.trim());
145
+ if (!header) {
146
+ header = cells.map((c) => c.toLowerCase());
147
+ continue;
148
+ }
149
+ if (speed !== "Standard" || cells.every((c) => /^-+$/.test(c)))
150
+ continue;
151
+ // A Training column is fine-tuning's table: the price of a fine-tuned model, not the model's own.
152
+ if (header.includes("modality") || header.includes("use case") || header.includes("training") || header[0] === "tool")
153
+ continue;
154
+ const at = header.indexOf("model");
155
+ if (at === -1)
156
+ continue;
157
+ const cell = (cells[at] ?? "").replace(/<[^>]*>/g, "").trim();
158
+ const name = cell.replace(/\s*\(.*\)\s*$/, "").trim();
159
+ if (!/^[a-z][a-z0-9.-]*$/.test(name) || NOT_A_TEXT_MODEL.test(name))
160
+ continue;
161
+ const col = (h) => usd(cells[header.indexOf(h)]);
162
+ const tier = (prefix) => {
163
+ const input = col(`${prefix}input`), output = col(`${prefix}output`);
164
+ if (input === undefined || output === undefined)
165
+ return undefined;
166
+ const cached = col(`${prefix}cached input`);
167
+ return { input, output, ...(cached !== undefined ? { cached } : {}) };
168
+ };
169
+ const entry = out.get(name) ?? { model: name, short: undefined };
170
+ if (header.includes("short context input")) {
171
+ const short = tier("short context "), long = tier("long context ");
172
+ if (!short)
173
+ continue;
174
+ entry.short = short;
175
+ if (long)
176
+ entry.long = long;
177
+ }
178
+ else {
179
+ const t = tier("");
180
+ if (!t)
181
+ continue;
182
+ if (/\(long context\)/i.test(cell))
183
+ entry.long = t;
184
+ else
185
+ entry.short = t;
186
+ }
187
+ out.set(name, entry);
188
+ }
189
+ return [...out.values()].filter((e) => e.short).sort((a, b) => a.model.localeCompare(b.model));
190
+ }
191
+ /**
192
+ * The prices in Anthropic's price page's model table (platform.claude.com
193
+ * pricing.md, "Model | Base input tokens | … | Cache hits and refreshes |
194
+ * Output tokens"): each "Claude Opus 5.5" row as `claude-opus-5-5`, notes in
195
+ * parentheses and footnote marks dropped. A model priced in two rows by
196
+ * prompt size (Haiku 5.5's "for prompts over 100,000 tokens") gets the
197
+ * second as its long tier. Cache writes are not read: they are 1.25x and 2x
198
+ * input by rule, which pricing.ts applies.
199
+ */
200
+ export function anthropicPagePrices(markdown) {
201
+ const out = new Map();
202
+ const usd = (c) => {
203
+ const m = c?.replace(/<sup>.*?<\/sup>/g, "").match(/^\$([0-9]+(?:\.[0-9]+)?) \/ MTok$/);
204
+ return m ? Number(m[1]) : undefined;
205
+ };
206
+ let header;
207
+ for (const raw of markdown.split("\n")) {
208
+ const line = raw.trim();
209
+ if (!line.startsWith("|")) {
210
+ header = undefined;
211
+ continue;
212
+ }
213
+ const cells = line.split("|").slice(1, -1).map((c) => c.trim());
214
+ if (!header) {
215
+ header = cells.map((c) => c.toLowerCase());
216
+ continue;
217
+ }
218
+ if (cells.every((c) => /^-+$/.test(c)))
219
+ continue;
220
+ const [m, i, o, h] = ["model", "base input tokens", "output tokens", "cache hits and refreshes"].map((k) => header.indexOf(k));
221
+ if (m === -1 || i === -1 || o === -1 || h === -1)
222
+ continue;
223
+ const cell = cells[m] ?? "";
224
+ const name = cell.replace(/\s*\(.*\)\s*$/, "").trim();
225
+ if (!/^Claude [A-Za-z]+ [0-9.]+$/.test(name))
226
+ continue;
227
+ const id = "claude-" + name.slice(7).toLowerCase().replace(/[ .]/g, "-");
228
+ const input = usd(cells[i]), output = usd(cells[o]), cached = usd(cells[h]);
229
+ if (input === undefined || output === undefined)
230
+ continue;
231
+ const tier = { input, output, ...(cached !== undefined ? { cached } : {}) };
232
+ const prev = out.get(id);
233
+ if (prev && /prompts over/i.test(cell))
234
+ prev.long = tier;
235
+ else if (!prev)
236
+ out.set(id, { model: id, short: tier });
237
+ }
238
+ return [...out.values()].sort((a, b) => a.model.localeCompare(b.model));
239
+ }
240
+ /**
241
+ * The prices in Google's price page (ai.google.dev/gemini-api/docs/pricing,
242
+ * its .md.txt): in each model's section, the Standard tab's paid-tier cells
243
+ * for input, output and context caching. A cell's first price is today's
244
+ * (a later "$4.00 starting December 1" line is the dated row's `then`, which
245
+ * the dated check covers); "prompts <= 200k" / "prompts > 200k" lines split
246
+ * a short and a long tier; per-hour storage lines and audio rates after a
247
+ * text rate are not read. A section whose cells do not read this way is
248
+ * left out rather than guessed.
249
+ */
250
+ export function googlePagePrices(markdown) {
251
+ const out = [];
252
+ const sections = markdown.split(/^## /m).slice(1);
253
+ for (const sec of sections) {
254
+ const id = sec.match(/\{% id="([a-z0-9.-]+)" %\}/)?.[1];
255
+ if (!id || !/^gemini-/.test(id) || NOT_A_TEXT_MODEL.test(id))
256
+ continue;
257
+ // The Standard tab when the section has tabs, else its first table.
258
+ const std = sec.indexOf('{% tab title="Standard" %}');
259
+ const body = std === -1 ? sec : sec.slice(std, sec.indexOf("{% /tab %}", std) >>> 0 || undefined);
260
+ const rows = body.split(/^\s*---\s*$/m);
261
+ const cellOf = (label) => {
262
+ const row = rows.find((r) => label.test(r.split("\n").find((l) => /^\s*\*\s/.test(l)) ?? ""));
263
+ if (!row)
264
+ return undefined;
265
+ const bullets = row.split(/^\s*\*\s/m).slice(1);
266
+ return bullets[2];
267
+ };
268
+ const tiers = (cell) => {
269
+ if (!cell)
270
+ return undefined;
271
+ let short, long;
272
+ for (const line of cell.split("\n")) {
273
+ const m = line.trim().match(/^\$([0-9]+(?:\.[0-9]+)?)\b(.*)$/);
274
+ if (!m || /starting|per hour|storage/i.test(m[2]))
275
+ continue;
276
+ const v = Number(m[1]);
277
+ if (/prompts\s*>\s*\d/i.test(m[2]))
278
+ long ??= v;
279
+ else
280
+ short ??= v;
281
+ }
282
+ return short === undefined ? undefined : { short, long };
283
+ };
284
+ const i = tiers(cellOf(/Input price/)), o = tiers(cellOf(/Output price/)), c = tiers(cellOf(/Context caching price/));
285
+ if (!i || !o)
286
+ continue;
287
+ const entry = { model: id, short: { input: i.short, output: o.short, ...(c ? { cached: c.short } : {}) } };
288
+ if (i.long !== undefined && o.long !== undefined)
289
+ entry.long = { input: i.long, output: o.long, ...(c?.long !== undefined ? { cached: c.long } : {}) };
290
+ out.push(entry);
291
+ }
292
+ return out.sort((a, b) => a.model.localeCompare(b.model));
293
+ }
120
294
  /**
121
295
  * The models Google's price page (ai.google.dev/gemini-api/docs/pricing, its
122
296
  * .md.txt) prices: each section's model id line (`*[\`gemini-4-argon\`](...)*`),
@@ -0,0 +1,11 @@
1
+ /**
2
+ * Does what we charge match what a provider's price page says? The weekly
3
+ * check (`scripts/check-models.mjs`) asked only whether each model had some
4
+ * price, so a row the page later changed (GPT-6 Rosalind went from $15 to
5
+ * $10 per 1M input) or a long-prompt tier a row left out (GPT-6 Astra for
6
+ * Law) stayed wrong without a red. This compares each of the page's
7
+ * Standard prices with our rate card for the model, as of `at`.
8
+ */
9
+ import type { PagePrice } from "./modelids.js";
10
+ /** One line per model whose price differs from the page's, in plain words; empty when all agree. */
11
+ export declare function pagePriceMismatches(prices: PagePrice[], at?: number): string[];
@@ -0,0 +1,32 @@
1
+ import { rateCard } from "./pricing.js";
2
+ const same = (a, b) => Math.abs(a - b) <= 1e-9 + 1e-6 * Math.max(a, b);
3
+ const money = (n) => "$" + String(Number(n.toFixed(4)));
4
+ /** One line per model whose price differs from the page's, in plain words; empty when all agree. */
5
+ export function pagePriceMismatches(prices, at = Date.now()) {
6
+ const out = [];
7
+ for (const p of prices) {
8
+ const card = rateCard(p.model, undefined, at);
9
+ // No price at all is the id check's job; an organization's contracted row is theirs, not the page's.
10
+ if (!card || card.org)
11
+ continue;
12
+ const diffs = [];
13
+ const tier = (label, page, ours) => {
14
+ if (!same(page.input, ours.inputPerM))
15
+ diffs.push(`${label} input ${money(page.input)} on the page, ${money(ours.inputPerM)} here`);
16
+ if (!same(page.output, ours.outputPerM))
17
+ diffs.push(`${label} output ${money(page.output)} on the page, ${money(ours.outputPerM)} here`);
18
+ if (page.cached !== undefined && !same(page.cached, ours.cacheReadPerM))
19
+ diffs.push(`${label} cached input ${money(page.cached)} on the page, ${money(ours.cacheReadPerM)} here`);
20
+ };
21
+ tier("short-context", p.short, card.rates);
22
+ if (p.long && !card.longRates)
23
+ diffs.push(`the page has a long-context price (${money(p.long.input)} / ${money(p.long.output)}) and src/pricing.ts has no long tier`);
24
+ else if (!p.long && card.longRates)
25
+ diffs.push("src/pricing.ts has a long tier the page does not list");
26
+ else if (p.long && card.longRates)
27
+ tier("long-context", p.long, card.longRates);
28
+ if (diffs.length)
29
+ out.push(`${p.model}: ${diffs.join("; ")}`);
30
+ }
31
+ return out;
32
+ }
package/dist/pricing.js CHANGED
@@ -151,15 +151,24 @@ const PRICING = [
151
151
  [openai("gpt-6.2-sol"), ...openaiLong(2, 10, 0.1)],
152
152
  [openai("gpt-6-astra"), ...openaiLong(10, 50, 1)],
153
153
  // GPT-6 Astra for Law's price is promotional "at least through December
154
- // 31, 2026" (read 2026-11-14): no end date to record yet.
155
- [openai("gpt-6-astra-law"), rate(10, 50, 1)],
154
+ // 31, 2026" (read 2026-11-14): no end date to record yet. Its long-context
155
+ // row ($20 / $75 / $2, read 2026-11-26) is 2x / 1.5x; the row had left it out.
156
+ [openai("gpt-6-astra-law"), ...openaiLong(10, 50, 1)],
157
+ // The healthcare configurations (read 2026-11-26) are priced as their base
158
+ // models, promotional "at least through December 31, 2026" like the Law ones.
159
+ [openai("gpt-6.2-astra-healthcare"), ...openaiLong(8, 40, 0.4)],
160
+ [openai("gpt-6.2-sol-healthcare"), ...openaiLong(2, 10, 0.1)],
161
+ [openai("gpt-6-astra-healthcare"), ...openaiLong(10, 50, 1)],
162
+ [openai("gpt-6.1-sol-healthcare"), ...openaiLong(2, 10, 0.1)],
156
163
  [openai("gpt-6.1-sol"), ...openaiLong(2, 10, 0.1)],
157
164
  [openai("gpt-6.1-terra"), ...openaiLong(1, 5, 0.05)],
158
165
  [openai("gpt-6-sol"), ...openaiLong(2, 10, 0.2)],
159
166
  [openai("gpt-6-luna"), ...openaiLong(0.1, 0.5, 0.01)],
160
167
  // gpt-6-cyber's long-context row ($40 / $150 / $4, read 2026-11-14) is 2x / 1.5x.
161
168
  [openai("gpt-6-cyber"), ...openaiLong(20, 100, 2)],
162
- [openai("gpt-6-rosalind"), ...openaiLong(15, 75, 1.5)],
169
+ // GPT-6 Rosalind: $10 / $50 / $1 (read 2026-11-26; $15 / $75 / $1.50 when
170
+ // first read), promotional "at least through December 31, 2026".
171
+ [openai("gpt-6-rosalind"), ...openaiLong(10, 50, 1)],
163
172
  [openai("gpt-rosalind-research"), rate(5, 25, 0.5)],
164
173
  [openai("gpt-rosalind-discovery"), rate(5, 25, 0.5)],
165
174
  // GPT-5.6 Sol's $4 / $20 is promotional "until November 30, 2026" (read
package/dist/proxy.d.ts CHANGED
@@ -83,7 +83,7 @@ export interface ProxyOptions extends OptimizeOptions {
83
83
  /** Default request body cap: far above any real request (a 1M-token context is ~4 MB of JSON, images aside). */
84
84
  export declare const DEFAULT_MAX_BODY_BYTES: number;
85
85
  /** Reported by /health so `autopilot status` can tell an outdated service from a current one. */
86
- export declare const PROXY_VERSION = "0.52.0";
86
+ export declare const PROXY_VERSION = "0.53.0";
87
87
  /**
88
88
  * Remove a leading `/t/<token>` from a request path, or return undefined when
89
89
  * the prefix is absent or the token differs. The comparison is constant time
package/dist/proxy.js CHANGED
@@ -25,7 +25,7 @@ import { makeGuard, refusal } from "./httpguard.js";
25
25
  /** Default request body cap: far above any real request (a 1M-token context is ~4 MB of JSON, images aside). */
26
26
  export const DEFAULT_MAX_BODY_BYTES = 100 * 1024 * 1024;
27
27
  /** Reported by /health so `autopilot status` can tell an outdated service from a current one. */
28
- export const PROXY_VERSION = "0.52.0";
28
+ export const PROXY_VERSION = "0.53.0";
29
29
  /** Connection-level headers that must not be forwarded. */
30
30
  const SKIP_REQUEST_HEADERS = new Set(["host", "content-length", "connection", "transfer-encoding", "accept-encoding", "expect"]);
31
31
  /** A reply carrying any of these has something for the limits ledger: a plan window, or the usage-credits state. */
package/dist/starts.d.ts CHANGED
@@ -97,17 +97,56 @@ export interface StartsReport {
97
97
  tokens: number;
98
98
  usd: number;
99
99
  };
100
+ /**
101
+ * The period's compactions, and the servers whose tools went whole into
102
+ * some start that each compaction was followed by a call to (#111915: a
103
+ * tool loaded through tool search is deferred again after a compaction,
104
+ * so with the server behind tool search each would load once more).
105
+ * Each load priced as one more request: the context at that call read
106
+ * from the cache, plus one of the server's tool definitions written.
107
+ */
108
+ compactions?: {
109
+ total: number;
110
+ after: Array<Array<{
111
+ server: string;
112
+ usd: number;
113
+ unpriced?: true;
114
+ }>>;
115
+ };
100
116
  }
117
+ /**
118
+ * What the reload count reads from a transcript: each compaction boundary,
119
+ * and each assistant row that calls an MCP tool, with the request's usage
120
+ * (the context at that call). Read once with the other extractors (scan.ts).
121
+ */
122
+ export declare const RELOAD_ROWS: Extractor<Record<string, never>>;
123
+ /** A Claude Code that ran sessions in the period: the entrypoint and version their transcripts recorded, and how many. */
124
+ export interface SessionHost {
125
+ /** "claude-desktop", "cli", "sdk-cli", "claude-vscode"... ("" when a transcript records none). */
126
+ entrypoint: string;
127
+ version?: string;
128
+ sessions: number;
129
+ }
130
+ /**
131
+ * Which Claude Code ran the sessions in the period: each entrypoint and
132
+ * version a main transcript recorded while it was in the period (limits.ts
133
+ * HOST_ROWS keeps a record where either changes), counted once per session.
134
+ * fix uses it to say when an install too old for a setting ran none of them.
135
+ */
136
+ export declare function sessionHosts(paths: string[], since: number): SessionHost[];
101
137
  /**
102
138
  * Every session's and subagent's start in the period, grouped by entrypoint
103
139
  * and subagent type, each priced on every request that re-read it.
104
140
  * `paths`: the main transcripts (subagents are found beside each).
141
+ * `compactions`: also count the compactions followed by a call to a server
142
+ * sent whole (fix's desktop-tools-defer; `overhead` does not ask).
105
143
  */
106
144
  export declare function measureStarts(opts?: {
107
145
  days?: number;
108
146
  paths?: string[];
109
147
  cwd?: string;
110
148
  home?: string;
149
+ compactions?: boolean;
111
150
  }): StartsReport;
112
151
  /** The servers whose tools went whole into some start and that the user's own config holds: `alwaysLoad: false` defers them. */
113
152
  export declare function deferrableConfigured(r: StartsReport): Array<{
package/dist/starts.js CHANGED
@@ -21,12 +21,13 @@
21
21
  import { readFileSync } from "node:fs";
22
22
  import { claudeMcpConfigs } from "./mcpschema.js";
23
23
  import { REQUEST_ROWS } from "./coldresume.js";
24
- import { rowsOf } from "./scan.js";
24
+ import { rowsOf, slimUsage } from "./scan.js";
25
25
  import { listSessions, isClaudeSession, replyCounter, textOf } from "./session.js";
26
26
  import { subagentFiles, workflowRunOf } from "./subagents.js";
27
27
  import { cacheWriteSplit, formatUsd, rateCard, ratesAt, usageCost } from "./pricing.js";
28
28
  import { formatTokens, isCodeLike, realModel, tokensForLength } from "./tokens.js";
29
29
  import { APP_TOOL_SERVERS } from "./mod/logic.js";
30
+ import { HOST_ROWS } from "./limits.js";
30
31
  const CLAUDE = "claude-opus-5";
31
32
  /**
32
33
  * What a start's measurement takes from a transcript: the entrypoint, the
@@ -140,6 +141,103 @@ export function mcpServerOf(name) {
140
141
  const m = /^mcp__(.+?)__/.exec(name);
141
142
  return m?.[1];
142
143
  }
144
+ /**
145
+ * What the reload count reads from a transcript: each compaction boundary,
146
+ * and each assistant row that calls an MCP tool, with the request's usage
147
+ * (the context at that call). Read once with the other extractors (scan.ts).
148
+ */
149
+ export const RELOAD_ROWS = {
150
+ id: "reloads.1",
151
+ init: () => ({}),
152
+ line(raw, row, out) {
153
+ const boundary = raw.includes('"compact_boundary"');
154
+ if (!boundary && !(raw.includes('"tool_use"') && raw.includes('"name":"mcp__')))
155
+ return;
156
+ let e;
157
+ try {
158
+ e = row();
159
+ }
160
+ catch {
161
+ return;
162
+ }
163
+ if (!e || typeof e !== "object")
164
+ return;
165
+ const ts = Date.parse(String(e.timestamp ?? ""));
166
+ if (!Number.isFinite(ts))
167
+ return;
168
+ const sc = e.isSidechain === true ? { sc: 1 } : {};
169
+ if (e.type === "system" && e.subtype === "compact_boundary") {
170
+ out.push({ k: "c", ts, ...sc, ...(typeof e.uuid === "string" ? { u: e.uuid.slice(0, 80) } : {}) });
171
+ return;
172
+ }
173
+ const content = e.type === "assistant" ? e.message?.content : undefined;
174
+ if (!Array.isArray(content))
175
+ return;
176
+ const srv = [];
177
+ for (const b of content) {
178
+ const s = b?.type === "tool_use" && typeof b.name === "string" ? mcpServerOf(b.name) : undefined;
179
+ if (s && !srv.includes(s.slice(0, 200)))
180
+ srv.push(s.slice(0, 200));
181
+ }
182
+ if (!srv.length)
183
+ return;
184
+ out.push({ k: "t", ts, ...sc, srv, ...(typeof e.message.model === "string" ? { m: e.message.model.slice(0, 80) } : {}), usage: slimUsage(e.message.usage) });
185
+ },
186
+ };
187
+ /**
188
+ * A transcript's compactions in the period, each with the servers called
189
+ * after it (before the next one on the same thread), each server once: its
190
+ * first call after the compaction is the one that would load it again. A
191
+ * compaction already seen in another transcript (a fork's copy) is skipped
192
+ * with the calls after it.
193
+ */
194
+ function compactionsIn(path, since, seen) {
195
+ const out = [];
196
+ const open = new Map();
197
+ for (const r of rowsOf(path, RELOAD_ROWS)) {
198
+ const th = r.sc ? "1" : "0";
199
+ if (r.k === "c") {
200
+ const copy = r.u !== undefined && seen.has(r.u);
201
+ if (r.u)
202
+ seen.add(r.u);
203
+ if (r.ts < since || copy) {
204
+ open.set(th, undefined);
205
+ continue;
206
+ }
207
+ const c = { list: [], servers: new Set() };
208
+ out.push(c.list);
209
+ open.set(th, c);
210
+ continue;
211
+ }
212
+ const c = open.get(th);
213
+ if (!c)
214
+ continue;
215
+ for (const s of r.srv) {
216
+ if (c.servers.has(s))
217
+ continue;
218
+ c.servers.add(s);
219
+ c.list.push({ server: s, at: r.ts, ...(r.m ? { model: r.m } : {}), usage: r.usage });
220
+ }
221
+ }
222
+ return out;
223
+ }
224
+ /**
225
+ * One more request at the call's context: all of it read from the cache, and
226
+ * the tool's definition (`defTokens`) written, at the call's own write
227
+ * lifetime and model rates. Undefined when the model has no price.
228
+ */
229
+ function reloadUsd(r, defTokens) {
230
+ const u = r.usage ?? {};
231
+ const prompt = (Number(u.input_tokens) || 0) + (Number(u.cache_read_input_tokens) || 0) + (Number(u.cache_creation_input_tokens) || 0);
232
+ const card = rateCard(realModel(r.model), u, r.at);
233
+ if (!card)
234
+ return undefined;
235
+ const split = cacheWriteSplit(u);
236
+ const all = split.fiveMinute + split.oneHour + split.twelveHour;
237
+ const def = Math.round(defTokens);
238
+ const oneHour = all > 0 ? Math.round((def * split.oneHour) / all) : 0;
239
+ return usageCost({ input_tokens: 0, cache_read_input_tokens: prompt, cache_creation_input_tokens: def, cache_creation: { ephemeral_5m_input_tokens: def - oneHour, ephemeral_1h_input_tokens: oneHour } }, ratesAt(card, prompt + def)).promptUsd;
240
+ }
143
241
  function quantile(sorted, q) {
144
242
  return sorted[Math.min(sorted.length - 1, Math.floor(sorted.length * q))];
145
243
  }
@@ -247,6 +345,38 @@ function measureStart(path, kind, since, runRows, parentEntry) {
247
345
  }
248
346
  return start;
249
347
  }
348
+ /**
349
+ * Which Claude Code ran the sessions in the period: each entrypoint and
350
+ * version a main transcript recorded while it was in the period (limits.ts
351
+ * HOST_ROWS keeps a record where either changes), counted once per session.
352
+ * fix uses it to say when an install too old for a setting ran none of them.
353
+ */
354
+ export function sessionHosts(paths, since) {
355
+ const out = new Map();
356
+ for (const path of paths) {
357
+ let hosts;
358
+ try {
359
+ hosts = rowsOf(path, HOST_ROWS);
360
+ }
361
+ catch {
362
+ continue;
363
+ }
364
+ const seen = new Set();
365
+ hosts.forEach((h, j) => {
366
+ // Superseded before the period began (a session resumed after an update): not this period's.
367
+ const next = hosts[j + 1];
368
+ if (next && next.ts > 0 && next.ts < since)
369
+ return;
370
+ const k = `${h.ep ?? ""}\u0000${h.v ?? ""}`;
371
+ if (seen.has(k))
372
+ return;
373
+ seen.add(k);
374
+ const cur = out.get(k) ?? out.set(k, { entrypoint: h.ep ?? "", ...(h.v ? { version: h.v } : {}), sessions: 0 }).get(k);
375
+ cur.sessions++;
376
+ });
377
+ }
378
+ return [...out.values()].sort((a, b) => b.sessions - a.sessions);
379
+ }
250
380
  /** Claude Code transcripts written in the last `days` days. */
251
381
  function claudeTranscripts(days) {
252
382
  const since = Date.now() - days * 86_400_000;
@@ -256,6 +386,8 @@ function claudeTranscripts(days) {
256
386
  * Every session's and subagent's start in the period, grouped by entrypoint
257
387
  * and subagent type, each priced on every request that re-read it.
258
388
  * `paths`: the main transcripts (subagents are found beside each).
389
+ * `compactions`: also count the compactions followed by a call to a server
390
+ * sent whole (fix's desktop-tools-defer; `overhead` does not ask).
259
391
  */
260
392
  export function measureStarts(opts = {}) {
261
393
  const days = opts.days ?? 30;
@@ -263,6 +395,17 @@ export function measureStarts(opts = {}) {
263
395
  const mains = (opts.paths ?? claudeTranscripts(days)).filter((p) => !/[\\/]\.codex[\\/]/.test(p) && !/[\\/]\.gemini[\\/]/.test(p));
264
396
  const starts = [];
265
397
  const runRows = new Set();
398
+ // Every compaction of the period (sessions and subagents), each with the servers called after it.
399
+ const compactions = [];
400
+ const compactionIds = new Set();
401
+ const reloadsOf = (file) => {
402
+ if (!opts.compactions)
403
+ return;
404
+ try {
405
+ compactions.push(...compactionsIn(file, since, compactionIds));
406
+ }
407
+ catch { /* unreadable: skipped */ }
408
+ };
266
409
  for (const path of mains) {
267
410
  let s;
268
411
  try {
@@ -273,6 +416,7 @@ export function measureStarts(opts = {}) {
273
416
  }
274
417
  if (s)
275
418
  starts.push(s);
419
+ reloadsOf(path);
276
420
  let parentEntry = s?.entrypoint;
277
421
  if (parentEntry === undefined) {
278
422
  try {
@@ -287,6 +431,7 @@ export function measureStarts(opts = {}) {
287
431
  starts.push(sub);
288
432
  }
289
433
  catch { /* unreadable: skipped */ }
434
+ reloadsOf(f.file);
290
435
  }
291
436
  }
292
437
  let configured = new Map();
@@ -355,6 +500,17 @@ export function measureStarts(opts = {}) {
355
500
  const usd = desktop.reduce((sum, s) => sum + s.usd * Math.max(0, s.tokens - t) / s.tokens, 0);
356
501
  report.gap = { desktop: d, terminal: t, tokens: d - t, usd };
357
502
  }
503
+ if (opts.compactions) {
504
+ // A load brings one tool's definition: the server's whole definitions on a start, over its tools.
505
+ const perTool = new Map(startServers(report).map((s) => [s.name, s.tools ? s.tokens / s.tools : 0]));
506
+ const after = compactions
507
+ .map((c) => c.filter((r) => perTool.has(r.server)).map((r) => {
508
+ const usd = reloadUsd(r, perTool.get(r.server));
509
+ return usd === undefined ? { server: r.server, usd: 0, unpriced: true } : { server: r.server, usd };
510
+ }))
511
+ .filter((c) => c.length);
512
+ report.compactions = { total: compactions.length, after };
513
+ }
358
514
  return report;
359
515
  }
360
516
  /** The servers whose tools went whole into some start and that the user's own config holds: `alwaysLoad: false` defers them. */
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "context-doctor",
3
- "version": "0.52.0",
3
+ "version": "0.53.0",
4
4
  "description": "Context and token optimizer for LLM agents: see where Claude Code, Cursor, Codex and Gemini CLI tokens go, then cut them: an every-prompt hook, smarter compaction, an autopilot proxy that edits history only when the prompt cache is cold, RAG chunk packing and an MCP server. Local, no API key. By gAI Ventures.",
5
5
  "keywords": [
6
6
  "agent",