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
package/dist/spend.js CHANGED
@@ -32,7 +32,8 @@
32
32
  * Not in the total: Claude Code's subagent progress summaries, side requests
33
33
  * no transcript records (progresssummaries.ts). They are estimated per
34
34
  * background subagent and shown beside the total as a range, the two ways
35
- * Anthropic may serve them (short notes, or the whole context).
35
+ * Anthropic may serve them (short notes, or the whole context); a subagent
36
+ * on Claude Code 2.1.328+ once, as notes on the small fast model.
36
37
  *
37
38
  * `savings` bills a narrower slice of the same Claude Code requests: the main
38
39
  * conversation's input (cache writes and reads included, output not), in
@@ -44,7 +45,7 @@ import { codexDir } from "./codexdir.js";
44
45
  import { homedir } from "node:os";
45
46
  import { closeSync, existsSync, openSync, readdirSync, readSync, statSync } from "node:fs";
46
47
  import { claudeFileUsage, claudeUsageFiles, codexEventKey, codexSessionsRoot, rolloutFiles, USAGE_ROWS } from "./limits.js";
47
- import { estimateProgressSummaries, PROGRESS_ROWS, PROGRESS_SUMMARIES_ENV } from "./progresssummaries.js";
48
+ import { estimateProgressSummaries, PROGRESS_ROWS, PROGRESS_SUMMARIES_ENV, SMALL_FAST_MODEL_NAME as SMALL_NAME, SMALL_NOTES_SINCE } from "./progresssummaries.js";
48
49
  import { listGeminiChats, readGeminiMessages } from "./gemini.js";
49
50
  import { cursorClaudeId, cursorUsage, SqliteUnavailableError } from "./cursor.js";
50
51
  import { copilotCalls } from "./copilotusage.js";
@@ -54,6 +55,7 @@ import { clineCalls } from "./cline.js";
54
55
  import { addModifiers, isUnbilledModel, NO_MODIFIERS, openAIUsage, priceChangedText, priceEndWord, requestCost } from "./pricing.js";
55
56
  import { managedSourcesLine, orgRates, orgRatesLine, priceBasis } from "./orgrates.js";
56
57
  import { compareSessions, renderComparison } from "./ccost.js";
58
+ import { AT_LIST_PRICES, creditsInputs, creditsOf, nothingPast, whenText } from "./credits.js";
57
59
  /**
58
60
  * What spend's dollars are: each request as it was billed (its tier, fast mode,
59
61
  * US-only, web searches) at list rates, or at the organization's rates.
@@ -763,7 +765,7 @@ function claudeProgressSummaries(since, until, tops, o) {
763
765
  return { set: o.set };
764
766
  const files = claudeUsageFiles(since, tops).filter((f) => f.subagent && !f.run).map((f) => f.file);
765
767
  const e = estimateProgressSummaries(files, { since, until, forkGateOff: o?.forkGateOff, offSince: o?.offSince });
766
- return e.calls ? { agents: e.summarized, calls: e.calls, notesUsd: e.notesUsd, forkUsd: e.forkUsd } : undefined;
768
+ return e.calls ? { agents: e.summarized, calls: e.calls, ...(e.smallCalls ? { smallCalls: e.smallCalls } : {}), notesUsd: e.notesUsd, forkUsd: e.forkUsd } : undefined;
767
769
  }
768
770
  /**
769
771
  * The longest window: ten years, older than any history these tools keep.
@@ -852,6 +854,14 @@ export function spendReport(days = 30, opts = {}) {
852
854
  const gaps = compareSessions(tops, items, since, until);
853
855
  if (gaps.length)
854
856
  report.claudeCode = { ccUsd: gaps.reduce((n, g) => n + g.ccUsd, 0), ourUsd: gaps.reduce((n, g) => n + g.ourUsd, 0), sessions: gaps };
857
+ // Claude Code past the plan's limit: only when the limits ledger says a limit ran out or credits were in use.
858
+ const inp = creditsInputs(since, { now: until, logPath: opts.limitsLogPath, extraUsage: opts.extraUsage, home: opts.home });
859
+ if (!nothingPast(inp)) {
860
+ const claude = items.filter((it) => it.tool === "claude" && it.ts >= since && it.ts <= until);
861
+ const c = creditsOf(claude, inp);
862
+ if (c.requests)
863
+ report.credits = { usd: c.usd, requests: c.requests, claudeUsd: claude.reduce((n, it) => n + it.usd, 0), fromHeaders: c.fromHeaders, inferred: c.inferred, since: c.episodes[0].ranOutAt };
864
+ }
855
865
  const progress = opts.progress === false ? undefined : claudeProgressSummaries(since, until, opts.claudePaths, opts.progress);
856
866
  return progress ? { ...report, progressSummaries: progress } : report;
857
867
  }
@@ -876,6 +886,21 @@ export function modifiersText(m) {
876
886
  }
877
887
  /** AI credits or premium requests: whole above 100, else to two places. */
878
888
  const creditsText = (n) => (n >= 100 ? Math.round(n).toLocaleString("en-US") : String(Math.round(n * 100) / 100));
889
+ /**
890
+ * Claude Code's dollars split at the plan's limit: what ran past it on usage
891
+ * credits, and the rest, inside the plan.
892
+ */
893
+ export function creditsSplitLines(c, now) {
894
+ const n = `${c.requests.toLocaleString("en-US")} ${c.requests === 1 ? "request" : "requests"}`;
895
+ const how = !c.inferred ? "paid from usage credits" : !c.fromHeaders ? "likely paid from usage credits (inferred from 100% readings)" : `paid from usage credits (${c.inferred.toLocaleString("en-US")} inferred from 100% readings)`;
896
+ return [
897
+ "",
898
+ `Past your plan's limit since ${whenText(c.since, now).replace(/^(at|on) /, "")}: ${usd(c.usd)} of Claude Code's ${usd(c.claudeUsd)},`,
899
+ ` ${n}, ${how},`,
900
+ ` ${orgRates() ? "at your rates above (an estimate)" : AT_LIST_PRICES}. The other ${usd(Math.max(0, c.claudeUsd - c.usd))} was inside the plan.`,
901
+ " `context-doctor limits` says when each limit ran out.",
902
+ ];
903
+ }
879
904
  /** 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`). */
880
905
  export function renderSpend(r, top = 8) {
881
906
  const lines = [];
@@ -902,6 +927,8 @@ export function renderSpend(r, top = 8) {
902
927
  }
903
928
  if (r.tools.length > 1)
904
929
  lines.push(`${"Total".padEnd(14)}${usd(r.usd).padStart(11)}`);
930
+ if (r.credits)
931
+ lines.push(...creditsSplitLines(r.credits, r.until));
905
932
  const list = (title, rows, more) => {
906
933
  lines.push("", title);
907
934
  for (const x of rows)
@@ -952,7 +979,13 @@ export function renderSpend(r, top = 8) {
952
979
  const ps = r.progressSummaries;
953
980
  if (ps && "calls" in ps) {
954
981
  lines.push(` Not in it: ~${ps.calls.toLocaleString("en-US")} subagent progress summaries (${ps.agents} background ${ps.agents === 1 ? "agent" : "agents"}), an estimate:`);
955
- lines.push(` ${usd(ps.notesUsd)} as notes, ${usd(ps.forkUsd)} at the whole context; no transcript records them`);
982
+ if (ps.smallCalls === ps.calls)
983
+ lines.push(` ${usd(ps.notesUsd)}, short notes on ${SMALL_NAME} (Claude Code ${SMALL_NOTES_SINCE}+); in no transcript`);
984
+ else {
985
+ lines.push(` ${usd(ps.notesUsd)} as notes, ${usd(ps.forkUsd)} at the whole context; no transcript records them`);
986
+ if (ps.smallCalls)
987
+ lines.push(` (${ps.smallCalls.toLocaleString("en-US")} of them on Claude Code ${SMALL_NOTES_SINCE}+: notes on ${SMALL_NAME} either way)`);
988
+ }
956
989
  }
957
990
  else if (ps)
958
991
  lines.push(` Subagent progress summaries: not estimated, ${PROGRESS_SUMMARIES_ENV} is set in ${ps.set}`);
@@ -1028,7 +1061,7 @@ export function renderSpendShare(r) {
1028
1061
  lines.push(`Billed above list rates: ${modifiersText(r.modifiers)}.`);
1029
1062
  const ps = r.progressSummaries;
1030
1063
  if (ps && "calls" in ps)
1031
- lines.push(`Not in it: Claude Code's subagent progress summaries, which no transcript records: ${usd(ps.notesUsd)}-${usd(ps.forkUsd)}, an estimate.`);
1064
+ lines.push(`Not in it: Claude Code's subagent progress summaries, which no transcript records: ${ps.smallCalls === ps.calls ? usd(ps.notesUsd) : `${usd(ps.notesUsd)}-${usd(ps.forkUsd)}`}, an estimate.`);
1032
1065
  const parts = [["cache writes", r.parts.writeUsd], ["cache reads", r.parts.readUsd], ["output", r.parts.outputUsd], ["uncached input", r.parts.inputUsd], ["web searches", r.parts.webSearchUsd ?? 0]];
1033
1066
  const [bigPart, bigUsd] = parts.sort((a, b) => b[1] - a[1])[0];
1034
1067
  const busiest = [...r.daily].sort((a, b) => b.usd - a.usd)[0];
package/dist/starts.d.ts CHANGED
@@ -33,6 +33,14 @@ export declare const START_ROWS: Extractor<{
33
33
  u?: 1;
34
34
  r?: 1;
35
35
  }>;
36
+ /**
37
+ * The MCP servers a transcript called a tool of, by name only: which starts
38
+ * needed a server whose tools could have waited behind tool search (fix's
39
+ * desktop-tools-defer prices only the starts that never called it).
40
+ */
41
+ export declare const CALL_ROWS: Extractor<{
42
+ seen: string[];
43
+ }>;
36
44
  /** An entrypoint as people call it. */
37
45
  export declare function entrypointName(e: string | undefined): string;
38
46
  /** The MCP server a tool name belongs to (`mcp__<server>__<tool>`), or undefined for a built-in. */
@@ -46,6 +54,12 @@ export interface StartServer {
46
54
  tokens: number;
47
55
  /** In the user's own MCP config (~/.claude.json, the folder's .mcp.json): `alwaysLoad: false` there defers it. */
48
56
  configured?: "user" | "project" | ".mcp.json";
57
+ /** Of `starts`, the ones whose session or subagent called one of its tools. */
58
+ calledStarts: number;
59
+ /** Its definitions' part of the starts that never called it, each start at its own rates: what keeping it behind tool search would have saved there. */
60
+ unusedUsd: number;
61
+ /** The same in the starts that did call it: with `unusedUsd`, its definitions' whole part of its starts, counted alike. */
62
+ calledUsd: number;
49
63
  }
50
64
  export interface StartGroup {
51
65
  kind: "session" | "subagent";
@@ -102,5 +116,17 @@ export declare function deferrableConfigured(r: StartsReport): Array<{
102
116
  tokens: number;
103
117
  usd: number;
104
118
  }>;
119
+ /** Every server whose tools went whole into some start, across the groups: its share of each group's deferrable part, as `overhead` lists it. */
120
+ export declare function startServers(r: StartsReport): Array<StartServer & {
121
+ usd: number;
122
+ }>;
123
+ /**
124
+ * The Desktop app's own servers (Claude_Browser, ccd_session, visualize,
125
+ * terminal) whose tools went whole into some start, and no config file of the
126
+ * user's holds: fix's desktop-tools-defer, which context-doctor's mod applies.
127
+ */
128
+ export declare function deferrableApp(r: StartsReport): Array<StartServer & {
129
+ usd: number;
130
+ }>;
105
131
  /** The starts section of `overhead`. */
106
- export declare function renderStarts(r: StartsReport): string[];
132
+ export declare function renderStarts(r: StartsReport, applied?: ReadonlySet<string>): string[];
package/dist/starts.js CHANGED
@@ -26,6 +26,7 @@ import { listSessions, isClaudeSession, replyCounter, textOf } from "./session.j
26
26
  import { subagentFiles, workflowRunOf } from "./subagents.js";
27
27
  import { cacheWriteSplit, formatUsd, rateCard, ratesAt, usageCost } from "./pricing.js";
28
28
  import { formatTokens, isCodeLike, realModel, tokensForLength } from "./tokens.js";
29
+ import { APP_TOOL_SERVERS } from "./mod/logic.js";
29
30
  const CLAUDE = "claude-opus-5";
30
31
  /**
31
32
  * What a start's measurement takes from a transcript: the entrypoint, the
@@ -90,6 +91,36 @@ export const START_ROWS = {
90
91
  }
91
92
  },
92
93
  };
94
+ /**
95
+ * The MCP servers a transcript called a tool of, by name only: which starts
96
+ * needed a server whose tools could have waited behind tool search (fix's
97
+ * desktop-tools-defer prices only the starts that never called it).
98
+ */
99
+ export const CALL_ROWS = {
100
+ id: "startcalls.1",
101
+ init: () => ({ seen: [] }),
102
+ line(raw, row, out, st) {
103
+ if (!raw.includes('"tool_use"') || !raw.includes('"name":"mcp__'))
104
+ return;
105
+ let e;
106
+ try {
107
+ e = row();
108
+ }
109
+ catch {
110
+ return;
111
+ }
112
+ const content = e?.message?.content;
113
+ if (!Array.isArray(content))
114
+ return;
115
+ for (const b of content) {
116
+ const server = b?.type === "tool_use" && typeof b.name === "string" ? mcpServerOf(b.name) : undefined;
117
+ if (!server || st.seen.includes(server))
118
+ continue;
119
+ st.seen.push(server);
120
+ out.push(server.slice(0, 200));
121
+ }
122
+ },
123
+ };
93
124
  /** An entrypoint as people call it. */
94
125
  export function entrypointName(e) {
95
126
  switch (e) {
@@ -211,6 +242,8 @@ function measureStart(path, kind, since, runRows, parentEntry) {
211
242
  s.tokens += t;
212
243
  }
213
244
  start.shape = { wholeTools, wholeTokens: Math.min(wholeTokens, tokens), mcpTokens: Math.min(mcpTokens, tokens), servers };
245
+ if (servers.size)
246
+ start.called = new Set(rowsOf(path, CALL_ROWS));
214
247
  }
215
248
  return start;
216
249
  }
@@ -275,10 +308,17 @@ export function measureStarts(opts = {}) {
275
308
  const servers = new Map();
276
309
  for (const s of shaped)
277
310
  for (const [name, v] of s.shape.servers) {
278
- const cur = servers.get(name) ?? servers.set(name, { name, starts: 0, tools: 0, tokens: 0, ...(configured.get(name) ? { configured: configured.get(name) } : {}) }).get(name);
311
+ const cur = servers.get(name) ?? servers.set(name, { name, starts: 0, tools: 0, tokens: 0, calledStarts: 0, unusedUsd: 0, calledUsd: 0, ...(configured.get(name) ? { configured: configured.get(name) } : {}) }).get(name);
279
312
  cur.starts++;
280
313
  cur.tools = Math.max(cur.tools, v.tools);
281
314
  cur.tokens += v.tokens;
315
+ const part = s.usd * Math.min(1, v.tokens / s.tokens);
316
+ if (s.called?.has(name)) {
317
+ cur.calledStarts++;
318
+ cur.calledUsd += part;
319
+ }
320
+ else
321
+ cur.unusedUsd += part;
282
322
  }
283
323
  for (const s of servers.values())
284
324
  s.tokens = Math.round(s.tokens / s.starts);
@@ -334,9 +374,38 @@ export function deferrableConfigured(r) {
334
374
  }
335
375
  return [...out.values()].sort((a, b) => b.usd - a.usd);
336
376
  }
377
+ /** Every server whose tools went whole into some start, across the groups: its share of each group's deferrable part, as `overhead` lists it. */
378
+ export function startServers(r) {
379
+ const servers = new Map();
380
+ for (const g of r.groups)
381
+ for (const s of g.servers) {
382
+ const share = g.deferrableUsd ? (g.deferrableUsd * s.tokens * s.starts) / (g.servers.reduce((t, x) => t + x.tokens * x.starts, 0) || 1) : 0;
383
+ const cur = servers.get(s.name);
384
+ if (cur) {
385
+ cur.usd += share;
386
+ cur.starts += s.starts;
387
+ cur.calledStarts += s.calledStarts;
388
+ cur.unusedUsd += s.unusedUsd;
389
+ cur.calledUsd += s.calledUsd;
390
+ cur.tokens = Math.max(cur.tokens, s.tokens);
391
+ cur.tools = Math.max(cur.tools, s.tools);
392
+ }
393
+ else
394
+ servers.set(s.name, { ...s, usd: share });
395
+ }
396
+ return [...servers.values()].sort((a, b) => b.usd - a.usd);
397
+ }
398
+ /**
399
+ * The Desktop app's own servers (Claude_Browser, ccd_session, visualize,
400
+ * terminal) whose tools went whole into some start, and no config file of the
401
+ * user's holds: fix's desktop-tools-defer, which context-doctor's mod applies.
402
+ */
403
+ export function deferrableApp(r) {
404
+ return startServers(r).filter((s) => !s.configured && APP_TOOL_SERVERS.includes(s.name));
405
+ }
337
406
  const tok = (n) => `~${formatTokens(n)}`;
338
407
  /** The starts section of `overhead`. */
339
- export function renderStarts(r) {
408
+ export function renderStarts(r, applied = new Set()) {
340
409
  const out = ["", "Session and subagent starts (the first request, before the first message)", "─".repeat(56)];
341
410
  if (r.groups.length === 0) {
342
411
  out.push(" No Claude Code session in the period to measure.");
@@ -368,21 +437,7 @@ export function renderStarts(r) {
368
437
  out.push(" No terminal sessions in the period to compare the Desktop app's start with (#105328 reports ~79k against ~13k).");
369
438
  }
370
439
  // What could be deferred, and whether any setting reaches it.
371
- const servers = new Map();
372
- for (const g of r.groups)
373
- for (const s of g.servers) {
374
- const share = g.deferrableUsd ? (g.deferrableUsd * s.tokens * s.starts) / (g.servers.reduce((t, x) => t + x.tokens * x.starts, 0) || 1) : 0;
375
- const cur = servers.get(s.name);
376
- if (cur) {
377
- cur.usd += share;
378
- cur.starts += s.starts;
379
- cur.tokens = Math.max(cur.tokens, s.tokens);
380
- cur.tools = Math.max(cur.tools, s.tools);
381
- }
382
- else
383
- servers.set(s.name, { ...s, usd: share });
384
- }
385
- const list = [...servers.values()].sort((a, b) => b.usd - a.usd);
440
+ const list = startServers(r);
386
441
  if (list.length) {
387
442
  out.push(" MCP tool definitions sent whole (not deferred behind tool search):");
388
443
  for (const s of list.slice(0, 8)) {
@@ -396,7 +451,15 @@ export function renderStarts(r) {
396
451
  if (app.length) {
397
452
  out.push(` No setting defers the ${app.length === 1 ? "server" : `${app.length} servers`} the app provides (${formatUsd(app.reduce((t, s) => t + s.usd, 0))} of the starts' cost): the Desktop app hands its own servers and connectors to Claude Code in-process with their tools marked to load upfront, and no MCP setting or ENABLE_TOOL_SEARCH value reaches them (tool search is on: the other tools are deferred). A subagent definition's \`tools:\` list or \`disallowedTools: mcp__*\` keeps them out of that agent's start, and out of its reach too.`);
398
453
  }
399
- if (list.some((s) => s.configured))
454
+ const own = app.filter((s) => APP_TOOL_SERVERS.includes(s.name));
455
+ // Applied already: the starts in this window before it still count the tools, so say so rather than offer it again.
456
+ if (own.length && applied.has("desktop-tools-defer"))
457
+ out.push(` Applied (\`fix --apply desktop-tools-defer\`): context-doctor's mod keeps ${own.map((s) => s.name).join(", ")} behind tool search in sessions started since; the older starts above still count them. Undo with \`fix undo desktop-tools-defer\`.`);
458
+ else if (own.length)
459
+ out.push(` \`context-doctor fix --apply desktop-tools-defer\` has context-doctor's mod keep ${own.map((s) => s.name).join(", ")} behind tool search in new sessions (Claude Code 2.1.326+ with the plugin; reversible with \`fix undo desktop-tools-defer\`); \`fix\` prices it on the starts that never called them.`);
460
+ if (list.some((s) => s.configured) && applied.has("mcp-defer"))
461
+ out.push(" Applied (`fix --apply mcp-defer`): your own servers are set to `alwaysLoad: false`; starts before that still count them. Undo with `fix undo mcp-defer`.");
462
+ else if (list.some((s) => s.configured))
400
463
  out.push(" `context-doctor fix --apply mcp-defer` sets `alwaysLoad: false` on the ones in your own config (reversible with `fix undo mcp-defer`).");
401
464
  }
402
465
  else if (r.groups.some((g) => g.shaped > 0)) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "context-doctor",
3
- "version": "0.49.1",
3
+ "version": "0.50.0",
4
4
  "description": "Context and token optimizer for LLM agents: see where Claude Code, Cursor, Codex and Gemini CLI tokens go, then cut them: an every-prompt hook, smarter compaction, an autopilot proxy that edits history only when the prompt cache is cold, RAG chunk packing and an MCP server. Local, no API key. By gAI Ventures.",
5
5
  "keywords": [
6
6
  "agent",