context-doctor 0.49.1 → 0.51.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 (57) hide show
  1. package/README.md +19 -17
  2. package/dist/apptools.d.ts +89 -0
  3. package/dist/apptools.js +203 -0
  4. package/dist/appwindow.d.ts +75 -0
  5. package/dist/appwindow.js +161 -0
  6. package/dist/budget.d.ts +20 -2
  7. package/dist/budget.js +43 -3
  8. package/dist/cachemisses.d.ts +70 -0
  9. package/dist/cachemisses.js +126 -0
  10. package/dist/ccost.js +8 -4
  11. package/dist/claudedir.d.ts +15 -0
  12. package/dist/claudedir.js +19 -1
  13. package/dist/cli.js +77 -29
  14. package/dist/clihelp.d.ts +5 -1
  15. package/dist/clihelp.js +9 -1
  16. package/dist/codexstatusline.d.ts +176 -0
  17. package/dist/codexstatusline.js +353 -0
  18. package/dist/compactwindow.d.ts +14 -2
  19. package/dist/compactwindow.js +30 -5
  20. package/dist/credits.d.ts +192 -0
  21. package/dist/credits.js +350 -0
  22. package/dist/doctor.d.ts +18 -0
  23. package/dist/doctor.js +62 -3
  24. package/dist/fanout.d.ts +2 -0
  25. package/dist/fanout.js +12 -2
  26. package/dist/fileparams.js +15 -3
  27. package/dist/fix.d.ts +48 -3
  28. package/dist/fix.js +112 -19
  29. package/dist/limits.d.ts +87 -2
  30. package/dist/limits.js +329 -29
  31. package/dist/mcp.d.ts +1 -0
  32. package/dist/mcp.js +106 -100
  33. package/dist/mod/api.d.ts +27 -1
  34. package/dist/mod/api.js +2 -1
  35. package/dist/mod/logic.d.ts +85 -1
  36. package/dist/mod/logic.js +118 -5
  37. package/dist/mod/register.d.ts +16 -2
  38. package/dist/mod/register.js +59 -5
  39. package/dist/modelids.d.ts +15 -0
  40. package/dist/modelids.js +35 -2
  41. package/dist/modmeasure.d.ts +7 -0
  42. package/dist/modmeasure.js +9 -0
  43. package/dist/orgrates.d.ts +4 -2
  44. package/dist/orgrates.js +21 -3
  45. package/dist/overhead.js +10 -3
  46. package/dist/pricing.js +7 -0
  47. package/dist/progresssummaries.d.ts +103 -1
  48. package/dist/progresssummaries.js +187 -11
  49. package/dist/proxy.d.ts +1 -1
  50. package/dist/proxy.js +9 -4
  51. package/dist/savings.js +3 -1
  52. package/dist/spend.d.ts +32 -3
  53. package/dist/spend.js +68 -6
  54. package/dist/starts.d.ts +34 -1
  55. package/dist/starts.js +88 -21
  56. package/dist/usagepane.js +1 -1
  57. package/package.json +1 -1
@@ -0,0 +1,350 @@
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`, `budget`), and by the
25
+ * budget's hook at a threshold it already speaks at: nothing is drawn or sent.
26
+ */
27
+ import { readExtraUsage } from "./claudedir.js";
28
+ import { claudeUsage, cleanReadings, CLAUDE_WINDOWS, limitsLogPath, modelLabel, readClaudeReadings, readOverageReadings, windowStatus } from "./limits.js";
29
+ const MIN = 60_000;
30
+ const HOUR = 60 * MIN;
31
+ const DAY = 24 * HOUR;
32
+ /** A credits reading stands for this long: the proxy writes it again every 15 minutes while it holds. */
33
+ const HEADER_STALE_MS = 16 * MIN;
34
+ /** 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). */
35
+ const HEADER_LAG_MS = MIN;
36
+ /** Two readings' resets this close name the same window period. */
37
+ const SAME_RESET_MS = 10 * MIN;
38
+ /** Credited requests with no window to tie them to start a new episode after this long apart. */
39
+ const EPISODE_GAP_MS = 5 * HOUR;
40
+ /**
41
+ * The stretches in which a Claude window stood at 100% or more: from its
42
+ * first such reading to the window's reset. Within a period the % never
43
+ * falls, so once a window reads 100% it is spent until it resets.
44
+ */
45
+ export function spentSpans(readings) {
46
+ const out = [];
47
+ for (const w of CLAUDE_WINDOWS) {
48
+ const rs = cleanReadings(readings.filter((r) => r.app === "claude" && r.window === w));
49
+ let open;
50
+ const close = (next) => {
51
+ if (!open)
52
+ return;
53
+ const end = Math.min(open.resetsAt ?? Infinity, next ?? Infinity);
54
+ out.push({ window: w, from: open.from, to: Number.isFinite(end) ? end : open.last + HEADER_STALE_MS, ...(open.resetsAt !== undefined ? { resetsAt: open.resetsAt } : {}) });
55
+ open = undefined;
56
+ };
57
+ for (const r of rs) {
58
+ if (open) {
59
+ const same = open.resetsAt !== undefined && r.resetsAt !== undefined ? Math.abs(open.resetsAt - r.resetsAt) <= SAME_RESET_MS : r.pct >= 100;
60
+ if (same && !(open.resetsAt !== undefined && r.ts >= open.resetsAt)) {
61
+ open.last = r.ts;
62
+ continue;
63
+ }
64
+ close(r.ts);
65
+ }
66
+ if (r.pct >= 100)
67
+ open = { window: w, from: r.ts, to: 0, last: r.ts, ...(r.resetsAt !== undefined ? { resetsAt: r.resetsAt } : {}) };
68
+ }
69
+ close();
70
+ }
71
+ return out.sort((a, b) => a.from - b.from);
72
+ }
73
+ /** The newest credits reading with an in-use word at or just after `ts`, if it still speaks for `ts`. */
74
+ function headerAt(overage, ts) {
75
+ let lo = 0, hi = overage.length - 1, at = -1;
76
+ while (lo <= hi) {
77
+ const mid = (lo + hi) >> 1;
78
+ if (overage[mid].ts <= ts + HEADER_LAG_MS) {
79
+ at = mid;
80
+ lo = mid + 1;
81
+ }
82
+ else
83
+ hi = mid - 1;
84
+ }
85
+ for (let i = at; i >= 0; i--) {
86
+ const o = overage[i];
87
+ if (ts - o.ts > HEADER_STALE_MS)
88
+ return undefined;
89
+ if (o.inUse !== undefined)
90
+ return o;
91
+ }
92
+ return undefined;
93
+ }
94
+ /**
95
+ * Sort requests (anything with a time and dollars: limits' usage points,
96
+ * spend's items) into runs past the limit. A request counts when the
97
+ * credits reading that speaks for it says in use, or, with no such
98
+ * reading, when it falls in a spent window and extra usage is not off.
99
+ */
100
+ export function creditsOf(points, inp) {
101
+ const overage = [...inp.overage].sort((a, b) => a.ts - b.ts);
102
+ const spans = spentSpans(inp.readings);
103
+ const infer = inp.extraUsage?.enabled !== false;
104
+ const spanAt = (ts) => {
105
+ let best;
106
+ for (const s of spans)
107
+ if (ts > s.from && ts <= s.to && (!best || s.to > best.to))
108
+ best = s;
109
+ return best;
110
+ };
111
+ const episodes = [];
112
+ let key;
113
+ for (const p of [...points].sort((a, b) => a.ts - b.ts)) {
114
+ if (p.ts > inp.now)
115
+ continue;
116
+ const h = headerAt(overage, p.ts);
117
+ let how;
118
+ let span;
119
+ if (h) {
120
+ if (!h.inUse)
121
+ continue;
122
+ how = "headers";
123
+ span = spanAt(p.ts);
124
+ }
125
+ else if (infer) {
126
+ span = spanAt(p.ts);
127
+ if (span)
128
+ how = "inferred";
129
+ }
130
+ if (!how)
131
+ continue;
132
+ const k = span ? `${span.window}:${span.from}` : "headers";
133
+ let e = episodes[episodes.length - 1];
134
+ if (!e || k !== key || (!span && p.ts - e.last > EPISODE_GAP_MS)) {
135
+ // An episode the API's replies alone mark ran out at the first reply that said so in this run.
136
+ 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;
137
+ e = {
138
+ ...(span ? { window: span.window } : {}),
139
+ ranOutAt: span ? span.from : firstInUse,
140
+ ...(span?.resetsAt !== undefined ? { resetsAt: span.resetsAt } : {}),
141
+ current: false, first: p.ts, last: p.ts, requests: 0, usd: 0, fromHeaders: 0, inferred: 0,
142
+ };
143
+ episodes.push(e);
144
+ key = k;
145
+ }
146
+ e.last = p.ts;
147
+ e.requests++;
148
+ e.usd += p.usd;
149
+ if (how === "headers")
150
+ e.fromHeaders++;
151
+ else
152
+ e.inferred++;
153
+ }
154
+ // Still past it: the window has not reset, or the newest credits reading says in use and still stands.
155
+ const newest = [...overage].reverse().find((o) => o.inUse !== undefined);
156
+ for (const e of episodes) {
157
+ const span = e.window ? spans.find((s) => s.window === e.window && s.from === e.ranOutAt) : undefined;
158
+ 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);
159
+ }
160
+ return {
161
+ episodes,
162
+ requests: episodes.reduce((n, e) => n + e.requests, 0),
163
+ usd: episodes.reduce((n, e) => n + e.usd, 0),
164
+ fromHeaders: episodes.reduce((n, e) => n + e.fromHeaders, 0),
165
+ inferred: episodes.reduce((n, e) => n + e.inferred, 0),
166
+ };
167
+ }
168
+ /** The ledger's readings for a period starting at `since`, a week earlier too (a weekly window spent before it still counts in it). */
169
+ export function creditsInputs(since, opts = {}) {
170
+ const now = opts.now ?? Date.now();
171
+ const path = opts.logPath ?? limitsLogPath();
172
+ const from = since - 7 * DAY;
173
+ const readings = readClaudeReadings(from, path);
174
+ const overage = readOverageReadings(from, path);
175
+ const extraUsage = opts.extraUsage === null ? undefined : opts.extraUsage ?? (spentSpans(readings).length ? readExtraUsage(opts.home) : undefined);
176
+ return { readings, overage, ...(extraUsage ? { extraUsage } : {}), now };
177
+ }
178
+ /** Nothing in the ledger could put a request past the limit: no spent window, no reply that said credits were in use. */
179
+ export function nothingPast(inp) {
180
+ return !inp.overage.some((o) => o.inUse) && (inp.extraUsage?.enabled === false || !spentSpans(inp.readings).length);
181
+ }
182
+ /**
183
+ * The last `days` days of Claude Code past the plan's limit, for `limits`:
184
+ * the ledger, and the transcripts only when the ledger says something was.
185
+ * Undefined when nothing was.
186
+ */
187
+ export function creditsReport(days = 30, opts = {}) {
188
+ const now = opts.now ?? Date.now();
189
+ return creditsSince(now - days * DAY, { ...opts, now });
190
+ }
191
+ /** The same from `since` to now (`budget`'s day or week). Undefined when nothing was past the limit. */
192
+ export function creditsSince(since, opts = {}) {
193
+ const now = opts.now ?? Date.now();
194
+ const inp = creditsInputs(since, { ...opts, now });
195
+ if (nothingPast(inp))
196
+ return undefined;
197
+ const starts = [...spentSpans(inp.readings).map((s) => s.from), ...inp.overage.filter((o) => o.inUse).map((o) => o.ts - HEADER_STALE_MS)];
198
+ const usage = claudeUsage(Math.max(since, Math.min(...starts)), now, opts.claudePaths).filter((p) => p.ts >= since);
199
+ const s = creditsOf(usage, inp);
200
+ return s.requests ? { ...s, ...(inp.extraUsage ? { extraUsage: inp.extraUsage } : {}) } : undefined;
201
+ }
202
+ /** The look-back the dollars an hour are read over: the same day `limits`' recent pace is. */
203
+ const AHEAD_LOOKBACK_MS = DAY;
204
+ /** Extra usage on, and nothing in `~/.claude.json` saying credits are not paying now. */
205
+ export function extraUsageOn(x) {
206
+ if (x?.enabled !== true)
207
+ return false;
208
+ return !(typeof x.disabledReason === "string" && x.disabledReason !== "fetch_error" && x.disabledReason !== "unknown");
209
+ }
210
+ /**
211
+ * The weekly window's run-out and what the hours past it would cost. Pure:
212
+ * `usage` is the last 24 hours' requests. Undefined unless extra usage is on
213
+ * and the weekly window, read recently, runs out before its reset at the
214
+ * recent pace, with dollars to price the hours at.
215
+ */
216
+ export function creditsAhead(status, extra, usage, now) {
217
+ if (!status || status.app !== "claude" || status.window !== "seven_day" || status.resetSince || status.stale)
218
+ return undefined;
219
+ if (status.runsOutAt === undefined || !status.beforeReset || status.resetsAt === undefined || !extraUsageOn(extra))
220
+ return undefined;
221
+ const from = now - AHEAD_LOOKBACK_MS;
222
+ const recent = usage.filter((p) => p.ts > from && p.ts <= now);
223
+ const total = recent.reduce((a, p) => a + p.usd, 0);
224
+ if (!(total > 0))
225
+ return undefined;
226
+ const usdPerHour = total / (AHEAD_LOOKBACK_MS / HOUR);
227
+ const hours = Math.max(0, status.resetsAt - Math.max(status.runsOutAt, now)) / HOUR;
228
+ if (!(hours > 0))
229
+ return undefined;
230
+ const byModel = new Map();
231
+ for (const p of recent)
232
+ if (p.model)
233
+ byModel.set(p.model, (byModel.get(p.model) ?? 0) + p.usd);
234
+ const [top] = [...byModel].sort((a, b) => b[1] - a[1]);
235
+ const out = { runsOutAt: status.runsOutAt, resetsAt: status.resetsAt, hours, usdPerHour, usd: hours * usdPerHour };
236
+ if (top && top[1] / total >= 0.5) {
237
+ out.model = top[0];
238
+ out.modelShare = top[1] / total;
239
+ }
240
+ if (status.averagePerHour !== undefined && status.averagePerHour > 0) {
241
+ out.averagePerHour = status.averagePerHour;
242
+ out.averageLasts = status.at + ((100 - status.pct) / status.averagePerHour) * HOUR >= status.resetsAt;
243
+ }
244
+ return out;
245
+ }
246
+ /**
247
+ * creditsAhead from this machine: `~/.claude.json` first, then the ledger's
248
+ * weekly window, and the transcripts of the last day only when both say it
249
+ * applies. Never throws: a command's own figures must not be lost to it.
250
+ */
251
+ export function creditsAheadNow(opts = {}) {
252
+ try {
253
+ const now = opts.now ?? Date.now();
254
+ const extra = opts.extraUsage === null ? undefined : opts.extraUsage ?? readExtraUsage(opts.home);
255
+ if (!extraUsageOn(extra))
256
+ return undefined;
257
+ const status = opts.status ?? windowStatus(cleanReadings(readClaudeReadings(now - 8 * DAY, opts.logPath ?? limitsLogPath()).filter((r) => r.window === "seven_day")), now);
258
+ if (!status?.beforeReset || status.runsOutAt === undefined || status.stale)
259
+ return undefined;
260
+ return creditsAhead(status, extra, claudeUsage(now - AHEAD_LOOKBACK_MS, now, opts.claudePaths), now);
261
+ }
262
+ catch {
263
+ return undefined;
264
+ }
265
+ }
266
+ /**
267
+ * One line: "Extra usage is on: at this pace your weekly limit runs out on
268
+ * Thu, Nov 26 at 18:19, 46 hours before it resets, and Claude Code would
269
+ * keep working on usage credits until then: about $1,234 at API list prices
270
+ * (an estimate), at your last 24 hours' $26.80 an hour, mostly Fable 5.2.
271
+ * At this week's average pace (0.55% an hour) it lasts until the reset."
272
+ */
273
+ export function creditsAheadLine(a, now) {
274
+ const hours = a.hours >= 10 ? Math.round(a.hours) : Math.round(a.hours * 10) / 10;
275
+ const mostly = a.model ? `, mostly ${modelLabel(a.model)}` : "";
276
+ const avg = a.averagePerHour === undefined ? ""
277
+ : a.averageLasts ? ` At this week's average pace (${pace(a.averagePerHour)}% an hour) it lasts until the reset.`
278
+ : ` At this week's average pace (${pace(a.averagePerHour)}% an hour) it runs out before the reset too.`;
279
+ return `Extra usage is on: at this pace your weekly limit runs out ${whenText(a.runsOutAt, now)}, ${hours} hour${hours === 1 ? "" : "s"} before it resets, and Claude Code would keep working on usage credits until then: about ${dollars(a.usd)} ${AT_LIST_PRICES}, at your last 24 hours' ${dollars(a.usdPerHour)} an hour${mostly}.${avg}`;
280
+ }
281
+ const pace = (v) => (v >= 10 ? Math.round(v).toString() : v >= 1 ? v.toFixed(1) : v.toFixed(2));
282
+ // ---------------------------------------------------------------------------
283
+ // Words
284
+ // ---------------------------------------------------------------------------
285
+ /** "$41.20", "$4.02", "$130". */
286
+ const dollars = (v) => (v >= 100 ? `$${Math.round(v).toLocaleString("en-US")}` : v > 0 && v < 0.005 ? "<$0.01" : `$${v.toFixed(2)}`);
287
+ /** "at 14:05" within the day, else "on Tue, Nov 17 at 14:05": local time. */
288
+ export function whenText(ms, now) {
289
+ const d = new Date(ms);
290
+ const t = `${String(d.getHours()).padStart(2, "0")}:${String(d.getMinutes()).padStart(2, "0")}`;
291
+ return Math.abs(ms - now) < 20 * HOUR ? `at ${t}` : `on ${d.toLocaleDateString("en-US", { weekday: "short", month: "short", day: "numeric" })} at ${t}`;
292
+ }
293
+ const WINDOW_NAME = { seven_day: "weekly limit", five_hour: "5-hour limit" };
294
+ /** The dollars, in the words every report uses: list prices, an estimate. */
295
+ export const AT_LIST_PRICES = "at API list prices (an estimate)";
296
+ /**
297
+ * One episode in plain words: "Your weekly limit ran out on Tue, Nov 17 at
298
+ * 14:05; 37 requests after that were paid from usage credits, about $41.20
299
+ * at API list prices (an estimate)." Inferred ones say so.
300
+ */
301
+ export function episodeLine(e, now) {
302
+ 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) /, "")}`;
303
+ const n = `${e.requests.toLocaleString("en-US")} ${e.requests === 1 ? "request" : "requests"}`;
304
+ const after = e.window ? " after that" : "";
305
+ const paid = !e.inferred
306
+ ? `${n}${after} ${e.requests === 1 ? "was" : "were"} paid from usage credits`
307
+ : !e.fromHeaders
308
+ ? `${n}${after} still went through, so most likely on usage credits (inferred)`
309
+ : `${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)`;
310
+ const still = e.current ? (e.resetsAt !== undefined ? ` Still past it; it resets ${whenText(e.resetsAt, now)}.` : " Still past it.") : "";
311
+ return `${head}; ${paid}, about ${dollars(e.usd)} ${AT_LIST_PRICES}.${still}`;
312
+ }
313
+ /** Lines for `limits`: one per episode, newest last, and what "inferred" and the dollars mean when it applies. */
314
+ export function creditsLines(r, now) {
315
+ if (!r.requests)
316
+ return [];
317
+ const out = r.episodes.map((e) => episodeLine(e, now));
318
+ if (r.inferred)
319
+ 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).");
320
+ 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.");
321
+ return out;
322
+ }
323
+ const REASON_WORDS = {
324
+ out_of_credits: "out of credits",
325
+ overage_not_provisioned: "not set up for this account",
326
+ org_level_disabled: "turned off for the organization",
327
+ org_level_disabled_until: "the spend cap is reached until it resets",
328
+ seat_tier_level_disabled: "off for this seat type",
329
+ member_level_disabled: "turned off for your seat",
330
+ seat_tier_zero_credit_limit: "a credit limit of zero for this seat type",
331
+ group_zero_credit_limit: "a credit limit of zero for your group",
332
+ member_zero_credit_limit: "a credit limit of zero for your seat",
333
+ org_service_level_disabled: "off for the organization's service",
334
+ no_limits_configured: "no credit limit configured",
335
+ };
336
+ /**
337
+ * `doctor`'s line on extra usage, from `~/.claude.json`: on, on but held
338
+ * back (and why), or off. Undefined when the file says nothing (an API key,
339
+ * never signed in).
340
+ */
341
+ export function extraUsageText(x) {
342
+ if (!x || x.enabled === undefined)
343
+ return undefined;
344
+ if (!x.enabled)
345
+ return { on: false, text: "off: when a plan limit runs out, Claude Code stops until it resets; nothing is paid from usage credits" };
346
+ const held = typeof x.disabledReason === "string" && x.disabledReason !== "fetch_error" && x.disabledReason !== "unknown"
347
+ ? `, but the last reply said credits are not paying now (${REASON_WORDS[x.disabledReason] ?? x.disabledReason.replace(/_/g, " ")})`
348
+ : "";
349
+ 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` };
350
+ }
package/dist/doctor.d.ts CHANGED
@@ -40,6 +40,24 @@ export declare function cacheTtlCheck(home?: string, env?: NodeJS.ProcessEnv): C
40
40
  */
41
41
  export declare function claudeCodeCostCheck(days?: number, now?: number): Check | undefined;
42
42
  export declare function unpricedModelsCheck(days?: number, now?: number, home?: string): Check | undefined;
43
+ /**
44
+ * The Desktop app's answer to its own auto-compact offer (appwindow.ts),
45
+ * only when one is on file: what it offered and what you chose. A fact, not
46
+ * a fault.
47
+ */
48
+ export declare function appWindowCheck(home?: string): Check | undefined;
49
+ /**
50
+ * Extra usage (usage credits past a plan's limit), as Claude Code cached it
51
+ * in `~/.claude.json`: on or off, and when on but held back, why. A fact,
52
+ * not a fault: "ok" either way. Undefined when the file says nothing.
53
+ */
54
+ export declare function extraUsageCheck(home?: string): Check | undefined;
55
+ /**
56
+ * The MCP servers the newest Desktop session handed context-doctor's mod
57
+ * (apptools.ts), their type and placement, and what desktop-tools-defer
58
+ * would do with them. A fact, not a fault: only when one is on file.
59
+ */
60
+ export declare function appToolsCheck(path?: string, now?: number): Check | undefined;
43
61
  /**
44
62
  * Devin (Cognition): the Devin CLI, and Devin Desktop (formerly Windsurf).
45
63
  * Checked against docs.devin.ai (2026-10-20): the CLI runs hooks from
package/dist/doctor.js CHANGED
@@ -12,7 +12,7 @@ import { accessSync, constants as fsConstants, existsSync, readFileSync } from "
12
12
  import { homedir, platform } from "node:os";
13
13
  import { dirname, join } from "node:path";
14
14
  import { fileURLToPath } from "node:url";
15
- import { ledgerPath, readLedger } from "./ledger.js";
15
+ import { ledgerPath, readLedger, statePath } from "./ledger.js";
16
16
  import { costCheck } from "./modmeasure.js";
17
17
  import { ago, MOD_SINCE, modActivity, modReadiness, PLUGIN_KEY, pluginStage, readPluginMarker } from "./claudeplugin.js";
18
18
  import { loadConfig } from "./config.js";
@@ -27,7 +27,9 @@ 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";
32
+ import { appAnswerText, readAppWindows } from "./appwindow.js";
31
33
  import { codexDir } from "./codexdir.js";
32
34
  import { periodSpend, readBudget } from "./budget.js";
33
35
  import { sessionPriceThresholds } from "./sessionprice.js";
@@ -36,6 +38,8 @@ import { claudeUsageFiles } from "./limits.js";
36
38
  import { compareSessions, comparisonCheck } from "./ccost.js";
37
39
  import { hasKnownPrice, isUnbilledModel, priceChangedText } from "./pricing.js";
38
40
  import { managedSourcesLine, orgRatesLine } from "./orgrates.js";
41
+ import { uncachedCheck } from "./cachemisses.js";
42
+ import { appToolsCheckText, recentToolLines } from "./apptools.js";
39
43
  function claudeDesktopConfigPath() {
40
44
  switch (platform()) {
41
45
  case "darwin": return join(homedir(), "Library", "Application Support", "Claude", "claude_desktop_config.json");
@@ -272,7 +276,8 @@ function claudeRouteChecks(layers, plugin, now = Date.now()) {
272
276
  mod = { label: "Mod", status: "skip", detail: "off: CONTEXT_DOCTOR_NO_MOD=1" };
273
277
  }
274
278
  else if (act.cost && now - act.cost < MOD_FRESH_MS) {
275
- mod = { label: "Mod", status: "ok", detail: `recording: last measured ${ago(act.cost, now)} (~/.claude/.context-doctor-session-cost.jsonl)${limits}` };
279
+ // Where the mod writes it (modmeasure.ts costLogPath): beside our state, ~/.claude only by default.
280
+ mod = { label: "Mod", status: "ok", detail: `recording: last measured ${ago(act.cost, now)} (${tilde(join(dirname(statePath()), ".context-doctor-session-cost.jsonl"))})${limits}` };
276
281
  }
277
282
  else if (act.cost) {
278
283
  mod = { label: "Mod", status: "warn", detail: `last measured ${ago(act.cost, now)}: no session that loaded the plugin since, or the mod stopped${limits}` };
@@ -411,6 +416,39 @@ export function unpricedModelsCheck(days = 30, now = Date.now(), home = homedir(
411
416
  detail: `no list price on file for ${named} in the last ${days} days: their dollars (spend, savings, fix, budget) are estimated from the model family or missing. A newer context-doctor may know them: npm install -g context-doctor@latest`,
412
417
  };
413
418
  }
419
+ /**
420
+ * The Desktop app's answer to its own auto-compact offer (appwindow.ts),
421
+ * only when one is on file: what it offered and what you chose. A fact, not
422
+ * a fault.
423
+ */
424
+ export function appWindowCheck(home) {
425
+ let text;
426
+ try {
427
+ text = appAnswerText(readAppWindows({ home }));
428
+ }
429
+ catch {
430
+ return undefined;
431
+ }
432
+ return text ? { label: "Desktop compact offer", status: "ok", detail: text } : undefined;
433
+ }
434
+ /**
435
+ * Extra usage (usage credits past a plan's limit), as Claude Code cached it
436
+ * in `~/.claude.json`: on or off, and when on but held back, why. A fact,
437
+ * not a fault: "ok" either way. Undefined when the file says nothing.
438
+ */
439
+ export function extraUsageCheck(home) {
440
+ const t = extraUsageText(readExtraUsage(home));
441
+ return t ? { label: "Extra usage", status: "ok", detail: t.text } : undefined;
442
+ }
443
+ /**
444
+ * The MCP servers the newest Desktop session handed context-doctor's mod
445
+ * (apptools.ts), their type and placement, and what desktop-tools-defer
446
+ * would do with them. A fact, not a fault: only when one is on file.
447
+ */
448
+ export function appToolsCheck(path, now = Date.now()) {
449
+ const text = appToolsCheckText(recentToolLines(30, now, path));
450
+ return text ? { label: "Desktop app tools", status: "ok", detail: text } : undefined;
451
+ }
414
452
  /**
415
453
  * Devin (Cognition): the Devin CLI, and Devin Desktop (formerly Windsurf).
416
454
  * Checked against docs.devin.ai (2026-10-20): the CLI runs hooks from
@@ -671,6 +709,18 @@ export async function runDoctor() {
671
709
  }
672
710
  if (claudeCodePresent())
673
711
  checks.push(...claudeRouteChecks(layers, plugin));
712
+ // Whether past a plan limit Claude Code keeps going on usage credits (real money): said, never judged.
713
+ const xu = extraUsageCheck();
714
+ if (xu)
715
+ checks.push(xu);
716
+ // What the Desktop app offered for auto-compact and what you answered, only when an answer is on file.
717
+ const aw = appWindowCheck();
718
+ if (aw)
719
+ checks.push(aw);
720
+ // Which servers the Desktop app hands context-doctor's mod, and whether desktop-tools-defer reaches them.
721
+ const at = appToolsCheck();
722
+ if (at)
723
+ checks.push(at);
674
724
  // Codex (OpenAI): MCP table in config.toml, hook in hooks.json, skill.
675
725
  const codexHome = codexDir();
676
726
  if (existsSync(codexHome)) {
@@ -913,6 +963,15 @@ export async function runDoctor() {
913
963
  else if (hooked)
914
964
  checks.push({ label: "Session price", status: "ok", detail: `said once when a session passes ${at.map((t) => `$${t.toLocaleString("en-US")}`).join(", ").replace(/, ([^,]+)$/, " and $1")} (CONTEXT_DOCTOR_SESSION_PRICE to change; CONTEXT_DOCTOR_NO_SESSION_PRICE=1 for off)` });
915
965
  }
966
+ // Requests the prompt cache never saw (anthropics/claude-code#111948), named by Claude Code version.
967
+ try {
968
+ const c = uncachedCheck();
969
+ if (c)
970
+ checks.push(c);
971
+ }
972
+ catch {
973
+ /* an unreadable transcript is no finding */
974
+ }
916
975
  // Models in the last 30 days with no list price of their own: their dollars everywhere are a guess or missing.
917
976
  {
918
977
  const c = unpricedModelsCheck();
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) {
@@ -171,11 +171,20 @@ function getOnce(url, env, deadline, maxBytes) {
171
171
  };
172
172
  const timeout = Math.max(1, deadline - monotonicNow());
173
173
  // The socket timeout is an idle timeout; a server dripping a byte at a
174
- // time would never trip it. This one bounds the whole download.
175
- const overall = setTimeout(() => {
174
+ // time would never trip it. This one bounds the whole download. A timer
175
+ // can fire before the monotonic clock reaches the deadline (a busy loop):
176
+ // it waits out the rest, so a download gives up only at the deadline and
177
+ // the call's next file finds the budget spent (CI read one in those ms).
178
+ const expire = () => {
179
+ const left = deadline - monotonicNow();
180
+ if (left > 0) {
181
+ overall = setTimeout(expire, Math.ceil(left));
182
+ return;
183
+ }
176
184
  req.destroy();
177
185
  done({ status: 0, error: "timed out" });
178
- }, timeout);
186
+ };
187
+ let overall = setTimeout(expire, timeout);
179
188
  const req = request(url, { method: "GET", lookup: guardedLookup(allowLoopback), timeout, headers: { accept: "*/*", "user-agent": "context-doctor" } }, (res) => {
180
189
  const status = res.statusCode ?? 0;
181
190
  if (status >= 300 && status < 400) {
@@ -211,6 +220,9 @@ function getOnce(url, env, deadline, maxBytes) {
211
220
  res.on("error", (e) => done({ status, error: e.message }));
212
221
  });
213
222
  req.on("timeout", () => {
223
+ // Idle as long as the whole budget, fired early: the overall timer ends it at the deadline.
224
+ if (deadline - monotonicNow() > 0)
225
+ return;
214
226
  req.destroy();
215
227
  done({ status: 0, error: "timed out" });
216
228
  });