context-doctor 0.50.0 → 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.
@@ -47,6 +47,30 @@
47
47
  * subagent whose transcript says `version` 2.1.328 or later is priced once,
48
48
  * at Haiku 5.5's rates (low and high the same); an older one as before.
49
49
  *
50
+ * Read again from the 2.1.330 binary: that is a terminal session on the
51
+ * Anthropic API's only. Per subagent, Claude Code reads its provider (from
52
+ * CLAUDE_CODE_USE_*: the Claude Code gateway, Bedrock, Foundry, Anthropic on
53
+ * AWS or Google Cloud, Mantle, Vertex, else the Anthropic API):
54
+ * - Bedrock, Vertex, Foundry or the gateway (CLAUDE_CODE_USE_GATEWAY): the
55
+ * notes, written by the subagent's OWN model ("release" mode).
56
+ * - Any other: a served flag (notes unless it says otherwise), and the
57
+ * writer is the small fast model only when ANTHROPIC_SMALL_FAST_MODEL and
58
+ * ANTHROPIC_DEFAULT_HAIKU_MODEL are both unset, the provider is the
59
+ * Anthropic API, and the API counts as Anthropic's: ANTHROPIC_BASE_URL
60
+ * unset or api.anthropic.com (or _CLAUDE_CODE_ASSUME_FIRST_PARTY_BASE_URL),
61
+ * or the key is an Anthropic API key (sk-ant-api..., not
62
+ * ANTHROPIC_AUTH_TOKEN, a claude.ai sign-in or /login's managed key).
63
+ * With no writer, the summary is the whole context on the agent's own
64
+ * model, the pre-2.1.328 form. A plain ANTHROPIC_BASE_URL is not the
65
+ * "gateway": a proxy on 127.0.0.1 (context-doctor's autopilot) leaves the
66
+ * provider the Anthropic API and fails the base-URL test, so on a Claude
67
+ * sign-in it gets the whole context.
68
+ * Which applied is told from the transcript where it can be (Bedrock and
69
+ * Vertex model and message ids), else from the settings and environment
70
+ * now (summaryRoute), autopilot's proxy counted from when autopilot was
71
+ * turned on. Where neither tells (an API key that may or may not be used
72
+ * behind a proxy), a range: Haiku notes low, the whole context high.
73
+ *
50
74
  * Estimated per subagent from what its transcript does record: the time of
51
75
  * each message (the ticks and whether the transcript changed), each reply's
52
76
  * prompt size and model (the context a fork would read, the rates). Each
@@ -54,8 +78,11 @@
54
78
  * tick held while the agent's own request waits on a cold cache (it fires
55
79
  * later, not more often), and the thinking a summary may do.
56
80
  */
57
- import { existsSync, readFileSync } from "node:fs";
81
+ import { existsSync, readFileSync, statSync } from "node:fs";
82
+ import { join } from "node:path";
58
83
  import { pick, rowsOf } from "./scan.js";
84
+ import { claudeDir } from "./claudedir.js";
85
+ import { effectiveEnv, settingsSources } from "./effective.js";
59
86
  import { requestCost } from "./pricing.js";
60
87
  import { realModel } from "./tokens.js";
61
88
  import { workflowRunOf } from "./subagents.js";
@@ -78,6 +105,92 @@ export const SMALL_FAST_MODEL_NAME = "Haiku 5.5";
78
105
  export const FORK_PROMPT_TOKENS = 150;
79
106
  /** Each summary's output: #86879's measured mean (21,966 tokens over 339 summaries). */
80
107
  export const SUMMARY_OUTPUT_TOKENS = 65;
108
+ /** Nothing set: the Anthropic API, notes by Haiku. */
109
+ export const ANTHROPIC_API_ROUTE = { form: "haiku", why: "Claude Code on the Anthropic API" };
110
+ /** The cloud a reply's ids name: Bedrock's (`anthropic.`, region-prefixed, an ARN; `msg_bdrk_`), Vertex's (`@date`; `msg_vrtx_`). */
111
+ export function replyCloud(model, id) {
112
+ const m = typeof model === "string" ? model : "";
113
+ const i = typeof id === "string" ? id : "";
114
+ if (/^(?:[a-z]{2,7}\.)?anthropic\.claude-[\w.-]*\d|^arn:aws[\w-]*:bedrock:/.test(m) || i.startsWith("msg_bdrk_"))
115
+ return "bedrock";
116
+ if (/^claude-[\w.-]+@/.test(m) || i.startsWith("msg_vrtx_"))
117
+ return "vertex";
118
+ return undefined;
119
+ }
120
+ const on = (v) => v !== undefined && !["", "0", "false", "no", "off"].includes(v.trim().toLowerCase());
121
+ /** Autopilot's own file and address (autopilot.ts autopilotPaths, proxyUrl), read here without its imports. */
122
+ const AUTOPILOT_CONFIG = ".context-doctor-autopilot.json";
123
+ /**
124
+ * Which form Claude Code 2.1.330 uses for a terminal subagent on a
125
+ * first-party model id, from the settings and environment as they are now
126
+ * (read only). Autopilot's proxy counts from when autopilot was turned on
127
+ * (its config file, written then); before it, the address it replaced.
128
+ */
129
+ export function summaryRoute(deps = {}) {
130
+ const env = deps.env ?? process.env;
131
+ const sources = deps.sources ?? settingsSources({ home: deps.home, cwd: deps.cwd, env });
132
+ const get = (n) => effectiveEnv(n, sources, env);
133
+ const provider = [
134
+ ["CLAUDE_CODE_USE_GATEWAY", "own-notes", "Claude Code is set to its gateway"],
135
+ ["CLAUDE_CODE_USE_BEDROCK", "own-notes", "Claude Code is set to Amazon Bedrock"],
136
+ ["CLAUDE_CODE_USE_FOUNDRY", "own-notes", "Claude Code is set to Microsoft Foundry"],
137
+ ["CLAUDE_CODE_USE_ANTHROPIC_AWS", "whole", "Claude Code is set to Anthropic on AWS"],
138
+ ["CLAUDE_CODE_USE_ANTHROPIC_GOOGLE_CLOUD", "whole", "Claude Code is set to Anthropic on Google Cloud"],
139
+ ["CLAUDE_CODE_USE_MANTLE", "whole", "Claude Code is set to Mantle"],
140
+ ["CLAUDE_CODE_USE_VERTEX", "own-notes", "Claude Code is set to Google Vertex AI"],
141
+ ];
142
+ for (const [name, form, why] of provider) {
143
+ const v = get(name);
144
+ if (v && on(v.value))
145
+ return { form, why: `${why} (${v.where})` };
146
+ }
147
+ for (const name of ["ANTHROPIC_SMALL_FAST_MODEL", "ANTHROPIC_DEFAULT_HAIKU_MODEL"]) {
148
+ const v = get(name);
149
+ if (v)
150
+ return { form: "whole", why: `${v.where} replaces the small model that writes them` };
151
+ }
152
+ const base = get("ANTHROPIC_BASE_URL");
153
+ const route = byBaseUrl(base?.value, base?.where ?? "", sources, env, "an address that is not Anthropic's");
154
+ if (!base)
155
+ return route;
156
+ // Autopilot's proxy: from when autopilot was turned on; before it, the address it replaced (none: the Anthropic API).
157
+ const cfgPath = join(claudeDir(deps.home, env), AUTOPILOT_CONFIG);
158
+ try {
159
+ const cfg = JSON.parse(readFileSync(cfgPath, "utf8"));
160
+ if (typeof cfg?.port === "number" && base.value.replace(/\/+$/, "") === `http://127.0.0.1:${cfg.port}`) {
161
+ const prev = typeof cfg.previousBaseUrl === "string" && cfg.previousBaseUrl ? cfg.previousBaseUrl : undefined;
162
+ return { ...byBaseUrl(base.value, base.where, sources, env, "context-doctor's autopilot proxy, not Anthropic's address"), since: statSync(cfgPath).mtimeMs, before: byBaseUrl(prev, `ANTHROPIC_BASE_URL=${prev} before autopilot`, sources, env, "an address that is not Anthropic's") };
163
+ }
164
+ }
165
+ catch {
166
+ /* no autopilot */
167
+ }
168
+ return route;
169
+ }
170
+ /** The form for an ANTHROPIC_BASE_URL: Anthropic's own host (or none) is the Anthropic API; any other needs an Anthropic API key for Haiku. */
171
+ function byBaseUrl(url, where, sources, env, label) {
172
+ if (!url)
173
+ return ANTHROPIC_API_ROUTE;
174
+ let host = "";
175
+ try {
176
+ host = new URL(url).host;
177
+ }
178
+ catch { /* not a URL: not Anthropic's */ }
179
+ const assume = effectiveEnv("_CLAUDE_CODE_ASSUME_FIRST_PARTY_BASE_URL", sources, env);
180
+ if (host === "api.anthropic.com" || (assume && on(assume.value)))
181
+ return ANTHROPIC_API_ROUTE;
182
+ const to = `Claude Code talks to ${label} (${where})`;
183
+ if (effectiveEnv("ANTHROPIC_AUTH_TOKEN", sources, env))
184
+ return { form: "whole", why: `${to} with ANTHROPIC_AUTH_TOKEN, not an Anthropic API key` };
185
+ const key = effectiveEnv("ANTHROPIC_API_KEY", sources, env);
186
+ const helper = sources.find((s) => typeof s.settings.apiKeyHelper === "string" && s.settings.apiKeyHelper.trim());
187
+ if ((key && key.value.startsWith("sk-ant-api")) || helper) {
188
+ return { form: "range", why: `${to}; they are notes by Haiku only if it uses your Anthropic API key (${key ? "ANTHROPIC_API_KEY" : "apiKeyHelper"}), and context-doctor cannot tell whether it does` };
189
+ }
190
+ if (key)
191
+ return { form: "whole", why: `${to} with an ANTHROPIC_API_KEY that is not an Anthropic API key` };
192
+ return { form: "whole", why: `${to} and you sign in with a Claude account, not an Anthropic API key` };
193
+ }
81
194
  /** How Claude Code reads the variable (a boolean: "1", "true", "yes", "on"). */
82
195
  export const disablesSummaries = (v) => ["1", "true", "yes", "on"].includes(String(v ?? "").trim().toLowerCase());
83
196
  /**
@@ -86,7 +199,7 @@ export const disablesSummaries = (v) => ["1", "true", "yes", "on"].includes(Stri
86
199
  * reply; its output is in the next prompt).
87
200
  */
88
201
  export const PROGRESS_ROWS = {
89
- id: "progress-summaries.1",
202
+ id: "progress-summaries.2",
90
203
  init: () => ({ head: false, ids: {} }),
91
204
  line(raw, row, out, st) {
92
205
  if (!raw.includes('"timestamp"'))
@@ -122,7 +235,8 @@ export const PROGRESS_ROWS = {
122
235
  const u = m.usage;
123
236
  const n = (v) => (typeof v === "number" && Number.isFinite(v) && v > 0 ? v : 0);
124
237
  const prompt = n(u.input_tokens) + n(u.cache_read_input_tokens) + n(u.cache_creation_input_tokens);
125
- out.push({ t: "r", ts, model: realModel(m.model), p: prompt, ...(u.speed === "fast" ? { speed: "fast" } : {}), ...(u.inference_geo === "us" ? { geo: "us" } : {}) });
238
+ const cloud = replyCloud(m.model, id);
239
+ out.push({ t: "r", ts, model: realModel(m.model), p: prompt, ...(u.speed === "fast" ? { speed: "fast" } : {}), ...(u.inference_geo === "us" ? { geo: "us" } : {}), ...(cloud ? { cloud } : {}) });
126
240
  },
127
241
  };
128
242
  export function readAgentMeta(file) {
@@ -158,13 +272,25 @@ export function eligibility(meta, entrypoint, opts = {}) {
158
272
  return "host";
159
273
  return opts.forkGateOff ? "fork-gate-off" : "yes";
160
274
  }
275
+ /** How one agent's summaries were written: its transcript's cloud, else the route at its start. */
276
+ export function agentRoute(recs, route = ANTHROPIC_API_ROUTE) {
277
+ const cloud = recs.find((x) => x.t === "r" && !!x.cloud)?.cloud;
278
+ if (cloud)
279
+ return { form: "own-notes", why: `the subagents ran on ${cloud === "bedrock" ? "Amazon Bedrock" : "Google Vertex AI"} (their model ids say so)` };
280
+ const first = recs.reduce((m, x) => (x.t === "m" && x.ts < m ? x.ts : m), Infinity);
281
+ let r = route;
282
+ while (r.since !== undefined && r.before && first < r.since)
283
+ r = r.before;
284
+ return r;
285
+ }
161
286
  /**
162
287
  * The ticks a running agent's timer made and the summaries they sent, from
163
288
  * its timeline: every 30 s from its first row to its last, a summary when
164
289
  * it has 3+ messages and more than at the last summary. Only ticks in
165
290
  * [since, until] are counted.
166
291
  */
167
- export function simulateAgent(recs, since = -Infinity, until = Infinity, smallNotes = false) {
292
+ export function simulateAgent(recs, since = -Infinity, until = Infinity, mode = "old") {
293
+ const form = mode === true ? "haiku" : mode === false ? "old" : mode;
168
294
  const msgs = recs.filter((r) => r.t === "m").map((r) => r.ts).sort((a, b) => a - b);
169
295
  const replies = recs.filter((r) => r.t === "r").sort((a, b) => a.ts - b.ts);
170
296
  const out = { calls: 0, notesUsd: 0, forkUsd: 0 };
@@ -194,29 +320,24 @@ export function simulateAgent(recs, since = -Infinity, until = Infinity, smallNo
194
320
  const read = cur ? cur.p : 0;
195
321
  const fresh = (next ? Math.max(0, next.p - read) : 0) + FORK_PROMPT_TOKENS;
196
322
  const b = { ...(ref.speed ? { speed: ref.speed } : {}), ...(ref.geo ? { inference_geo: ref.geo } : {}) };
197
- if (smallNotes) {
198
- // 2.1.328+: the notes on the small fast model, the one way it sends them (the agent's fast mode is not the writer's).
199
- const small = requestCost(SMALL_FAST_MODEL, { input_tokens: NOTES_TOKENS, cache_read_input_tokens: 0, cache_creation_input_tokens: 0, output_tokens: SUMMARY_OUTPUT_TOKENS, ...(ref.geo ? { inference_geo: ref.geo } : {}) }, at);
200
- if (!small)
201
- continue;
202
- out.calls++;
203
- out.forkUsd += small.totalUsd;
204
- out.notesUsd += small.totalUsd;
205
- continue;
206
- }
207
- const fork = requestCost(model, { input_tokens: fresh, cache_read_input_tokens: read, cache_creation_input_tokens: 0, output_tokens: SUMMARY_OUTPUT_TOKENS, ...b }, at);
208
- const notes = requestCost(model, { input_tokens: NOTES_TOKENS, cache_read_input_tokens: 0, cache_creation_input_tokens: 0, output_tokens: SUMMARY_OUTPUT_TOKENS, ...b }, at);
209
- if (!fork || !notes)
323
+ // 2.1.328+ on the Anthropic API: the notes on the small fast model, the one way it sends them (the agent's fast mode is not the writer's).
324
+ const small = form === "haiku" || form === "range" ? requestCost(SMALL_FAST_MODEL, { input_tokens: NOTES_TOKENS, cache_read_input_tokens: 0, cache_creation_input_tokens: 0, output_tokens: SUMMARY_OUTPUT_TOKENS, ...(ref.geo ? { inference_geo: ref.geo } : {}) }, at) : undefined;
325
+ const fork = form === "old" || form === "whole" || form === "range" ? requestCost(model, { input_tokens: fresh, cache_read_input_tokens: read, cache_creation_input_tokens: 0, output_tokens: SUMMARY_OUTPUT_TOKENS, ...b }, at) : undefined;
326
+ const notes = form === "old" || form === "own-notes" ? requestCost(model, { input_tokens: NOTES_TOKENS, cache_read_input_tokens: 0, cache_creation_input_tokens: 0, output_tokens: SUMMARY_OUTPUT_TOKENS, ...b }, at) : undefined;
327
+ const [low, high] = form === "haiku" ? [small, small] : form === "own-notes" ? [notes, notes] : form === "whole" ? [fork, fork] : form === "range" ? [small, fork] : [notes, fork];
328
+ if (!low || !high)
210
329
  continue;
211
330
  out.calls++;
212
- out.forkUsd += fork.totalUsd;
213
- out.notesUsd += notes.totalUsd;
331
+ out.forkUsd += high.totalUsd;
332
+ out.notesUsd += low.totalUsd;
214
333
  }
215
334
  return out;
216
335
  }
217
336
  /** The summaries of the subagents in `files` (their `.jsonl` transcripts), estimated. */
218
337
  export function estimateProgressSummaries(files, opts = {}) {
219
338
  const r = { agents: 0, summarized: 0, calls: 0, smallCalls: 0, notesUsd: 0, forkUsd: 0, none: {}, hosts: [] };
339
+ const routes = new Map();
340
+ let value = 0;
220
341
  const hosts = new Set();
221
342
  for (const file of files) {
222
343
  let recs;
@@ -244,16 +365,27 @@ export function estimateProgressSummaries(files, opts = {}) {
244
365
  if (first > until)
245
366
  why = "off";
246
367
  else {
247
- const small = !!head?.version && compareVersions(head.version, SMALL_NOTES_SINCE) >= 0;
248
- const s = simulateAgent(recs, opts.since, until, small);
368
+ const recent = !!head?.version && compareVersions(head.version, SMALL_NOTES_SINCE) >= 0;
369
+ const route = recent ? agentRoute(recs, opts.route) : undefined;
370
+ const s = simulateAgent(recs, opts.since, until, route?.form ?? "old");
249
371
  // One that ran under 30 s, or outside the window, sent none.
250
372
  if (s.calls)
251
373
  r.summarized++;
252
374
  r.calls += s.calls;
253
- if (small)
254
- r.smallCalls += s.calls;
255
375
  r.notesUsd += s.notesUsd;
256
376
  r.forkUsd += s.forkUsd;
377
+ value += route ? s.forkUsd : s.notesUsd;
378
+ if (route?.form === "haiku")
379
+ r.smallCalls += s.calls;
380
+ else if (route && s.calls) {
381
+ const k = `${route.form}\n${route.why}`;
382
+ const g = routes.get(k) ?? { form: route.form, why: route.why, calls: 0, agents: 0, lowUsd: 0, highUsd: 0 };
383
+ g.calls += s.calls;
384
+ g.agents++;
385
+ g.lowUsd += s.notesUsd;
386
+ g.highUsd += s.forkUsd;
387
+ routes.set(k, g);
388
+ }
257
389
  continue;
258
390
  }
259
391
  }
@@ -262,8 +394,22 @@ export function estimateProgressSummaries(files, opts = {}) {
262
394
  r.none[why] = (r.none[why] ?? 0) + 1;
263
395
  }
264
396
  r.hosts = [...hosts].sort();
397
+ if (routes.size) {
398
+ r.routes = [...routes.values()].sort((a, b) => b.highUsd - a.highUsd);
399
+ r.valueUsd = value;
400
+ }
265
401
  return r;
266
402
  }
403
+ /** A 2.1.328+ form in words: what each summary sent, and on what. */
404
+ export function formWords(form) {
405
+ if (form === "haiku")
406
+ return `short notes, written by ${SMALL_FAST_MODEL_NAME}`;
407
+ if (form === "own-notes")
408
+ return "short notes, written by the subagent's own model";
409
+ if (form === "whole")
410
+ return "the subagent's whole context, on its own model";
411
+ return `short notes by ${SMALL_FAST_MODEL_NAME} (low) or the whole context (high)`;
412
+ }
267
413
  /** "the Desktop app", "the SDK or -p": a host as a person knows it. */
268
414
  export function hostName(entrypoint) {
269
415
  if (entrypoint === "claude-desktop")
package/dist/proxy.d.ts CHANGED
@@ -83,7 +83,7 @@ export interface ProxyOptions extends OptimizeOptions {
83
83
  /** Default request body cap: far above any real request (a 1M-token context is ~4 MB of JSON, images aside). */
84
84
  export declare const DEFAULT_MAX_BODY_BYTES: number;
85
85
  /** Reported by /health so `autopilot status` can tell an outdated service from a current one. */
86
- export declare const PROXY_VERSION = "0.50.0";
86
+ export declare const PROXY_VERSION = "0.51.0";
87
87
  /**
88
88
  * Remove a leading `/t/<token>` from a request path, or return undefined when
89
89
  * the prefix is absent or the token differs. The comparison is constant time
package/dist/proxy.js CHANGED
@@ -25,7 +25,7 @@ import { makeGuard, refusal } from "./httpguard.js";
25
25
  /** Default request body cap: far above any real request (a 1M-token context is ~4 MB of JSON, images aside). */
26
26
  export const DEFAULT_MAX_BODY_BYTES = 100 * 1024 * 1024;
27
27
  /** Reported by /health so `autopilot status` can tell an outdated service from a current one. */
28
- export const PROXY_VERSION = "0.50.0";
28
+ export const PROXY_VERSION = "0.51.0";
29
29
  /** Connection-level headers that must not be forwarded. */
30
30
  const SKIP_REQUEST_HEADERS = new Set(["host", "content-length", "connection", "transfer-encoding", "accept-encoding", "expect"]);
31
31
  /** A reply carrying any of these has something for the limits ledger: a plan window, or the usage-credits state. */
package/dist/spend.d.ts CHANGED
@@ -40,7 +40,7 @@
40
40
  * sessions with 10+ requests. `spend` counts every request, its output and
41
41
  * subagents too; on the requests both count, the dollars are the same.
42
42
  */
43
- import { type ProgressOptions } from "./progresssummaries.js";
43
+ import { type ProgressOptions, type ProgressSummaryEstimate } from "./progresssummaries.js";
44
44
  import { type Modifiers } from "./pricing.js";
45
45
  import { type SessionGap } from "./ccost.js";
46
46
  import type { ExtraUsage } from "./claudedir.js";
@@ -298,6 +298,7 @@ export interface SpendReport {
298
298
  * Claude Code's subagent progress summaries, estimated (no transcript records them): NOT in `usd`.
299
299
  * `notesUsd` as short notes (served since November 2026), `forkUsd` as the whole context (before).
300
300
  * `smallCalls`: of `calls`, those on Claude Code 2.1.328+, notes on the small fast model in both figures (absent when none).
301
+ * `routes`: the 2.1.328+ ones not on the Anthropic API, by form and why (absent when none): their figures are in both.
301
302
  * `set`: CLAUDE_CODE_DISABLE_AGENT_PROGRESS_SUMMARIES is set there, since when unknown: not estimated.
302
303
  * Absent when no subagent got any.
303
304
  */
@@ -305,6 +306,7 @@ export interface SpendReport {
305
306
  agents: number;
306
307
  calls: number;
307
308
  smallCalls?: number;
309
+ routes?: ProgressSummaryEstimate["routes"];
308
310
  notesUsd: number;
309
311
  forkUsd: number;
310
312
  } | {
@@ -356,7 +358,7 @@ export interface SpendOptions {
356
358
  * The progress summaries' estimate: the fork gate, when the variable turned them off
357
359
  * (fix's record), or where it is set with no record (then not estimated); false: none.
358
360
  */
359
- progress?: false | (Pick<ProgressOptions, "forkGateOff" | "offSince"> & {
361
+ progress?: false | (Pick<ProgressOptions, "forkGateOff" | "offSince" | "route"> & {
360
362
  set?: string;
361
363
  });
362
364
  /** The limits ledger to read for requests past the plan's limit (tests); default ~/.claude's. */
package/dist/spend.js CHANGED
@@ -45,7 +45,7 @@ import { codexDir } from "./codexdir.js";
45
45
  import { homedir } from "node:os";
46
46
  import { closeSync, existsSync, openSync, readdirSync, readSync, statSync } from "node:fs";
47
47
  import { claudeFileUsage, claudeUsageFiles, codexEventKey, codexSessionsRoot, rolloutFiles, USAGE_ROWS } from "./limits.js";
48
- import { estimateProgressSummaries, PROGRESS_ROWS, PROGRESS_SUMMARIES_ENV, SMALL_FAST_MODEL_NAME as SMALL_NAME, SMALL_NOTES_SINCE } from "./progresssummaries.js";
48
+ import { estimateProgressSummaries, formWords, PROGRESS_ROWS, PROGRESS_SUMMARIES_ENV, SMALL_FAST_MODEL_NAME as SMALL_NAME, SMALL_NOTES_SINCE } from "./progresssummaries.js";
49
49
  import { listGeminiChats, readGeminiMessages } from "./gemini.js";
50
50
  import { cursorClaudeId, cursorUsage, SqliteUnavailableError } from "./cursor.js";
51
51
  import { copilotCalls } from "./copilotusage.js";
@@ -764,8 +764,8 @@ function claudeProgressSummaries(since, until, tops, o) {
764
764
  if (o?.set && o.offSince === undefined)
765
765
  return { set: o.set };
766
766
  const files = claudeUsageFiles(since, tops).filter((f) => f.subagent && !f.run).map((f) => f.file);
767
- const e = estimateProgressSummaries(files, { since, until, forkGateOff: o?.forkGateOff, offSince: o?.offSince });
768
- return e.calls ? { agents: e.summarized, calls: e.calls, ...(e.smallCalls ? { smallCalls: e.smallCalls } : {}), notesUsd: e.notesUsd, forkUsd: e.forkUsd } : undefined;
767
+ const e = estimateProgressSummaries(files, { since, until, forkGateOff: o?.forkGateOff, offSince: o?.offSince, route: o?.route });
768
+ return e.calls ? { agents: e.summarized, calls: e.calls, ...(e.smallCalls ? { smallCalls: e.smallCalls } : {}), ...(e.routes?.length ? { routes: e.routes } : {}), notesUsd: e.notesUsd, forkUsd: e.forkUsd } : undefined;
769
769
  }
770
770
  /**
771
771
  * The longest window: ten years, older than any history these tools keep.
@@ -870,6 +870,24 @@ export function spendReport(days = 30, opts = {}) {
870
870
  // ---------------------------------------------------------------------------
871
871
  /** What an iteration type is, in the report's words. */
872
872
  const ITERATION_NAME = { advisor_message: ["advisor call", "advisor calls"], message: ["attempt a fallback model replaced", "attempts a fallback model replaced"], fallback_message: ["fallback attempt replaced again", "fallback attempts replaced again"], compaction: ["server-side compaction", "server-side compactions"] };
873
+ /** The summaries' low and high figures are one (every form known). */
874
+ const oneFigure = (ps) => ps.forkUsd - ps.notesUsd < 0.005;
875
+ /** `text` in lines of at most 80 characters: the first indented by `first`, the rest by `rest`. */
876
+ function wrapLines(text, first, rest) {
877
+ const out = [];
878
+ let line = first;
879
+ for (const w of text.split(" ")) {
880
+ if (line.trim() && (line + " " + w).length > 80) {
881
+ out.push(line);
882
+ line = rest + w;
883
+ }
884
+ else
885
+ line = line.trim() ? `${line} ${w}` : line + w;
886
+ }
887
+ if (line.trim())
888
+ out.push(line);
889
+ return out;
890
+ }
873
891
  export const usd = (n) => (n >= 100 ? `$${Math.round(n).toLocaleString("en-US")}` : n > 0 && n < 0.005 ? "<$0.01" : `$${n.toFixed(2)}`);
874
892
  const share = (part, whole) => (whole > 0 ? `${Math.round((part / whole) * 100)}%` : "");
875
893
  const MONTHS = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
@@ -981,6 +999,17 @@ export function renderSpend(r, top = 8) {
981
999
  lines.push(` Not in it: ~${ps.calls.toLocaleString("en-US")} subagent progress summaries (${ps.agents} background ${ps.agents === 1 ? "agent" : "agents"}), an estimate:`);
982
1000
  if (ps.smallCalls === ps.calls)
983
1001
  lines.push(` ${usd(ps.notesUsd)}, short notes on ${SMALL_NAME} (Claude Code ${SMALL_NOTES_SINCE}+); in no transcript`);
1002
+ else if (ps.routes?.length) {
1003
+ // 2.1.328+ off the Anthropic API: each form with its count and why, wrapped.
1004
+ lines.push(` ${oneFigure(ps) ? usd(ps.forkUsd) : `${usd(ps.notesUsd)} to ${usd(ps.forkUsd)}`}; no transcript records them. How each was sent:`);
1005
+ if (ps.smallCalls)
1006
+ lines.push(` - ${ps.smallCalls.toLocaleString("en-US")}: ${formWords("haiku")} (Claude Code ${SMALL_NOTES_SINCE}+)`);
1007
+ for (const g of ps.routes)
1008
+ lines.push(...wrapLines(`- ${g.calls.toLocaleString("en-US")}: ${formWords(g.form)}${g.form === "range" ? `, ${usd(g.lowUsd)} to ${usd(g.highUsd)}: context-doctor cannot tell which` : `, ${usd(g.highUsd)}`}. Why: ${g.why}.`, " ", " "));
1009
+ const old = ps.calls - (ps.smallCalls ?? 0) - ps.routes.reduce((n, g) => n + g.calls, 0);
1010
+ if (old > 0)
1011
+ lines.push(` - ${old.toLocaleString("en-US")}: before Claude Code ${SMALL_NOTES_SINCE}, notes (low) or the whole context`);
1012
+ }
984
1013
  else {
985
1014
  lines.push(` ${usd(ps.notesUsd)} as notes, ${usd(ps.forkUsd)} at the whole context; no transcript records them`);
986
1015
  if (ps.smallCalls)
@@ -1061,7 +1090,7 @@ export function renderSpendShare(r) {
1061
1090
  lines.push(`Billed above list rates: ${modifiersText(r.modifiers)}.`);
1062
1091
  const ps = r.progressSummaries;
1063
1092
  if (ps && "calls" in ps)
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.`);
1093
+ lines.push(`Not in it: Claude Code's subagent progress summaries, which no transcript records: ${ps.smallCalls === ps.calls || oneFigure(ps) ? usd(ps.notesUsd) : `${usd(ps.notesUsd)}-${usd(ps.forkUsd)}`}, an estimate.`);
1065
1094
  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]];
1066
1095
  const [bigPart, bigUsd] = parts.sort((a, b) => b[1] - a[1])[0];
1067
1096
  const busiest = [...r.daily].sort((a, b) => b.usd - a.usd)[0];
package/dist/starts.d.ts CHANGED
@@ -128,5 +128,12 @@ export declare function startServers(r: StartsReport): Array<StartServer & {
128
128
  export declare function deferrableApp(r: StartsReport): Array<StartServer & {
129
129
  usd: number;
130
130
  }>;
131
+ /** Every start's cost over the period as billed, and the subagents' part of it; `unpriced` when a start had a model with no price. */
132
+ export declare function startsTotal(r: StartsReport): {
133
+ usd: number;
134
+ subagentUsd: number;
135
+ subagents: boolean;
136
+ unpriced: boolean;
137
+ };
131
138
  /** The starts section of `overhead`. */
132
139
  export declare function renderStarts(r: StartsReport, applied?: ReadonlySet<string>): string[];
package/dist/starts.js CHANGED
@@ -404,6 +404,11 @@ export function deferrableApp(r) {
404
404
  return startServers(r).filter((s) => !s.configured && APP_TOOL_SERVERS.includes(s.name));
405
405
  }
406
406
  const tok = (n) => `~${formatTokens(n)}`;
407
+ /** Every start's cost over the period as billed, and the subagents' part of it; `unpriced` when a start had a model with no price. */
408
+ export function startsTotal(r) {
409
+ const subs = r.groups.filter((g) => g.kind === "subagent");
410
+ return { usd: r.groups.reduce((t, g) => t + g.usd, 0), subagentUsd: subs.reduce((t, g) => t + g.usd, 0), subagents: subs.length > 0, unpriced: r.groups.some((g) => g.unpriced) };
411
+ }
407
412
  /** The starts section of `overhead`. */
408
413
  export function renderStarts(r, applied = new Set()) {
409
414
  const out = ["", "Session and subagent starts (the first request, before the first message)", "─".repeat(56)];
@@ -424,9 +429,8 @@ export function renderStarts(r, applied = new Set()) {
424
429
  line(`${entrypointName(g.entrypoint)} sessions`, g);
425
430
  for (const g of subs)
426
431
  line(`${g.agentType} (subagent)${new Set(subs.map((x) => x.entrypoint)).size > 1 ? ` (${entrypointName(g.entrypoint)})` : ""}`, g);
427
- const total = r.groups.reduce((t, g) => t + g.usd, 0);
428
- const subUsd = subs.reduce((t, g) => t + g.usd, 0);
429
- out.push(` Every start, re-read at each step over ${r.days} days: ${formatUsd(total)}${subs.length ? ` (subagents ${formatUsd(subUsd)})` : ""}. Token counts are the API's; tool sizes are estimates from their length.`);
432
+ const t = startsTotal(r);
433
+ out.push(` Every start, re-read at each step over ${r.days} days: ${formatUsd(t.usd)}${t.subagents ? ` (subagents ${formatUsd(t.subagentUsd)})` : ""}. Token counts are the API's; tool sizes are estimates from their length.`);
430
434
  if (r.gap && r.gap.tokens > 0) {
431
435
  out.push(` Desktop app vs terminal: a Desktop session starts ~${formatTokens(r.gap.tokens)} tokens larger (median ${tok(r.gap.desktop)} against ${tok(r.gap.terminal)}): ${formatUsd(r.gap.usd)} of its starts' cost in ${r.days} days.`);
432
436
  }
package/dist/usagepane.js CHANGED
@@ -112,7 +112,7 @@ export function limitFitsOf(r) {
112
112
  const move = r.changes.filter((c) => c.window === "five_hour" || c.window === "seven_day").sort((a, b) => b.at - a.at)[0];
113
113
  return {
114
114
  ...(Object.keys(fits).length ? { limitFits: fits } : {}),
115
- ...(move ? { limitMove: { window: move.window, at: move.at, before: round(move.usdPerPctBefore), after: round(move.usdPerPctAfter), factor: round(move.factor) } } : {}),
115
+ ...(move ? { limitMove: { window: move.window, at: move.at, before: round(move.usdPerPctBefore), after: round(move.usdPerPctAfter), factor: round(move.factor), ...(move.cause && move.cause !== "limit" ? { cause: move.cause } : {}), ...(move.mix && (move.cause === "mix" || move.cause === "both") ? { model: move.mix.grew } : {}) } } : {}),
116
116
  ...(r.noFiveHour ? { noFiveHour: true } : {}),
117
117
  };
118
118
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "context-doctor",
3
- "version": "0.50.0",
3
+ "version": "0.51.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",