context-doctor 0.47.0 → 0.49.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 (84) hide show
  1. package/README.md +17 -14
  2. package/dist/ab.d.ts +51 -3
  3. package/dist/ab.js +68 -26
  4. package/dist/abclaude.d.ts +167 -0
  5. package/dist/abclaude.js +511 -0
  6. package/dist/abstore.d.ts +46 -0
  7. package/dist/abstore.js +58 -0
  8. package/dist/budget.d.ts +5 -2
  9. package/dist/budget.js +21 -7
  10. package/dist/cache.js +3 -3
  11. package/dist/cachemisses.d.ts +3 -0
  12. package/dist/cachemisses.js +8 -0
  13. package/dist/cachettl.js +6 -2
  14. package/dist/ccost.d.ts +160 -0
  15. package/dist/ccost.js +304 -0
  16. package/dist/cli.js +154 -32
  17. package/dist/cline.d.ts +41 -0
  18. package/dist/cline.js +174 -0
  19. package/dist/coldresume.d.ts +11 -0
  20. package/dist/coldresume.js +3 -3
  21. package/dist/coldreturns.d.ts +145 -0
  22. package/dist/coldreturns.js +282 -0
  23. package/dist/compactcost.d.ts +10 -4
  24. package/dist/compactcost.js +12 -7
  25. package/dist/compactwindow.js +2 -2
  26. package/dist/copilotusage.d.ts +78 -0
  27. package/dist/copilotusage.js +193 -0
  28. package/dist/doctor.d.ts +6 -0
  29. package/dist/doctor.js +17 -4
  30. package/dist/fix.d.ts +35 -4
  31. package/dist/fix.js +55 -8
  32. package/dist/install.js +2 -0
  33. package/dist/limits.d.ts +222 -14
  34. package/dist/limits.js +684 -33
  35. package/dist/mcp.d.ts +4 -0
  36. package/dist/mcp.js +142 -98
  37. package/dist/mcpclient.js +73 -42
  38. package/dist/mcpdefer.d.ts +47 -0
  39. package/dist/mcpdefer.js +91 -0
  40. package/dist/mod/api.d.ts +72 -2
  41. package/dist/mod/api.js +5 -1
  42. package/dist/mod/logic.d.ts +281 -0
  43. package/dist/mod/logic.js +336 -0
  44. package/dist/mod/register.d.ts +35 -2
  45. package/dist/mod/register.js +283 -6
  46. package/dist/modelids.d.ts +58 -0
  47. package/dist/modelids.js +133 -1
  48. package/dist/modmeasure.d.ts +6 -4
  49. package/dist/modmeasure.js +8 -4
  50. package/dist/opencode.d.ts +57 -0
  51. package/dist/opencode.js +234 -0
  52. package/dist/orgrates.d.ts +7 -0
  53. package/dist/orgrates.js +19 -0
  54. package/dist/overhead.d.ts +3 -0
  55. package/dist/overhead.js +5 -1
  56. package/dist/pricing.d.ts +59 -2
  57. package/dist/pricing.js +139 -12
  58. package/dist/proxy.d.ts +8 -1
  59. package/dist/proxy.js +13 -1
  60. package/dist/savings.d.ts +5 -1
  61. package/dist/savings.js +11 -5
  62. package/dist/scan.d.ts +3 -1
  63. package/dist/scan.js +8 -1
  64. package/dist/sessionprice.d.ts +5 -0
  65. package/dist/sessionprice.js +5 -1
  66. package/dist/spend.d.ts +86 -3
  67. package/dist/spend.js +240 -23
  68. package/dist/spendplace.d.ts +40 -0
  69. package/dist/spendplace.js +93 -0
  70. package/dist/spendteam.d.ts +160 -0
  71. package/dist/spendteam.js +286 -0
  72. package/dist/starts.d.ts +106 -0
  73. package/dist/starts.js +406 -0
  74. package/dist/statusline.d.ts +2 -2
  75. package/dist/statusline.js +2 -2
  76. package/dist/subagentmodel.js +9 -7
  77. package/dist/subagentpay.d.ts +31 -2
  78. package/dist/subagentpay.js +232 -68
  79. package/dist/subagents.js +3 -3
  80. package/dist/tasks.js +3 -2
  81. package/dist/tooloutput.js +5 -5
  82. package/dist/usagepane.d.ts +77 -0
  83. package/dist/usagepane.js +287 -0
  84. package/package.json +6 -3
package/dist/starts.js ADDED
@@ -0,0 +1,406 @@
1
+ /**
2
+ * The start of every session and every subagent: the first request's prompt
3
+ * before the first message, per Claude Code entrypoint (the Desktop app, the
4
+ * terminal, the SDK) and per subagent type, priced across the period.
5
+ *
6
+ * Every later request re-reads that start: from the cache at the read price
7
+ * on a warm step, written again at the write price on a cold one. On the
8
+ * author's machine a Desktop-app session starts at a median ~70k tokens and a
9
+ * general-purpose subagent at ~52k, re-read at each of its steps (#105328:
10
+ * a terminal session starts at ~13k, because the tools the terminal defers
11
+ * behind tool search the app sends whole).
12
+ *
13
+ * Claude Code records what it sent: each transcript's `api-request-shape`
14
+ * rows carry the request's system prompt and every tool definition, with
15
+ * `defer_loading` on the ones held behind tool search, and the
16
+ * `deferred_tools_delta` attachments name the ones announced as deferred. So
17
+ * the part of a start that could be deferred, MCP tool definitions sent whole,
18
+ * is read from the request itself; its tokens are estimated from its length
19
+ * (Claude's ratios), the start itself is the API's own count.
20
+ */
21
+ import { readFileSync } from "node:fs";
22
+ import { claudeMcpConfigs } from "./mcpschema.js";
23
+ import { REQUEST_ROWS } from "./coldresume.js";
24
+ import { rowsOf } from "./scan.js";
25
+ import { listSessions, isClaudeSession, replyCounter, textOf } from "./session.js";
26
+ import { subagentFiles, workflowRunOf } from "./subagents.js";
27
+ import { cacheWriteSplit, formatUsd, rateCard, ratesAt, usageCost } from "./pricing.js";
28
+ import { formatTokens, isCodeLike, realModel, tokensForLength } from "./tokens.js";
29
+ const CLAUDE = "claude-opus-5";
30
+ /**
31
+ * What a start's measurement takes from a transcript: the entrypoint, the
32
+ * first request's query source (it names a subagent's type), the first user
33
+ * message's length (never its text), the tools announced as deferred before
34
+ * the first reply, and the first request's shape as names and lengths. A
35
+ * handful of records per transcript, read once (scan.ts).
36
+ */
37
+ export const START_ROWS = {
38
+ id: "starts.1",
39
+ init: () => ({}),
40
+ line(raw, row, out, st) {
41
+ const want = (!st.e && raw.includes('"entrypoint"')) ||
42
+ (!st.q && raw.includes('"api-request"')) ||
43
+ (!st.s && raw.includes('"api-request-shape"')) ||
44
+ (!st.u && raw.includes('"user"')) ||
45
+ (!st.r && (raw.includes('"deferred_tools_delta"') || raw.includes('"usage"')));
46
+ if (!want)
47
+ return;
48
+ let e;
49
+ try {
50
+ e = row();
51
+ }
52
+ catch {
53
+ return;
54
+ }
55
+ if (!e || typeof e !== "object")
56
+ return;
57
+ if (!st.e && typeof e.entrypoint === "string" && e.entrypoint) {
58
+ st.e = 1;
59
+ out.push({ k: "e", v: e.entrypoint.slice(0, 40) });
60
+ }
61
+ if (e.type === "api-request" && !st.q && typeof e.querySource === "string") {
62
+ st.q = 1;
63
+ out.push({ k: "q", v: e.querySource.slice(0, 120) });
64
+ }
65
+ if (e.type === "api-request-shape" && !st.s && e.shape && typeof e.shape === "object") {
66
+ st.s = 1;
67
+ const tools = [];
68
+ for (const t of Array.isArray(e.shape.tools) ? e.shape.tools : []) {
69
+ if (!t || typeof t !== "object" || typeof t.name !== "string")
70
+ continue;
71
+ tools.push([t.name.slice(0, 200), JSON.stringify(t).length, t.defer_loading === true ? 1 : 0]);
72
+ }
73
+ const sys = e.shape.system === undefined ? 0 : JSON.stringify(e.shape.system).length;
74
+ out.push({ k: "s", sys, tools });
75
+ }
76
+ if (!st.r && e.type === "attachment" && e.attachment?.type === "deferred_tools_delta" && Array.isArray(e.attachment.addedNames)) {
77
+ out.push({ k: "d", names: e.attachment.addedNames.filter((n) => typeof n === "string").map((n) => n.slice(0, 200)) });
78
+ }
79
+ if (!st.u && e.type === "user" && !e.isMeta) {
80
+ const text = textOf(e.message?.content);
81
+ if (text) {
82
+ st.u = 1;
83
+ out.push({ k: "u", len: text.length, code: isCodeLike(text) });
84
+ }
85
+ }
86
+ if (!st.r && e.type === "assistant") {
87
+ const u = e.message?.usage;
88
+ if (u && (Number(u.input_tokens) || 0) + (Number(u.cache_read_input_tokens) || 0) + (Number(u.cache_creation_input_tokens) || 0) > 0)
89
+ st.r = 1;
90
+ }
91
+ },
92
+ };
93
+ /** An entrypoint as people call it. */
94
+ export function entrypointName(e) {
95
+ switch (e) {
96
+ case "claude-desktop": return "Desktop app";
97
+ case "cli": return "terminal";
98
+ case "sdk-cli": return "claude -p / SDK";
99
+ case "sdk-ts":
100
+ case "sdk-py": return "Agent SDK";
101
+ case "claude-vscode": return "VS Code";
102
+ case undefined:
103
+ case "": return "unknown";
104
+ default: return e;
105
+ }
106
+ }
107
+ /** The MCP server a tool name belongs to (`mcp__<server>__<tool>`), or undefined for a built-in. */
108
+ export function mcpServerOf(name) {
109
+ const m = /^mcp__(.+?)__/.exec(name);
110
+ return m?.[1];
111
+ }
112
+ function quantile(sorted, q) {
113
+ return sorted[Math.min(sorted.length - 1, Math.floor(sorted.length * q))];
114
+ }
115
+ /** The subagent's type: its meta file's `agentType`, else the first request's query source, else a workflow agent. */
116
+ function agentTypeOf(file, querySource) {
117
+ try {
118
+ const t = JSON.parse(readFileSync(file.replace(/\.jsonl$/, ".meta.json"), "utf8"))?.agentType;
119
+ if (typeof t === "string" && t)
120
+ return t.slice(0, 80);
121
+ }
122
+ catch { /* none */ }
123
+ const q = querySource && /^agent:(?:builtin|custom|plugin|user|project)?:?(.+)$/.exec(querySource)?.[1];
124
+ if (q)
125
+ return q.slice(0, 80);
126
+ return workflowRunOf(file) ? "workflow" : "unknown";
127
+ }
128
+ /** One transcript's start and what it cost across the period, or undefined when it has none to measure. */
129
+ function measureStart(path, kind, since, runRows, parentEntry) {
130
+ const meta = rowsOf(path, START_ROWS);
131
+ let entrypoint = parentEntry, querySource, user, shape;
132
+ const deferred = new Set();
133
+ for (const r of meta) {
134
+ if (r.k === "e")
135
+ entrypoint = r.v;
136
+ else if (r.k === "q")
137
+ querySource = r.v;
138
+ else if (r.k === "u")
139
+ user = r;
140
+ else if (r.k === "d")
141
+ for (const n of r.names)
142
+ deferred.add(n);
143
+ else if (r.k === "s")
144
+ shape = r;
145
+ }
146
+ const sighting = replyCounter(runRows);
147
+ let tokens;
148
+ let usd = 0, requests = 0, priced = true, started = false;
149
+ for (const e of rowsOf(path, REQUEST_ROWS)) {
150
+ if (!e || e.type !== "assistant" || !e.message?.usage)
151
+ continue;
152
+ // A session's own thread; a subagent's transcript is all sidechain.
153
+ if (kind === "session" && e.isSidechain)
154
+ continue;
155
+ const seen = sighting(e);
156
+ if (seen === "repeat")
157
+ continue;
158
+ const u = e.message.usage;
159
+ const read = Number(u.cache_read_input_tokens) || 0, write = Number(u.cache_creation_input_tokens) || 0, input = Number(u.input_tokens) || 0;
160
+ const prompt = input + read + write;
161
+ const at = Date.parse(e.timestamp);
162
+ if (!(prompt > 0) || !Number.isFinite(at))
163
+ continue;
164
+ if (!started) {
165
+ started = true;
166
+ // A fork's first request is its parent's: not a start of its own.
167
+ if (seen !== "new")
168
+ return undefined;
169
+ tokens = Math.max(0, prompt - (user ? tokensForLength(user.len, user.code, CLAUDE) : 0));
170
+ if (tokens <= 1000)
171
+ return undefined;
172
+ }
173
+ if (seen === "copy" || at < since)
174
+ continue;
175
+ requests++;
176
+ // The start's tokens on this request, at the rates it paid for them: read from the cache first, then written, then uncached.
177
+ const part = Math.min(tokens, prompt);
178
+ const r = Math.min(part, read);
179
+ const w = Math.min(part - r, write);
180
+ const split = cacheWriteSplit(u);
181
+ const all = split.fiveMinute + split.oneHour + split.twelveHour;
182
+ const oneHour = all > 0 ? (w * split.oneHour) / all : 0;
183
+ const card = rateCard(realModel(e.message.model), u, at);
184
+ if (!card) {
185
+ priced = false;
186
+ continue;
187
+ }
188
+ usd += usageCost({ input_tokens: part - r - w, cache_read_input_tokens: r, cache_creation_input_tokens: w, cache_creation: { ephemeral_5m_input_tokens: w - oneHour, ephemeral_1h_input_tokens: oneHour } }, ratesAt(card, prompt)).promptUsd;
189
+ }
190
+ if (tokens === undefined || requests === 0)
191
+ return undefined;
192
+ const start = { kind, entrypoint, tokens, usd, priced, requests };
193
+ if (kind === "subagent")
194
+ start.agentType = agentTypeOf(path, querySource);
195
+ if (shape) {
196
+ const servers = new Map();
197
+ let wholeTools = 0, wholeTokens = 0, mcpTokens = 0;
198
+ for (const [name, chars, d] of shape.tools) {
199
+ if (d || deferred.has(name))
200
+ continue;
201
+ // Tool definitions are mostly descriptions: prose ratios (an estimate, labelled so).
202
+ const t = tokensForLength(chars, false, CLAUDE);
203
+ wholeTools++;
204
+ wholeTokens += t;
205
+ const server = mcpServerOf(name);
206
+ if (!server)
207
+ continue;
208
+ mcpTokens += t;
209
+ const s = servers.get(server) ?? servers.set(server, { tools: 0, tokens: 0 }).get(server);
210
+ s.tools++;
211
+ s.tokens += t;
212
+ }
213
+ start.shape = { wholeTools, wholeTokens: Math.min(wholeTokens, tokens), mcpTokens: Math.min(mcpTokens, tokens), servers };
214
+ }
215
+ return start;
216
+ }
217
+ /** Claude Code transcripts written in the last `days` days. */
218
+ function claudeTranscripts(days) {
219
+ const since = Date.now() - days * 86_400_000;
220
+ return listSessions(10_000).filter((s) => isClaudeSession(s) && s.modifiedAt.getTime() >= since).map((s) => s.path);
221
+ }
222
+ /**
223
+ * Every session's and subagent's start in the period, grouped by entrypoint
224
+ * and subagent type, each priced on every request that re-read it.
225
+ * `paths`: the main transcripts (subagents are found beside each).
226
+ */
227
+ export function measureStarts(opts = {}) {
228
+ const days = opts.days ?? 30;
229
+ const since = Date.now() - days * 86_400_000;
230
+ const mains = (opts.paths ?? claudeTranscripts(days)).filter((p) => !/[\\/]\.codex[\\/]/.test(p) && !/[\\/]\.gemini[\\/]/.test(p));
231
+ const starts = [];
232
+ const runRows = new Set();
233
+ for (const path of mains) {
234
+ let s;
235
+ try {
236
+ s = measureStart(path, "session", since, runRows);
237
+ }
238
+ catch {
239
+ continue;
240
+ }
241
+ if (s)
242
+ starts.push(s);
243
+ let parentEntry = s?.entrypoint;
244
+ if (parentEntry === undefined) {
245
+ try {
246
+ parentEntry = rowsOf(path, START_ROWS).find((r) => r.k === "e")?.v;
247
+ }
248
+ catch { /* unreadable */ }
249
+ }
250
+ for (const f of subagentFiles(path, since)) {
251
+ try {
252
+ const sub = measureStart(f.file, "subagent", since, undefined, parentEntry);
253
+ if (sub)
254
+ starts.push(sub);
255
+ }
256
+ catch { /* unreadable: skipped */ }
257
+ }
258
+ }
259
+ let configured = new Map();
260
+ try {
261
+ configured = new Map(claudeMcpConfigs(opts.cwd, opts.home).map((c) => [c.name, c.scope]));
262
+ }
263
+ catch { /* none */ }
264
+ const byKey = new Map();
265
+ for (const s of starts) {
266
+ const k = `${s.kind}\u0000${s.entrypoint ?? ""}\u0000${s.agentType ?? ""}`;
267
+ (byKey.get(k) ?? byKey.set(k, []).get(k)).push(s);
268
+ }
269
+ const groups = [];
270
+ for (const list of byKey.values()) {
271
+ const first = list[0];
272
+ const sorted = list.map((s) => s.tokens).sort((a, b) => a - b);
273
+ const shaped = list.filter((s) => s.shape);
274
+ const med = (xs) => (xs.length ? xs.sort((a, b) => a - b)[Math.floor(xs.length / 2)] : undefined);
275
+ const servers = new Map();
276
+ for (const s of shaped)
277
+ for (const [name, v] of s.shape.servers) {
278
+ const cur = servers.get(name) ?? servers.set(name, { name, starts: 0, tools: 0, tokens: 0, ...(configured.get(name) ? { configured: configured.get(name) } : {}) }).get(name);
279
+ cur.starts++;
280
+ cur.tools = Math.max(cur.tools, v.tools);
281
+ cur.tokens += v.tokens;
282
+ }
283
+ for (const s of servers.values())
284
+ s.tokens = Math.round(s.tokens / s.starts);
285
+ const g = {
286
+ kind: first.kind,
287
+ entrypoint: first.entrypoint ?? "",
288
+ ...(first.agentType ? { agentType: first.agentType } : {}),
289
+ starts: list.length,
290
+ median: quantile(sorted, 0.5),
291
+ p10: quantile(sorted, 0.1),
292
+ p90: quantile(sorted, 0.9),
293
+ requests: list.reduce((t, s) => t + s.requests, 0),
294
+ usd: list.reduce((t, s) => t + s.usd, 0),
295
+ unpriced: list.filter((s) => !s.priced).length,
296
+ shaped: shaped.length,
297
+ servers: [...servers.values()].sort((a, b) => b.starts * b.tokens - a.starts * a.tokens),
298
+ };
299
+ if (shaped.length) {
300
+ g.wholeTokens = med(shaped.map((s) => s.shape.wholeTokens));
301
+ g.mcpTokens = med(shaped.map((s) => s.shape.mcpTokens));
302
+ g.wholeTools = med(shaped.map((s) => s.shape.wholeTools));
303
+ g.deferrableUsd = shaped.reduce((t, s) => t + s.usd * Math.min(1, s.shape.mcpTokens / s.tokens), 0);
304
+ }
305
+ groups.push(g);
306
+ }
307
+ groups.sort((a, b) => (a.kind === b.kind ? b.usd - a.usd : a.kind === "session" ? -1 : 1));
308
+ const report = { days, groups };
309
+ const desktop = starts.filter((s) => s.kind === "session" && s.entrypoint === "claude-desktop");
310
+ const terminal = starts.filter((s) => s.kind === "session" && s.entrypoint === "cli");
311
+ if (desktop.length && terminal.length) {
312
+ const d = quantile(desktop.map((s) => s.tokens).sort((a, b) => a - b), 0.5);
313
+ const t = quantile(terminal.map((s) => s.tokens).sort((a, b) => a - b), 0.5);
314
+ // What the Desktop app's starts cost above a terminal-sized start, each at its own requests' rates.
315
+ const usd = desktop.reduce((sum, s) => sum + s.usd * Math.max(0, s.tokens - t) / s.tokens, 0);
316
+ report.gap = { desktop: d, terminal: t, tokens: d - t, usd };
317
+ }
318
+ return report;
319
+ }
320
+ /** The servers whose tools went whole into some start and that the user's own config holds: `alwaysLoad: false` defers them. */
321
+ export function deferrableConfigured(r) {
322
+ const out = new Map();
323
+ for (const g of r.groups) {
324
+ if (!g.mcpTokens || !g.deferrableUsd)
325
+ continue;
326
+ for (const s of g.servers) {
327
+ if (!s.configured)
328
+ continue;
329
+ const cur = out.get(s.name) ?? out.set(s.name, { name: s.name, scope: s.configured, tokens: 0, usd: 0 }).get(s.name);
330
+ cur.tokens = Math.max(cur.tokens, s.tokens);
331
+ // Its share of the group's deferrable part, by its tokens on the starts it went into.
332
+ cur.usd += g.deferrableUsd * (s.tokens * s.starts) / (g.servers.reduce((t, x) => t + x.tokens * x.starts, 0) || 1);
333
+ }
334
+ }
335
+ return [...out.values()].sort((a, b) => b.usd - a.usd);
336
+ }
337
+ const tok = (n) => `~${formatTokens(n)}`;
338
+ /** The starts section of `overhead`. */
339
+ export function renderStarts(r) {
340
+ const out = ["", "Session and subagent starts (the first request, before the first message)", "─".repeat(56)];
341
+ if (r.groups.length === 0) {
342
+ out.push(" No Claude Code session in the period to measure.");
343
+ return out;
344
+ }
345
+ const line = (label, g) => {
346
+ const cost = `${formatUsd(g.usd)}${g.unpriced ? "+" : ""}`;
347
+ out.push(` ${label.padEnd(30)} ${String(g.starts).padStart(4)} median ${tok(g.median).padStart(6)} (p10 ${tok(g.p10)}, p90 ${tok(g.p90)}) ${g.requests.toLocaleString("en-US")} steps re-read it: ${cost}`);
348
+ if (g.mcpTokens !== undefined && g.wholeTokens !== undefined) {
349
+ out.push(` ${"".padEnd(30)} tools sent whole ${tok(g.wholeTokens)} (${g.wholeTools} tools), of which MCP ${tok(g.mcpTokens)}${g.deferrableUsd ? `: ${formatUsd(g.deferrableUsd)} of the ${cost}` : ""}${g.shaped < g.starts ? ` (${g.shaped} of ${g.starts} starts record their tools)` : ""}`);
350
+ }
351
+ };
352
+ const sessions = r.groups.filter((g) => g.kind === "session");
353
+ const subs = r.groups.filter((g) => g.kind === "subagent");
354
+ for (const g of sessions)
355
+ line(`${entrypointName(g.entrypoint)} sessions`, g);
356
+ for (const g of subs)
357
+ line(`${g.agentType} (subagent)${new Set(subs.map((x) => x.entrypoint)).size > 1 ? ` (${entrypointName(g.entrypoint)})` : ""}`, g);
358
+ const total = r.groups.reduce((t, g) => t + g.usd, 0);
359
+ const subUsd = subs.reduce((t, g) => t + g.usd, 0);
360
+ out.push(` Every start, re-read at each step over ${r.days} days: ${formatUsd(total)}${subs.length ? ` (subagents ${formatUsd(subUsd)})` : ""}. Token counts are the API's; tool sizes are estimates from their length.`);
361
+ if (r.gap && r.gap.tokens > 0) {
362
+ out.push(` Desktop app vs terminal: a Desktop session starts ~${formatTokens(r.gap.tokens)} tokens larger (median ${tok(r.gap.desktop)} against ${tok(r.gap.terminal)}): ${formatUsd(r.gap.usd)} of its starts' cost in ${r.days} days.`);
363
+ }
364
+ else if (r.gap) {
365
+ out.push(` Desktop app vs terminal: a Desktop session starts no larger here (median ${tok(r.gap.desktop)} against ${tok(r.gap.terminal)}).`);
366
+ }
367
+ else if (sessions.some((g) => g.entrypoint === "claude-desktop")) {
368
+ out.push(" No terminal sessions in the period to compare the Desktop app's start with (#105328 reports ~79k against ~13k).");
369
+ }
370
+ // What could be deferred, and whether any setting reaches it.
371
+ const servers = new Map();
372
+ for (const g of r.groups)
373
+ for (const s of g.servers) {
374
+ const share = g.deferrableUsd ? (g.deferrableUsd * s.tokens * s.starts) / (g.servers.reduce((t, x) => t + x.tokens * x.starts, 0) || 1) : 0;
375
+ const cur = servers.get(s.name);
376
+ if (cur) {
377
+ cur.usd += share;
378
+ cur.starts += s.starts;
379
+ cur.tokens = Math.max(cur.tokens, s.tokens);
380
+ cur.tools = Math.max(cur.tools, s.tools);
381
+ }
382
+ else
383
+ servers.set(s.name, { ...s, usd: share });
384
+ }
385
+ const list = [...servers.values()].sort((a, b) => b.usd - a.usd);
386
+ if (list.length) {
387
+ out.push(" MCP tool definitions sent whole (not deferred behind tool search):");
388
+ for (const s of list.slice(0, 8)) {
389
+ const where = s.configured ? `your ${s.configured === "user" ? "~/.claude.json" : s.configured === "project" ? "~/.claude.json (this project)" : ".mcp.json"}: \`alwaysLoad: false\` defers it` : "provided by the app or a connector";
390
+ const name = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(s.name) ? `claude.ai connector ${s.name.slice(0, 8)}` : s.name;
391
+ out.push(` ${name.padEnd(28)} ${String(s.tools).padStart(3)} tools ${tok(s.tokens).padStart(6)} ${formatUsd(s.usd).padStart(8)} ${where}`);
392
+ }
393
+ if (list.length > 8)
394
+ out.push(` … ${list.length - 8} more`);
395
+ const app = list.filter((s) => !s.configured);
396
+ if (app.length) {
397
+ out.push(` No setting defers the ${app.length === 1 ? "server" : `${app.length} servers`} the app provides (${formatUsd(app.reduce((t, s) => t + s.usd, 0))} of the starts' cost): the Desktop app hands its own servers and connectors to Claude Code in-process with their tools marked to load upfront, and no MCP setting or ENABLE_TOOL_SEARCH value reaches them (tool search is on: the other tools are deferred). A subagent definition's \`tools:\` list or \`disallowedTools: mcp__*\` keeps them out of that agent's start, and out of its reach too.`);
398
+ }
399
+ if (list.some((s) => s.configured))
400
+ out.push(" `context-doctor fix --apply mcp-defer` sets `alwaysLoad: false` on the ones in your own config (reversible with `fix undo mcp-defer`).");
401
+ }
402
+ else if (r.groups.some((g) => g.shaped > 0)) {
403
+ out.push(" Every MCP tool definition was deferred behind tool search: nothing of the start to defer.");
404
+ }
405
+ return out;
406
+ }
@@ -15,7 +15,7 @@
15
15
  * (`prompt_cache.last_miss_cause`) goes to
16
16
  * ~/.claude/.context-doctor-misses.jsonl for `cache-misses`. And the limit
17
17
  * ledger: when Claude Code passes `rate_limits`
18
- * (Pro and Max), each new 5-hour and weekly reading is appended to
18
+ * (Pro, Max and Ultra; Ultra has no 5-hour window), each new reading is appended to
19
19
  * ~/.claude/.context-doctor-limits.jsonl for `context-doctor limits`.
20
20
  *
21
21
  * With a spend budget set (`context-doctor budget`), the session's cost gives
@@ -33,7 +33,7 @@ import { type RecordedUsage } from "./pricing.js";
33
33
  interface StatusInput {
34
34
  session_id?: string;
35
35
  transcript_path?: string;
36
- /** Pro/Max (or a gateway's spend limit), after the first reply: each window's used_percentage and resets_at. */
36
+ /** Pro, Max and Ultra (or a gateway's spend limit), after the first reply: each window's used_percentage and resets_at (no five_hour on Ultra). */
37
37
  rate_limits?: unknown;
38
38
  model?: {
39
39
  id?: string;
@@ -15,7 +15,7 @@
15
15
  * (`prompt_cache.last_miss_cause`) goes to
16
16
  * ~/.claude/.context-doctor-misses.jsonl for `cache-misses`. And the limit
17
17
  * ledger: when Claude Code passes `rate_limits`
18
- * (Pro and Max), each new 5-hour and weekly reading is appended to
18
+ * (Pro, Max and Ultra; Ultra has no 5-hour window), each new reading is appended to
19
19
  * ~/.claude/.context-doctor-limits.jsonl for `context-doctor limits`.
20
20
  *
21
21
  * With a spend budget set (`context-doctor budget`), the session's cost gives
@@ -200,7 +200,7 @@ export async function runStatusLine() {
200
200
  // After the line is out: the limit readings `context-doctor limits` fits
201
201
  // (only when Claude Code sends them; a few bytes, only on a change).
202
202
  if (process.env.CONTEXT_DOCTOR_NO_LIMITS_LOG !== "1")
203
- recordLimits(input?.rate_limits);
203
+ recordLimits(input?.rate_limits, undefined, undefined, "statusline");
204
204
  // And Claude Code's diagnosis of a new cache miss, for `cache-misses`
205
205
  // (2.1.260+; one short line per miss, nothing on other refreshes).
206
206
  if (process.env.CONTEXT_DOCTOR_NO_MISS_LOG !== "1")
@@ -34,7 +34,7 @@ import { existsSync, readdirSync, readFileSync, realpathSync, statSync } from "n
34
34
  import { homedir } from "node:os";
35
35
  import { dirname, join, resolve } from "node:path";
36
36
  import { pick, rowsOf, slimUsage } from "./scan.js";
37
- import { pricingFor, rateCard, ratesAt, requestCost, usageCost, WEB_SEARCH_USD } from "./pricing.js";
37
+ import { billedCost, pricingFor, rateCard, ratesAt, requestCost, usageCost, WEB_SEARCH_USD } from "./pricing.js";
38
38
  import { realModel } from "./tokens.js";
39
39
  import { claudeDir } from "./claudedir.js";
40
40
  import { subagentTranscripts } from "./cachettl.js";
@@ -73,7 +73,7 @@ const READ_ONLY = new Set(["Explore", "Plan"]);
73
73
  * last row); the working folder once, to find the project's agent files.
74
74
  */
75
75
  export const SUBAGENT_ROWS = {
76
- id: "subagent-requests.2",
76
+ id: "subagent-requests.3",
77
77
  init: () => ({ out: {}, cwd: false }),
78
78
  line(raw, row, out, st) {
79
79
  const usage = raw.includes('"usage"');
@@ -107,7 +107,7 @@ export const SUBAGENT_ROWS = {
107
107
  }
108
108
  if (id)
109
109
  st.out[id] = output;
110
- out.push({ t: "r", ...pick(e, ["uuid", "timestamp"]), id, model: m.model, usage: slimUsage(m.usage) });
110
+ out.push({ t: "r", ...pick(e, ["uuid", "timestamp"]), id, model: m.model, usage: slimUsage(m.usage, { iterations: true }) });
111
111
  },
112
112
  };
113
113
  /** The `.md` files under `dir`, subfolders included (Claude Code reads agent folders recursively). */
@@ -348,11 +348,13 @@ export function replaySubagentModels(opts) {
348
348
  const price = pricingFor(model);
349
349
  const u = r.usage;
350
350
  // Each arm as that model would bill these tokens (requestCost): its tier (Haiku 5.5 over 100k), US-only, web searches.
351
- const asBilled = requestCost(model, u, at);
351
+ const asBilled = billedCost(model, u, at);
352
352
  if (!price || !asBilled) {
353
353
  unpriced++;
354
354
  continue;
355
355
  }
356
+ // The iterations its usage leaves out (an advisor's call, a declined attempt): billed, and unchanged by a move.
357
+ const extra = asBilled.extra?.usd ?? 0;
356
358
  const atCand = requestCost(candidate, u, at);
357
359
  const atHaiku = requestCost(HAIKU, u, at);
358
360
  const billed = asBilled.totalUsd;
@@ -361,14 +363,14 @@ export function replaySubagentModels(opts) {
361
363
  t.requests++;
362
364
  counted = true;
363
365
  t.billedUsd += billed;
364
- t.atCandidateUsd += move ? other.totalUsd : billed;
365
- t.atHaikuUsd += atHaiku.totalUsd;
366
+ t.atCandidateUsd += move ? other.totalUsd + (other === asBilled ? 0 : extra) : billed;
367
+ t.atHaikuUsd += atHaiku.totalUsd + extra;
366
368
  if (promptTokens(u) > HAIKU_TIER)
367
369
  t.over100k++;
368
370
  if (move)
369
371
  add(movedBy, model, billed);
370
372
  if (how.moves)
371
- add(beforeBy, model, atCand.totalUsd);
373
+ add(beforeBy, model, atCand.totalUsd + extra);
372
374
  if (r.id)
373
375
  priced.set(r.id, { billed: asBilled.rates, other: other.rates, haiku: atHaiku.rates, cand: atCand.rates, model });
374
376
  }
@@ -24,6 +24,7 @@
24
24
  * window for a hard task) and what the parent would have spent on its own tool
25
25
  * calls, so "did not pay" means "did not pay in context", not "was a mistake".
26
26
  */
27
+ import { type Extractor } from "./scan.js";
27
28
  import { type ModelPricing } from "./pricing.js";
28
29
  /**
29
30
  * The model `fix` offers the subagents (subagentmodel.ts): the id the price
@@ -80,16 +81,44 @@ export interface SubagentTokens {
80
81
  write: number;
81
82
  output: number;
82
83
  }
84
+ /**
85
+ * What `subagents` takes from a subagent's transcript, through the shared
86
+ * scan (scan.ts), so a second run reads only what was appended: each reply's
87
+ * id, model, time and usage (every row, for the output a streamed reply
88
+ * settles on its last: a later row keeps only that), and the tool output
89
+ * each user row hands it, as tokens. The task is read from the transcript's
90
+ * head when needed (subagentTask): the cache keeps no message text.
91
+ */
92
+ export declare const SUBAGENT_ROWS: Extractor<{
93
+ ids: Record<string, 1>;
94
+ }>;
95
+ /**
96
+ * A subagent's task: the first user row with text, read from the
97
+ * transcript's head (16 KB at a time, at most 1 MB): only for a subagent
98
+ * whose meta file gives no description.
99
+ */
100
+ export declare function subagentTask(path: string): string;
101
+ /**
102
+ * What `subagents` takes from a parent transcript, through the shared scan:
103
+ * its main-thread replies (time, model, prompt size, what changes their
104
+ * rates, cache writes by lifetime), its compactions, and every row that
105
+ * mentions one of its subagents (the Agent tool's result for that call, a
106
+ * background agent's task notification), as tokens and the ids it names:
107
+ * the calls of the Agent tool it made (kept in the state), and the ids a
108
+ * notification names (`<task-id>`, `<tool-use-id>`, `agentId:`).
109
+ */
110
+ export declare const PARENT_ROWS: Extractor<{
111
+ calls: string[];
112
+ }>;
83
113
  /**
84
114
  * A subagent's bill (each request as billed, requestCost), steps, startup
85
115
  * context, start time, the tool output it read, and the rates its first
86
- * request billed at.
116
+ * request billed at. Read through the shared scan (SUBAGENT_ROWS).
87
117
  */
88
118
  export declare function scanSubagent(path: string): {
89
119
  costUsd: number;
90
120
  atSonnetUsd: number;
91
121
  readTokens: number;
92
- task: string;
93
122
  steps: number;
94
123
  startup: number;
95
124
  start: number;