context-doctor 0.49.1 → 0.50.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 (46) hide show
  1. package/README.md +15 -14
  2. package/dist/appwindow.d.ts +69 -0
  3. package/dist/appwindow.js +147 -0
  4. package/dist/ccost.js +8 -4
  5. package/dist/claudedir.d.ts +15 -0
  6. package/dist/claudedir.js +19 -1
  7. package/dist/cli.js +59 -23
  8. package/dist/clihelp.d.ts +5 -1
  9. package/dist/clihelp.js +9 -1
  10. package/dist/codexstatusline.d.ts +176 -0
  11. package/dist/codexstatusline.js +353 -0
  12. package/dist/compactwindow.d.ts +14 -2
  13. package/dist/compactwindow.js +30 -5
  14. package/dist/credits.d.ts +130 -0
  15. package/dist/credits.js +265 -0
  16. package/dist/doctor.d.ts +6 -0
  17. package/dist/doctor.js +15 -1
  18. package/dist/fanout.d.ts +2 -0
  19. package/dist/fanout.js +12 -2
  20. package/dist/fix.d.ts +37 -1
  21. package/dist/fix.js +67 -9
  22. package/dist/limits.d.ts +45 -1
  23. package/dist/limits.js +121 -9
  24. package/dist/mcp.d.ts +1 -0
  25. package/dist/mcp.js +106 -100
  26. package/dist/mod/api.d.ts +27 -1
  27. package/dist/mod/api.js +2 -1
  28. package/dist/mod/logic.d.ts +39 -0
  29. package/dist/mod/logic.js +42 -1
  30. package/dist/mod/register.d.ts +4 -0
  31. package/dist/mod/register.js +25 -1
  32. package/dist/modelids.js +2 -2
  33. package/dist/orgrates.d.ts +4 -2
  34. package/dist/orgrates.js +21 -3
  35. package/dist/overhead.js +2 -1
  36. package/dist/pricing.js +7 -0
  37. package/dist/progresssummaries.d.ts +20 -1
  38. package/dist/progresssummaries.js +33 -3
  39. package/dist/proxy.d.ts +1 -1
  40. package/dist/proxy.js +9 -4
  41. package/dist/savings.js +3 -1
  42. package/dist/spend.d.ts +28 -1
  43. package/dist/spend.js +38 -5
  44. package/dist/starts.d.ts +27 -1
  45. package/dist/starts.js +81 -18
  46. package/package.json +1 -1
@@ -0,0 +1,265 @@
1
+ /**
2
+ * Past the plan's limit: which Claude Code requests were paid from usage
3
+ * credits ("extra usage"), and about how much.
4
+ *
5
+ * With extra usage on, Claude Code keeps working when a weekly or 5-hour
6
+ * limit runs out and the requests are paid from credits: real money that
7
+ * the limits' % no longer shows. Two sources say when:
8
+ *
9
+ * - The proxy records the API's `anthropic-ratelimit-unified-overage-*`
10
+ * headers into the limits ledger (limits.ts recordOverage). A request
11
+ * made while the newest of those readings (at most 16 minutes old) said
12
+ * `in-use: true` was paid from credits; `false` says it was not.
13
+ * - The plugin's mod and the status line hand over only the windows' %,
14
+ * nothing about credits. A request that still went through (it has
15
+ * usage in its transcript) after a window read 100% and before that
16
+ * window reset is past the limit, and with extra usage on most likely
17
+ * paid from credits: counted as inferred, and said to be. With extra
18
+ * usage off (`~/.claude.json`, claudedir.ts readExtraUsage) nothing is
19
+ * inferred.
20
+ *
21
+ * Dollars are each request at API list prices, as `spend` prices it.
22
+ * Whether usage credits are billed at exactly those prices is not verified
23
+ * here, so every figure is said to be an estimate. Read only by commands
24
+ * the user runs (`limits`, `spend`, `doctor`): nothing is drawn or sent.
25
+ */
26
+ import { readExtraUsage } from "./claudedir.js";
27
+ import { claudeUsage, cleanReadings, CLAUDE_WINDOWS, limitsLogPath, readClaudeReadings, readOverageReadings } from "./limits.js";
28
+ const MIN = 60_000;
29
+ const HOUR = 60 * MIN;
30
+ const DAY = 24 * HOUR;
31
+ /** A credits reading stands for this long: the proxy writes it again every 15 minutes while it holds. */
32
+ const HEADER_STALE_MS = 16 * MIN;
33
+ /** A reading written this long after a request's row still speaks for it (the row and the reading are written around the same reply). */
34
+ const HEADER_LAG_MS = MIN;
35
+ /** Two readings' resets this close name the same window period. */
36
+ const SAME_RESET_MS = 10 * MIN;
37
+ /** Credited requests with no window to tie them to start a new episode after this long apart. */
38
+ const EPISODE_GAP_MS = 5 * HOUR;
39
+ /**
40
+ * The stretches in which a Claude window stood at 100% or more: from its
41
+ * first such reading to the window's reset. Within a period the % never
42
+ * falls, so once a window reads 100% it is spent until it resets.
43
+ */
44
+ export function spentSpans(readings) {
45
+ const out = [];
46
+ for (const w of CLAUDE_WINDOWS) {
47
+ const rs = cleanReadings(readings.filter((r) => r.app === "claude" && r.window === w));
48
+ let open;
49
+ const close = (next) => {
50
+ if (!open)
51
+ return;
52
+ const end = Math.min(open.resetsAt ?? Infinity, next ?? Infinity);
53
+ out.push({ window: w, from: open.from, to: Number.isFinite(end) ? end : open.last + HEADER_STALE_MS, ...(open.resetsAt !== undefined ? { resetsAt: open.resetsAt } : {}) });
54
+ open = undefined;
55
+ };
56
+ for (const r of rs) {
57
+ if (open) {
58
+ const same = open.resetsAt !== undefined && r.resetsAt !== undefined ? Math.abs(open.resetsAt - r.resetsAt) <= SAME_RESET_MS : r.pct >= 100;
59
+ if (same && !(open.resetsAt !== undefined && r.ts >= open.resetsAt)) {
60
+ open.last = r.ts;
61
+ continue;
62
+ }
63
+ close(r.ts);
64
+ }
65
+ if (r.pct >= 100)
66
+ open = { window: w, from: r.ts, to: 0, last: r.ts, ...(r.resetsAt !== undefined ? { resetsAt: r.resetsAt } : {}) };
67
+ }
68
+ close();
69
+ }
70
+ return out.sort((a, b) => a.from - b.from);
71
+ }
72
+ /** The newest credits reading with an in-use word at or just after `ts`, if it still speaks for `ts`. */
73
+ function headerAt(overage, ts) {
74
+ let lo = 0, hi = overage.length - 1, at = -1;
75
+ while (lo <= hi) {
76
+ const mid = (lo + hi) >> 1;
77
+ if (overage[mid].ts <= ts + HEADER_LAG_MS) {
78
+ at = mid;
79
+ lo = mid + 1;
80
+ }
81
+ else
82
+ hi = mid - 1;
83
+ }
84
+ for (let i = at; i >= 0; i--) {
85
+ const o = overage[i];
86
+ if (ts - o.ts > HEADER_STALE_MS)
87
+ return undefined;
88
+ if (o.inUse !== undefined)
89
+ return o;
90
+ }
91
+ return undefined;
92
+ }
93
+ /**
94
+ * Sort requests (anything with a time and dollars: limits' usage points,
95
+ * spend's items) into runs past the limit. A request counts when the
96
+ * credits reading that speaks for it says in use, or, with no such
97
+ * reading, when it falls in a spent window and extra usage is not off.
98
+ */
99
+ export function creditsOf(points, inp) {
100
+ const overage = [...inp.overage].sort((a, b) => a.ts - b.ts);
101
+ const spans = spentSpans(inp.readings);
102
+ const infer = inp.extraUsage?.enabled !== false;
103
+ const spanAt = (ts) => {
104
+ let best;
105
+ for (const s of spans)
106
+ if (ts > s.from && ts <= s.to && (!best || s.to > best.to))
107
+ best = s;
108
+ return best;
109
+ };
110
+ const episodes = [];
111
+ let key;
112
+ for (const p of [...points].sort((a, b) => a.ts - b.ts)) {
113
+ if (p.ts > inp.now)
114
+ continue;
115
+ const h = headerAt(overage, p.ts);
116
+ let how;
117
+ let span;
118
+ if (h) {
119
+ if (!h.inUse)
120
+ continue;
121
+ how = "headers";
122
+ span = spanAt(p.ts);
123
+ }
124
+ else if (infer) {
125
+ span = spanAt(p.ts);
126
+ if (span)
127
+ how = "inferred";
128
+ }
129
+ if (!how)
130
+ continue;
131
+ const k = span ? `${span.window}:${span.from}` : "headers";
132
+ let e = episodes[episodes.length - 1];
133
+ if (!e || k !== key || (!span && p.ts - e.last > EPISODE_GAP_MS)) {
134
+ // An episode the API's replies alone mark ran out at the first reply that said so in this run.
135
+ const firstInUse = !span && h ? overage.filter((o) => o.inUse && o.ts <= p.ts + HEADER_LAG_MS && p.ts - o.ts <= EPISODE_GAP_MS).reduce((m, o) => Math.min(m, o.ts), h.ts) : p.ts;
136
+ e = {
137
+ ...(span ? { window: span.window } : {}),
138
+ ranOutAt: span ? span.from : firstInUse,
139
+ ...(span?.resetsAt !== undefined ? { resetsAt: span.resetsAt } : {}),
140
+ current: false, first: p.ts, last: p.ts, requests: 0, usd: 0, fromHeaders: 0, inferred: 0,
141
+ };
142
+ episodes.push(e);
143
+ key = k;
144
+ }
145
+ e.last = p.ts;
146
+ e.requests++;
147
+ e.usd += p.usd;
148
+ if (how === "headers")
149
+ e.fromHeaders++;
150
+ else
151
+ e.inferred++;
152
+ }
153
+ // Still past it: the window has not reset, or the newest credits reading says in use and still stands.
154
+ const newest = [...overage].reverse().find((o) => o.inUse !== undefined);
155
+ for (const e of episodes) {
156
+ const span = e.window ? spans.find((s) => s.window === e.window && s.from === e.ranOutAt) : undefined;
157
+ e.current = span ? inp.now < span.to && (span.resetsAt !== undefined || inp.now - e.last <= HEADER_STALE_MS) : Boolean(newest?.inUse && inp.now - newest.ts <= HEADER_STALE_MS && newest.ts >= e.first - HEADER_LAG_MS);
158
+ }
159
+ return {
160
+ episodes,
161
+ requests: episodes.reduce((n, e) => n + e.requests, 0),
162
+ usd: episodes.reduce((n, e) => n + e.usd, 0),
163
+ fromHeaders: episodes.reduce((n, e) => n + e.fromHeaders, 0),
164
+ inferred: episodes.reduce((n, e) => n + e.inferred, 0),
165
+ };
166
+ }
167
+ /** The ledger's readings for a period starting at `since`, a week earlier too (a weekly window spent before it still counts in it). */
168
+ export function creditsInputs(since, opts = {}) {
169
+ const now = opts.now ?? Date.now();
170
+ const path = opts.logPath ?? limitsLogPath();
171
+ const from = since - 7 * DAY;
172
+ const readings = readClaudeReadings(from, path);
173
+ const overage = readOverageReadings(from, path);
174
+ const extraUsage = opts.extraUsage === null ? undefined : opts.extraUsage ?? (spentSpans(readings).length ? readExtraUsage(opts.home) : undefined);
175
+ return { readings, overage, ...(extraUsage ? { extraUsage } : {}), now };
176
+ }
177
+ /** Nothing in the ledger could put a request past the limit: no spent window, no reply that said credits were in use. */
178
+ export function nothingPast(inp) {
179
+ return !inp.overage.some((o) => o.inUse) && (inp.extraUsage?.enabled === false || !spentSpans(inp.readings).length);
180
+ }
181
+ /**
182
+ * The last `days` days of Claude Code past the plan's limit, for `limits`:
183
+ * the ledger, and the transcripts only when the ledger says something was.
184
+ * Undefined when nothing was.
185
+ */
186
+ export function creditsReport(days = 30, opts = {}) {
187
+ const now = opts.now ?? Date.now();
188
+ const since = now - days * DAY;
189
+ const inp = creditsInputs(since, { ...opts, now });
190
+ if (nothingPast(inp))
191
+ return undefined;
192
+ const starts = [...spentSpans(inp.readings).map((s) => s.from), ...inp.overage.filter((o) => o.inUse).map((o) => o.ts - HEADER_STALE_MS)];
193
+ const usage = claudeUsage(Math.max(since, Math.min(...starts)), now, opts.claudePaths).filter((p) => p.ts >= since);
194
+ const s = creditsOf(usage, inp);
195
+ return s.requests ? { ...s, ...(inp.extraUsage ? { extraUsage: inp.extraUsage } : {}) } : undefined;
196
+ }
197
+ // ---------------------------------------------------------------------------
198
+ // Words
199
+ // ---------------------------------------------------------------------------
200
+ /** "$41.20", "$4.02", "$130". */
201
+ const dollars = (v) => (v >= 100 ? `$${Math.round(v).toLocaleString("en-US")}` : v > 0 && v < 0.005 ? "<$0.01" : `$${v.toFixed(2)}`);
202
+ /** "at 14:05" within the day, else "on Tue, Nov 17 at 14:05": local time. */
203
+ export function whenText(ms, now) {
204
+ const d = new Date(ms);
205
+ const t = `${String(d.getHours()).padStart(2, "0")}:${String(d.getMinutes()).padStart(2, "0")}`;
206
+ return Math.abs(ms - now) < 20 * HOUR ? `at ${t}` : `on ${d.toLocaleDateString("en-US", { weekday: "short", month: "short", day: "numeric" })} at ${t}`;
207
+ }
208
+ const WINDOW_NAME = { seven_day: "weekly limit", five_hour: "5-hour limit" };
209
+ /** The dollars, in the words every report uses: list prices, an estimate. */
210
+ export const AT_LIST_PRICES = "at API list prices (an estimate)";
211
+ /**
212
+ * One episode in plain words: "Your weekly limit ran out on Tue, Nov 17 at
213
+ * 14:05; 37 requests after that were paid from usage credits, about $41.20
214
+ * at API list prices (an estimate)." Inferred ones say so.
215
+ */
216
+ export function episodeLine(e, now) {
217
+ const head = e.window ? `Your ${WINDOW_NAME[e.window]} ran out ${whenText(e.ranOutAt, now)}` : `Past your plan's limit from ${whenText(e.ranOutAt, now).replace(/^(at|on) /, "")}`;
218
+ const n = `${e.requests.toLocaleString("en-US")} ${e.requests === 1 ? "request" : "requests"}`;
219
+ const after = e.window ? " after that" : "";
220
+ const paid = !e.inferred
221
+ ? `${n}${after} ${e.requests === 1 ? "was" : "were"} paid from usage credits`
222
+ : !e.fromHeaders
223
+ ? `${n}${after} still went through, so most likely on usage credits (inferred)`
224
+ : `${n}${after} ${e.requests === 1 ? "was" : "were"} paid from usage credits (${e.fromHeaders.toLocaleString("en-US")} as the API's replies said, ${e.inferred.toLocaleString("en-US")} inferred)`;
225
+ const still = e.current ? (e.resetsAt !== undefined ? ` Still past it; it resets ${whenText(e.resetsAt, now)}.` : " Still past it.") : "";
226
+ return `${head}; ${paid}, about ${dollars(e.usd)} ${AT_LIST_PRICES}.${still}`;
227
+ }
228
+ /** Lines for `limits`: one per episode, newest last, and what "inferred" and the dollars mean when it applies. */
229
+ export function creditsLines(r, now) {
230
+ if (!r.requests)
231
+ return [];
232
+ const out = r.episodes.map((e) => episodeLine(e, now));
233
+ if (r.inferred)
234
+ out.push("Inferred: Claude Code's readings stop at 100% and say nothing about credits; a request that still went through past it was most likely paid from them (the proxy, `context-doctor autopilot on`, reads the API's own word).");
235
+ out.push("Whether usage credits bill at exactly API list prices is not confirmed: the dollars are an estimate; your Claude account's usage page has the bill.");
236
+ return out;
237
+ }
238
+ const REASON_WORDS = {
239
+ out_of_credits: "out of credits",
240
+ overage_not_provisioned: "not set up for this account",
241
+ org_level_disabled: "turned off for the organization",
242
+ org_level_disabled_until: "the spend cap is reached until it resets",
243
+ seat_tier_level_disabled: "off for this seat type",
244
+ member_level_disabled: "turned off for your seat",
245
+ seat_tier_zero_credit_limit: "a credit limit of zero for this seat type",
246
+ group_zero_credit_limit: "a credit limit of zero for your group",
247
+ member_zero_credit_limit: "a credit limit of zero for your seat",
248
+ org_service_level_disabled: "off for the organization's service",
249
+ no_limits_configured: "no credit limit configured",
250
+ };
251
+ /**
252
+ * `doctor`'s line on extra usage, from `~/.claude.json`: on, on but held
253
+ * back (and why), or off. Undefined when the file says nothing (an API key,
254
+ * never signed in).
255
+ */
256
+ export function extraUsageText(x) {
257
+ if (!x || x.enabled === undefined)
258
+ return undefined;
259
+ if (!x.enabled)
260
+ return { on: false, text: "off: when a plan limit runs out, Claude Code stops until it resets; nothing is paid from usage credits" };
261
+ const held = typeof x.disabledReason === "string" && x.disabledReason !== "fetch_error" && x.disabledReason !== "unknown"
262
+ ? `, but the last reply said credits are not paying now (${REASON_WORDS[x.disabledReason] ?? x.disabledReason.replace(/_/g, " ")})`
263
+ : "";
264
+ return { on: true, text: `on${held}: when a plan limit runs out, Claude Code keeps working and the requests are paid from usage credits, real money. \`context-doctor limits\` and \`spend\` say how much` };
265
+ }
package/dist/doctor.d.ts CHANGED
@@ -51,6 +51,12 @@ export declare function unpricedModelsCheck(days?: number, now?: number, home?:
51
51
  * does not (Desktop) and has no transcript to measure either way: say that,
52
52
  * rather than nothing or a false "ok".
53
53
  */
54
+ /**
55
+ * Extra usage (usage credits past a plan's limit), as Claude Code cached it
56
+ * in `~/.claude.json`: on or off, and when on but held back, why. A fact,
57
+ * not a fault: "ok" either way. Undefined when the file says nothing.
58
+ */
59
+ export declare function extraUsageCheck(home?: string): Check | undefined;
54
60
  export declare function devinCheck(home?: string): Check;
55
61
  /**
56
62
  * How long the handshake may take: 15 s, or CONTEXT_DOCTOR_MCP_HANDSHAKE_MS.
package/dist/doctor.js CHANGED
@@ -27,7 +27,8 @@ import { describeDesktopUsage, desktopUsage } from "./desktopusage.js";
27
27
  import { withInvocation } from "./invocation.js";
28
28
  import { describeInstalls, modelSwitchReadiness, PRE_MODEL_SWITCH_SINCE } from "./modelswitch.js";
29
29
  import { describeCosts, subagentCostsPath } from "./fanout.js";
30
- import { claudeCodePresent, claudeDir, claudeJsonPath } from "./claudedir.js";
30
+ import { claudeCodePresent, claudeDir, claudeJsonPath, readExtraUsage } from "./claudedir.js";
31
+ import { extraUsageText } from "./credits.js";
31
32
  import { codexDir } from "./codexdir.js";
32
33
  import { periodSpend, readBudget } from "./budget.js";
33
34
  import { sessionPriceThresholds } from "./sessionprice.js";
@@ -422,6 +423,15 @@ export function unpricedModelsCheck(days = 30, now = Date.now(), home = homedir(
422
423
  * does not (Desktop) and has no transcript to measure either way: say that,
423
424
  * rather than nothing or a false "ok".
424
425
  */
426
+ /**
427
+ * Extra usage (usage credits past a plan's limit), as Claude Code cached it
428
+ * in `~/.claude.json`: on or off, and when on but held back, why. A fact,
429
+ * not a fault: "ok" either way. Undefined when the file says nothing.
430
+ */
431
+ export function extraUsageCheck(home) {
432
+ const t = extraUsageText(readExtraUsage(home));
433
+ return t ? { label: "Extra usage", status: "ok", detail: t.text } : undefined;
434
+ }
425
435
  export function devinCheck(home = homedir()) {
426
436
  const label = "Devin";
427
437
  const app = [join("/Applications", "Devin.app"), join(home, "Applications", "Devin.app"), join(home, "Library", "Application Support", "Devin"), join(home, ".devin")].find((p) => existsSync(p));
@@ -671,6 +681,10 @@ export async function runDoctor() {
671
681
  }
672
682
  if (claudeCodePresent())
673
683
  checks.push(...claudeRouteChecks(layers, plugin));
684
+ // Whether past a plan limit Claude Code keeps going on usage credits (real money): said, never judged.
685
+ const xu = extraUsageCheck();
686
+ if (xu)
687
+ checks.push(xu);
674
688
  // Codex (OpenAI): MCP table in config.toml, hook in hooks.json, skill.
675
689
  const codexHome = codexDir();
676
690
  if (existsSync(codexHome)) {
package/dist/fanout.d.ts CHANGED
@@ -40,6 +40,8 @@ export interface SubagentCosts {
40
40
  days: number;
41
41
  /** Subagents measured (each priced at list price, as `subagents` does). */
42
42
  n: number;
43
+ /** Only the newest files were read (the hook's bounded measure): not every subagent of the period. */
44
+ limited?: boolean;
43
45
  all?: CostStat;
44
46
  byType: Record<string, CostStat>;
45
47
  /** "<type>|<model>" */
package/dist/fanout.js CHANGED
@@ -109,13 +109,21 @@ export function measureSubagentCosts(days = 30, opts = {}) {
109
109
  }
110
110
  files.sort((a, b) => b.at - a.at);
111
111
  const runs = [];
112
+ let limited = files.length > (opts.limit ?? Infinity);
112
113
  for (const f of files.slice(0, opts.limit ?? Infinity)) {
113
- if (opts.budgetMs !== undefined && Date.now() - started > opts.budgetMs)
114
+ if (opts.budgetMs !== undefined && Date.now() - started > opts.budgetMs) {
115
+ limited = true;
114
116
  break;
117
+ }
115
118
  try {
116
119
  const s = scanSubagent(f.file);
117
120
  if (!(s.costUsd > 0))
118
121
  continue;
122
+ // Each by its own start, as `subagents` counts them: a file touched in the
123
+ // window can hold a run from before it (131 of 300 here, so the medians
124
+ // said 300 subagents where `subagents` said 169 for the same 30 days).
125
+ if (Number.isFinite(s.start) && s.start < since)
126
+ continue;
119
127
  let type = "unknown";
120
128
  try {
121
129
  type = String(JSON.parse(readFileSync(f.meta, "utf8"))?.agentType ?? "unknown").slice(0, 60);
@@ -138,6 +146,7 @@ export function measureSubagentCosts(days = 30, opts = {}) {
138
146
  computedAt: now,
139
147
  days,
140
148
  n: runs.length,
149
+ ...(limited ? { limited: true } : {}),
141
150
  all: runs.length ? stat(runs) : undefined,
142
151
  byType: group((r) => r.type),
143
152
  byTypeModel: group((r) => (r.model ? `${r.type}|${r.model}` : undefined)),
@@ -325,7 +334,8 @@ export function fanoutHook(input, costs, sessionId, now = Date.now()) {
325
334
  export function describeCosts(c) {
326
335
  if (!c || !c.all)
327
336
  return "no subagent runs measured yet";
328
- return `${c.n} subagents in ${c.days} days, median ${formatUsd(c.all.median)} (${basename(subagentCostsPath())})`;
337
+ // The hook measures the newest 80 at most: "80 subagents in 30 days" read as a count, beside `subagents`' 169.
338
+ return `${c.limited ? `the newest ${c.n} subagents of the last ${c.days} days` : `${c.n} subagents in ${c.days} days`}, median ${formatUsd(c.all.median)} (${basename(subagentCostsPath())})`;
329
339
  }
330
340
  /** The medians the subagent price quotes, for `context-doctor subagents`. */
331
341
  export function renderCostMedians(c) {
package/dist/fix.d.ts CHANGED
@@ -48,7 +48,7 @@ import { type SubagentModelReplay } from "./subagentmodel.js";
48
48
  import { type ToolOutputReplay } from "./tooloutput.js";
49
49
  import { type ProgressSummaryEstimate } from "./progresssummaries.js";
50
50
  import { type CodexCompactReport } from "./codexcompact.js";
51
- export type FixId = "compact-window" | "cache-ttl" | "cache-ttl-subagents" | "autopilot" | "tool-search" | "prune" | "subagent-model" | "tool-output" | "codex-compact" | "progress-summaries" | "mcp-defer";
51
+ export type FixId = "compact-window" | "cache-ttl" | "cache-ttl-subagents" | "autopilot" | "tool-search" | "prune" | "subagent-model" | "tool-output" | "codex-compact" | "progress-summaries" | "mcp-defer" | "desktop-tools-defer";
52
52
  export interface Fix {
53
53
  id: FixId;
54
54
  title: string;
@@ -93,6 +93,15 @@ export interface FixInputs {
93
93
  compactionsPerWeek: number;
94
94
  nowPerWeek: number;
95
95
  current?: number;
96
+ /**
97
+ * The Desktop app's own window offer and the server's windows (appwindow.ts), when any is on file:
98
+ * what to say under the lever, the models answered (by name), and the sessions on them left as they ran.
99
+ */
100
+ app?: {
101
+ lines: string[];
102
+ answered: string[];
103
+ leftSessions: number;
104
+ };
96
105
  };
97
106
  ttl?: CacheTtlReport;
98
107
  currentTtl?: CurrentTtl;
@@ -174,7 +183,34 @@ export interface FixInputs {
174
183
  }>;
175
184
  days: number;
176
185
  };
186
+ /**
187
+ * The Desktop app's own MCP servers whose tools went whole into starts
188
+ * (starts.ts deferrableApp): per server, its starts, the ones whose session
189
+ * or subagent called it, its share of the starts' cost as `overhead` lists
190
+ * it, the part from starts that never called it, and (counted the same way)
191
+ * the part from starts that did.
192
+ */
193
+ desktopTools?: {
194
+ servers: Array<{
195
+ name: string;
196
+ tools: number;
197
+ tokens: number;
198
+ starts: number;
199
+ calledStarts: number;
200
+ usd: number;
201
+ unusedUsd: number;
202
+ calledUsd?: number;
203
+ }>;
204
+ days: number;
205
+ };
206
+ /** CONTEXT_DOCTOR_DEFER_MCP where the user (or fix) set it: applied, never overwritten. */
207
+ desktopToolsSet?: {
208
+ value: string;
209
+ where: string;
210
+ };
177
211
  }
212
+ /** The Claude Code version whose `tool.describe` names a tool's MCP server and lets a mod answer `isDeferred`. */
213
+ export declare const DESKTOP_TOOLS_DEFER_SINCE = "2.1.326";
178
214
  export declare const money: (n: number) => string;
179
215
  /** " (48%)", or " (37% of subagents)" for a share of something else. */
180
216
  export declare const share: (f: Fix) => string;
package/dist/fix.js CHANGED
@@ -52,13 +52,16 @@ import { compactWindowOverrides, effectiveEnv, processEnvWhere, settingsSources,
52
52
  import { claudeJsonPath, tilde } from "./claudedir.js";
53
53
  import { applyPrune, undoPrune } from "./prune.js";
54
54
  import { applyMcpDefer, MCP_DEFER_SINCE, undoMcpDefer } from "./mcpdefer.js";
55
+ import { DEFER_APP_TOOLS_ENV, deferredServers, KEEP_APP_SERVERS } from "./mod/logic.js";
55
56
  import { fallbackStateDir, readLedger } from "./ledger.js";
56
57
  import { claudeDir } from "./claudedir.js";
57
58
  import { comparisonLine } from "./abstore.js";
58
59
  import { movedFromNames, renderSubagentTypes, subagentModelSavedSince, SUBAGENT_CANDIDATE, SUBAGENT_CANDIDATE_NAME, SUBAGENT_MODEL_ENV } from "./subagentmodel.js";
59
60
  import { BASH_OUTPUT_DEFAULT, BASH_OUTPUT_KEY, BASH_OUTPUT_SINCE, breakEven, renderToolOutputCaps, toolOutputSavedSince } from "./tooloutput.js";
60
- import { disablesSummaries, estimateProgressSummaries, hostName, PROGRESS_SUMMARIES_ENV, PROGRESS_SUMMARIES_OFF, PROGRESS_SUMMARIES_SINCE } from "./progresssummaries.js";
61
+ import { disablesSummaries, estimateProgressSummaries, hostName, PROGRESS_SUMMARIES_ENV, PROGRESS_SUMMARIES_OFF, PROGRESS_SUMMARIES_SINCE, SMALL_FAST_MODEL_NAME, SMALL_NOTES_SINCE } from "./progresssummaries.js";
61
62
  import { CODEX_COMPACT_KEY, CODEX_COMPACT_LIMIT, codexCompactOverrides, codexCompactSavedSince, codexConfigPath, renderCodexLimits, setTopLevelInt, topLevelValue } from "./codexcompact.js";
63
+ /** The Claude Code version whose `tool.describe` names a tool's MCP server and lets a mod answer `isDeferred`. */
64
+ export const DESKTOP_TOOLS_DEFER_SINCE = "2.1.326";
62
65
  /**
63
66
  * The Claude Code version that first reads each setting a fix writes, from
64
67
  * its changelog (2.1.243 added promptCacheTtl and subagentPromptCacheTtl,
@@ -67,7 +70,7 @@ import { CODEX_COMPACT_KEY, CODEX_COMPACT_LIMIT, codexCompactOverrides, codexCom
67
70
  * the subagent variable ahead of agent definitions there). autoCompactWindow
68
71
  * is not in 2.1.62 and the changelog does not say when it came: not named.
69
72
  */
70
- const SINCE = { "mcp-defer": MCP_DEFER_SINCE, "cache-ttl": CACHE_TTL_SINCE, "cache-ttl-subagents": CACHE_TTL_SINCE, "tool-output": BASH_OUTPUT_SINCE, "progress-summaries": PROGRESS_SUMMARIES_SINCE };
73
+ const SINCE = { "mcp-defer": MCP_DEFER_SINCE, "desktop-tools-defer": DESKTOP_TOOLS_DEFER_SINCE, "cache-ttl": CACHE_TTL_SINCE, "cache-ttl-subagents": CACHE_TTL_SINCE, "tool-output": BASH_OUTPUT_SINCE, "progress-summaries": PROGRESS_SUMMARIES_SINCE };
71
74
  /** Below this a priced fix is not worth a setting. */
72
75
  const MIN_USD = 1;
73
76
  export const money = (n) => (n >= 100 ? `$${Math.round(n).toLocaleString("en-US")}` : `$${n.toFixed(2)}`);
@@ -93,8 +96,13 @@ export function planFixes(i) {
93
96
  state: applied ? "applied" : "available",
94
97
  note: applied ? `autoCompactWindow is ${cw.current}` : undefined,
95
98
  value: cw.window,
99
+ ...(cw.app && !applied ? { detail: [...cw.app.lines, ...(cw.app.answered.length ? [`Applying writes one window for every model; whether it or the app's choice wins for ${cw.app.answered.join(", ")} is not recorded here.`] : [])] } : {}),
96
100
  });
97
101
  }
102
+ else if (cw.app && cw.app.leftSessions > 0) {
103
+ // Under a dollar once the sessions on the app's answered models are left alone: say why, offer nothing.
104
+ fixes.push({ id: "compact-window", title: "Compact earlier", basis: "", quality: "", change: "", state: "not-here", note: `you answered the Desktop app's own window offer for ${cw.app.answered.join(", ")}, so ${cw.app.leftSessions === 1 ? "its session is" : `its ${cw.app.leftSessions} sessions are`} left alone; the rest would save under $1` });
105
+ }
98
106
  }
99
107
  for (const kind of ["main", "subagents"]) {
100
108
  const r = i.ttl?.[kind];
@@ -212,7 +220,8 @@ export function planFixes(i) {
212
220
  savedUsd: best.savedUsd,
213
221
  savedShare: best.savedUsd / to.billedUsd,
214
222
  // Main conversations and subagents alike: the cap applies to both.
215
- shareOf: "of input, subagents included",
223
+ // Its own base, named: the header's input leaves subagents out, this one counts them.
224
+ shareOf: `of ${money(to.billedUsd)} input, subagents included`,
216
225
  basis: `${best.moved.toLocaleString("en-US")} of ${best.results.toLocaleString("en-US")} Bash results were longer; the tokens past a 2,000-character preview priced at each later request that re-read them until a compaction (cache reads, one write); an estimate: a file the model opens again costs about ${money(each)} a time and is not counted, and the saving covers it opening up to ${pct(breakEven(best))} of them`,
217
226
  quality: "long output goes to a file the model can still open; it sees the first 2,000 characters and the path, as it already does past 30,000",
218
227
  // Nothing is lost, only moved (in `--apply all` for the same reason).
@@ -259,7 +268,7 @@ export function planFixes(i) {
259
268
  savedUsd: ps.notesUsd,
260
269
  savedShare: billed > 0 ? ps.notesUsd / billed : undefined,
261
270
  shareOf: "of subagents",
262
- basis: `${ps.calls.toLocaleString("en-US")} summaries for ${ps.summarized} background subagent${ps.summarized === 1 ? "" : "s"}, one each 30 s while one ran and its transcript changed; no transcript records them, so an estimate: ~1,850 tokens of notes each (what Anthropic serves since November 2026), ${money(ps.forkUsd)} if each sent the whole context, as before`,
271
+ basis: `${ps.calls.toLocaleString("en-US")} summaries for ${ps.summarized} background subagent${ps.summarized === 1 ? "" : "s"}, one each 30 s while one ran and its transcript changed; no transcript records them, so an estimate: ${ps.smallCalls === ps.calls ? `~1,850 tokens of notes each, written by ${SMALL_FAST_MODEL_NAME} (Claude Code ${SMALL_NOTES_SINCE}+)` : `~1,850 tokens of notes each (what Anthropic serves since November 2026)${ps.smallCalls ? `, by ${SMALL_FAST_MODEL_NAME} for the ${ps.smallCalls.toLocaleString("en-US")} on Claude Code ${SMALL_NOTES_SINCE}+` : ""}, ${money(ps.forkUsd)} if each sent the whole context, as before`}`,
263
272
  quality: "none to the work: a summary never enters the subagent's context; you lose the 3-5 word progress line on a running subagent's task row",
264
273
  qualityFree: true,
265
274
  change: `${where}: env.${PROGRESS_SUMMARIES_ENV} = "${PROGRESS_SUMMARIES_OFF}" (Claude Code ${PROGRESS_SUMMARIES_SINCE}+)`,
@@ -285,6 +294,35 @@ export function planFixes(i) {
285
294
  value: "false",
286
295
  });
287
296
  }
297
+ const dt = i.desktopTools;
298
+ if (i.desktopToolsSet) {
299
+ const named = deferredServers(i.desktopToolsSet.value);
300
+ fixes.push({ id: "desktop-tools-defer", title: "The Desktop app's own tools behind tool search", basis: "set", quality: "", change: `env.${DEFER_APP_TOOLS_ENV}`, state: named.length ? "applied" : "not-here", note: named.length ? `context-doctor's mod keeps ${named.join(", ")} behind tool search (${i.desktopToolsSet.where})` : `${i.desktopToolsSet.where} names no server: left as you set it`, value: i.desktopToolsSet.value });
301
+ }
302
+ else if (dt) {
303
+ // A server called in at least half the starts it went into would cost a tool-search step in most of them: kept in front.
304
+ const pick = dt.servers.filter((s) => !KEEP_APP_SERVERS.includes(s.name) && s.calledStarts * 2 < s.starts && s.unusedUsd > 0).sort((a, b) => b.unusedUsd - a.unusedUsd);
305
+ const kept = dt.servers.filter((s) => !pick.includes(s)).map((s) => s.name);
306
+ const usd = pick.reduce((t, s) => t + s.unusedUsd, 0);
307
+ if (pick.length && usd >= MIN_USD) {
308
+ // Counted as the headline is, start by start: overhead's per-server share is spread by tokens and can come out below it.
309
+ const exact = pick.every((s) => s.calledUsd !== undefined);
310
+ const all = pick.reduce((t, s) => t + (exact ? s.unusedUsd + s.calledUsd : s.usd), 0);
311
+ const value = pick.map((s) => s.name).join(",");
312
+ fixes.push({
313
+ id: "desktop-tools-defer",
314
+ title: `Keep the Desktop app's own tools behind tool search (${pick.map((s) => s.name).join(", ")})`,
315
+ savedUsd: usd,
316
+ basis: `the Desktop app sends these tools' definitions whole into every session and subagent start, and each step re-reads them: ${pick.map((s) => `${s.name} ~${s.tokens < 1000 ? s.tokens : k(s.tokens)} tokens, called in ${s.calledStarts} of ${s.starts} starts`).join("; ")}. The figure is what that cost in the ${i.desktopTools.days} days' starts that never called them (${money(all)} counting the ones that did${exact ? "" : ", as overhead lists it"}; those would load a tool through tool search instead)`,
317
+ quality: `Claude loads one of these tools through tool search the first time a conversation needs it: one more step then. Kept in front: ${[...KEEP_APP_SERVERS, ...kept.filter((n) => !KEEP_APP_SERVERS.includes(n))].join(", ")} (called in most sessions). It takes effect in new sessions only, so no running conversation's cache is written again. Not measured here: applied only when named`,
318
+ change: `${where}: env.${DEFER_APP_TOOLS_ENV} = "${value}", read by context-doctor's mod (its plugin, Claude Code ${DESKTOP_TOOLS_DEFER_SINCE}+)`,
319
+ state: "available",
320
+ value,
321
+ // Built from Claude Code's mods declarations; whether the app's in-process servers raise tool.describe is not yet seen on a live session.
322
+ detail: ["Not yet confirmed on a live Desktop session: after applying, start a new session and run context-doctor overhead; these servers should no longer be listed as sent whole."],
323
+ });
324
+ }
325
+ }
288
326
  for (const f of fixes) {
289
327
  const o = i.overrides?.[f.id];
290
328
  if (o?.length && f.state === "available")
@@ -361,13 +399,14 @@ const KEY_PATH = {
361
399
  "subagent-model": ["env", SUBAGENT_MODEL_ENV],
362
400
  "tool-output": [BASH_OUTPUT_KEY],
363
401
  "progress-summaries": ["env", PROGRESS_SUMMARIES_ENV],
402
+ "desktop-tools-defer": ["env", DEFER_APP_TOOLS_ENV],
364
403
  };
365
404
  /** Fixes that never overwrite a value already there: the user set it. */
366
- const YOURS = new Set(["subagent-model", "tool-output", "progress-summaries"]);
405
+ const YOURS = new Set(["subagent-model", "tool-output", "progress-summaries", "desktop-tools-defer"]);
367
406
  /** The environment variable a settings fix writes, when the shell's own value is the user's too. */
368
- const SHELL_ENV = { "subagent-model": SUBAGENT_MODEL_ENV, "progress-summaries": PROGRESS_SUMMARIES_ENV };
407
+ const SHELL_ENV = { "subagent-model": SUBAGENT_MODEL_ENV, "progress-summaries": PROGRESS_SUMMARIES_ENV, "desktop-tools-defer": DEFER_APP_TOOLS_ENV };
369
408
  /** Fixes with a quality cost not measured here: applied only when named, never by `--apply all`. */
370
- const NAMED_ONLY = new Set(["subagent-model", "mcp-defer"]);
409
+ const NAMED_ONLY = new Set(["subagent-model", "mcp-defer", "desktop-tools-defer"]);
371
410
  /** What would keep this fix's value from taking effect, as Claude Code merges settings. */
372
411
  export function fixOverrides(id, deps = {}) {
373
412
  // Codex reads its own config.toml: a profile's value, or a project's file.
@@ -400,6 +439,18 @@ export function fixOverrides(id, deps = {}) {
400
439
  // A project's, local or managed env is applied over the user's: a value there that does not turn them off wins.
401
440
  return sources.filter((s) => s.name !== "user" && s.settings.env?.[PROGRESS_SUMMARIES_ENV] !== undefined && s.settings.env[PROGRESS_SUMMARIES_ENV] !== null && !disablesSummaries(s.settings.env[PROGRESS_SUMMARIES_ENV])).map((s) => `${PROGRESS_SUMMARIES_ENV}=${s.settings.env[PROGRESS_SUMMARIES_ENV]} in ${tilde(s.path)} env`);
402
441
  }
442
+ if (id === "desktop-tools-defer") {
443
+ // A project's, local or managed env is applied over the user's; CONTEXT_DOCTOR_NO_MOD=1 turns the mod off.
444
+ const out = sources.filter((s) => s.name !== "user" && s.settings.env?.[DEFER_APP_TOOLS_ENV] !== undefined && s.settings.env[DEFER_APP_TOOLS_ENV] !== null).map((s) => `${DEFER_APP_TOOLS_ENV}=${s.settings.env[DEFER_APP_TOOLS_ENV]} in ${tilde(s.path)} env`);
445
+ const off = effectiveEnv("CONTEXT_DOCTOR_NO_MOD", sources, env);
446
+ if (off?.value === "1")
447
+ out.push(`${off.where} (context-doctor's mod is off)`);
448
+ // A deferred tool is loaded through tool search: with it off, deferring cannot work as the lever says.
449
+ const ts = effectiveEnv("ENABLE_TOOL_SEARCH", sources, env);
450
+ if (ts && /^(false|0|no|off)$/i.test(ts.value.trim()))
451
+ out.push(`${ts.where} (tool search is off)`);
452
+ return out;
453
+ }
403
454
  if (id === "tool-output") {
404
455
  // Merged settings: a project's or managed value wins over the user's (BASH_MAX_OUTPUT_LENGTH does not: the setting replaces it).
405
456
  return sources.filter((s) => s.name !== "user" && s.settings[BASH_OUTPUT_KEY] !== undefined).map((s) => `${BASH_OUTPUT_KEY} ${JSON.stringify(s.settings[BASH_OUTPUT_KEY])} in ${tilde(s.path)}`);
@@ -857,7 +908,7 @@ export function savedSince(records, opts = {}) {
857
908
  }
858
909
  else if (r.id === "progress-summaries") {
859
910
  const s = progressSummariesSavedSince(r.at, opts.subagentPaths);
860
- out.push({ id: r.id, at: r.at, savedUsd: s.summarized ? s.notesUsd : undefined, detail: s.summarized ? `estimated: ${s.calls.toLocaleString("en-US")} summaries it stopped for ${s.summarized} background subagent${s.summarized === 1 ? "" : "s"} on Claude Code ${PROGRESS_SUMMARIES_SINCE}+, as notes (${money(s.forkUsd)} at the whole context)` : "no background subagent in a terminal session since" });
911
+ out.push({ id: r.id, at: r.at, savedUsd: s.summarized ? s.notesUsd : undefined, detail: s.summarized ? `estimated: ${s.calls.toLocaleString("en-US")} summaries it stopped for ${s.summarized} background subagent${s.summarized === 1 ? "" : "s"} on Claude Code ${PROGRESS_SUMMARIES_SINCE}+, as notes${s.smallCalls === s.calls ? ` by ${SMALL_FAST_MODEL_NAME} (${SMALL_NOTES_SINCE}+)` : ` (${money(s.forkUsd)} at the whole context)`}` : "no background subagent in a terminal session since" });
861
912
  }
862
913
  else if (r.id === "autopilot") {
863
914
  const ledger = opts.ledger ?? readLedger();
@@ -884,6 +935,7 @@ const LABEL = {
884
935
  "codex-compact": "Codex auto-compact limit",
885
936
  "progress-summaries": "Subagent progress summaries",
886
937
  "mcp-defer": "MCP servers sent whole",
938
+ "desktop-tools-defer": "The Desktop app's own tools",
887
939
  };
888
940
  /**
889
941
  * Priced levers that save part of the same dollars, and why: each is
@@ -900,6 +952,12 @@ const OVERLAPS = [
900
952
  ["tool-output", "subagent-model", "long output in subagents is priced at the subagents' model, which subagent-model changes"],
901
953
  ["subagent-model", "cache-ttl-subagents", "the subagents' cache is priced at their model's rates, which subagent-model changes"],
902
954
  ["progress-summaries", "subagent-model", "the progress summaries run on the subagents' model, which subagent-model changes"],
955
+ ["desktop-tools-defer", "cache-ttl", "the main conversation's cache lifetime changes what re-reading the app's tool definitions costs"],
956
+ ["desktop-tools-defer", "cache-ttl-subagents", "the subagents' cache lifetime changes what re-reading the app's tool definitions costs in their starts"],
957
+ ["desktop-tools-defer", "subagent-model", "the app's tool definitions in subagent starts are priced at the subagents' model, which subagent-model changes"],
958
+ ["mcp-defer", "cache-ttl", "the main conversation's cache lifetime changes what re-reading your servers' tool definitions costs"],
959
+ ["mcp-defer", "cache-ttl-subagents", "the subagents' cache lifetime changes what re-reading your servers' tool definitions costs in their starts"],
960
+ ["mcp-defer", "subagent-model", "your servers' tool definitions in subagent starts are priced at the subagents' model, which subagent-model changes"],
903
961
  ];
904
962
  /** The overlap lines for the priced fixes in a plan, "a and b: why;" each. */
905
963
  export function overlaps(fixes) {
@@ -917,7 +975,7 @@ export function renderFixPlan(days, billedUsd, fixes, since, command = (s) => `c
917
975
  else if (codexBilledUsd > 0)
918
976
  out.push(`Last ${days} days of your Codex sessions, ${money(codexBilledUsd)} of input ${priceBasis()}`);
919
977
  else
920
- out.push(`Last ${days} days of your Claude Code sessions, ${money(billedUsd)} of input ${priceBasis()}`);
978
+ out.push(`Last ${days} days of your Claude Code sessions, ${money(billedUsd)} of input in the main conversations (subagents not counted) ${priceBasis()}`);
921
979
  out.push("─".repeat(66));
922
980
  const avail = fixes.filter((f) => f.state === "available");
923
981
  // No input billed: there is no history to measure, which is not "all applied".