context-doctor 0.45.0 → 0.47.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/README.md +8 -3
- package/dist/ab.js +3 -2
- package/dist/autopilot.js +9 -5
- package/dist/blob.js +66 -12
- package/dist/budget.d.ts +10 -1
- package/dist/budget.js +37 -8
- package/dist/cachemisses.js +5 -3
- package/dist/cacheplan.js +2 -2
- package/dist/cachettl.js +2 -1
- package/dist/ci.js +2 -1
- package/dist/claudeplugin.d.ts +97 -0
- package/dist/claudeplugin.js +142 -0
- package/dist/cli.js +126 -39
- package/dist/coldresume.d.ts +6 -0
- package/dist/coldresume.js +7 -6
- package/dist/compactcost.d.ts +74 -0
- package/dist/compactcost.js +115 -0
- package/dist/compactwindow.js +5 -4
- package/dist/cursor.js +2 -0
- package/dist/doctor.js +106 -17
- package/dist/extract.js +4 -3
- package/dist/fanout.d.ts +15 -0
- package/dist/fanout.js +31 -10
- package/dist/firstfix.d.ts +43 -0
- package/dist/firstfix.js +80 -0
- package/dist/fix.d.ts +46 -2
- package/dist/fix.js +109 -20
- package/dist/hook.js +6 -2
- package/dist/httpguard.d.ts +13 -0
- package/dist/httpguard.js +22 -0
- package/dist/install.d.ts +21 -9
- package/dist/install.js +211 -40
- package/dist/limits.d.ts +5 -0
- package/dist/limits.js +26 -2
- package/dist/mcp.js +63 -62
- package/dist/missledger.js +5 -3
- package/dist/mod/api.d.ts +135 -0
- package/dist/mod/api.js +12 -0
- package/dist/mod/logic.d.ts +158 -0
- package/dist/mod/logic.js +244 -0
- package/dist/mod/register.d.ts +60 -0
- package/dist/mod/register.js +251 -0
- package/dist/modelids.d.ts +24 -0
- package/dist/modelids.js +65 -0
- package/dist/modelswitch.js +8 -4
- package/dist/modmeasure.d.ts +121 -0
- package/dist/modmeasure.js +310 -0
- package/dist/orgrates.d.ts +93 -0
- package/dist/orgrates.js +214 -0
- package/dist/overhead.js +11 -8
- package/dist/pack.d.ts +13 -0
- package/dist/pack.js +68 -3
- package/dist/preferences.js +2 -1
- package/dist/pricing.d.ts +26 -0
- package/dist/pricing.js +61 -7
- package/dist/progresssummaries.d.ts +148 -0
- package/dist/progresssummaries.js +248 -0
- package/dist/proxy.d.ts +1 -1
- package/dist/proxy.js +1 -1
- package/dist/prune.d.ts +8 -0
- package/dist/prune.js +11 -1
- package/dist/savings.js +8 -6
- package/dist/sessionprice.d.ts +22 -0
- package/dist/sessionprice.js +46 -14
- package/dist/spend.d.ts +46 -3
- package/dist/spend.js +86 -10
- package/dist/statusline.js +2 -2
- package/dist/subagentmodel.d.ts +12 -0
- package/dist/subagentmodel.js +17 -4
- package/dist/subagentpay.d.ts +15 -1
- package/dist/subagentpay.js +58 -25
- package/dist/subagents.js +4 -0
- package/dist/toolcwd.d.ts +14 -0
- package/dist/toolcwd.js +17 -0
- package/package.json +1 -1
package/dist/spend.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* `context-doctor spend`: one bill across every AI coding tool on this
|
|
3
|
-
* machine, at list
|
|
3
|
+
* machine, each request as billed at list rates.
|
|
4
4
|
*
|
|
5
5
|
* Each tool keeps its own record of what it sent, and none adds them up:
|
|
6
6
|
*
|
|
@@ -29,6 +29,11 @@
|
|
|
29
29
|
* (scan.ts), so a second run reads only what was appended since; Cursor's
|
|
30
30
|
* replies are kept per chat until the chat changes.
|
|
31
31
|
*
|
|
32
|
+
* Not in the total: Claude Code's subagent progress summaries, side requests
|
|
33
|
+
* no transcript records (progresssummaries.ts). They are estimated per
|
|
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).
|
|
36
|
+
*
|
|
32
37
|
* `savings` bills a narrower slice of the same Claude Code requests: the main
|
|
33
38
|
* conversation's input (cache writes and reads included, output not), in
|
|
34
39
|
* sessions with 10+ requests. `spend` counts every request, its output and
|
|
@@ -38,11 +43,19 @@ import { basename, dirname, join } from "node:path";
|
|
|
38
43
|
import { codexDir } from "./codexdir.js";
|
|
39
44
|
import { homedir } from "node:os";
|
|
40
45
|
import { closeSync, existsSync, openSync, readdirSync, readSync, statSync } from "node:fs";
|
|
41
|
-
import { claudeFileUsage, claudeUsageFiles, codexEventKey, codexSessionsRoot, rolloutFiles } from "./limits.js";
|
|
46
|
+
import { claudeFileUsage, claudeUsageFiles, codexEventKey, codexSessionsRoot, rolloutFiles, USAGE_ROWS } from "./limits.js";
|
|
47
|
+
import { estimateProgressSummaries, PROGRESS_ROWS, PROGRESS_SUMMARIES_ENV } from "./progresssummaries.js";
|
|
42
48
|
import { listGeminiChats, readGeminiMessages } from "./gemini.js";
|
|
43
49
|
import { cursorClaudeId, cursorUsage, SqliteUnavailableError } from "./cursor.js";
|
|
44
50
|
import { addModifiers, isUnbilledModel, NO_MODIFIERS, openAIUsage, priceChangedText, requestCost } from "./pricing.js";
|
|
45
|
-
import {
|
|
51
|
+
import { managedSourcesLine, orgRates, orgRatesLine, priceBasis } from "./orgrates.js";
|
|
52
|
+
/**
|
|
53
|
+
* What spend's dollars are: each request as it was billed (its tier, fast mode,
|
|
54
|
+
* US-only, web searches) at list rates, or at the organization's rates.
|
|
55
|
+
* "At list prices" was true before those were priced; it no longer is.
|
|
56
|
+
*/
|
|
57
|
+
const spendBasis = () => (orgRates() ? priceBasis() : "as billed at list rates");
|
|
58
|
+
import { pick, prescan, rowsOf } from "./scan.js";
|
|
46
59
|
import { formatTokens } from "./tokens.js";
|
|
47
60
|
import { withInvocation } from "./invocation.js";
|
|
48
61
|
const DAY = 86_400_000;
|
|
@@ -117,6 +130,8 @@ export function claudeSpend(since, until = Infinity, tops, onProgress) {
|
|
|
117
130
|
usd: r.usd, inputUsd, readUsd, writeUsd: Math.max(0, r.promptUsd - inputUsd - readUsd), outputUsd: Math.max(0, r.usd - r.promptUsd - r.modifiers.webSearchUsd), priced: Boolean(price),
|
|
118
131
|
};
|
|
119
132
|
label(item, r);
|
|
133
|
+
if (r.compaction)
|
|
134
|
+
item.compaction = true;
|
|
120
135
|
if (r.model)
|
|
121
136
|
item.model = r.model;
|
|
122
137
|
if (f.run)
|
|
@@ -299,9 +314,12 @@ function headParent(file) {
|
|
|
299
314
|
* The rollouts of the agents a Codex thread spawned (and theirs), for the
|
|
300
315
|
* session price: those written since the thread began in its own folder,
|
|
301
316
|
* the day folders from then to `now` (by local and UTC date) and the
|
|
302
|
-
* archive. Only each candidate's first line is read
|
|
317
|
+
* archive. Only each candidate's first line is read, and with `known` only
|
|
318
|
+
* once: a rollout's first line (its own session_meta) never changes, so
|
|
319
|
+
* what it named is kept there by file name, and a prompt reads only the
|
|
320
|
+
* rollouts written since the last (`known.changed` says when to save it).
|
|
303
321
|
*/
|
|
304
|
-
export function codexSpawnedRollouts(parent, now = Date.now(), home = homedir()) {
|
|
322
|
+
export function codexSpawnedRollouts(parent, now = Date.now(), home = homedir(), known) {
|
|
305
323
|
const id = rolloutId(parent);
|
|
306
324
|
if (!id)
|
|
307
325
|
return [];
|
|
@@ -324,6 +342,7 @@ export function codexSpawnedRollouts(parent, now = Date.now(), home = homedir())
|
|
|
324
342
|
dirs.add(join(root, String(y), String(mo).padStart(2, "0"), String(dd).padStart(2, "0")));
|
|
325
343
|
}
|
|
326
344
|
const heads = new Map();
|
|
345
|
+
const kept = {};
|
|
327
346
|
for (const dir of dirs) {
|
|
328
347
|
let names;
|
|
329
348
|
try {
|
|
@@ -336,14 +355,32 @@ export function codexSpawnedRollouts(parent, now = Date.now(), home = homedir())
|
|
|
336
355
|
const f = join(dir, n);
|
|
337
356
|
if (!n.startsWith("rollout-") || !n.endsWith(".jsonl") || f === parent || heads.has(f))
|
|
338
357
|
continue;
|
|
358
|
+
const k = known?.heads[n];
|
|
359
|
+
if (Array.isArray(k) && typeof k[0] === "string") {
|
|
360
|
+
heads.set(f, { id: k[0], ...(typeof k[1] === "string" ? { parent: k[1] } : {}) });
|
|
361
|
+
kept[n] = k;
|
|
362
|
+
continue;
|
|
363
|
+
}
|
|
339
364
|
try {
|
|
340
365
|
if (statSync(f).mtimeMs < born)
|
|
341
366
|
continue;
|
|
342
|
-
|
|
367
|
+
const h = headParent(f);
|
|
368
|
+
heads.set(f, h);
|
|
369
|
+
// Kept only once its id is there: a rollout caught before its first line was written is read again.
|
|
370
|
+
if (known && h.id) {
|
|
371
|
+
kept[n] = h.parent ? [h.id, h.parent] : [h.id];
|
|
372
|
+
known.changed = true;
|
|
373
|
+
}
|
|
343
374
|
}
|
|
344
375
|
catch { /* vanished */ }
|
|
345
376
|
}
|
|
346
377
|
}
|
|
378
|
+
if (known) {
|
|
379
|
+
// A rollout gone from every folder looked in is forgotten.
|
|
380
|
+
if (Object.keys(known.heads).some((n) => !(n in kept)))
|
|
381
|
+
known.changed = true;
|
|
382
|
+
known.heads = kept;
|
|
383
|
+
}
|
|
347
384
|
// Children, then theirs.
|
|
348
385
|
const mine = new Set([id]);
|
|
349
386
|
const out = [];
|
|
@@ -486,7 +523,12 @@ export function summarizeSpend(items, days, since, until, skipped = []) {
|
|
|
486
523
|
const runs = new Set();
|
|
487
524
|
const mods = { ...NO_MODIFIERS };
|
|
488
525
|
const changed = new Map();
|
|
526
|
+
const compactions = { requests: 0, usd: 0 };
|
|
489
527
|
for (const it of items) {
|
|
528
|
+
if (it.compaction) {
|
|
529
|
+
compactions.requests++;
|
|
530
|
+
compactions.usd += it.usd;
|
|
531
|
+
}
|
|
490
532
|
if (it.modifiers)
|
|
491
533
|
addModifiers(mods, it.modifiers);
|
|
492
534
|
if (it.changedOn) {
|
|
@@ -566,10 +608,19 @@ export function summarizeSpend(items, days, since, until, skipped = []) {
|
|
|
566
608
|
parts,
|
|
567
609
|
...(anyModifier(mods) ? { modifiers: mods } : {}),
|
|
568
610
|
...(changed.size ? { priceChanged: [...changed.values()].sort((a, b) => b.usd - a.usd) } : {}),
|
|
611
|
+
...(compactions.requests ? { compactions } : {}),
|
|
569
612
|
sessions: [...sessions.values()].sort(byUsd),
|
|
570
613
|
skipped,
|
|
571
614
|
};
|
|
572
615
|
}
|
|
616
|
+
/** The subagent progress summaries Claude Code wrote in the window, for the report. */
|
|
617
|
+
function claudeProgressSummaries(since, until, tops, o) {
|
|
618
|
+
if (o?.set && o.offSince === undefined)
|
|
619
|
+
return { set: o.set };
|
|
620
|
+
const files = claudeUsageFiles(since, tops).filter((f) => f.subagent && !f.run).map((f) => f.file);
|
|
621
|
+
const e = estimateProgressSummaries(files, { since, until, forkGateOff: o?.forkGateOff, offSince: o?.offSince });
|
|
622
|
+
return e.calls ? { agents: e.summarized, calls: e.calls, notesUsd: e.notesUsd, forkUsd: e.forkUsd } : undefined;
|
|
623
|
+
}
|
|
573
624
|
/**
|
|
574
625
|
* The longest window: ten years, older than any history these tools keep.
|
|
575
626
|
* Unbounded, `--days 10000000` listed every empty day of it (51 s, and
|
|
@@ -582,6 +633,9 @@ export function spendReport(days = 30, opts = {}) {
|
|
|
582
633
|
const until = opts.now ?? Date.now();
|
|
583
634
|
const since = until - days * DAY;
|
|
584
635
|
const home = opts.home ?? homedir();
|
|
636
|
+
// A subagent's transcript read once for its usage and its timeline (the progress summaries).
|
|
637
|
+
if (opts.progress !== false)
|
|
638
|
+
prescan([{ paths: claudeUsageFiles(since, opts.claudePaths).filter((f) => f.subagent && !f.run).map((f) => f.file), extractors: [USAGE_ROWS, PROGRESS_ROWS] }]);
|
|
585
639
|
const items = [...claudeSpend(since, until, opts.claudePaths, opts.onProgress), ...codexSpend(since, until, home), ...geminiSpend(since, until, home)];
|
|
586
640
|
const skipped = [];
|
|
587
641
|
try {
|
|
@@ -591,7 +645,9 @@ export function spendReport(days = 30, opts = {}) {
|
|
|
591
645
|
if (e instanceof SqliteUnavailableError)
|
|
592
646
|
skipped.push({ tool: "cursor", reason: "reading Cursor's history needs SQLite: Node 22.13+ or the sqlite3 command" });
|
|
593
647
|
}
|
|
594
|
-
|
|
648
|
+
const report = summarizeSpend(items, days, since, until, skipped);
|
|
649
|
+
const progress = opts.progress === false ? undefined : claudeProgressSummaries(since, until, opts.claudePaths, opts.progress);
|
|
650
|
+
return progress ? { ...report, progressSummaries: progress } : report;
|
|
595
651
|
}
|
|
596
652
|
// ---------------------------------------------------------------------------
|
|
597
653
|
// Rendering
|
|
@@ -620,7 +676,13 @@ export function renderSpend(r, top = 8) {
|
|
|
620
676
|
return lines.join("\n");
|
|
621
677
|
}
|
|
622
678
|
lines.push("What your AI coding cost, across every tool here");
|
|
623
|
-
lines.push(`Last ${r.days === 1 ? "day" : `${r.days} days`},
|
|
679
|
+
lines.push(`Last ${r.days === 1 ? "day" : `${r.days} days`}, ${spendBasis()}`);
|
|
680
|
+
const org = orgRatesLine();
|
|
681
|
+
if (org)
|
|
682
|
+
lines.push(org);
|
|
683
|
+
const ahead = managedSourcesLine();
|
|
684
|
+
if (ahead)
|
|
685
|
+
lines.push(ahead);
|
|
624
686
|
lines.push("─".repeat(60));
|
|
625
687
|
for (const t of r.tools) {
|
|
626
688
|
const unit = t.tool === "cursor" ? "replies" : "requests";
|
|
@@ -660,9 +722,20 @@ export function renderSpend(r, top = 8) {
|
|
|
660
722
|
// What the requests' own billing added to the list rates, already in the parts above.
|
|
661
723
|
if (r.modifiers)
|
|
662
724
|
lines.push(` Of it, billed above list rates: ${modifiersText(r.modifiers)}`);
|
|
725
|
+
// A compaction's own request is in no row's usage: estimated from the context it read and the summary it wrote.
|
|
726
|
+
if (r.compactions)
|
|
727
|
+
lines.push(` Of it, ${r.compactions.requests.toLocaleString("en-US")} Claude Code ${r.compactions.requests === 1 ? "compaction's own request" : "compactions' own requests"} ${usd(r.compactions.usd)}, an estimate (no row records their usage)`);
|
|
663
728
|
const claude = r.tools.find((t) => t.tool === "claude");
|
|
664
729
|
if (claude?.subagentUsd)
|
|
665
730
|
lines.push(` Claude Code subagents ${usd(claude.subagentUsd)} (${share(claude.subagentUsd, r.usd)}): context-doctor subagents says which paid off`);
|
|
731
|
+
// Side requests no transcript records: a range, outside the total.
|
|
732
|
+
const ps = r.progressSummaries;
|
|
733
|
+
if (ps && "calls" in ps) {
|
|
734
|
+
lines.push(` Not in it: ~${ps.calls.toLocaleString("en-US")} subagent progress summaries (${ps.agents} background ${ps.agents === 1 ? "agent" : "agents"}), an estimate:`);
|
|
735
|
+
lines.push(` ${usd(ps.notesUsd)} as notes, ${usd(ps.forkUsd)} at the whole context; no transcript records them`);
|
|
736
|
+
}
|
|
737
|
+
else if (ps)
|
|
738
|
+
lines.push(` Subagent progress summaries: not estimated, ${PROGRESS_SUMMARIES_ENV} is set in ${ps.set}`);
|
|
666
739
|
if (claude?.workflowUsd)
|
|
667
740
|
lines.push(` Claude Code workflow agents ${usd(claude.workflowUsd)} (${share(claude.workflowUsd, r.usd)}), in ${runsText(claude.workflowRuns ?? 0)}`);
|
|
668
741
|
lines.push(" Biggest sessions:");
|
|
@@ -696,7 +769,7 @@ export function renderSpend(r, top = 8) {
|
|
|
696
769
|
notes.push(`${TOOL_NAME[s.tool]} not read: ${s.reason}.`);
|
|
697
770
|
if (notes.length)
|
|
698
771
|
lines.push("", ...notes);
|
|
699
|
-
lines.push("", "
|
|
772
|
+
lines.push("", "As an API key is billed; on a subscription the same tokens come out");
|
|
700
773
|
lines.push("of your plan's limits instead. Share yours: context-doctor spend --share");
|
|
701
774
|
return withInvocation(lines.map((l) => l.trimEnd()).join("\n"));
|
|
702
775
|
}
|
|
@@ -708,7 +781,7 @@ export function renderSpendShare(r) {
|
|
|
708
781
|
if (r.requests === 0)
|
|
709
782
|
return "context-doctor found no AI coding usage to measure yet.";
|
|
710
783
|
const tools = r.tools.map((t) => `${t.name} ${t.estimate ? "~" : ""}${usd(t.usd)}${t.estimate ? " (estimate)" : ""}`).join(", ");
|
|
711
|
-
const lines = [`My AI coding, last ${r.days === 1 ? "day" : `${r.days} days`},
|
|
784
|
+
const lines = [`My AI coding, last ${r.days === 1 ? "day" : `${r.days} days`}, ${spendBasis()}: ${usd(r.usd)}${r.tools.length > 1 ? ` (${tools})` : ` in ${r.tools[0].name}`}.`];
|
|
712
785
|
const claude = r.tools.find((t) => t.tool === "claude");
|
|
713
786
|
if (claude?.subagentUsd)
|
|
714
787
|
lines.push(`Claude Code subagents: ${usd(claude.subagentUsd)} of it.`);
|
|
@@ -725,6 +798,9 @@ export function renderSpendShare(r) {
|
|
|
725
798
|
lines.push(`Of it, ${usd(r.priceChanged.reduce((s, c) => s + c.usd, 0))} is on models priced past the day their price changed, an estimate.`);
|
|
726
799
|
if (r.modifiers)
|
|
727
800
|
lines.push(`Billed above list rates: ${modifiersText(r.modifiers)}.`);
|
|
801
|
+
const ps = r.progressSummaries;
|
|
802
|
+
if (ps && "calls" in ps)
|
|
803
|
+
lines.push(`Not in it: Claude Code's subagent progress summaries, which no transcript records: ${usd(ps.notesUsd)}-${usd(ps.forkUsd)}, an estimate.`);
|
|
728
804
|
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]];
|
|
729
805
|
const [bigPart, bigUsd] = parts.sort((a, b) => b[1] - a[1])[0];
|
|
730
806
|
const busiest = [...r.daily].sort((a, b) => b.usd - a.usd)[0];
|
package/dist/statusline.js
CHANGED
|
@@ -30,7 +30,7 @@
|
|
|
30
30
|
*/
|
|
31
31
|
import { closeSync, openSync, readSync, statSync } from "node:fs";
|
|
32
32
|
import { contextWindowFor, formatTokens } from "./tokens.js";
|
|
33
|
-
import { CACHE_WRITE_1H, CACHE_WRITE_5M, formatUsd, rateCard, ratesAt } from "./pricing.js";
|
|
33
|
+
import { CACHE_WRITE_1H, CACHE_WRITE_5M, formatUsd, rateCard, ratesAt, writePerM } from "./pricing.js";
|
|
34
34
|
import { recordLimits } from "./limits.js";
|
|
35
35
|
import { recordMiss } from "./missledger.js";
|
|
36
36
|
import { budgetStatus } from "./budget.js";
|
|
@@ -115,7 +115,7 @@ export function cacheClock(pc, model, nowMs = Date.now(), billing, prompt) {
|
|
|
115
115
|
const card = rateCard(model, billing, nowMs);
|
|
116
116
|
const price = card && ratesAt(card, prompt ?? tokens ?? 0);
|
|
117
117
|
const oneHour = pc.ttl === "1h";
|
|
118
|
-
const extra = tokens !== undefined && price ? (tokens * (price
|
|
118
|
+
const extra = tokens !== undefined && price ? (tokens * (writePerM(price, oneHour ? CACHE_WRITE_1H : CACHE_WRITE_5M) - price.cacheReadPerM)) / 1e6 : undefined;
|
|
119
119
|
const cost = tokens === undefined ? undefined : extra !== undefined && extra > 0 ? `+${formatUsd(extra)}` : `${formatTokens(tokens)} re-write`;
|
|
120
120
|
// Epoch seconds within two hours of now: milliseconds, 1e300 and the like
|
|
121
121
|
// would print a nonsense time ("NaN:NaN"), so they count as no expiry.
|
package/dist/subagentmodel.d.ts
CHANGED
|
@@ -31,6 +31,7 @@
|
|
|
31
31
|
* Requests on a model no pricier than the candidate stay as billed.
|
|
32
32
|
*/
|
|
33
33
|
import { type Extractor } from "./scan.js";
|
|
34
|
+
import { type ModelPricing, type RecordedUsage } from "./pricing.js";
|
|
34
35
|
import { SUBAGENT_CANDIDATE, SUBAGENT_CANDIDATE_NAME } from "./subagentpay.js";
|
|
35
36
|
export { SUBAGENT_CANDIDATE, SUBAGENT_CANDIDATE_NAME };
|
|
36
37
|
/** The environment variable the lever writes. */
|
|
@@ -114,6 +115,17 @@ export interface SubagentModelOptions {
|
|
|
114
115
|
}
|
|
115
116
|
/** The agent type Claude Code recorded beside a subagent's transcript ("unknown" for an older one without it). */
|
|
116
117
|
export declare function agentTypeOf(transcript: string): string;
|
|
118
|
+
/**
|
|
119
|
+
* A request at the baseline mix: prices are linear in each rate, so it costs
|
|
120
|
+
* the mix of what each model would bill it, each priced by its whole card (an
|
|
121
|
+
* organization's row keeps its own cache-write rate, and its multiplier
|
|
122
|
+
* scales the web searches as requestCost does). A mix of one model is
|
|
123
|
+
* exactly requestCost.
|
|
124
|
+
*/
|
|
125
|
+
export declare function atBaseline(base: ModelPricing, u: RecordedUsage, at: number, mix?: Record<string, number>): {
|
|
126
|
+
totalUsd: number;
|
|
127
|
+
rates: ModelPricing;
|
|
128
|
+
};
|
|
117
129
|
/**
|
|
118
130
|
* Replay every subagent request in [since, until): as billed, and with the
|
|
119
131
|
* requests CLAUDE_CODE_SUBAGENT_MODEL would move at the candidate model.
|
package/dist/subagentmodel.js
CHANGED
|
@@ -40,6 +40,7 @@ import { claudeDir } from "./claudedir.js";
|
|
|
40
40
|
import { subagentTranscripts } from "./cachettl.js";
|
|
41
41
|
import { workflowRunOf } from "./subagents.js";
|
|
42
42
|
import { managedDir } from "./effective.js";
|
|
43
|
+
import { orgRates } from "./orgrates.js";
|
|
43
44
|
import { SUBAGENT_CANDIDATE, SUBAGENT_CANDIDATE_NAME } from "./subagentpay.js";
|
|
44
45
|
export { SUBAGENT_CANDIDATE, SUBAGENT_CANDIDATE_NAME };
|
|
45
46
|
/** The environment variable the lever writes. */
|
|
@@ -251,11 +252,23 @@ function blend(mix, u, at) {
|
|
|
251
252
|
const rate = (k) => parts.reduce((s, [p, w]) => s + (p[k] * w) / total, 0);
|
|
252
253
|
return { inputPerM: rate("inputPerM"), outputPerM: rate("outputPerM"), cacheReadPerM: rate("cacheReadPerM") };
|
|
253
254
|
}
|
|
254
|
-
/**
|
|
255
|
-
|
|
256
|
-
|
|
255
|
+
/**
|
|
256
|
+
* A request at the baseline mix: prices are linear in each rate, so it costs
|
|
257
|
+
* the mix of what each model would bill it, each priced by its whole card (an
|
|
258
|
+
* organization's row keeps its own cache-write rate, and its multiplier
|
|
259
|
+
* scales the web searches as requestCost does). A mix of one model is
|
|
260
|
+
* exactly requestCost.
|
|
261
|
+
*/
|
|
262
|
+
export function atBaseline(base, u, at, mix) {
|
|
257
263
|
const searches = Number(u?.server_tool_use?.web_search_requests) > 0 ? Number(u.server_tool_use.web_search_requests) : 0;
|
|
258
|
-
|
|
264
|
+
const parts = Object.entries(mix ?? {}).flatMap(([m, w]) => { const c = w > 0 ? rateCard(m, u, at) : undefined; return c ? [{ c, w }] : []; });
|
|
265
|
+
const total = parts.reduce((n, p) => n + p.w, 0);
|
|
266
|
+
if (total > 0) {
|
|
267
|
+
const prompt = promptTokens(u);
|
|
268
|
+
const usd = parts.reduce((n, { c, w }) => n + (w / total) * (usageCost(u, ratesAt(c, prompt)).totalUsd + (c.webSearch ? searches * WEB_SEARCH_USD * (c.scale ?? 1) : 0)), 0);
|
|
269
|
+
return { totalUsd: usd, rates: blend(mix, u, at) ?? base };
|
|
270
|
+
}
|
|
271
|
+
return { totalUsd: usageCost(u, base).totalUsd + searches * WEB_SEARCH_USD * (orgRates()?.multiplier ?? 1), rates: base };
|
|
259
272
|
}
|
|
260
273
|
const cheaper = (a, b) => a.inputPerM < b.inputPerM || (a.inputPerM === b.inputPerM && a.outputPerM < b.outputPerM);
|
|
261
274
|
/**
|
package/dist/subagentpay.d.ts
CHANGED
|
@@ -24,6 +24,7 @@
|
|
|
24
24
|
* window for a hard task) and what the parent would have spent on its own tool
|
|
25
25
|
* calls, so "did not pay" means "did not pay in context", not "was a mistake".
|
|
26
26
|
*/
|
|
27
|
+
import { type ModelPricing } from "./pricing.js";
|
|
27
28
|
/**
|
|
28
29
|
* The model `fix` offers the subagents (subagentmodel.ts): the id the price
|
|
29
30
|
* table knows, which Claude Code's model catalog maps to every provider's
|
|
@@ -72,7 +73,18 @@ export interface PaybackReport {
|
|
|
72
73
|
}>;
|
|
73
74
|
};
|
|
74
75
|
}
|
|
75
|
-
/** A subagent's
|
|
76
|
+
/** A subagent's tokens by what they bill as: uncached input, cache reads, cache writes, output (settled). */
|
|
77
|
+
export interface SubagentTokens {
|
|
78
|
+
input: number;
|
|
79
|
+
read: number;
|
|
80
|
+
write: number;
|
|
81
|
+
output: number;
|
|
82
|
+
}
|
|
83
|
+
/**
|
|
84
|
+
* A subagent's bill (each request as billed, requestCost), steps, startup
|
|
85
|
+
* context, start time, the tool output it read, and the rates its first
|
|
86
|
+
* request billed at.
|
|
87
|
+
*/
|
|
76
88
|
export declare function scanSubagent(path: string): {
|
|
77
89
|
costUsd: number;
|
|
78
90
|
atSonnetUsd: number;
|
|
@@ -83,6 +95,8 @@ export declare function scanSubagent(path: string): {
|
|
|
83
95
|
start: number;
|
|
84
96
|
model?: string;
|
|
85
97
|
writeMult: number;
|
|
98
|
+
rates?: ModelPricing;
|
|
99
|
+
tokens: SubagentTokens;
|
|
86
100
|
};
|
|
87
101
|
export declare function subagentPayback(days?: number, paths?: string[], onProgress?: (done: number, total: number) => void): PaybackReport;
|
|
88
102
|
export declare function renderPayback(r: PaybackReport, top?: number): string;
|
package/dist/subagentpay.js
CHANGED
|
@@ -29,7 +29,8 @@ import { basename, join } from "node:path";
|
|
|
29
29
|
import { forEachLine, listSessions, outputSettler, replyCounter, isClaudeSession } from "./session.js";
|
|
30
30
|
import { subagentFiles, workflowRunInfo } from "./subagents.js";
|
|
31
31
|
import { estimateTokens, formatTokens, realModel } from "./tokens.js";
|
|
32
|
-
import { cacheWriteSplit, formatUsd,
|
|
32
|
+
import { cacheWriteSplit, formatUsd, rateCard, ratesAt, requestCost, writeMultiplier, writePerM } from "./pricing.js";
|
|
33
|
+
import { priceBasis } from "./orgrates.js";
|
|
33
34
|
/**
|
|
34
35
|
* The model `fix` offers the subagents (subagentmodel.ts): the id the price
|
|
35
36
|
* table knows, which Claude Code's model catalog maps to every provider's
|
|
@@ -56,13 +57,31 @@ function blockTokens(content) {
|
|
|
56
57
|
}
|
|
57
58
|
return n;
|
|
58
59
|
}
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
60
|
+
const cheaper = (a, b) => a.inputPerM < b.inputPerM || (a.inputPerM === b.inputPerM && a.outputPerM < b.outputPerM);
|
|
61
|
+
/**
|
|
62
|
+
* A request as billed (requestCost: its tier, fast mode, US-only, its date,
|
|
63
|
+
* web searches) and re-priced for the Sonnet line: at Sonnet 5.5 when that
|
|
64
|
+
* bills it for less, else as billed.
|
|
65
|
+
*/
|
|
66
|
+
function billed(model, u, at) {
|
|
67
|
+
const own = requestCost(model, u, at);
|
|
68
|
+
if (!own)
|
|
69
|
+
return undefined;
|
|
70
|
+
const sonnet = requestCost(SUBAGENT_CANDIDATE, u, at);
|
|
71
|
+
const moved = cheaper(sonnet.rates, own.rates);
|
|
72
|
+
return { usd: own.totalUsd, sonnetUsd: moved ? sonnet.totalUsd : own.totalUsd, rates: own.rates, sonnetRates: moved ? sonnet.rates : own.rates };
|
|
73
|
+
}
|
|
74
|
+
/**
|
|
75
|
+
* A subagent's bill (each request as billed, requestCost), steps, startup
|
|
76
|
+
* context, start time, the tool output it read, and the rates its first
|
|
77
|
+
* request billed at.
|
|
78
|
+
*/
|
|
63
79
|
export function scanSubagent(path) {
|
|
64
|
-
|
|
80
|
+
const tokens = { input: 0, read: 0, write: 0, output: 0 };
|
|
81
|
+
let costUsd = 0, atSonnetUsd = 0, readTokens = 0, task = "", model, firstRates;
|
|
65
82
|
let steps = 0, startup = 0, start = Infinity, writes5m = 0, writes1h = 0;
|
|
83
|
+
// The rates of the last reply, for the output its later rows settle.
|
|
84
|
+
let last;
|
|
66
85
|
const sighting = replyCounter();
|
|
67
86
|
const settle = outputSettler();
|
|
68
87
|
forEachLine(path, (line) => {
|
|
@@ -91,10 +110,11 @@ export function scanSubagent(path) {
|
|
|
91
110
|
if (seen === "repeat") {
|
|
92
111
|
// A later row of the same reply: only its final output count is new.
|
|
93
112
|
const more = settle(e, false);
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
113
|
+
if (more)
|
|
114
|
+
tokens.output += more;
|
|
115
|
+
if (more && last) {
|
|
116
|
+
costUsd += (more * last.rates.outputPerM) / 1e6;
|
|
117
|
+
atSonnetUsd += (more * last.sonnetRates.outputPerM) / 1e6;
|
|
98
118
|
}
|
|
99
119
|
return;
|
|
100
120
|
}
|
|
@@ -110,19 +130,25 @@ export function scanSubagent(path) {
|
|
|
110
130
|
if (steps === 0)
|
|
111
131
|
startup = n("input_tokens") + n("cache_creation_input_tokens") + n("cache_read_input_tokens");
|
|
112
132
|
steps++;
|
|
133
|
+
tokens.input += n("input_tokens");
|
|
134
|
+
tokens.read += n("cache_read_input_tokens");
|
|
135
|
+
tokens.write += n("cache_creation_input_tokens");
|
|
136
|
+
tokens.output += n("output_tokens");
|
|
113
137
|
const w = cacheWriteSplit(u);
|
|
114
138
|
writes5m += w.fiveMinute;
|
|
115
139
|
writes1h += w.oneHour;
|
|
116
|
-
const
|
|
117
|
-
|
|
140
|
+
const b = billed(model, u, Number.isFinite(at) ? at : undefined);
|
|
141
|
+
last = b;
|
|
142
|
+
if (!b)
|
|
118
143
|
return;
|
|
119
|
-
|
|
120
|
-
|
|
144
|
+
firstRates ??= b.rates;
|
|
145
|
+
costUsd += b.usd;
|
|
146
|
+
atSonnetUsd += b.sonnetUsd;
|
|
121
147
|
});
|
|
122
|
-
return { costUsd, atSonnetUsd, readTokens, task: task.replace(/\s+/g, " ").slice(0, 90), steps, startup, start, model, writeMult: writeMultiplier(writes5m, writes1h) };
|
|
148
|
+
return { costUsd, atSonnetUsd, readTokens, task: task.replace(/\s+/g, " ").slice(0, 90), steps, startup, start, model, writeMult: writeMultiplier(writes5m, writes1h), ...(firstRates ? { rates: firstRates } : {}), tokens };
|
|
123
149
|
}
|
|
124
150
|
function scanParent(path, ids) {
|
|
125
|
-
const view = { requests: [], prompts: [], compactions: [], writes5m: 0, writes1h: 0, returns: new Map() };
|
|
151
|
+
const view = { requests: [], prompts: [], models: [], billing: [], compactions: [], writes5m: 0, writes1h: 0, returns: new Map() };
|
|
126
152
|
let lastId;
|
|
127
153
|
forEachLine(path, (line) => {
|
|
128
154
|
const hits = [...ids].filter((id) => line.includes(id));
|
|
@@ -143,15 +169,17 @@ function scanParent(path, ids) {
|
|
|
143
169
|
// Placeholder messages Claude Code writes itself ("<synthetic>") are not API requests.
|
|
144
170
|
if (e?.type === "assistant" && !e.isSidechain && e.message?.usage && e.message.id !== lastId && realModel(e.message.model)) {
|
|
145
171
|
lastId = e.message.id;
|
|
172
|
+
view.model = realModel(e.message.model) ?? view.model;
|
|
146
173
|
if (Number.isFinite(at)) {
|
|
147
174
|
const u = e.message.usage;
|
|
148
175
|
view.requests.push(at);
|
|
149
176
|
view.prompts.push((u.input_tokens ?? 0) + (u.cache_creation_input_tokens ?? 0) + (u.cache_read_input_tokens ?? 0));
|
|
177
|
+
view.billing.push({ speed: u.speed, inference_geo: u.inference_geo });
|
|
178
|
+
view.models.push(view.model);
|
|
150
179
|
}
|
|
151
180
|
const w = cacheWriteSplit(e.message.usage);
|
|
152
181
|
view.writes5m += w.fiveMinute;
|
|
153
182
|
view.writes1h += w.oneHour;
|
|
154
|
-
view.model = realModel(e.message.model) ?? view.model;
|
|
155
183
|
return;
|
|
156
184
|
}
|
|
157
185
|
if (!hits.length || !Number.isFinite(at) || e?.type === "assistant")
|
|
@@ -213,7 +241,6 @@ export function subagentPayback(days = 30, paths, onProgress) {
|
|
|
213
241
|
});
|
|
214
242
|
const ids = new Set(metas.flatMap((m) => [m.id, m.meta.toolUseId].filter((x) => Boolean(x))));
|
|
215
243
|
const view = scanParent(parent, ids);
|
|
216
|
-
const price = pricingFor(view.model);
|
|
217
244
|
// What the parent pays to write a token to its cache, from its own usage.
|
|
218
245
|
const parentWrite = writeMultiplier(view.writes5m, view.writes1h);
|
|
219
246
|
for (const m of metas) {
|
|
@@ -230,18 +257,24 @@ export function subagentPayback(days = 30, paths, onProgress) {
|
|
|
230
257
|
const laterRequests = view.requests.filter((t) => t > from && t < until).length;
|
|
231
258
|
const carried = Math.max(0, s.readTokens - returnedTokens);
|
|
232
259
|
// The parent's context when the subagent started: its last request before then.
|
|
233
|
-
let parentContextTokens = 0;
|
|
234
|
-
for (let i = 0; i < view.requests.length && view.requests[i] <= s.start; i++)
|
|
260
|
+
let parentContextTokens = 0, last = -1;
|
|
261
|
+
for (let i = 0; i < view.requests.length && view.requests[i] <= s.start; i++) {
|
|
235
262
|
parentContextTokens = view.prompts[i];
|
|
236
|
-
|
|
263
|
+
last = i;
|
|
264
|
+
}
|
|
265
|
+
// The parent's rates as its next request would have billed them (rateCard: its tier at that context, fast mode and US-only as its last request, the day).
|
|
266
|
+
// The parent as it ran then: a session that moved to another model later (Fable 5.1 to 5.2) is priced on the one it was on.
|
|
267
|
+
const card = rateCard(last >= 0 ? view.models[last] : view.model, last >= 0 ? view.billing[last] : undefined, Number.isFinite(s.start) ? s.start : undefined);
|
|
268
|
+
const price = card && ratesAt(card, parentContextTokens);
|
|
269
|
+
const sub = s.rates ?? price;
|
|
237
270
|
let inParentUsd = s.costUsd, avoidedUsd = 0;
|
|
238
271
|
if (price && sub) {
|
|
239
272
|
// Each side's cache writes at its own TTL mix (subagents write at 5
|
|
240
273
|
// minutes, the main thread mostly at 1 hour) and reads at its model's rate.
|
|
241
|
-
const startupUsd = (s.startup * (s.writeMult
|
|
274
|
+
const startupUsd = (s.startup * (writePerM(sub, s.writeMult) + Math.max(0, s.steps - 1) * sub.cacheReadPerM)) / 1e6;
|
|
242
275
|
const work = Math.max(0, s.costUsd - startupUsd) * (price.inputPerM / sub.inputPerM);
|
|
243
276
|
const rideAlong = (parentContextTokens * s.steps * price.cacheReadPerM) / 1e6;
|
|
244
|
-
avoidedUsd = (carried * (parentWrite
|
|
277
|
+
avoidedUsd = (carried * (writePerM(price, parentWrite) + laterRequests * price.cacheReadPerM)) / 1e6;
|
|
245
278
|
inParentUsd = work + rideAlong + avoidedUsd;
|
|
246
279
|
}
|
|
247
280
|
out.push({
|
|
@@ -271,7 +304,7 @@ export function subagentPayback(days = 30, paths, onProgress) {
|
|
|
271
304
|
}
|
|
272
305
|
/** The workflow agents' lines of `subagents`: what they cost, by run. */
|
|
273
306
|
function renderWorkflows(w, top) {
|
|
274
|
-
const out = ["", `Workflow agents: ${w.agents} in ${w.runs} workflow run${w.runs === 1 ? "" : "s"}, ${formatUsd(w.costUsd)}
|
|
307
|
+
const out = ["", `Workflow agents: ${w.agents} in ${w.runs} workflow run${w.runs === 1 ? "" : "s"}, ${formatUsd(w.costUsd)} ${priceBasis(false)} (each run's work handed off whole, so not weighed against the parent).`];
|
|
275
308
|
if (w.costUsd - w.atSonnetUsd >= 1)
|
|
276
309
|
out.push(`At ${SUBAGENT_CANDIDATE_NAME} (where they ran on a pricier model): ~${formatUsd(w.atSonnetUsd)}, token counts as recorded: an estimate.`);
|
|
277
310
|
for (const r of w.byRun.slice(0, top))
|
|
@@ -288,7 +321,7 @@ export function renderPayback(r, top = 8) {
|
|
|
288
321
|
const cost = all.reduce((s, a) => s + a.costUsd, 0);
|
|
289
322
|
const inParent = all.reduce((s, a) => s + a.inParentUsd, 0);
|
|
290
323
|
const paid = all.filter((a) => a.netUsd > 0);
|
|
291
|
-
out.push(`Last ${r.days} days: ${all.length} subagents in ${r.sessions} sessions cost ${formatUsd(cost)}
|
|
324
|
+
out.push(`Last ${r.days} days: ${all.length} subagents in ${r.sessions} sessions cost ${formatUsd(cost)} ${priceBasis(false)}.`, `The same work done in the parent would have cost ~${formatUsd(inParent)}: ${paid.length} of ${all.length} were cheaper as subagents, net ${inParent - cost >= 0 ? "+" : "−"}${formatUsd(Math.abs(inParent - cost))}.`);
|
|
292
325
|
const sonnet = all.reduce((s, a) => s + a.atSonnetUsd, 0);
|
|
293
326
|
if (cost - sonnet >= 1)
|
|
294
327
|
out.push(`At ${SUBAGENT_CANDIDATE_NAME} (where they ran on a pricier model) the same requests come to ~${formatUsd(sonnet)}, token counts as recorded: an estimate. context-doctor fix says which of them a setting moves.`);
|
package/dist/subagents.js
CHANGED
|
@@ -17,6 +17,7 @@ import { readdirSync, readFileSync, statSync } from "node:fs";
|
|
|
17
17
|
import { basename, join } from "node:path";
|
|
18
18
|
import { formatTokens } from "./tokens.js";
|
|
19
19
|
import { formatUsd, requestCost } from "./pricing.js";
|
|
20
|
+
import { orgRatesLine } from "./orgrates.js";
|
|
20
21
|
import { forEachLine, outputSettler, replyCounter } from "./session.js";
|
|
21
22
|
import { realModel } from "./tokens.js";
|
|
22
23
|
/** Where Claude Code keeps a session's subagents: beside the transcript, under its id. */
|
|
@@ -233,6 +234,9 @@ export function renderSubagents(report, parentInputUsd, top = 5, options = {}) {
|
|
|
233
234
|
return null;
|
|
234
235
|
const lines = [];
|
|
235
236
|
lines.push("Subagents (their own windows, your bill)");
|
|
237
|
+
const org = orgRatesLine();
|
|
238
|
+
if (org)
|
|
239
|
+
lines.push(org);
|
|
236
240
|
lines.push("─".repeat(56));
|
|
237
241
|
const cost = report.unpriced === 0 ? formatUsd(report.totalCostUsd) : `${formatUsd(report.totalCostUsd)}+ (${report.unpriced} unpriced)`;
|
|
238
242
|
lines.push(`${report.agents.length} subagent(s) made ${report.agents.reduce((t, a) => t + a.calls, 0)} API calls: ` +
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The working folder for a program run by its bare name (git, pdftotext,
|
|
3
|
+
* unzip, sqlite3, netstat, schtasks…).
|
|
4
|
+
*
|
|
5
|
+
* On Windows, Node (libuv) looks a bare name up in the child's working
|
|
6
|
+
* folder before PATH, as cmd.exe does. Run from a project, `pack .`, the
|
|
7
|
+
* MCP server's pack_context (whose working folder is the project its client
|
|
8
|
+
* opened) and `ci` ran a git.exe committed to that repository, or a
|
|
9
|
+
* pdftotext.exe beside the documents, instead of the real one. These
|
|
10
|
+
* programs get every path absolute (git with -C), so they run from the
|
|
11
|
+
* user's own temp folder instead, where a clone or a download cannot put a
|
|
12
|
+
* program by that name.
|
|
13
|
+
*/
|
|
14
|
+
export declare function toolCwd(): string;
|
package/dist/toolcwd.js
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The working folder for a program run by its bare name (git, pdftotext,
|
|
3
|
+
* unzip, sqlite3, netstat, schtasks…).
|
|
4
|
+
*
|
|
5
|
+
* On Windows, Node (libuv) looks a bare name up in the child's working
|
|
6
|
+
* folder before PATH, as cmd.exe does. Run from a project, `pack .`, the
|
|
7
|
+
* MCP server's pack_context (whose working folder is the project its client
|
|
8
|
+
* opened) and `ci` ran a git.exe committed to that repository, or a
|
|
9
|
+
* pdftotext.exe beside the documents, instead of the real one. These
|
|
10
|
+
* programs get every path absolute (git with -C), so they run from the
|
|
11
|
+
* user's own temp folder instead, where a clone or a download cannot put a
|
|
12
|
+
* program by that name.
|
|
13
|
+
*/
|
|
14
|
+
import { tmpdir } from "node:os";
|
|
15
|
+
export function toolCwd() {
|
|
16
|
+
return tmpdir();
|
|
17
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "context-doctor",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.47.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",
|