context-doctor 0.40.0 → 0.41.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.
package/dist/hook.js CHANGED
@@ -28,6 +28,7 @@ import { modelSwitchMessage } from "./modelswitch.js";
28
28
  import { compactFacts, compactInstructions } from "./precompact.js";
29
29
  import { fanoutHook, subagentCosts } from "./fanout.js";
30
30
  import { claudeDir } from "./claudedir.js";
31
+ import { budgetVerdict } from "./budget.js";
31
32
  /** Default nudge threshold; a project budget or env var can lower/raise it. */
32
33
  const DEFAULT_WARN_TOKENS = 80_000;
33
34
  /**
@@ -260,17 +261,41 @@ export async function runHook(app) {
260
261
  const cursor = input.hook_event_name === "postToolUse" || input.hook_event_name === "postToolUseFailure" || input.hook_event_name === "sessionStart";
261
262
  if (input.hook_event_name === "beforeSubmitPrompt" || (input.cursor_version && !cursor))
262
263
  return;
264
+ // A spend budget (budget.ts), before each prompt in Claude Code, Codex and
265
+ // Gemini CLI: a line to the user at 50%, 80% and 100%, and with --block,
266
+ // over it, the prompt held. No budget set: one failed read.
267
+ let budgetNote;
268
+ if (!cursor && (input.hook_event_name === undefined || input.hook_event_name === "UserPromptSubmit" || input.hook_event_name === "BeforeAgent")) {
269
+ let v;
270
+ try {
271
+ v = budgetVerdict();
272
+ }
273
+ catch { /* a damaged ledger must not cost the rest of the hook */ }
274
+ if (v?.block) {
275
+ // Claude Code and Codex: decision "block" (the prompt is erased, the
276
+ // reason shown); Gemini CLI's BeforeAgent: decision "deny".
277
+ process.stdout.write(JSON.stringify({ decision: input.hook_event_name === "BeforeAgent" ? "deny" : "block", reason: v.block }) + "\n");
278
+ return;
279
+ }
280
+ budgetNote = v?.message;
281
+ }
282
+ const sayBudget = () => { if (budgetNote)
283
+ console.log(JSON.stringify({ systemMessage: budgetNote })); };
263
284
  const transcriptPath = input.transcript_path;
264
- if (!transcriptPath || !existsSync(transcriptPath))
285
+ if (!transcriptPath || !existsSync(transcriptPath)) {
286
+ sayBudget();
265
287
  return;
288
+ }
266
289
  // Fast path 1: a small transcript cannot exceed the threshold — exit on a
267
290
  // single stat() without reading the file. This is the every-prompt cost
268
291
  // for lean sessions: ~1ms.
269
292
  const { config } = loadConfig(input.cwd ?? input.workspace_roots?.[0] ?? process.cwd());
270
293
  const threshold = warnThreshold(config.budget?.maxTokens);
271
294
  const sizeBytes = statSync(transcriptPath).size;
272
- if (sizeBytes < minBytesForWarn(threshold))
295
+ if (sizeBytes < minBytesForWarn(threshold)) {
296
+ sayBudget();
273
297
  return;
298
+ }
274
299
  // Fast path 2: growth gate BEFORE parsing. If the file hasn't grown ~40%
275
300
  // since the last full parse, nothing new can trigger — exit without the
276
301
  // expensive read. Heavy-but-quiet sessions cost one stat + tiny state read.
@@ -280,7 +305,7 @@ export async function runHook(app) {
280
305
  // before the growth gate, because a return after idle involves no growth.
281
306
  // Once per idle period; the tail read is ~1 ms and only on large files.
282
307
  const notes = [];
283
- let notice;
308
+ let notice = budgetNote;
284
309
  // Silent when Claude Code compacts this very prompt itself (the context
285
310
  // is past its auto-compact window, e.g. one set smaller since): an offer
286
311
  // would arrive after the compaction it proposes. Below the window the
@@ -293,7 +318,7 @@ export async function runHook(app) {
293
318
  let cr = prev.cr;
294
319
  if (cold && cold.lastReplyAt !== prev.cr) {
295
320
  notes.push(renderColdResume(cold));
296
- notice = renderColdResumeNotice(cold);
321
+ notice = [budgetNote, renderColdResumeNotice(cold)].filter(Boolean).join("\n");
297
322
  cr = cold.lastReplyAt;
298
323
  recordLedger({ ev: "cold_resume", sid: sessionId.slice(0, 12), tok: cold.tokens, model: cold.model });
299
324
  }
@@ -325,8 +350,10 @@ export async function runHook(app) {
325
350
  }
326
351
  // Slow path (growth events only): full parse + profile.
327
352
  const parsed = parseSessionFile(transcriptPath);
328
- if (parsed.messageCount === 0)
353
+ if (parsed.messageCount === 0) {
354
+ sayBudget();
329
355
  return;
356
+ }
330
357
  const model = parsed.model ?? input.model;
331
358
  const profile = profileConversation(parseConversation(parsed.conversationJson), model);
332
359
  // Prefer the API's own figure when the transcript carries it: it includes
package/dist/install.js CHANGED
@@ -1394,6 +1394,8 @@ const OUR_CLAUDE_FILES = [
1394
1394
  ".context-doctor-limits.jsonl",
1395
1395
  ".context-doctor-misses.jsonl",
1396
1396
  ".context-doctor-subagent-costs.json",
1397
+ ".context-doctor-budget.json",
1398
+ ".context-doctor-budget-state.json",
1397
1399
  ];
1398
1400
  export async function runUninstall() {
1399
1401
  changes = 0;
package/dist/limits.d.ts CHANGED
@@ -70,6 +70,8 @@ export declare function recordLimits(rateLimits: unknown, now?: number, path?: s
70
70
  /** Every Claude reading in the log since `since`. */
71
71
  export declare function readClaudeReadings(since?: number, path?: string): LimitReading[];
72
72
  export declare function codexSessionsRoot(home?: string): string;
73
+ /** Codex rollouts under `root` (YYYY/MM/DD folders, or flat) written since `since`. */
74
+ export declare function rolloutFiles(root: string, since: number): string[];
73
75
  /**
74
76
  * Codex readings and usage since `since`. A token_count event repeats the
75
77
  * last request's usage when only the limits were refreshed, so a request is
@@ -79,19 +81,50 @@ export declare function codexLimitData(since: number, root?: string): {
79
81
  readings: LimitReading[];
80
82
  usage: UsagePoint[];
81
83
  };
82
- /**
83
- * Every Claude Code request between `since` and `until`, main threads and
84
- * subagents alike (both draw on the same limits), each reply once.
85
- */
86
84
  /**
87
85
  * What the usage fit takes from a Claude Code transcript (subagents' too):
88
86
  * every assistant row with usage, in order. A later row of a reply already
89
87
  * met keeps only its id and output tokens: it is a repeat, read only for the
90
- * output a streamed reply settles on its last row.
88
+ * output a streamed reply settles on its last row. `isSidechain` is kept for
89
+ * `spend`, which tells a subagent inlined in an older transcript from the
90
+ * main thread.
91
91
  */
92
92
  export declare const USAGE_ROWS: Extractor<{
93
93
  ids: Record<string, 1>;
94
94
  }>;
95
+ /** One Claude Code request as `claudeFileUsage` reads it: the usage point, and what `spend` and `budget` add up. */
96
+ export interface ClaudeRequest extends UsagePoint {
97
+ /** The row's uuid: what tells a fork's copy of a reply from the reply itself. */
98
+ uuid?: string;
99
+ /** The reply's message id, which its later rows share. */
100
+ id?: string;
101
+ /** Written as a subagent's, inline in the main transcript (older Claude Code). */
102
+ sidechain?: boolean;
103
+ /** The prompt's part of `usd` (input, cache writes, cache reads): what `savings` bills. */
104
+ promptUsd: number;
105
+ }
106
+ /**
107
+ * The requests of one Claude Code transcript between `since` and `until`,
108
+ * each reply once, its output settled on its last row. `runRows` is shared
109
+ * by every file of one report, so a fork's copy of its parent's replies is
110
+ * counted once, in the file met first (replyCounter). Throws when the
111
+ * transcript cannot be read.
112
+ */
113
+ export declare function claudeFileUsage(file: string, since: number, until?: number, runRows?: Set<string>): ClaudeRequest[];
114
+ /**
115
+ * The Claude Code transcripts written since `since`: each session's main
116
+ * transcript (`tops`, or every one under the projects folder, newest
117
+ * first), each followed by its subagents'.
118
+ */
119
+ export declare function claudeUsageFiles(since: number, tops?: string[]): Array<{
120
+ file: string;
121
+ top: string;
122
+ subagent: boolean;
123
+ }>;
124
+ /**
125
+ * Every Claude Code request between `since` and `until`, main threads and
126
+ * subagents alike (both draw on the same limits), each reply once.
127
+ */
95
128
  export declare function claudeUsage(since: number, until?: number, paths?: string[]): UsagePoint[];
96
129
  export interface WindowStatus {
97
130
  window: string;
package/dist/limits.js CHANGED
@@ -177,7 +177,8 @@ export function readClaudeReadings(since = 0, path = limitsLogPath()) {
177
177
  export function codexSessionsRoot(home = homedir()) {
178
178
  return join(home, ".codex", "sessions");
179
179
  }
180
- function rolloutFiles(root, since) {
180
+ /** Codex rollouts under `root` (YYYY/MM/DD folders, or flat) written since `since`. */
181
+ export function rolloutFiles(root, since) {
181
182
  const out = [];
182
183
  const walk = (dir, depth) => {
183
184
  let names;
@@ -286,18 +287,16 @@ export function codexLimitData(since, root = codexSessionsRoot()) {
286
287
  // ---------------------------------------------------------------------------
287
288
  // Claude usage: every request on this machine, subagents included
288
289
  // ---------------------------------------------------------------------------
289
- /**
290
- * Every Claude Code request between `since` and `until`, main threads and
291
- * subagents alike (both draw on the same limits), each reply once.
292
- */
293
290
  /**
294
291
  * What the usage fit takes from a Claude Code transcript (subagents' too):
295
292
  * every assistant row with usage, in order. A later row of a reply already
296
293
  * met keeps only its id and output tokens: it is a repeat, read only for the
297
- * output a streamed reply settles on its last row.
294
+ * output a streamed reply settles on its last row. `isSidechain` is kept for
295
+ * `spend`, which tells a subagent inlined in an older transcript from the
296
+ * main thread.
298
297
  */
299
298
  export const USAGE_ROWS = {
300
- id: "usage.1",
299
+ id: "usage.2",
301
300
  init: () => ({ ids: {} }),
302
301
  line(line, row, out, st) {
303
302
  if (!line.includes('"usage"'))
@@ -319,63 +318,96 @@ export const USAGE_ROWS = {
319
318
  }
320
319
  st.ids[m.id] = 1;
321
320
  }
322
- out.push(pick({ ...e, message: pick({ ...m, usage: slimUsage(m.usage) }, ["id", "model", "usage"]) }, ["type", "uuid", "timestamp", "message"]));
321
+ out.push(pick({ ...e, isSidechain: e.isSidechain === true || undefined, message: pick({ ...m, usage: slimUsage(m.usage) }, ["id", "model", "usage"]) }, ["type", "uuid", "timestamp", "isSidechain", "message"]));
323
322
  },
324
323
  };
325
- export function claudeUsage(since, until = Infinity, paths) {
326
- const tops = paths ?? listSessions(10_000).filter((s) => isClaudeSession(s) && s.modifiedAt.getTime() >= since).map((s) => s.path);
324
+ /**
325
+ * The requests of one Claude Code transcript between `since` and `until`,
326
+ * each reply once, its output settled on its last row. `runRows` is shared
327
+ * by every file of one report, so a fork's copy of its parent's replies is
328
+ * counted once, in the file met first (replyCounter). Throws when the
329
+ * transcript cannot be read.
330
+ */
331
+ export function claudeFileUsage(file, since, until = Infinity, runRows) {
332
+ const out = [];
333
+ const sighting = replyCounter(runRows);
334
+ const settle = outputSettler();
335
+ const byId = new Map();
336
+ rowsOf(file, USAGE_ROWS).forEach((e) => {
337
+ const m = e?.message;
338
+ if (e?.type !== "assistant" || !m?.usage)
339
+ return;
340
+ const seen = sighting(e);
341
+ if (seen === "repeat") {
342
+ const known = typeof m.id === "string" ? byId.get(m.id) : undefined;
343
+ const more = settle(e, false);
344
+ if (known && more) {
345
+ known.point.output += more;
346
+ if (known.price)
347
+ known.point.usd += (more * known.price.outputPerM) / 1e6;
348
+ }
349
+ return;
350
+ }
351
+ if (seen !== "new")
352
+ return;
353
+ settle(e, true);
354
+ const ts = Date.parse(String(e.timestamp ?? ""));
355
+ if (!Number.isFinite(ts) || ts < since || ts > until)
356
+ return;
357
+ const u = m.usage;
358
+ const point = { ts, app: "claude", model: realModel(m.model), input: num(u.input_tokens), read: num(u.cache_read_input_tokens), write: num(u.cache_creation_input_tokens), output: num(u.output_tokens), usd: 0, promptUsd: 0 };
359
+ if (point.input + point.read + point.write === 0)
360
+ return;
361
+ if (typeof e.uuid === "string")
362
+ point.uuid = e.uuid;
363
+ if (typeof m.id === "string")
364
+ point.id = m.id;
365
+ if (e.isSidechain === true)
366
+ point.sidechain = true;
367
+ const price = pricingFor(point.model);
368
+ if (price) {
369
+ const c = usageCost(u, price);
370
+ point.usd = c.totalUsd;
371
+ point.promptUsd = c.promptUsd;
372
+ }
373
+ out.push(point);
374
+ if (typeof m.id === "string")
375
+ byId.set(m.id, { point, price });
376
+ });
377
+ return out;
378
+ }
379
+ /**
380
+ * The Claude Code transcripts written since `since`: each session's main
381
+ * transcript (`tops`, or every one under the projects folder, newest
382
+ * first), each followed by its subagents'.
383
+ */
384
+ export function claudeUsageFiles(since, tops) {
385
+ const mains = tops ?? listSessions(10_000).filter((s) => isClaudeSession(s) && s.modifiedAt.getTime() >= since).map((s) => s.path);
327
386
  const files = [];
328
- for (const t of tops) {
329
- files.push(t);
387
+ for (const t of mains) {
388
+ files.push({ file: t, top: t, subagent: false });
330
389
  const dir = subagentDir(t);
331
390
  try {
332
391
  for (const f of readdirSync(dir))
333
392
  if (f.endsWith(".jsonl") && statSync(join(dir, f)).mtimeMs >= since)
334
- files.push(join(dir, f));
393
+ files.push({ file: join(dir, f), top: t, subagent: true });
335
394
  }
336
395
  catch {
337
396
  /* no subagents */
338
397
  }
339
398
  }
399
+ return files;
400
+ }
401
+ /**
402
+ * Every Claude Code request between `since` and `until`, main threads and
403
+ * subagents alike (both draw on the same limits), each reply once.
404
+ */
405
+ export function claudeUsage(since, until = Infinity, paths) {
340
406
  const out = [];
341
407
  const runRows = new Set();
342
- for (const file of files) {
343
- const sighting = replyCounter(runRows);
344
- const settle = outputSettler();
345
- const byId = new Map();
408
+ for (const { file } of claudeUsageFiles(since, paths)) {
346
409
  try {
347
- rowsOf(file, USAGE_ROWS).forEach((e) => {
348
- const m = e?.message;
349
- if (e?.type !== "assistant" || !m?.usage)
350
- return;
351
- const seen = sighting(e);
352
- if (seen === "repeat") {
353
- const known = typeof m.id === "string" ? byId.get(m.id) : undefined;
354
- const more = settle(e, false);
355
- if (known && more) {
356
- known.point.output += more;
357
- if (known.price)
358
- known.point.usd += (more * known.price.outputPerM) / 1e6;
359
- }
360
- return;
361
- }
362
- if (seen !== "new")
363
- return;
364
- settle(e, true);
365
- const ts = Date.parse(String(e.timestamp ?? ""));
366
- if (!Number.isFinite(ts) || ts < since || ts > until)
367
- return;
368
- const u = m.usage;
369
- const point = { ts, app: "claude", model: realModel(m.model), input: num(u.input_tokens), read: num(u.cache_read_input_tokens), write: num(u.cache_creation_input_tokens), output: num(u.output_tokens), usd: 0 };
370
- if (point.input + point.read + point.write === 0)
371
- return;
372
- const price = pricingFor(point.model);
373
- if (price)
374
- point.usd = usageCost(u, price).totalUsd;
375
- out.push(point);
376
- if (typeof m.id === "string")
377
- byId.set(m.id, { point, price });
378
- });
410
+ out.push(...claudeFileUsage(file, since, until, runRows));
379
411
  }
380
412
  catch {
381
413
  /* skip an unreadable transcript */
package/dist/mcp.js CHANGED
@@ -107,7 +107,7 @@ data:
107
107
  ${i.text.slice(-e)}`,masked:r.count+i.count+o}}function Rx(t,e){let r=e??{},n=["command","file_path","path","pattern","url","query","cmd","description","prompt"].find(s=>typeof r[s]=="string"),o=n?String(r[n]):typeof e=="string"?e:JSON.stringify(e??"");return`${t}: ${o.slice(0,2e3)}`}function GO(t,e=JO){let r=[],n=0,o=0,s=0,i=0,a=/[\\/]subagents[\\/]agent-[^\\/]*\.jsonl$/.test(t)||void 0,c=new Map,u=(m,p,f)=>{let g=f.trim();if(!g)return;s++;let h=WO(g);for(r.push({n:s,at:typeof m=="string"?m:void 0,kind:p,raw:h,compactedBy:0,c:i}),o+=zx(h);o>e&&n<r.length-1;)o-=zx(r[n].raw),r[n].raw={whole:""},n++;n>1024&&(r.splice(0,n),n=0),c.size>1e5&&c.clear()};$p(t,m=>{let p;try{p=JSON.parse(m)}catch{return}if(!p||typeof p!="object")return;if(p.payload&&typeof p.payload=="object"&&typeof p.type=="string"&&!p.message){let h=p.payload;if(p.type==="compacted"||h.type==="context_compacted"){i++;return}if(p.type!=="response_item")return;if(h.type==="message"&&(h.role==="user"||h.role==="assistant"))return u(p.timestamp,h.role,kp(h.content));if(h.type==="function_call"||h.type==="custom_tool_call"||h.type==="local_shell_call"){let _=String(h.name??(h.type==="local_shell_call"?"shell":h.type));typeof h.call_id=="string"&&c.set(h.call_id,_);let v=h.arguments??h.input??h.action;if(typeof v=="string")try{v=JSON.parse(v)}catch{}return u(p.timestamp,"tool call",Rx(_,v))}return/_call_output$/.test(String(h.type))?u(p.timestamp,`tool output (${c.get(h.call_id)??"tool"})`,kp(h.output)):void 0}if(p.type==="system"&&p.subtype==="compact_boundary"){i++;return}if(p.isCompactSummary)return;let f=p.message;if(!f||(a===void 0&&(a=p.isSidechain===!0),p.isSidechain&&!a))return;let g=f.content;if(p.type==="user"){if(typeof g=="string")return u(p.timestamp,"user",g);if(!Array.isArray(g))return;for(let h of g)h?.type==="tool_result"?u(p.timestamp,`tool output (${c.get(h.tool_use_id)??"tool"})`,kp(h.content)):typeof h?.text=="string"&&u(p.timestamp,"user",h.text);return}if(p.type==="assistant"&&Array.isArray(g))for(let h of g)h?.type==="text"?u(p.timestamp,"assistant",String(h.text??"")):h?.type==="tool_use"&&(typeof h.id=="string"&&c.set(h.id,String(h.name??"tool")),u(p.timestamp,"tool call",Rx(String(h.name??"tool"),h.input)))});let l=0;return{entries:r.slice(n).map(({c:m,raw:p,...f})=>{let g=KO(p);return l+=g.masked,{...f,text:g.text,compactedBy:i-m}}),total:s,compactions:i,masked:l}}function XO(t){try{let e=FO(t,"r");try{let r=Buffer.alloc(65536),n=HO(e,r,0,r.length,0),o=r.subarray(0,n).toString("utf8").split(`
108
108
  `)[0],s=JSON.parse(o)?.payload?.cwd;return typeof s=="string"?s:void 0}finally{UO(e)}}catch{return}}function Px(t){let e;try{for(let r of Ba(t)){if(!r.endsWith(".jsonl"))continue;let n=_n(t,r),o=Sp(n).mtimeMs;(!e||o>e.at)&&(e={path:n,at:o})}}catch{}return e}function YO(t,e){let r=_n(e,".codex","sessions");if(!Ha(r))return;let n=Date.now()-7*864e5,o=[],s=(i,a)=>{let c;try{c=Ba(i)}catch{return}for(let u of c){let l=_n(i,u),d;try{d=Sp(l)}catch{continue}d.isDirectory()?a<3&&s(l,a+1):u.endsWith(".jsonl")&&d.mtimeMs>=n&&o.push({path:l,at:d.mtimeMs})}};return s(r,0),o.sort((i,a)=>a.at-i.at).find(i=>XO(i.path)===Cx(t))}function Ax(t=process.env,e=process.cwd(),r=Tp(),n={}){let o=t.CLAUDE_CODE_SESSION_ID?.trim();if(o&&/^[\w.-]+$/.test(o)){let a=QO(o,r);if(a&&a.endsWith(`${o}.jsonl`)){if(n.envMayBeStale){let c=Px(BO(a));if(c&&c.path!==a&&c.at>Sp(a).mtimeMs)return{path:c.path,how:`the newest Claude Code session in this project (${Ix(c.path,".jsonl")}; CLAUDE_CODE_SESSION_ID still names ${o}, as after /clear)`}}return{path:a,how:`this Claude Code session (${o})`}}}let s=Px(Tx(e,r)),i=YO(e,r);return i&&(!s||i.at>s.at)?{path:i.path,how:"the newest Codex session started in this folder"}:s?{path:s.path,how:"the newest Claude Code session in this folder"}:void 0}function QO(t,e=Tp()){if((VO(t)||t.includes("/")||t.includes("\\"))&&Ha(t))return Cx(t);if(!/^[\w.-]+$/.test(t))return;let r=_n(io(e),"projects"),n=[];try{n=Ba(r)}catch{}for(let a of n){let c=_n(r,a,`${t}.jsonl`);if(Ha(c))return c}let o=_n(e,".codex","sessions"),s,i=(a,c)=>{if(s)return;let u;try{u=Ba(a)}catch{return}for(let l of u){let d=_n(a,l);if(l.endsWith(".jsonl")&&l.includes(t)){s=d;return}c<3&&!l.includes(".")&&i(d,c+1)}};return Ha(o)&&i(o,0),s}function Ox(t,e,r={}){let n=GO(t),{entries:o,compactions:s}=n,i=new Map,a=o.map(p=>{let f=`#${p.n}`;return i.set(f,p),{name:f,text:p.text}}),c=Math.max(200,r.budget??2e3),u=Gv(a,{query:e,budget:c,maxChunkTokens:300}),l=p=>p.compactedBy===0?"in context":`before compaction ${s-p.compactedBy+1} of ${s}`,d=[...u.selected].sort((p,f)=>f.score-p.score).map(p=>{let f=i.get(p.source);return{id:p.id,n:f.n,at:f.at,kind:f.kind,where:l(f),tokens:p.tokens,score:p.score,text:p.text}}),m=u.chunks.filter(p=>p.score>0&&!u.selected.includes(p)).length;return{path:t,how:r.how??"the session named",query:e,entries:n.total,compactions:s,totalTokens:u.totalTokens,hits:d,masked:n.masked,more:m,leftOut:n.total-o.length}}function Nx(t,e=Tp()){let r=Ix(t.path).replace(/\.jsonl$/,"").slice(0,48),n=[`RECALL from ${t.how}${t.how.includes(r)?"":` (${r})`}: ${t.entries} entries, ~${z(t.totalTokens)} tokens, ${t.compactions} compaction${t.compactions===1?"":"s"}.`];if(!t.hits.length)return n.push(`Nothing in it matches "${t.query}". Try the words the output itself would use (a file name, an error, a command).`),n.join(`
109
109
  `);n.push(`Best ${t.hits.length} excerpt${t.hits.length===1?"":"s"} for "${t.query}", best first${t.more?` (${t.more} more matched; a narrower query or a larger max_tokens gets them)`:""}:`),t.masked&&n.push(`${t.masked} secret-looking string${t.masked===1?"":"s"} masked.`),t.leftOut&&n.push(`The oldest ${t.leftOut} entries were not searched: the transcript is that large.`);for(let o of t.hits){let s=o.at?o.at.slice(0,16).replace("T"," ")+" UTC":"time not recorded";n.push("",`\u2500\u2500 entry ${o.n} of ${t.entries} \xB7 ${s} \xB7 ${o.kind} \xB7 ${o.where} \xB7 ~${z(o.tokens)}`,o.text)}return n.join(`
110
- `).replaceAll(e,"~")}var BN=["dedupe","trim-tool-results","trim-tool-calls","strip-base64","prune-history"],VN={approx_tokens:1e7,approx_lines:1e6,approx_words:5e6,approx_chars:4e7};function Lp(t,e,r){if(nx(t)==="full")return{content:[{type:"text",text:e}]};let n=r();return{content:[{type:"text",text:n.text}],structuredContent:n.structured,_meta:n.meta}}async function bb(t,e,r){if(!t.server.getClientCapabilities()?.elicitation?.form)return{asked:!1};try{let n=await t.server.elicitInput({mode:"form",message:e,requestedSchema:{type:"object",properties:r}},{timeout:12e4});return n.action==="accept"?{asked:!0,ok:!0,content:n.content??{}}:{asked:!0,ok:!1,content:{},why:n.action==="decline"?"the user declined":"the user dismissed the prompt"}}catch(n){return n instanceof I&&n.code===A.RequestTimeout?{asked:!0,ok:!1,content:{},why:"no answer within two minutes"}:{asked:!0,ok:!1,content:{},why:"the consent form failed, so nothing was assumed"}}}function wb({http:t=!1,storeHandoffs:e=!t}={}){let r=!t,n=new wa({name:"context-doctor",version:"0.40.0"},{instructions:rx,maxToolInputElements:1e4});n.tool("profile_context","Profile a conversation's context: token breakdown, largest blocks, wasted context. Pass `conversation` (JSON or text) or, in a chat app, a `sketch` (~120 tokens). Call it when the user asks about tokens, cost, speed or limits, and once past ~30 turns or 3+ large pastes. Act on the top finding.",{conversation:Z.string().optional().describe("JSON or text; in a chat app pass `sketch`"),sketch:Z.object({turns:Z.number().int().nonnegative().describe("Exchanges so far"),model:Z.string().optional(),blocks:Z.array(Z.object({turn:Z.number().int().positive(),kind:Z.enum(["paste","code","tool_result","image","base64","text"]),label:Z.string().describe("Short name"),approx_tokens:Z.number().optional(),approx_lines:Z.number().optional(),approx_words:Z.number().optional(),approx_chars:Z.number().optional(),repeated:Z.number().int().optional().describe("Times it appears (2+ = duplicate)"),stale:Z.boolean().optional().describe("Acted on, no longer needed")})).describe("Only blocks over ~500 tokens, repeated, or images.")}).optional().describe("For chat apps. One size hint per block: lines for code, words for prose, chars for logs."),model:Z.string().optional().describe("e.g. claude-sonnet-5")},{title:"Profile context",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},async({conversation:i,sketch:a,model:c},u)=>{if(a){let m=h=>({isError:!0,content:[{type:"text",text:h}]});if(a.turns>1e5)return m(`sketch.turns is ${a.turns}; the most that makes sense is 100000.`);if(a.blocks.length>500)return m(`sketch.blocks has ${a.blocks.length} blocks; list at most 500 (only those over ~500 tokens, repeated, or images).`);for(let[h,_]of a.blocks.entries()){if(_.turn>1e5)return m(`sketch.blocks[${h}].turn is ${_.turn}; the most that makes sense is 100000.`);if(_.repeated!==void 0&&(_.repeated<1||_.repeated>1e3))return m(`sketch.blocks[${h}].repeated is ${_.repeated}; give 1 to 1000.`);for(let[v,y]of Object.entries(VN)){let x=_[v];if(typeof x=="number"&&!(x>0))return m(`sketch.blocks[${h}].${v} is ${x}; a size is above 0.`);if(typeof x=="number"&&x>y)return m(`sketch.blocks[${h}].${v} is ${x}; the most that makes sense is ${y}. Give a rough size of the block itself.`)}}let p=i?"Note: both `conversation` and `sketch` were passed; profiled the sketch only. Pass one.\n\n":"",f=Sv({...a,model:a.model??c},{record:!t}),g=p+kv(f);return Lp(u?._meta,g,()=>{let h=sx(f,g);return{...h,text:p+h.text}})}if(!i)return{isError:!0,content:[{type:"text",text:"Pass either `conversation` (full JSON or text) or `sketch` (turns + large/repeated blocks). In a chat app, use `sketch`."}]};let l=hv(rv(i),c),d=bv(l);return Lp(u?._meta,d,()=>ox(l,d))}),n.tool("optimize_context","Rewrite a conversation to reclaim tokens (dedupe, trim stale tool results, strip base64; prune-history is lossy). Returns slimmed JSON and the savings. Use after profile_context finds waste the user wants fixed; prune-history only with the user's consent, then write the summary the result asks for.",{conversation:Z.string().describe("Conversation JSON"),strategies:Z.array(Z.enum(BN)).optional().describe("Default: dedupe, trim-tool-results, strip-base64"),keep_recent:Z.number().int().nonnegative().optional().describe("Tail messages kept (default 6)"),max_tool_result_tokens:Z.number().int().positive().optional().describe("Per trimmed result (default 300)")},{title:"Optimize context",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},async({conversation:i,strategies:a,keep_recent:c,max_tool_result_tokens:u})=>{let l="";if(a?.includes("prune-history")){let _=await bb(n,`Prune old turns from this conversation? It is lossy: all but the last ${Math.max(2,c??6)} messages are replaced by a summary the assistant writes.`,{prune:{type:"boolean",title:"Replace old turns with a summary",default:!0}});_.asked&&(!_.ok||_.content.prune===!1)&&(a=a.filter(v=>v!=="prune-history"),l=`
110
+ `).replaceAll(e,"~")}var BN=["dedupe","trim-tool-results","trim-tool-calls","strip-base64","prune-history"],VN={approx_tokens:1e7,approx_lines:1e6,approx_words:5e6,approx_chars:4e7};function Lp(t,e,r){if(nx(t)==="full")return{content:[{type:"text",text:e}]};let n=r();return{content:[{type:"text",text:n.text}],structuredContent:n.structured,_meta:n.meta}}async function bb(t,e,r){if(!t.server.getClientCapabilities()?.elicitation?.form)return{asked:!1};try{let n=await t.server.elicitInput({mode:"form",message:e,requestedSchema:{type:"object",properties:r}},{timeout:12e4});return n.action==="accept"?{asked:!0,ok:!0,content:n.content??{}}:{asked:!0,ok:!1,content:{},why:n.action==="decline"?"the user declined":"the user dismissed the prompt"}}catch(n){return n instanceof I&&n.code===A.RequestTimeout?{asked:!0,ok:!1,content:{},why:"no answer within two minutes"}:{asked:!0,ok:!1,content:{},why:"the consent form failed, so nothing was assumed"}}}function wb({http:t=!1,storeHandoffs:e=!t}={}){let r=!t,n=new wa({name:"context-doctor",version:"0.41.0"},{instructions:rx,maxToolInputElements:1e4});n.tool("profile_context","Profile a conversation's context: token breakdown, largest blocks, wasted context. Pass `conversation` (JSON or text) or, in a chat app, a `sketch` (~120 tokens). Call it when the user asks about tokens, cost, speed or limits, and once past ~30 turns or 3+ large pastes. Act on the top finding.",{conversation:Z.string().optional().describe("JSON or text; in a chat app pass `sketch`"),sketch:Z.object({turns:Z.number().int().nonnegative().describe("Exchanges so far"),model:Z.string().optional(),blocks:Z.array(Z.object({turn:Z.number().int().positive(),kind:Z.enum(["paste","code","tool_result","image","base64","text"]),label:Z.string().describe("Short name"),approx_tokens:Z.number().optional(),approx_lines:Z.number().optional(),approx_words:Z.number().optional(),approx_chars:Z.number().optional(),repeated:Z.number().int().optional().describe("Times it appears (2+ = duplicate)"),stale:Z.boolean().optional().describe("Acted on, no longer needed")})).describe("Only blocks over ~500 tokens, repeated, or images.")}).optional().describe("For chat apps. One size hint per block: lines for code, words for prose, chars for logs."),model:Z.string().optional().describe("e.g. claude-sonnet-5")},{title:"Profile context",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},async({conversation:i,sketch:a,model:c},u)=>{if(a){let m=h=>({isError:!0,content:[{type:"text",text:h}]});if(a.turns>1e5)return m(`sketch.turns is ${a.turns}; the most that makes sense is 100000.`);if(a.blocks.length>500)return m(`sketch.blocks has ${a.blocks.length} blocks; list at most 500 (only those over ~500 tokens, repeated, or images).`);for(let[h,_]of a.blocks.entries()){if(_.turn>1e5)return m(`sketch.blocks[${h}].turn is ${_.turn}; the most that makes sense is 100000.`);if(_.repeated!==void 0&&(_.repeated<1||_.repeated>1e3))return m(`sketch.blocks[${h}].repeated is ${_.repeated}; give 1 to 1000.`);for(let[v,y]of Object.entries(VN)){let x=_[v];if(typeof x=="number"&&!(x>0))return m(`sketch.blocks[${h}].${v} is ${x}; a size is above 0.`);if(typeof x=="number"&&x>y)return m(`sketch.blocks[${h}].${v} is ${x}; the most that makes sense is ${y}. Give a rough size of the block itself.`)}}let p=i?"Note: both `conversation` and `sketch` were passed; profiled the sketch only. Pass one.\n\n":"",f=Sv({...a,model:a.model??c},{record:!t}),g=p+kv(f);return Lp(u?._meta,g,()=>{let h=sx(f,g);return{...h,text:p+h.text}})}if(!i)return{isError:!0,content:[{type:"text",text:"Pass either `conversation` (full JSON or text) or `sketch` (turns + large/repeated blocks). In a chat app, use `sketch`."}]};let l=hv(rv(i),c),d=bv(l);return Lp(u?._meta,d,()=>ox(l,d))}),n.tool("optimize_context","Rewrite a conversation to reclaim tokens (dedupe, trim stale tool results, strip base64; prune-history is lossy). Returns slimmed JSON and the savings. Use after profile_context finds waste the user wants fixed; prune-history only with the user's consent, then write the summary the result asks for.",{conversation:Z.string().describe("Conversation JSON"),strategies:Z.array(Z.enum(BN)).optional().describe("Default: dedupe, trim-tool-results, strip-base64"),keep_recent:Z.number().int().nonnegative().optional().describe("Tail messages kept (default 6)"),max_tool_result_tokens:Z.number().int().positive().optional().describe("Per trimmed result (default 300)")},{title:"Optimize context",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},async({conversation:i,strategies:a,keep_recent:c,max_tool_result_tokens:u})=>{let l="";if(a?.includes("prune-history")){let _=await bb(n,`Prune old turns from this conversation? It is lossy: all but the last ${Math.max(2,c??6)} messages are replaced by a summary the assistant writes.`,{prune:{type:"boolean",title:"Replace old turns with a summary",default:!0}});_.asked&&(!_.ok||_.content.prune===!1)&&(a=a.filter(v=>v!=="prune-history"),l=`
111
111
  prune-history skipped: ${_.ok?"the user unticked it":_.why}.`)}let d=vv(i,{strategies:a,keepRecent:c,maxToolResultTokens:u}),m=d.tokensBefore-d.tokensAfter;m>0&&!t&&Ra({ev:"optimize",src:"mcp",saved:m,model:d.conversation?.model});let p=`Saved ~${z(m)} tokens (${z(d.tokensBefore)} \u2192 ${z(d.tokensAfter)}) via ${d.applied.length} change(s):
112
112
  `+d.applied.map(_=>`- [${_.strategy}] message #${_.messageIndex}: ${_.note} (~${z(_.tokensSaved)})`).join(`
113
113
  `)+l,f=1e5,g=JSON.stringify(d.conversation),h=[{type:"text",text:p},g.length<=f?{type:"text",text:g}:{type:"text",text:`[optimized conversation is ${g.length} chars \u2014 too large to echo into this context. Tell the user the savings above and that \`npx context-doctor optimize <file> --out slim.json\` produces the file directly.]`}];return d.prunedDigest&&h.push({type:"text",text:`ACTION REQUIRED (you, the assistant calling this tool): the pruned turns are digested below. Write a dense factual summary of them (\u2264150 tokens: decisions, current state, open items, key identifiers) and replace the '[context-doctor: ... pruned]' stub message in the conversation above with your summary before presenting the result.
package/dist/proxy.d.ts CHANGED
@@ -65,7 +65,7 @@ export interface ProxyOptions extends OptimizeOptions {
65
65
  /** Default request body cap: far above any real request (a 1M-token context is ~4 MB of JSON, images aside). */
66
66
  export declare const DEFAULT_MAX_BODY_BYTES: number;
67
67
  /** Reported by /health so `autopilot status` can tell an outdated service from a current one. */
68
- export declare const PROXY_VERSION = "0.40.0";
68
+ export declare const PROXY_VERSION = "0.41.0";
69
69
  /**
70
70
  * Remove a leading `/t/<token>` from a request path, or return undefined when
71
71
  * the prefix is absent or the token differs. The comparison is constant time
package/dist/proxy.js CHANGED
@@ -24,7 +24,7 @@ import { withPromptCacheKey } from "./cachekey.js";
24
24
  /** Default request body cap: far above any real request (a 1M-token context is ~4 MB of JSON, images aside). */
25
25
  export const DEFAULT_MAX_BODY_BYTES = 100 * 1024 * 1024;
26
26
  /** Reported by /health so `autopilot status` can tell an outdated service from a current one. */
27
- export const PROXY_VERSION = "0.40.0";
27
+ export const PROXY_VERSION = "0.41.0";
28
28
  /** Connection-level headers that must not be forwarded. */
29
29
  const SKIP_REQUEST_HEADERS = new Set(["host", "content-length", "connection", "transfer-encoding", "accept-encoding", "expect"]);
30
30
  const SKIP_RESPONSE_HEADERS = new Set(["content-length", "content-encoding", "transfer-encoding", "connection"]);
package/dist/scan.d.ts CHANGED
@@ -83,6 +83,14 @@ export declare function prescan(jobs: Array<{
83
83
  export declare function rowsOf<R = any>(path: string, ex: Extractor<any>, opts?: {
84
84
  keep?: boolean;
85
85
  }): R[];
86
+ /**
87
+ * A report's own record for a source that is not a transcript (Cursor's
88
+ * database), kept beside the transcripts' entries: written the same way,
89
+ * pruned with them when its source is gone or untouched for 120 days, and
90
+ * removed by `uninstall`. Undefined when none is kept or it is damaged.
91
+ */
92
+ export declare function readSideEntry<T>(path: string, id: string): T | undefined;
93
+ export declare function writeSideEntry(path: string, id: string, value: unknown): void;
86
94
  /** Forget this run's records (tests). */
87
95
  export declare function clearScanMemo(): void;
88
96
  /**
package/dist/scan.js CHANGED
@@ -357,6 +357,27 @@ export function rowsOf(path, ex, opts = {}) {
357
357
  }
358
358
  return (e.tail.length ? e.rows.concat(e.tail) : e.rows);
359
359
  }
360
+ /**
361
+ * A report's own record for a source that is not a transcript (Cursor's
362
+ * database), kept beside the transcripts' entries: written the same way,
363
+ * pruned with them when its source is gone or untouched for 120 days, and
364
+ * removed by `uninstall`. Undefined when none is kept or it is damaged.
365
+ */
366
+ export function readSideEntry(path, id) {
367
+ if (disabled())
368
+ return undefined;
369
+ try {
370
+ const v = JSON.parse(readFileSync(entryFile(path, id), "utf8"));
371
+ return v?.path === path && v.id === id ? v.value : undefined;
372
+ }
373
+ catch {
374
+ return undefined;
375
+ }
376
+ }
377
+ export function writeSideEntry(path, id, value) {
378
+ // "path" first: pruning reads it from the file's head.
379
+ persist({ path, id, value }, entryFile(path, id));
380
+ }
360
381
  /** Forget this run's records (tests). */
361
382
  export function clearScanMemo() {
362
383
  memo.clear();
@@ -0,0 +1,176 @@
1
+ /**
2
+ * `context-doctor spend`: one bill across every AI coding tool on this
3
+ * machine, at list prices.
4
+ *
5
+ * Each tool keeps its own record of what it sent, and none adds them up:
6
+ *
7
+ * - Claude Code: every reply's `usage` in its transcripts, the main
8
+ * conversation and each subagent's (`<session>/subagents/agent-*.jsonl`),
9
+ * read as `limits` reads them (claudeFileUsage): each reply once, its
10
+ * output settled on its last row, a fork's copy of its parent counted once.
11
+ * - Codex: the `token_count` events of its rollouts (~/.codex/sessions and
12
+ * archived_sessions), a request each time the running total moves, as
13
+ * `limits` counts them; the model from `turn_context`, the folder from
14
+ * `session_meta`.
15
+ * - Gemini CLI: each `gemini` message's `tokens` in ~/.gemini/tmp/<project>/chats,
16
+ * the last copy of a message written twice. A message later rewound was
17
+ * still billed, so it is counted.
18
+ * - Cursor: the `tokenCount` on its agent replies (cursorUsage). It records
19
+ * no cache split, so every input token is priced uncached: an estimate,
20
+ * and an upper bound. Replies on Auto ("default") have no list price and
21
+ * are counted, not priced.
22
+ *
23
+ * Priced at pricing.ts's list prices (usageCost), as every report here is.
24
+ * Claude Code, Codex and Gemini CLI are read through the shared scan
25
+ * (scan.ts), so a second run reads only what was appended since; Cursor's
26
+ * replies are kept per chat until the chat changes.
27
+ *
28
+ * `savings` bills a narrower slice of the same Claude Code requests: the main
29
+ * conversation's input (cache writes and reads included, output not), in
30
+ * sessions with 10+ requests. `spend` counts every request, its output and
31
+ * subagents too; on the requests both count, the dollars are the same.
32
+ */
33
+ import { type Extractor } from "./scan.js";
34
+ export type Tool = "claude" | "codex" | "gemini" | "cursor";
35
+ export declare const TOOLS: Tool[];
36
+ export declare const TOOL_NAME: Record<Tool, string>;
37
+ /** One request (a Cursor reply), priced. */
38
+ export interface SpendItem {
39
+ tool: Tool;
40
+ ts: number;
41
+ project: string;
42
+ /** The session it belongs to: its transcript's name, or Cursor's chat id. */
43
+ session: string;
44
+ model?: string;
45
+ input: number;
46
+ read: number;
47
+ write: number;
48
+ output: number;
49
+ /** At list price; 0 when the model has no price on file (`priced` false). */
50
+ usd: number;
51
+ inputUsd: number;
52
+ writeUsd: number;
53
+ readUsd: number;
54
+ outputUsd: number;
55
+ priced: boolean;
56
+ /** Claude Code: run by a subagent. */
57
+ subagent?: boolean;
58
+ /** Claude Code: the reply's row uuid, which a fork's copy shares. */
59
+ key?: string;
60
+ }
61
+ /** A project's name as `savings` shows it: the folder's path with "-" for separators, less "-Users-<you>-". */
62
+ export declare function projectName(folder: string): string;
63
+ /**
64
+ * Claude Code's requests between `since` and `until`, main threads and
65
+ * subagents, over `tops` (default: every transcript written since `since`).
66
+ */
67
+ export declare function claudeSpend(since: number, until?: number, tops?: string[], onProgress?: (done: number, total: number) => void): SpendItem[];
68
+ /**
69
+ * What `spend` takes from a Codex rollout: its folder, each model change,
70
+ * and every token_count event's last request and running total.
71
+ */
72
+ export declare const CODEX_SPEND_ROWS: Extractor<null>;
73
+ /** The requests of one Codex rollout since `since`. Throws when it cannot be read. */
74
+ export declare function codexFileSpend(file: string, since: number, until?: number): SpendItem[];
75
+ /** Codex rollouts written since `since`: the live ones and the archived. */
76
+ export declare function codexFiles(since: number, home?: string): string[];
77
+ export declare function codexSpend(since: number, until?: number, home?: string): SpendItem[];
78
+ /**
79
+ * What `spend` takes from a Gemini CLI chat (JSONL): each `gemini` message's
80
+ * id, time, model and token counts. A message without a time of its own
81
+ * takes the last time met before it.
82
+ */
83
+ export declare const GEMINI_SPEND_ROWS: Extractor<{
84
+ ts: string;
85
+ }>;
86
+ /** The billed messages of one Gemini CLI chat since `since`. Throws when it cannot be read. */
87
+ export declare function geminiFileSpend(file: string, since: number, until?: number): SpendItem[];
88
+ export declare function geminiFiles(since: number, home?: string): string[];
89
+ export declare function geminiSpend(since: number, until?: number, home?: string): SpendItem[];
90
+ export declare function cursorSpend(since: number, until?: number): SpendItem[];
91
+ export interface ToolSpend {
92
+ tool: Tool;
93
+ name: string;
94
+ usd: number;
95
+ requests: number;
96
+ tokens: {
97
+ input: number;
98
+ read: number;
99
+ write: number;
100
+ output: number;
101
+ };
102
+ /** Claude Code: what its subagents cost, inside `usd`. */
103
+ subagentUsd?: number;
104
+ /** Cursor: priced without a cache split, an upper bound. */
105
+ estimate?: boolean;
106
+ /** Requests whose model has no list price, counted but not in `usd`. */
107
+ unpriced: number;
108
+ unpricedTokens: number;
109
+ unpricedModels: string[];
110
+ }
111
+ export interface SpendRow {
112
+ usd: number;
113
+ requests: number;
114
+ byTool: Partial<Record<Tool, number>>;
115
+ }
116
+ export interface SpendReport {
117
+ days: number;
118
+ since: number;
119
+ until: number;
120
+ usd: number;
121
+ requests: number;
122
+ tools: ToolSpend[];
123
+ projects: Array<SpendRow & {
124
+ project: string;
125
+ }>;
126
+ models: Array<SpendRow & {
127
+ model: string;
128
+ }>;
129
+ /** Every local day of the window, oldest first. */
130
+ daily: Array<SpendRow & {
131
+ day: string;
132
+ }>;
133
+ /** The bill by what it paid for. */
134
+ parts: {
135
+ inputUsd: number;
136
+ writeUsd: number;
137
+ readUsd: number;
138
+ outputUsd: number;
139
+ };
140
+ sessions: Array<{
141
+ tool: Tool;
142
+ project: string;
143
+ session: string;
144
+ model?: string;
145
+ usd: number;
146
+ requests: number;
147
+ first: number;
148
+ last: number;
149
+ }>;
150
+ /** A tool that could not be read (Cursor without SQLite), and why. */
151
+ skipped: Array<{
152
+ tool: Tool;
153
+ reason: string;
154
+ }>;
155
+ }
156
+ /** The local calendar day of `ts`, "YYYY-MM-DD". */
157
+ export declare function localDay(ts: number): string;
158
+ /** Add up priced requests into the report. */
159
+ export declare function summarizeSpend(items: SpendItem[], days: number, since: number, until: number, skipped?: SpendReport["skipped"]): SpendReport;
160
+ export interface SpendOptions {
161
+ home?: string;
162
+ /** Claude Code transcripts to read instead of every one written in the window (tests). */
163
+ claudePaths?: string[];
164
+ onProgress?: (done: number, total: number) => void;
165
+ now?: number;
166
+ }
167
+ /** The last `days` days, every tool on this machine. A tool with nothing on disk is just absent. */
168
+ export declare function spendReport(days?: number, opts?: SpendOptions): SpendReport;
169
+ export declare const usd: (n: number) => string;
170
+ /** The full report, kept within 80 columns. `top`: rows per list. */
171
+ export declare function renderSpend(r: SpendReport, top?: number): string;
172
+ /**
173
+ * `spend --share`: totals only. No project names, paths or session ids, so
174
+ * sharing it leaks nothing.
175
+ */
176
+ export declare function renderSpendShare(r: SpendReport): string;