context-doctor 0.43.0 → 0.45.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 +4 -2
- package/dist/budget.d.ts +23 -3
- package/dist/budget.js +184 -50
- package/dist/cache.js +5 -4
- package/dist/cachemisses.js +1 -1
- package/dist/cachettl.d.ts +5 -1
- package/dist/cachettl.js +16 -29
- package/dist/ci.js +18 -2
- package/dist/cli.js +16 -12
- package/dist/codexcompact.d.ts +24 -3
- package/dist/codexcompact.js +221 -48
- package/dist/coldresume.js +16 -8
- package/dist/compactwindow.js +14 -9
- package/dist/cursor.d.ts +10 -0
- package/dist/cursor.js +20 -0
- package/dist/doctor.d.ts +9 -0
- package/dist/doctor.js +52 -0
- package/dist/extract.d.ts +2 -2
- package/dist/extract.js +14 -3
- package/dist/fanout.js +4 -2
- package/dist/fix.d.ts +8 -1
- package/dist/fix.js +59 -13
- package/dist/hook.js +45 -15
- package/dist/httpguard.d.ts +9 -1
- package/dist/httpguard.js +5 -4
- package/dist/install.js +56 -19
- package/dist/lens.js +7 -7
- package/dist/limits.d.ts +17 -4
- package/dist/limits.js +41 -29
- package/dist/mcp.js +63 -63
- package/dist/mcpclient.js +19 -19
- package/dist/mcpschema.js +10 -12
- package/dist/overhead.d.ts +7 -2
- package/dist/overhead.js +11 -3
- package/dist/pack.js +87 -23
- package/dist/pricing.d.ts +125 -6
- package/dist/pricing.js +304 -59
- package/dist/proxy.d.ts +26 -1
- package/dist/proxy.js +45 -5
- package/dist/prune.d.ts +8 -0
- package/dist/prune.js +73 -10
- package/dist/savings.js +17 -9
- package/dist/scan.d.ts +7 -1
- package/dist/scan.js +19 -1
- package/dist/sessionprice.d.ts +9 -2
- package/dist/sessionprice.js +95 -36
- package/dist/settingsedit.js +3 -2
- package/dist/spend.d.ts +75 -10
- package/dist/spend.js +279 -37
- package/dist/statusline.d.ts +10 -2
- package/dist/statusline.js +17 -8
- package/dist/subagentmodel.d.ts +2 -2
- package/dist/subagentmodel.js +42 -25
- package/dist/subagentpay.d.ts +17 -0
- package/dist/subagentpay.js +41 -2
- package/dist/subagents.d.ts +24 -0
- package/dist/subagents.js +93 -27
- package/dist/tasks.js +9 -6
- package/dist/tooloutput.d.ts +2 -0
- package/dist/tooloutput.js +16 -5
- package/package.json +1 -1
package/dist/subagentmodel.js
CHANGED
|
@@ -34,10 +34,11 @@ import { existsSync, readdirSync, readFileSync, realpathSync, statSync } from "n
|
|
|
34
34
|
import { homedir } from "node:os";
|
|
35
35
|
import { dirname, join, resolve } from "node:path";
|
|
36
36
|
import { pick, rowsOf, slimUsage } from "./scan.js";
|
|
37
|
-
import { pricingFor, usageCost } from "./pricing.js";
|
|
37
|
+
import { pricingFor, rateCard, ratesAt, requestCost, usageCost, WEB_SEARCH_USD } from "./pricing.js";
|
|
38
38
|
import { realModel } from "./tokens.js";
|
|
39
39
|
import { claudeDir } from "./claudedir.js";
|
|
40
40
|
import { subagentTranscripts } from "./cachettl.js";
|
|
41
|
+
import { workflowRunOf } from "./subagents.js";
|
|
41
42
|
import { managedDir } from "./effective.js";
|
|
42
43
|
import { SUBAGENT_CANDIDATE, SUBAGENT_CANDIDATE_NAME } from "./subagentpay.js";
|
|
43
44
|
export { SUBAGENT_CANDIDATE, SUBAGENT_CANDIDATE_NAME };
|
|
@@ -56,6 +57,11 @@ const BUILT_IN = {
|
|
|
56
57
|
fork: "inherit",
|
|
57
58
|
"claude-code-guide": "haiku",
|
|
58
59
|
"statusline-setup": "sonnet",
|
|
60
|
+
// A workflow agent (subagents/workflows/<run>/): read from the 2.1.317 binary, its model is the
|
|
61
|
+
// script's agent() `model`, then CLAUDE_CODE_WORKFLOW_SUBAGENT_MODEL, then this lever's
|
|
62
|
+
// CLAUDE_CODE_SUBAGENT_MODEL, then the main conversation's. Scripts seldom name one (none of the
|
|
63
|
+
// author's 9 runs did), so the variable moves them.
|
|
64
|
+
"workflow-subagent": undefined,
|
|
59
65
|
};
|
|
60
66
|
/** Types that only read (no Edit or Write): the ones a smaller model is most often enough for. */
|
|
61
67
|
const READ_ONLY = new Set(["Explore", "Plan"]);
|
|
@@ -66,7 +72,7 @@ const READ_ONLY = new Set(["Explore", "Plan"]);
|
|
|
66
72
|
* last row); the working folder once, to find the project's agent files.
|
|
67
73
|
*/
|
|
68
74
|
export const SUBAGENT_ROWS = {
|
|
69
|
-
id: "subagent-requests.
|
|
75
|
+
id: "subagent-requests.2",
|
|
70
76
|
init: () => ({ out: {}, cwd: false }),
|
|
71
77
|
line(raw, row, out, st) {
|
|
72
78
|
const usage = raw.includes('"usage"');
|
|
@@ -227,19 +233,30 @@ export function agentTypeOf(transcript) {
|
|
|
227
233
|
catch {
|
|
228
234
|
/* older Claude Code: no meta */
|
|
229
235
|
}
|
|
230
|
-
|
|
236
|
+
// A workflow agent's folder says what it is when its meta file is missing.
|
|
237
|
+
return workflowRunOf(transcript) ? "workflow-subagent" : "unknown";
|
|
231
238
|
}
|
|
232
239
|
const tokens = (v) => (typeof v === "number" && Number.isFinite(v) && v > 0 ? v : 0);
|
|
233
240
|
const promptTokens = (u) => tokens(u?.input_tokens) + tokens(u?.cache_read_input_tokens) + tokens(u?.cache_creation_input_tokens);
|
|
234
|
-
/**
|
|
235
|
-
|
|
236
|
-
|
|
241
|
+
/**
|
|
242
|
+
* The rates of a mix of models (shares adding to 1), each as it would bill
|
|
243
|
+
* `u` (its tier, US-only: rateCard) when given; undefined when none has a price.
|
|
244
|
+
*/
|
|
245
|
+
function blend(mix, u, at) {
|
|
246
|
+
const rates = (m) => { const c = rateCard(m, u, at); return c && ratesAt(c, promptTokens(u ?? {})); };
|
|
247
|
+
const parts = Object.entries(mix).map(([m, w]) => [rates(m), w]).filter((x) => !!x[0] && x[1] > 0);
|
|
237
248
|
const total = parts.reduce((s, [, w]) => s + w, 0);
|
|
238
249
|
if (!(total > 0))
|
|
239
250
|
return undefined;
|
|
240
251
|
const rate = (k) => parts.reduce((s, [p, w]) => s + (p[k] * w) / total, 0);
|
|
241
252
|
return { inputPerM: rate("inputPerM"), outputPerM: rate("outputPerM"), cacheReadPerM: rate("cacheReadPerM") };
|
|
242
253
|
}
|
|
254
|
+
/** A request at the baseline mix (prices are linear in each rate: the blend of its costs), web searches as any Claude model bills them. */
|
|
255
|
+
function atBaseline(base, u, at, mix) {
|
|
256
|
+
const rates = (mix && blend(mix, u, at)) || base;
|
|
257
|
+
const searches = Number(u?.server_tool_use?.web_search_requests) > 0 ? Number(u.server_tool_use.web_search_requests) : 0;
|
|
258
|
+
return { totalUsd: usageCost(u, rates).totalUsd + searches * WEB_SEARCH_USD, rates };
|
|
259
|
+
}
|
|
243
260
|
const cheaper = (a, b) => a.inputPerM < b.inputPerM || (a.inputPerM === b.inputPerM && a.outputPerM < b.outputPerM);
|
|
244
261
|
/**
|
|
245
262
|
* Replay every subagent request in [since, until): as billed, and with the
|
|
@@ -251,7 +268,6 @@ const cheaper = (a, b) => a.inputPerM < b.inputPerM || (a.inputPerM === b.inputP
|
|
|
251
268
|
export function replaySubagentModels(opts) {
|
|
252
269
|
const candidate = opts.candidate ?? SUBAGENT_CANDIDATE;
|
|
253
270
|
const cand = pricingFor(candidate);
|
|
254
|
-
const haiku = pricingFor(HAIKU);
|
|
255
271
|
const base = opts.baseline ? blend(opts.baseline) : undefined;
|
|
256
272
|
const until = opts.until ?? Infinity;
|
|
257
273
|
const home = opts.home ?? homedir();
|
|
@@ -297,9 +313,9 @@ export function replaySubagentModels(opts) {
|
|
|
297
313
|
continue;
|
|
298
314
|
t.billedUsd += (r.more * q.billed.outputPerM) / 1e6;
|
|
299
315
|
t.atCandidateUsd += (r.more * q.other.outputPerM) / 1e6;
|
|
300
|
-
t.atHaikuUsd += (r.more * haiku.outputPerM) / 1e6;
|
|
316
|
+
t.atHaikuUsd += (r.more * q.haiku.outputPerM) / 1e6;
|
|
301
317
|
if (how.moves)
|
|
302
|
-
add(beforeBy, q.model, (r.more * cand.outputPerM) / 1e6);
|
|
318
|
+
add(beforeBy, q.model, (r.more * q.cand.outputPerM) / 1e6);
|
|
303
319
|
continue;
|
|
304
320
|
}
|
|
305
321
|
if (r?.t !== "r")
|
|
@@ -317,28 +333,31 @@ export function replaySubagentModels(opts) {
|
|
|
317
333
|
seen.add(r.id);
|
|
318
334
|
}
|
|
319
335
|
const price = pricingFor(model);
|
|
320
|
-
|
|
336
|
+
const u = r.usage;
|
|
337
|
+
// Each arm as that model would bill these tokens (requestCost): its tier (Haiku 5.5 over 100k), US-only, web searches.
|
|
338
|
+
const asBilled = requestCost(model, u, at);
|
|
339
|
+
if (!price || !asBilled) {
|
|
321
340
|
unpriced++;
|
|
322
341
|
continue;
|
|
323
342
|
}
|
|
324
|
-
const
|
|
325
|
-
const
|
|
326
|
-
const
|
|
343
|
+
const atCand = requestCost(candidate, u, at);
|
|
344
|
+
const atHaiku = requestCost(HAIKU, u, at);
|
|
345
|
+
const billed = asBilled.totalUsd;
|
|
327
346
|
const move = how.moves && (base ? true : cheaper(cand, price));
|
|
328
|
-
const other = move ?
|
|
347
|
+
const other = move ? base ? atBaseline(base, u, at, opts.baseline) : atCand : asBilled;
|
|
329
348
|
t.requests++;
|
|
330
349
|
counted = true;
|
|
331
350
|
t.billedUsd += billed;
|
|
332
|
-
t.atCandidateUsd += move ?
|
|
333
|
-
t.atHaikuUsd +=
|
|
351
|
+
t.atCandidateUsd += move ? other.totalUsd : billed;
|
|
352
|
+
t.atHaikuUsd += atHaiku.totalUsd;
|
|
334
353
|
if (promptTokens(u) > HAIKU_TIER)
|
|
335
354
|
t.over100k++;
|
|
336
355
|
if (move)
|
|
337
356
|
add(movedBy, model, billed);
|
|
338
357
|
if (how.moves)
|
|
339
|
-
add(beforeBy, model,
|
|
358
|
+
add(beforeBy, model, atCand.totalUsd);
|
|
340
359
|
if (r.id)
|
|
341
|
-
priced.set(r.id, { billed:
|
|
360
|
+
priced.set(r.id, { billed: asBilled.rates, other: other.rates, haiku: atHaiku.rates, cand: atCand.rates, model });
|
|
342
361
|
}
|
|
343
362
|
if (counted)
|
|
344
363
|
t.agents++;
|
|
@@ -377,6 +396,9 @@ export function renderSubagentTypes(r) {
|
|
|
377
396
|
const head = `${t.type.slice(0, 19).padEnd(20)}${String(t.agents).padStart(6)}${usd(t.billedUsd).padStart(11)}`;
|
|
378
397
|
out.push(head + (t.moves ? usd(t.atCandidateUsd).padStart(col.length + 3) : ` unchanged: ${t.why}`));
|
|
379
398
|
}
|
|
399
|
+
// Workflow agents follow this variable too; Claude Code has one of their own, which this lever does not set.
|
|
400
|
+
if (r.byType.some((t) => t.type === "workflow-subagent"))
|
|
401
|
+
out.push("Workflow agents move with it unless the workflow's script names a model. For them alone: CLAUDE_CODE_WORKFLOW_SUBAGENT_MODEL (it also overrides a model the script names).");
|
|
380
402
|
const ro = r.byType.filter((t) => t.readOnly);
|
|
381
403
|
if (ro.length) {
|
|
382
404
|
const billed = ro.reduce((s, t) => s + t.billedUsd, 0);
|
|
@@ -384,13 +406,8 @@ export function renderSubagentTypes(r) {
|
|
|
384
406
|
const over = ro.reduce((s, t) => s + t.over100k, 0);
|
|
385
407
|
const reqs = ro.reduce((s, t) => s + t.requests, 0);
|
|
386
408
|
const what = `Read-only work (${ro.map((t) => t.type).join(", ")}, ${usd(billed)}) at Haiku 5.5`;
|
|
387
|
-
// Haiku 5.5's rates hold to 100k-token prompts;
|
|
388
|
-
|
|
389
|
-
out.push(`${what}: ~${usd(haiku)}.`);
|
|
390
|
-
else if (over <= 0.1 * reqs)
|
|
391
|
-
out.push(`${what}: over ~${usd(haiku)} (${over} of ${reqs} requests had prompts over 100k tokens, which Haiku bills higher).`);
|
|
392
|
-
else
|
|
393
|
-
out.push(`${what}: not priced, ${over} of ${reqs} requests had prompts over 100k tokens, where Haiku bills a higher rate.`);
|
|
409
|
+
// Haiku 5.5's rates hold to 100k-token prompts; a longer one bills all of it at 5x, priced in.
|
|
410
|
+
out.push(`${what}: ~${usd(haiku)}${over ? ` (${over} of ${reqs} requests had prompts over 100k tokens, at Haiku's higher rates for those)` : ""}.`);
|
|
394
411
|
out.push("Only an agent of your own runs there (`model: haiku` in its file); the built-ins keep the main conversation's model.");
|
|
395
412
|
}
|
|
396
413
|
return out;
|
package/dist/subagentpay.d.ts
CHANGED
|
@@ -54,6 +54,23 @@ export interface PaybackReport {
|
|
|
54
54
|
days: number;
|
|
55
55
|
sessions: number;
|
|
56
56
|
subagents: SubagentPayback[];
|
|
57
|
+
/**
|
|
58
|
+
* Workflow agents (subagents/workflows/<run>/): their bill, by run. Not
|
|
59
|
+
* weighed against the parent: a workflow is work the parent hands off
|
|
60
|
+
* whole, not a read it would otherwise do itself.
|
|
61
|
+
*/
|
|
62
|
+
workflows?: {
|
|
63
|
+
runs: number;
|
|
64
|
+
agents: number;
|
|
65
|
+
costUsd: number;
|
|
66
|
+
atSonnetUsd: number;
|
|
67
|
+
byRun: Array<{
|
|
68
|
+
name: string;
|
|
69
|
+
agents: number;
|
|
70
|
+
costUsd: number;
|
|
71
|
+
start: number;
|
|
72
|
+
}>;
|
|
73
|
+
};
|
|
57
74
|
}
|
|
58
75
|
/** A subagent's bill (usage priced as the cache bills it), steps, startup context, start time and the tool output it read. */
|
|
59
76
|
export declare function scanSubagent(path: string): {
|
package/dist/subagentpay.js
CHANGED
|
@@ -27,6 +27,7 @@
|
|
|
27
27
|
import { existsSync, readdirSync, readFileSync } from "node:fs";
|
|
28
28
|
import { basename, join } from "node:path";
|
|
29
29
|
import { forEachLine, listSessions, outputSettler, replyCounter, isClaudeSession } from "./session.js";
|
|
30
|
+
import { subagentFiles, workflowRunInfo } from "./subagents.js";
|
|
30
31
|
import { estimateTokens, formatTokens, realModel } from "./tokens.js";
|
|
31
32
|
import { cacheWriteSplit, formatUsd, pricingFor, usageCost, writeMultiplier } from "./pricing.js";
|
|
32
33
|
/**
|
|
@@ -171,8 +172,29 @@ export function subagentPayback(days = 30, paths, onProgress) {
|
|
|
171
172
|
const sessions = paths ?? listSessions(10_000).filter((s) => isClaudeSession(s) && s.modifiedAt.getTime() >= since).map((s) => s.path);
|
|
172
173
|
const out = [];
|
|
173
174
|
let withSubagents = 0;
|
|
175
|
+
const runs = new Map();
|
|
174
176
|
for (const [index, parent] of sessions.entries()) {
|
|
175
177
|
onProgress?.(index, sessions.length);
|
|
178
|
+
for (const f of subagentFiles(parent)) {
|
|
179
|
+
if (!f.run)
|
|
180
|
+
continue;
|
|
181
|
+
let w;
|
|
182
|
+
try {
|
|
183
|
+
w = scanSubagent(f.file);
|
|
184
|
+
}
|
|
185
|
+
catch {
|
|
186
|
+
continue;
|
|
187
|
+
}
|
|
188
|
+
// Each by its own start, as the Agent tool's below.
|
|
189
|
+
if (!(w.steps > 0) || (Number.isFinite(w.start) && w.start < since))
|
|
190
|
+
continue;
|
|
191
|
+
const key = `${parent}\u0000${f.run}`;
|
|
192
|
+
const r = runs.get(key) ?? runs.set(key, { name: workflowRunInfo(parent, f.run).name ?? f.run, agents: 0, costUsd: 0, atSonnetUsd: 0, start: w.start }).get(key);
|
|
193
|
+
r.agents++;
|
|
194
|
+
r.costUsd += w.costUsd;
|
|
195
|
+
r.atSonnetUsd += w.atSonnetUsd;
|
|
196
|
+
r.start = Math.min(r.start, w.start);
|
|
197
|
+
}
|
|
176
198
|
const dir = join(parent.replace(/\.jsonl$/, ""), "subagents");
|
|
177
199
|
if (!existsSync(dir))
|
|
178
200
|
continue;
|
|
@@ -241,13 +263,28 @@ export function subagentPayback(days = 30, paths, onProgress) {
|
|
|
241
263
|
if (out.length > before)
|
|
242
264
|
withSubagents++;
|
|
243
265
|
}
|
|
244
|
-
|
|
266
|
+
const byRun = [...runs.values()].sort((a, b) => b.costUsd - a.costUsd);
|
|
267
|
+
const workflows = byRun.length
|
|
268
|
+
? { runs: byRun.length, agents: byRun.reduce((n, r) => n + r.agents, 0), costUsd: byRun.reduce((n, r) => n + r.costUsd, 0), atSonnetUsd: byRun.reduce((n, r) => n + r.atSonnetUsd, 0), byRun: byRun.map(({ atSonnetUsd: _s, ...r }) => r) }
|
|
269
|
+
: undefined;
|
|
270
|
+
return { days, sessions: withSubagents, subagents: out, ...(workflows ? { workflows } : {}) };
|
|
271
|
+
}
|
|
272
|
+
/** The workflow agents' lines of `subagents`: what they cost, by run. */
|
|
273
|
+
function renderWorkflows(w, top) {
|
|
274
|
+
const out = ["", `Workflow agents: ${w.agents} in ${w.runs} workflow run${w.runs === 1 ? "" : "s"}, ${formatUsd(w.costUsd)} at list price (each run's work handed off whole, so not weighed against the parent).`];
|
|
275
|
+
if (w.costUsd - w.atSonnetUsd >= 1)
|
|
276
|
+
out.push(`At ${SUBAGENT_CANDIDATE_NAME} (where they ran on a pricier model): ~${formatUsd(w.atSonnetUsd)}, token counts as recorded: an estimate.`);
|
|
277
|
+
for (const r of w.byRun.slice(0, top))
|
|
278
|
+
out.push(` ${formatUsd(r.costUsd).padStart(9)} ${String(r.agents).padStart(3)} agents ${r.name.slice(0, 60)}`);
|
|
279
|
+
if (w.byRun.length > top)
|
|
280
|
+
out.push(` … and ${w.byRun.length - top} more`);
|
|
281
|
+
return out;
|
|
245
282
|
}
|
|
246
283
|
export function renderPayback(r, top = 8) {
|
|
247
284
|
const out = ["DO SUBAGENTS PAY FOR THEMSELVES?", "═".repeat(56)];
|
|
248
285
|
const all = r.subagents;
|
|
249
286
|
if (!all.length)
|
|
250
|
-
return [...out, `No subagents in the last ${r.days} days
|
|
287
|
+
return [...out, `No subagents in the last ${r.days} days.`, ...(r.workflows ? renderWorkflows(r.workflows, top) : [])].join("\n");
|
|
251
288
|
const cost = all.reduce((s, a) => s + a.costUsd, 0);
|
|
252
289
|
const inParent = all.reduce((s, a) => s + a.inParentUsd, 0);
|
|
253
290
|
const paid = all.filter((a) => a.netUsd > 0);
|
|
@@ -277,5 +314,7 @@ export function renderPayback(r, top = 8) {
|
|
|
277
314
|
out.push(` −${formatUsd(-a.netUsd).padEnd(8)} ${String(a.steps).padStart(3)} steps, parent at ~${formatTokens(a.parentContextTokens)}, read ~${formatTokens(a.readTokens)} ${a.task}`);
|
|
278
315
|
}
|
|
279
316
|
out.push("", "Counts context only: a subagent can still be worth it for parallel time or a clean window on a hard task.", "Subagents pay most when the parent is already large (every step there re-reads it) and least for short tasks from a small parent.");
|
|
317
|
+
if (r.workflows)
|
|
318
|
+
out.push(...renderWorkflows(r.workflows, top));
|
|
280
319
|
return out.join("\n");
|
|
281
320
|
}
|
package/dist/subagents.d.ts
CHANGED
|
@@ -37,9 +37,33 @@ export interface SubagentReport {
|
|
|
37
37
|
totalCostUsd: number;
|
|
38
38
|
/** Agents whose model has no price on file, so the total undercounts. */
|
|
39
39
|
unpriced: number;
|
|
40
|
+
/** How many of `agents` are workflow agents (subagents/workflows/<run>/), in how many runs. */
|
|
41
|
+
workflowAgents?: number;
|
|
42
|
+
workflowRuns?: number;
|
|
40
43
|
}
|
|
41
44
|
/** Where Claude Code keeps a session's subagents: beside the transcript, under its id. */
|
|
42
45
|
export declare function subagentDir(transcriptPath: string): string;
|
|
46
|
+
/**
|
|
47
|
+
* Every subagent transcript of a session: the Agent tool's
|
|
48
|
+
* (`subagents/agent-*.jsonl`) and the workflow agents'
|
|
49
|
+
* (`subagents/workflows/<run>/agent-*.jsonl`, one folder per workflow run,
|
|
50
|
+
* the run's own record in `<session>/workflows/<run>.json`). Workflow agents
|
|
51
|
+
* bill to the session like any subagent, and every reader skipped their
|
|
52
|
+
* folder: on the author's machine, 804 transcripts and ~$1,354 in 30 days.
|
|
53
|
+
* `since`: only files written since then. `run`: the workflow run's id.
|
|
54
|
+
*/
|
|
55
|
+
export declare function subagentFiles(transcriptPath: string, since?: number): Array<{
|
|
56
|
+
file: string;
|
|
57
|
+
run?: string;
|
|
58
|
+
}>;
|
|
59
|
+
/** The workflow run a subagent transcript belongs to (its folder under subagents/workflows), or undefined. */
|
|
60
|
+
export declare function workflowRunOf(file: string): string | undefined;
|
|
61
|
+
/** A workflow run's own record, `<session>/workflows/<run>.json`: its name and default model, when Claude Code wrote one. */
|
|
62
|
+
export declare function workflowRunInfo(transcriptPath: string, run: string): {
|
|
63
|
+
name?: string;
|
|
64
|
+
model?: string;
|
|
65
|
+
status?: string;
|
|
66
|
+
};
|
|
43
67
|
/** Account for every subagent of a session, or null when there are none. */
|
|
44
68
|
export declare function subagentReport(transcriptPath: string): SubagentReport | null;
|
|
45
69
|
export interface SubagentRenderOptions {
|
package/dist/subagents.js
CHANGED
|
@@ -13,16 +13,83 @@
|
|
|
13
13
|
* Reads only the lines that matter (usage, first user turn, timestamps) and
|
|
14
14
|
* never the whole content, so a session with 49 subagents stays fast.
|
|
15
15
|
*/
|
|
16
|
-
import {
|
|
16
|
+
import { readdirSync, readFileSync, statSync } from "node:fs";
|
|
17
17
|
import { basename, join } from "node:path";
|
|
18
18
|
import { formatTokens } from "./tokens.js";
|
|
19
|
-
import { formatUsd,
|
|
19
|
+
import { formatUsd, requestCost } from "./pricing.js";
|
|
20
20
|
import { forEachLine, outputSettler, replyCounter } from "./session.js";
|
|
21
21
|
import { realModel } from "./tokens.js";
|
|
22
22
|
/** Where Claude Code keeps a session's subagents: beside the transcript, under its id. */
|
|
23
23
|
export function subagentDir(transcriptPath) {
|
|
24
24
|
return join(transcriptPath.replace(/\.jsonl$/, ""), "subagents");
|
|
25
25
|
}
|
|
26
|
+
/**
|
|
27
|
+
* Every subagent transcript of a session: the Agent tool's
|
|
28
|
+
* (`subagents/agent-*.jsonl`) and the workflow agents'
|
|
29
|
+
* (`subagents/workflows/<run>/agent-*.jsonl`, one folder per workflow run,
|
|
30
|
+
* the run's own record in `<session>/workflows/<run>.json`). Workflow agents
|
|
31
|
+
* bill to the session like any subagent, and every reader skipped their
|
|
32
|
+
* folder: on the author's machine, 804 transcripts and ~$1,354 in 30 days.
|
|
33
|
+
* `since`: only files written since then. `run`: the workflow run's id.
|
|
34
|
+
*/
|
|
35
|
+
export function subagentFiles(transcriptPath, since = -Infinity) {
|
|
36
|
+
const dir = subagentDir(transcriptPath);
|
|
37
|
+
const out = [];
|
|
38
|
+
const add = (file, run) => {
|
|
39
|
+
try {
|
|
40
|
+
if (since === -Infinity || statSync(file).mtimeMs >= since)
|
|
41
|
+
out.push(run ? { file, run } : { file });
|
|
42
|
+
}
|
|
43
|
+
catch { /* gone */ }
|
|
44
|
+
};
|
|
45
|
+
let names;
|
|
46
|
+
try {
|
|
47
|
+
names = readdirSync(dir);
|
|
48
|
+
}
|
|
49
|
+
catch {
|
|
50
|
+
return out;
|
|
51
|
+
}
|
|
52
|
+
for (const f of names)
|
|
53
|
+
if (f.endsWith(".jsonl"))
|
|
54
|
+
add(join(dir, f));
|
|
55
|
+
if (!names.includes("workflows"))
|
|
56
|
+
return out;
|
|
57
|
+
let runs;
|
|
58
|
+
try {
|
|
59
|
+
runs = readdirSync(join(dir, "workflows"));
|
|
60
|
+
}
|
|
61
|
+
catch {
|
|
62
|
+
return out;
|
|
63
|
+
}
|
|
64
|
+
for (const run of runs) {
|
|
65
|
+
let agents;
|
|
66
|
+
try {
|
|
67
|
+
agents = readdirSync(join(dir, "workflows", run));
|
|
68
|
+
}
|
|
69
|
+
catch {
|
|
70
|
+
continue;
|
|
71
|
+
}
|
|
72
|
+
for (const f of agents)
|
|
73
|
+
if (f.endsWith(".jsonl"))
|
|
74
|
+
add(join(dir, "workflows", run, f), run);
|
|
75
|
+
}
|
|
76
|
+
return out;
|
|
77
|
+
}
|
|
78
|
+
/** The workflow run a subagent transcript belongs to (its folder under subagents/workflows), or undefined. */
|
|
79
|
+
export function workflowRunOf(file) {
|
|
80
|
+
return /[\\/]subagents[\\/]workflows[\\/]([^\\/]+)[\\/][^\\/]+\.jsonl$/.exec(file)?.[1];
|
|
81
|
+
}
|
|
82
|
+
/** A workflow run's own record, `<session>/workflows/<run>.json`: its name and default model, when Claude Code wrote one. */
|
|
83
|
+
export function workflowRunInfo(transcriptPath, run) {
|
|
84
|
+
try {
|
|
85
|
+
const j = JSON.parse(readFileSync(join(transcriptPath.replace(/\.jsonl$/, ""), "workflows", `${run}.json`), "utf8"));
|
|
86
|
+
const s = (v) => (typeof v === "string" && v ? v.slice(0, 80) : undefined);
|
|
87
|
+
return { ...(s(j?.workflowName) ? { name: s(j.workflowName) } : {}), ...(s(j?.defaultModel) ? { model: s(j.defaultModel) } : {}), ...(s(j?.status) ? { status: s(j.status) } : {}) };
|
|
88
|
+
}
|
|
89
|
+
catch {
|
|
90
|
+
return {};
|
|
91
|
+
}
|
|
92
|
+
}
|
|
26
93
|
function n(v) {
|
|
27
94
|
return typeof v === "number" && Number.isFinite(v) && v >= 0 ? v : 0;
|
|
28
95
|
}
|
|
@@ -40,6 +107,8 @@ function summarize(path) {
|
|
|
40
107
|
let last;
|
|
41
108
|
let cost = 0;
|
|
42
109
|
let priced = true;
|
|
110
|
+
// The last reply's rates: its later rows settle its output at them.
|
|
111
|
+
let rates;
|
|
43
112
|
// One reply is written as several rows with the same usage; counting rows
|
|
44
113
|
// doubled the calls and the bill (a real session: 6156 calls / $769 per
|
|
45
114
|
// row against 3228 / $387 per reply).
|
|
@@ -81,7 +150,7 @@ function summarize(path) {
|
|
|
81
150
|
if (seen === "repeat") {
|
|
82
151
|
// A later row of the same reply: only its final output count is new.
|
|
83
152
|
const more = settle(e, false);
|
|
84
|
-
const p = more ?
|
|
153
|
+
const p = more ? rates : undefined;
|
|
85
154
|
s.outputTokens += more;
|
|
86
155
|
if (p)
|
|
87
156
|
cost += (more * p.outputPerM) / 1_000_000;
|
|
@@ -96,15 +165,14 @@ function summarize(path) {
|
|
|
96
165
|
s.inputBilledTokens += input + read + write;
|
|
97
166
|
s.cacheReadTokens += read;
|
|
98
167
|
s.outputTokens += out;
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
else
|
|
168
|
+
// Subagents write at the 5-minute TTL (1.25x), the main thread mostly
|
|
169
|
+
// at 1 hour (2x); the usage records which. As billed: requestCost.
|
|
170
|
+
const c = requestCost(s.model, u, Number.isFinite(at) ? at : undefined);
|
|
171
|
+
rates = c?.rates;
|
|
172
|
+
if (c)
|
|
173
|
+
cost += c.totalUsd;
|
|
174
|
+
else
|
|
106
175
|
priced = false;
|
|
107
|
-
}
|
|
108
176
|
}
|
|
109
177
|
});
|
|
110
178
|
if (first !== undefined && last !== undefined)
|
|
@@ -115,20 +183,13 @@ function summarize(path) {
|
|
|
115
183
|
}
|
|
116
184
|
/** Account for every subagent of a session, or null when there are none. */
|
|
117
185
|
export function subagentReport(transcriptPath) {
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
let files;
|
|
122
|
-
try {
|
|
123
|
-
files = readdirSync(dir).filter((f) => f.startsWith("agent-") && f.endsWith(".jsonl"));
|
|
124
|
-
}
|
|
125
|
-
catch {
|
|
126
|
-
return null;
|
|
127
|
-
}
|
|
128
|
-
if (files.length === 0)
|
|
186
|
+
// The Agent tool's subagents and the workflow agents alike: both bill to this session.
|
|
187
|
+
const found = subagentFiles(transcriptPath).filter((f) => basename(f.file).startsWith("agent-"));
|
|
188
|
+
if (found.length === 0)
|
|
129
189
|
return null;
|
|
130
|
-
const
|
|
131
|
-
|
|
190
|
+
const runOf = new Map(found.map((f) => [f.file, f.run]));
|
|
191
|
+
const summarized = found
|
|
192
|
+
.map((f) => f.file)
|
|
132
193
|
.filter((p) => {
|
|
133
194
|
try {
|
|
134
195
|
return statSync(p).size > 0;
|
|
@@ -137,17 +198,20 @@ export function subagentReport(transcriptPath) {
|
|
|
137
198
|
return false;
|
|
138
199
|
}
|
|
139
200
|
})
|
|
140
|
-
.map(summarize)
|
|
141
|
-
.filter((a) => a.calls > 0)
|
|
142
|
-
.sort((a, b) => (b.estCostUsd ?? 0) - (a.estCostUsd ?? 0) || b.inputBilledTokens - a.inputBilledTokens);
|
|
201
|
+
.map((p) => ({ s: summarize(p), run: runOf.get(p) }))
|
|
202
|
+
.filter((a) => a.s.calls > 0)
|
|
203
|
+
.sort((a, b) => (b.s.estCostUsd ?? 0) - (a.s.estCostUsd ?? 0) || b.s.inputBilledTokens - a.s.inputBilledTokens);
|
|
204
|
+
const agents = summarized.map((a) => a.s);
|
|
143
205
|
if (agents.length === 0)
|
|
144
206
|
return null;
|
|
207
|
+
const runs = new Set(summarized.flatMap((a) => (a.run ? [a.run] : [])));
|
|
145
208
|
return {
|
|
146
209
|
agents,
|
|
147
210
|
totalInputBilled: agents.reduce((t, a) => t + a.inputBilledTokens, 0),
|
|
148
211
|
totalOutput: agents.reduce((t, a) => t + a.outputTokens, 0),
|
|
149
212
|
totalCostUsd: agents.reduce((t, a) => t + (a.estCostUsd ?? 0), 0),
|
|
150
213
|
unpriced: agents.filter((a) => a.estCostUsd === undefined).length,
|
|
214
|
+
...(runs.size ? { workflowAgents: summarized.filter((a) => a.run).length, workflowRuns: runs.size } : {}),
|
|
151
215
|
};
|
|
152
216
|
}
|
|
153
217
|
function fmtDuration(ms) {
|
|
@@ -173,6 +237,8 @@ export function renderSubagents(report, parentInputUsd, top = 5, options = {}) {
|
|
|
173
237
|
const cost = report.unpriced === 0 ? formatUsd(report.totalCostUsd) : `${formatUsd(report.totalCostUsd)}+ (${report.unpriced} unpriced)`;
|
|
174
238
|
lines.push(`${report.agents.length} subagent(s) made ${report.agents.reduce((t, a) => t + a.calls, 0)} API calls: ` +
|
|
175
239
|
`${formatTokens(report.totalInputBilled)} input billed, ${formatTokens(report.totalOutput)} output, ~${cost}.`);
|
|
240
|
+
if (report.workflowAgents)
|
|
241
|
+
lines.push(`${report.workflowAgents} of them are workflow agents, in ${report.workflowRuns} workflow run${report.workflowRuns === 1 ? "" : "s"}.`);
|
|
176
242
|
if (parentInputUsd !== undefined && parentInputUsd > 0 && report.totalCostUsd > 0) {
|
|
177
243
|
const ratio = report.totalCostUsd / parentInputUsd;
|
|
178
244
|
lines.push(ratio >= 1
|
package/dist/tasks.js
CHANGED
|
@@ -21,7 +21,7 @@
|
|
|
21
21
|
import { realModel } from "./tokens.js";
|
|
22
22
|
import { basename } from "node:path";
|
|
23
23
|
import { forEachLine, listSessions, outputSettler, replyCounter, isClaudeSession } from "./session.js";
|
|
24
|
-
import { formatUsd,
|
|
24
|
+
import { formatUsd, requestCost } from "./pricing.js";
|
|
25
25
|
/**
|
|
26
26
|
* One session's bill, priced as the prompt cache bills it, from the usage the
|
|
27
27
|
* transcript records. `since` counts only requests and commits from then on,
|
|
@@ -32,6 +32,8 @@ import { formatUsd, pricingFor, usageCost } from "./pricing.js";
|
|
|
32
32
|
export function sessionCost(path, since = 0, counted = { rows: new Set(), commits: new Set() }) {
|
|
33
33
|
let cwd, model;
|
|
34
34
|
let start = Infinity, end = 0, usd = 0, requests = 0, commits = 0;
|
|
35
|
+
// The last counted reply's rates (requestCost's): its later rows settle its output at them.
|
|
36
|
+
let rates;
|
|
35
37
|
const commitCalls = new Map();
|
|
36
38
|
const sighting = replyCounter(counted.rows);
|
|
37
39
|
const settle = outputSettler();
|
|
@@ -81,7 +83,7 @@ export function sessionCost(path, since = 0, counted = { rows: new Set(), commit
|
|
|
81
83
|
if (seen === "repeat") {
|
|
82
84
|
// A later row of a counted reply: only its final output count is new.
|
|
83
85
|
const more = settle(e, false);
|
|
84
|
-
const price = more ?
|
|
86
|
+
const price = more ? rates : undefined;
|
|
85
87
|
if (price)
|
|
86
88
|
usd += (more * price.outputPerM) / 1e6;
|
|
87
89
|
return;
|
|
@@ -94,11 +96,12 @@ export function sessionCost(path, since = 0, counted = { rows: new Set(), commit
|
|
|
94
96
|
end = Math.max(end, at);
|
|
95
97
|
}
|
|
96
98
|
model = realModel(e.message.model) ?? model;
|
|
97
|
-
// Each request at its own model's price: one session can switch models.
|
|
98
|
-
const
|
|
99
|
-
if (!
|
|
99
|
+
// Each request at its own model's price, as billed: one session can switch models.
|
|
100
|
+
const c = requestCost(model, e.message.usage, Number.isFinite(at) ? at : undefined);
|
|
101
|
+
if (!c)
|
|
100
102
|
return;
|
|
101
|
-
|
|
103
|
+
rates = c.rates;
|
|
104
|
+
usd += c.totalUsd;
|
|
102
105
|
settle(e, true);
|
|
103
106
|
requests++;
|
|
104
107
|
});
|
package/dist/tooloutput.d.ts
CHANGED
|
@@ -41,6 +41,8 @@ import { type Extractor } from "./scan.js";
|
|
|
41
41
|
export declare const BASH_OUTPUT_KEY = "bashOutputMaxChars";
|
|
42
42
|
/** The environment variable the setting replaces (a value the user set there is theirs). */
|
|
43
43
|
export declare const BASH_OUTPUT_ENV = "BASH_MAX_OUTPUT_LENGTH";
|
|
44
|
+
/** The first Claude Code that reads the setting (its docs; older versions ignore it). */
|
|
45
|
+
export declare const BASH_OUTPUT_SINCE = "2.1.261";
|
|
44
46
|
/** Claude Code's inline ceiling for a successful command, unset. */
|
|
45
47
|
export declare const BASH_OUTPUT_DEFAULT = 30000;
|
|
46
48
|
/** What Claude Code clamps the setting to. */
|
package/dist/tooloutput.js
CHANGED
|
@@ -38,13 +38,15 @@
|
|
|
38
38
|
*/
|
|
39
39
|
import { listSessions, isClaudeSession, replyCounter } from "./session.js";
|
|
40
40
|
import { pick, rowsOf, slimUsage } from "./scan.js";
|
|
41
|
-
import { cacheWriteSplit,
|
|
41
|
+
import { cacheWriteSplit, rateCard, ratesAt, requestCost, writeMultiplier } from "./pricing.js";
|
|
42
42
|
import { isCodeLike, realModel, tokensForLength } from "./tokens.js";
|
|
43
43
|
import { subagentTranscripts } from "./cachettl.js";
|
|
44
44
|
/** The settings key the lever writes. */
|
|
45
45
|
export const BASH_OUTPUT_KEY = "bashOutputMaxChars";
|
|
46
46
|
/** The environment variable the setting replaces (a value the user set there is theirs). */
|
|
47
47
|
export const BASH_OUTPUT_ENV = "BASH_MAX_OUTPUT_LENGTH";
|
|
48
|
+
/** The first Claude Code that reads the setting (its docs; older versions ignore it). */
|
|
49
|
+
export const BASH_OUTPUT_SINCE = "2.1.261";
|
|
48
50
|
/** Claude Code's inline ceiling for a successful command, unset. */
|
|
49
51
|
export const BASH_OUTPUT_DEFAULT = 30_000;
|
|
50
52
|
/** What Claude Code clamps the setting to. */
|
|
@@ -88,7 +90,7 @@ function resultText(content) {
|
|
|
88
90
|
return s;
|
|
89
91
|
}
|
|
90
92
|
export const TOOL_OUTPUT_ROWS = {
|
|
91
|
-
id: "tool-output.
|
|
93
|
+
id: "tool-output.2",
|
|
92
94
|
init: () => ({ ids: {}, calls: {} }),
|
|
93
95
|
line(raw, row, out, st) {
|
|
94
96
|
if (!raw.includes('"usage"') && !raw.includes('"tool_use"') && !raw.includes('"tool_result"') && !raw.includes("compact_boundary"))
|
|
@@ -207,14 +209,17 @@ function timeline(path, since, until, runRows) {
|
|
|
207
209
|
for (const x of unsized[th].splice(0))
|
|
208
210
|
x.model = m;
|
|
209
211
|
}
|
|
210
|
-
const
|
|
212
|
+
const card = rateCard(m, u, at);
|
|
213
|
+
const price = card && ratesAt(card, prompt);
|
|
214
|
+
const below = card?.over !== undefined && prompt > card.over ? card.rates : undefined;
|
|
211
215
|
out.push({
|
|
212
216
|
k: "r", prompt,
|
|
213
217
|
readPerM: price?.cacheReadPerM ?? 0,
|
|
214
218
|
writePerM: (price?.inputPerM ?? 0) * writeMult,
|
|
215
219
|
cold: num(u.cache_creation_input_tokens) > COLD_SHARE * prompt,
|
|
216
220
|
counted: !!price && seen === "new" && at >= since && at < until,
|
|
217
|
-
billedUsd:
|
|
221
|
+
billedUsd: requestCost(m, u, at)?.promptUsd ?? 0,
|
|
222
|
+
...(below && price ? { over: card.over, lower: below.inputPerM / price.inputPerM } : {}),
|
|
218
223
|
});
|
|
219
224
|
}
|
|
220
225
|
return threads;
|
|
@@ -264,6 +269,7 @@ function walk(lines, move, kind) {
|
|
|
264
269
|
// Never more than the request held.
|
|
265
270
|
const held = live.reduce((n, x) => n + x.e, 0);
|
|
266
271
|
const scale = held > s.prompt ? s.prompt / held : 1;
|
|
272
|
+
let here = 0;
|
|
267
273
|
for (const x of live) {
|
|
268
274
|
if (x.fresh && s.counted) {
|
|
269
275
|
moved++;
|
|
@@ -272,10 +278,15 @@ function walk(lines, move, kind) {
|
|
|
272
278
|
if (s.counted) {
|
|
273
279
|
const t = x.e * scale;
|
|
274
280
|
tokens += t;
|
|
275
|
-
|
|
281
|
+
const usd = (t * (x.fresh || s.cold ? s.writePerM : s.readPerM)) / 1e6;
|
|
282
|
+
savedUsd += usd;
|
|
283
|
+
here += usd;
|
|
276
284
|
}
|
|
277
285
|
x.fresh = false;
|
|
278
286
|
}
|
|
287
|
+
// Under its tier's threshold now: the rest of its prompt bills at the lower rates too.
|
|
288
|
+
if (s.counted && s.over !== undefined && s.lower !== undefined && s.prompt - held * scale <= s.over)
|
|
289
|
+
savedUsd += Math.max(0, s.billedUsd - here) * (1 - s.lower);
|
|
279
290
|
}
|
|
280
291
|
}
|
|
281
292
|
return { moved, results, tokens, savedUsd, openUsd };
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "context-doctor",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.45.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",
|