context-doctor 0.48.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 (74) hide show
  1. package/README.md +15 -14
  2. package/dist/abclaude.js +1 -1
  3. package/dist/budget.d.ts +5 -2
  4. package/dist/budget.js +21 -7
  5. package/dist/cache.js +3 -3
  6. package/dist/cachemisses.d.ts +3 -0
  7. package/dist/cachemisses.js +8 -0
  8. package/dist/cachettl.js +6 -2
  9. package/dist/ccost.d.ts +160 -0
  10. package/dist/ccost.js +304 -0
  11. package/dist/cli.js +135 -32
  12. package/dist/cline.d.ts +41 -0
  13. package/dist/cline.js +174 -0
  14. package/dist/coldresume.d.ts +11 -0
  15. package/dist/coldresume.js +3 -3
  16. package/dist/coldreturns.d.ts +145 -0
  17. package/dist/coldreturns.js +282 -0
  18. package/dist/compactcost.d.ts +10 -4
  19. package/dist/compactcost.js +12 -7
  20. package/dist/compactwindow.js +2 -2
  21. package/dist/copilotusage.d.ts +78 -0
  22. package/dist/copilotusage.js +193 -0
  23. package/dist/doctor.d.ts +6 -0
  24. package/dist/doctor.js +17 -4
  25. package/dist/fix.d.ts +28 -2
  26. package/dist/fix.js +49 -5
  27. package/dist/limits.d.ts +222 -14
  28. package/dist/limits.js +684 -33
  29. package/dist/mcp.js +1 -1
  30. package/dist/mcpdefer.d.ts +47 -0
  31. package/dist/mcpdefer.js +91 -0
  32. package/dist/mod/api.d.ts +72 -2
  33. package/dist/mod/api.js +5 -1
  34. package/dist/mod/logic.d.ts +281 -0
  35. package/dist/mod/logic.js +336 -0
  36. package/dist/mod/register.d.ts +35 -2
  37. package/dist/mod/register.js +283 -6
  38. package/dist/modmeasure.d.ts +6 -4
  39. package/dist/modmeasure.js +8 -4
  40. package/dist/opencode.d.ts +57 -0
  41. package/dist/opencode.js +234 -0
  42. package/dist/orgrates.d.ts +7 -0
  43. package/dist/orgrates.js +19 -0
  44. package/dist/overhead.d.ts +3 -0
  45. package/dist/overhead.js +5 -1
  46. package/dist/pricing.d.ts +59 -2
  47. package/dist/pricing.js +125 -10
  48. package/dist/proxy.d.ts +8 -1
  49. package/dist/proxy.js +13 -1
  50. package/dist/savings.d.ts +5 -1
  51. package/dist/savings.js +11 -5
  52. package/dist/scan.d.ts +3 -1
  53. package/dist/scan.js +8 -1
  54. package/dist/sessionprice.d.ts +5 -0
  55. package/dist/sessionprice.js +5 -1
  56. package/dist/spend.d.ts +86 -3
  57. package/dist/spend.js +240 -23
  58. package/dist/spendplace.d.ts +40 -0
  59. package/dist/spendplace.js +93 -0
  60. package/dist/spendteam.d.ts +160 -0
  61. package/dist/spendteam.js +286 -0
  62. package/dist/starts.d.ts +106 -0
  63. package/dist/starts.js +406 -0
  64. package/dist/statusline.d.ts +2 -2
  65. package/dist/statusline.js +2 -2
  66. package/dist/subagentmodel.js +9 -7
  67. package/dist/subagentpay.d.ts +31 -2
  68. package/dist/subagentpay.js +232 -68
  69. package/dist/subagents.js +3 -3
  70. package/dist/tasks.js +3 -2
  71. package/dist/tooloutput.js +5 -5
  72. package/dist/usagepane.d.ts +77 -0
  73. package/dist/usagepane.js +287 -0
  74. package/package.json +1 -1
package/dist/savings.js CHANGED
@@ -16,7 +16,7 @@ import { AutoClearer } from "./autoclear.js";
16
16
  import { coldResumeEvents } from "./coldresume.js";
17
17
  import { listSessions, isClaudeSession } from "./session.js";
18
18
  import { rowsOf } from "./scan.js";
19
- import { CACHE_WRITE_1H, CACHE_WRITE_5M, cacheWriteSplit, rateCard, ratesAt, requestCost, writeMultiplier } from "./pricing.js";
19
+ import { billedCost, CACHE_WRITE_1H, CACHE_WRITE_5M, cacheWriteSplit, rateCard, ratesAt, writeMultiplier } from "./pricing.js";
20
20
  import { priceBasis } from "./orgrates.js";
21
21
  import { estimateTokens, formatTokens, realModel } from "./tokens.js";
22
22
  import { withInvocation } from "./invocation.js";
@@ -143,7 +143,8 @@ function replayExtractor(id, options, makeClearer, replay) {
143
143
  k: "r", now, cold,
144
144
  bw: fresh + read * 0.1 + ttl.fiveMinute * CACHE_WRITE_5M + ttl.oneHour * CACHE_WRITE_1H,
145
145
  // No time of its own (now is 0 then): priced as of now, as requestCost prices one.
146
- usd: requestCost(pm, u, now || undefined)?.promptUsd ?? 0,
146
+ // With the iterations its usage leaves out (billedCost): an advisor's call, a declined attempt.
147
+ usd: billedCost(pm, u, now || undefined)?.promptUsd ?? 0,
147
148
  raw: fresh + read + write,
148
149
  };
149
150
  // Only what is set: a record read back from the cache must equal this one.
@@ -197,8 +198,8 @@ function replayExtractor(id, options, makeClearer, replay) {
197
198
  load: (v) => ({ ...v, ids: new Set(v.ids), base: loadArm(v.base, options), auto: loadArm(v.auto, options) }),
198
199
  };
199
200
  }
200
- const REPLAY = replayExtractor("replay.4", {}, undefined, true);
201
- const BILL = replayExtractor("bill.4", {}, undefined, false);
201
+ const REPLAY = replayExtractor("replay.5", {}, undefined, true);
202
+ const BILL = replayExtractor("bill.5", {}, undefined, false);
202
203
  /** What `estimateSavings` reads from each transcript, with or without autopilot's replay (for `prescan`). */
203
204
  export const savingsRows = (replay = true) => (replay ? REPLAY : BILL);
204
205
  /**
@@ -353,7 +354,7 @@ export function estimateSavings(days = 30, options = {}, paths, onProgress, repl
353
354
  }
354
355
  const tokens = (n) => (n >= 1e9 ? `${(n / 1e9).toFixed(1)}B` : formatTokens(n));
355
356
  const usd = (n) => (n >= 100 ? `$${Math.round(n).toLocaleString("en-US")}` : `$${n.toFixed(2)}`);
356
- export function renderSavings(r, autopilotOn = false, cw, missLines, limitLines, lensLines) {
357
+ export function renderSavings(r, autopilotOn = false, cw, missLines, limitLines, lensLines, keepWarm) {
357
358
  const lines = [];
358
359
  if (r.sessions.length === 0) {
359
360
  lines.push(`No Claude Code sessions with 10+ requests in the last ${r.days} days to replay.`);
@@ -375,6 +376,11 @@ export function renderSavings(r, autopilotOn = false, cw, missLines, limitLines,
375
376
  lines.push(" expired. Running /compact then, net of the compaction itself, would");
376
377
  lines.push(" have saved this. The every-prompt hook points these moments out, in");
377
378
  lines.push(" every Claude Code surface, the desktop app included.");
379
+ if (keepWarm && keepWarm.netUsd >= 1) {
380
+ // Not a third column to add up: it replaces the re-write compaction cannot avoid.
381
+ lines.push(` Or keep the cache warm while away, up to ${keepWarm.hours} h: ${usd(keepWarm.netUsd)} net of`);
382
+ lines.push(` ${usd(keepWarm.pingUsd)} in pings (/context-doctor-keep-warm; each gap: cache-misses).`);
383
+ }
378
384
  lines.push("");
379
385
  if (allDesktop) {
380
386
  lines.push(`2. Autopilot ${"n/a".padStart(9)}`);
package/dist/scan.d.ts CHANGED
@@ -109,4 +109,6 @@ export declare function pick(o: any, keys: readonly string[]): any;
109
109
  * records `speed`, `inference_geo` and `server_tool_use`; kept on each, they
110
110
  * would grow every record for nothing.
111
111
  */
112
- export declare const slimUsage: (u: any) => unknown;
112
+ export declare const slimUsage: (u: any, opts?: {
113
+ iterations?: boolean;
114
+ }) => unknown;
package/dist/scan.js CHANGED
@@ -43,6 +43,7 @@ import { createHash, randomBytes } from "node:crypto";
43
43
  import { homedir } from "node:os";
44
44
  import { isAbsolute, join } from "node:path";
45
45
  import { PROXY_VERSION } from "./proxy.js";
46
+ import { extraIterations } from "./pricing.js";
46
47
  /** Bumped when the entry layout below changes. */
47
48
  const SCHEMA = 1;
48
49
  const DAY = 86_400_000;
@@ -507,7 +508,7 @@ const USAGE_KEYS = ["input_tokens", "cache_creation_input_tokens", "cache_read_i
507
508
  * records `speed`, `inference_geo` and `server_tool_use`; kept on each, they
508
509
  * would grow every record for nothing.
509
510
  */
510
- export const slimUsage = (u) => {
511
+ export const slimUsage = (u, opts = {}) => {
511
512
  const out = pick(u, USAGE_KEYS);
512
513
  if (!out || typeof out !== "object" || Array.isArray(out))
513
514
  return out;
@@ -518,5 +519,11 @@ export const slimUsage = (u) => {
518
519
  const searches = u.server_tool_use?.web_search_requests;
519
520
  if (typeof searches === "number" && searches > 0)
520
521
  out.server_tool_use = { web_search_requests: searches };
522
+ // The request's iterations, only where some bill beyond its top-level usage (an advisor's, a
523
+ // declined attempt's: extraIterations); every request has one, the request itself, kept for nothing.
524
+ if (opts.iterations && extraIterations(u).length)
525
+ out.iterations = u.iterations.map((t) => pick(t, ITERATION_KEYS));
521
526
  return out;
522
527
  };
528
+ /** What an iteration is priced from (extraIterations). */
529
+ const ITERATION_KEYS = ["type", "model", "input_tokens", "cache_creation_input_tokens", "cache_read_input_tokens", "output_tokens", "cache_creation"];
@@ -84,6 +84,11 @@ export interface SessionTotal {
84
84
  estimatedUsd: number;
85
85
  /** Bytes read to bring the entries up to date. */
86
86
  read: number;
87
+ /** Each file's own dollars and requests (the main transcript, each subagent's), as counted in `usd`: the usage pane's per-subagent cost. */
88
+ byFile: Record<string, {
89
+ usd: number;
90
+ requests: number;
91
+ }>;
87
92
  /** Keeps the entries, so the next look reads only what was appended. */
88
93
  save: () => void;
89
94
  }
@@ -202,10 +202,12 @@ export function sessionTotal(input, now = Date.now()) {
202
202
  // Each reply once: a fork's copy shares its key with the reply it copied.
203
203
  const seen = new Set();
204
204
  let usd = 0, subagentUsd = 0, workflowUsd = 0, unpriced = 0, estimatedUsd = 0;
205
+ const byFile = {};
205
206
  for (const [file, whose] of files) {
206
207
  const e = kept[file];
207
208
  if (!e)
208
209
  continue;
210
+ const mine = (byFile[file] = { usd: 0, requests: 0 });
209
211
  const x = new Set((e.x ?? []).map(([i]) => i)), y = new Set((e.y ?? []).map(([i]) => i));
210
212
  e.k.forEach((key, i) => {
211
213
  if (key) {
@@ -214,6 +216,8 @@ export function sessionTotal(input, now = Date.now()) {
214
216
  seen.add(key);
215
217
  }
216
218
  usd += e.d[i];
219
+ mine.usd += e.d[i];
220
+ mine.requests++;
217
221
  if (whose === "sub")
218
222
  subagentUsd += e.d[i];
219
223
  if (whose === "workflow")
@@ -240,7 +244,7 @@ export function sessionTotal(input, now = Date.now()) {
240
244
  }
241
245
  catch { /* read again next time */ }
242
246
  };
243
- return { app, usd, subagentUsd, workflowUsd, unpriced, estimatedUsd, read, save };
247
+ return { app, usd, subagentUsd, workflowUsd, unpriced, estimatedUsd, read, byFile, save };
244
248
  }
245
249
  /** Keeps a look's entries once it read enough to be worth it, as the threshold check does. */
246
250
  export function saveIfWorthIt(t) {
package/dist/spend.d.ts CHANGED
@@ -41,8 +41,15 @@
41
41
  */
42
42
  import { type ProgressOptions } from "./progresssummaries.js";
43
43
  import { type Modifiers } from "./pricing.js";
44
+ import { type SessionGap } from "./ccost.js";
45
+ /**
46
+ * What spend's dollars are: each request as it was billed (its tier, fast mode,
47
+ * US-only, web searches) at list rates, or at the organization's rates.
48
+ * "At list prices" was true before those were priced; it no longer is.
49
+ */
50
+ export declare const spendBasis: () => string;
44
51
  import { type Extractor } from "./scan.js";
45
- export type Tool = "claude" | "codex" | "gemini" | "cursor";
52
+ export type Tool = "claude" | "codex" | "gemini" | "cursor" | "copilot" | "opencode" | "cline";
46
53
  export declare const TOOLS: Tool[];
47
54
  export declare const TOOL_NAME: Record<Tool, string>;
48
55
  /** One request (a Cursor reply), priced. */
@@ -78,6 +85,23 @@ export interface SpendItem {
78
85
  key?: string;
79
86
  /** Claude Code: a compaction's own request, which no row records usage for: estimated from the context it read and its summary (compactcost.ts). */
80
87
  compaction?: boolean;
88
+ /** Copilot CLI: the AI credits it used (one is $0.01), as Copilot recorded them; not in `usd`. */
89
+ credits?: number;
90
+ /** Copilot CLI: the premium requests it counted (its multiplier); not in `usd`. */
91
+ premium?: number;
92
+ /** The folder it ran in, and its git root and branch where the tool recorded them (spendplace.ts). Read for `--by repo` and `--by branch` only; never exported. */
93
+ cwd?: string;
94
+ root?: string;
95
+ branch?: string;
96
+ /** Its repository's name (spendplace.ts repoName), set when the report groups by repository or branch. */
97
+ repo?: string;
98
+ /**
99
+ * Claude Code: an iteration of a request that its top-level usage leaves
100
+ * out, billed on top at its own model (pricing.ts extraIterations): its
101
+ * type, "advisor_message" (the advisor tool's call) or the attempt a
102
+ * fallback replaced ("message"). Not a request of its own: not in the counts.
103
+ */
104
+ iteration?: string;
81
105
  }
82
106
  /**
83
107
  * A project folder's name (its path with "-" for separators, as Claude Code
@@ -95,7 +119,7 @@ export declare const anyModifier: (m: Modifiers | undefined) => m is Modifiers;
95
119
  * Claude Code's requests between `since` and `until`, main threads and
96
120
  * subagents, over `tops` (default: every transcript written since `since`).
97
121
  */
98
- export declare function claudeSpend(since: number, until?: number, tops?: string[], onProgress?: (done: number, total: number) => void): SpendItem[];
122
+ export declare function claudeSpend(since: number, until?: number, tops?: string[], onProgress?: (done: number, total: number) => void, place?: boolean): SpendItem[];
99
123
  /**
100
124
  * What `spend` takes from a Codex rollout: its folder, its own id and the
101
125
  * thread that spawned it (the first session_meta), each model change, and
@@ -150,6 +174,16 @@ export declare function geminiFileSpend(file: string, since: number, until?: num
150
174
  export declare function geminiFiles(since: number, home?: string): string[];
151
175
  export declare function geminiSpend(since: number, until?: number, home?: string): SpendItem[];
152
176
  export declare function cursorSpend(since: number, until?: number): SpendItem[];
177
+ /**
178
+ * Copilot CLI's model calls (copilotusage.ts), each priced at its model's
179
+ * list price where the table has one, else counted. What Copilot bills is
180
+ * its AI credits and premium requests, kept beside the price, not in it.
181
+ */
182
+ export declare function copilotSpend(since: number, until?: number, home?: string): SpendItem[];
183
+ /** OpenCode's model calls (opencode.ts), each at its model's list price. Throws SqliteUnavailableError when its database cannot be read here. */
184
+ export declare function opencodeSpend(since: number, until?: number, home?: string): SpendItem[];
185
+ /** Cline's requests (cline.ts), each at its model's list price; one with no model is counted, not priced. */
186
+ export declare function clineSpend(since: number, until?: number, home?: string): SpendItem[];
153
187
  export interface ToolSpend {
154
188
  tool: Tool;
155
189
  name: string;
@@ -168,6 +202,9 @@ export interface ToolSpend {
168
202
  workflowRuns?: number;
169
203
  /** Cursor: priced without a cache split, an upper bound. */
170
204
  estimate?: boolean;
205
+ /** Copilot CLI: the AI credits and premium requests it recorded, beside `usd` (which is the tokens at list price). */
206
+ credits?: number;
207
+ premium?: number;
171
208
  /** Requests whose model has no list price, counted but not in `usd`. */
172
209
  unpriced: number;
173
210
  unpricedTokens: number;
@@ -194,6 +231,15 @@ export interface SpendReport {
194
231
  projects: Array<SpendRow & {
195
232
  project: string;
196
233
  }>;
234
+ /** By repository (`--by repo` or `--by branch`): a folder's git repository, else the project. Absent otherwise. */
235
+ repos?: Array<SpendRow & {
236
+ repo: string;
237
+ }>;
238
+ /** By repository and branch (`--by branch`); a request whose tool records no branch has none. Absent otherwise. */
239
+ branches?: Array<SpendRow & {
240
+ repo: string;
241
+ branch?: string;
242
+ }>;
197
243
  models: Array<SpendRow & {
198
244
  model: string;
199
245
  }>;
@@ -223,6 +269,21 @@ export interface SpendReport {
223
269
  requests: number;
224
270
  usd: number;
225
271
  };
272
+ /** Claude Code: iterations billed beyond their request's top-level usage (the advisor's calls, attempts a fallback replaced), by type: inside `usd`; absent when none. */
273
+ iterations?: Record<string, {
274
+ calls: number;
275
+ usd: number;
276
+ models: string[];
277
+ }>;
278
+ /**
279
+ * Claude Code's own figure (its `cost-state` records) beside ours, per
280
+ * session wholly in the window that has one (ccost.ts); absent when none.
281
+ */
282
+ claudeCode?: {
283
+ ccUsd: number;
284
+ ourUsd: number;
285
+ sessions: SessionGap[];
286
+ };
226
287
  /**
227
288
  * Claude Code's subagent progress summaries, estimated (no transcript records them): NOT in `usd`.
228
289
  * `notesUsd` as short notes (served since November 2026), `forkUsd` as the whole context (before).
@@ -259,6 +320,8 @@ export declare function localDay(ts: number): string;
259
320
  export declare function summarizeSpend(items: SpendItem[], days: number, since: number, until: number, skipped?: SpendReport["skipped"]): SpendReport;
260
321
  export interface SpendOptions {
261
322
  home?: string;
323
+ /** Group by repository, or by repository and branch, besides project: reads where each request ran (spendplace.ts). */
324
+ by?: "project" | "repo" | "branch";
262
325
  /** Claude Code transcripts to read instead of every one written in the window (tests). */
263
326
  claudePaths?: string[];
264
327
  onProgress?: (done: number, total: number) => void;
@@ -277,12 +340,32 @@ export interface SpendOptions {
277
340
  * --json died on a string too long), and 1e9 days fell off the calendar.
278
341
  */
279
342
  export declare const MAX_SPEND_DAYS = 3650;
343
+ /**
344
+ * One Claude Code session's comparison with Claude Code's own figure (ccost.ts):
345
+ * its transcript and its subagents', to its last `cost-state`. Undefined when
346
+ * it has none, or cannot be read.
347
+ */
348
+ export declare function claudeCodeSession(top: string): SessionGap | undefined;
349
+ /**
350
+ * A session's requests priced past the day their model's price ended or
351
+ * changed, said as `spend` says it: which price, and the one used instead.
352
+ * Undefined when none (or the transcript cannot be read).
353
+ */
354
+ export declare function sessionPriceEnded(top: string): string | undefined;
355
+ /** Every request of the last `days` days, every tool on this machine, and what could not be read. */
356
+ export declare function collectSpend(days?: number, opts?: SpendOptions): {
357
+ items: SpendItem[];
358
+ days: number;
359
+ since: number;
360
+ until: number;
361
+ skipped: SpendReport["skipped"];
362
+ };
280
363
  /** The last `days` days, every tool on this machine. A tool with nothing on disk is just absent. */
281
364
  export declare function spendReport(days?: number, opts?: SpendOptions): SpendReport;
282
365
  export declare const usd: (n: number) => string;
283
366
  /** "fast mode +$4.10, US-only +$0.93, web searches $0.12 (12), long-prompt tier +$0.40": what each billing modifier added, the ones that added anything. */
284
367
  export declare function modifiersText(m: Modifiers): string;
285
- /** The full report, kept within 80 columns. `top`: rows per list. */
368
+ /** The full report, kept within 80 columns. `top`: rows per list. Grouped by repository or branch instead of project when the report has them (`--by`). */
286
369
  export declare function renderSpend(r: SpendReport, top?: number): string;
287
370
  /**
288
371
  * `spend --share`: totals only. No project names, paths or session ids, so