context-doctor 0.41.0 → 0.43.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 +7 -4
- package/dist/ab.js +3 -1
- package/dist/autopilot.d.ts +1 -1
- package/dist/autopilot.js +38 -24
- package/dist/budget.d.ts +54 -1
- package/dist/budget.js +207 -53
- package/dist/cachettl.js +12 -9
- package/dist/claudedir.d.ts +8 -0
- package/dist/claudedir.js +19 -0
- package/dist/cli.js +90 -15
- package/dist/codexcompact.d.ts +116 -0
- package/dist/codexcompact.js +415 -0
- package/dist/codexdir.d.ts +11 -0
- package/dist/codexdir.js +20 -0
- package/dist/codexroute.d.ts +1 -0
- package/dist/codexroute.js +3 -1
- package/dist/compactwindow.js +12 -9
- package/dist/cursor.js +20 -5
- package/dist/doctor.d.ts +9 -0
- package/dist/doctor.js +42 -14
- package/dist/effective.d.ts +18 -0
- package/dist/effective.js +39 -4
- package/dist/extract.d.ts +12 -3
- package/dist/extract.js +39 -12
- package/dist/fileparams.d.ts +1 -1
- package/dist/fileparams.js +8 -8
- package/dist/fix.d.ts +33 -4
- package/dist/fix.js +221 -19
- package/dist/hook.js +35 -5
- package/dist/install.js +106 -47
- package/dist/ledger.d.ts +17 -1
- package/dist/ledger.js +31 -1
- package/dist/limits.d.ts +15 -1
- package/dist/limits.js +71 -28
- package/dist/mcp.js +58 -58
- package/dist/overhead.js +2 -1
- package/dist/pack.js +3 -2
- package/dist/proxy.d.ts +1 -1
- package/dist/proxy.js +1 -1
- package/dist/recall.js +3 -2
- package/dist/scan.d.ts +2 -0
- package/dist/scan.js +2 -1
- package/dist/session.js +2 -1
- package/dist/sessionprice.d.ts +71 -0
- package/dist/sessionprice.js +216 -0
- package/dist/settingsedit.d.ts +4 -0
- package/dist/settingsedit.js +61 -3
- package/dist/spend.d.ts +8 -1
- package/dist/spend.js +27 -10
- package/dist/subagentmodel.d.ts +19 -4
- package/dist/subagentmodel.js +116 -28
- package/dist/tooloutput.d.ts +118 -0
- package/dist/tooloutput.js +355 -0
- package/package.json +1 -1
package/dist/spend.js
CHANGED
|
@@ -31,9 +31,10 @@
|
|
|
31
31
|
* subagents too; on the requests both count, the dollars are the same.
|
|
32
32
|
*/
|
|
33
33
|
import { basename, dirname, join } from "node:path";
|
|
34
|
+
import { codexDir } from "./codexdir.js";
|
|
34
35
|
import { homedir } from "node:os";
|
|
35
36
|
import { existsSync, statSync } from "node:fs";
|
|
36
|
-
import { claudeFileUsage, claudeUsageFiles, codexSessionsRoot, rolloutFiles } from "./limits.js";
|
|
37
|
+
import { claudeFileUsage, claudeUsageFiles, codexEventKey, codexSessionsRoot, rolloutFiles } from "./limits.js";
|
|
37
38
|
import { listGeminiChats, readGeminiMessages } from "./gemini.js";
|
|
38
39
|
import { cursorUsage, SqliteUnavailableError } from "./cursor.js";
|
|
39
40
|
import { openAIUsage, pricingFor, usageCost } from "./pricing.js";
|
|
@@ -111,7 +112,7 @@ export function claudeSpend(since, until = Infinity, tops, onProgress) {
|
|
|
111
112
|
* and every token_count event's last request and running total.
|
|
112
113
|
*/
|
|
113
114
|
export const CODEX_SPEND_ROWS = {
|
|
114
|
-
id: "codex-spend.
|
|
115
|
+
id: "codex-spend.2",
|
|
115
116
|
init: () => null,
|
|
116
117
|
line(line, row, out) {
|
|
117
118
|
if (!line.includes('"token_count"') && !line.includes('"turn_context"') && !line.includes('"session_meta"'))
|
|
@@ -139,7 +140,7 @@ export const CODEX_SPEND_ROWS = {
|
|
|
139
140
|
if (!last || typeof last !== "object")
|
|
140
141
|
return;
|
|
141
142
|
const total = p.info?.total_token_usage?.total_tokens;
|
|
142
|
-
out.push({ k: "t", ts: String(e.timestamp ?? ""), total: typeof total === "number" ? total : 0, u: pick(last, ["input_tokens", "cached_input_tokens", "cache_write_input_tokens", "output_tokens", "input_tokens_details", "prompt_tokens", "prompt_tokens_details", "completion_tokens"]) });
|
|
143
|
+
out.push({ k: "t", ts: String(e.timestamp ?? ""), total: typeof total === "number" ? total : 0, key: codexEventKey(p.info?.total_token_usage, last), u: pick(last, ["input_tokens", "cached_input_tokens", "cache_write_input_tokens", "output_tokens", "input_tokens_details", "prompt_tokens", "prompt_tokens_details", "completion_tokens"]) });
|
|
143
144
|
},
|
|
144
145
|
};
|
|
145
146
|
const num = (v) => (typeof v === "number" && Number.isFinite(v) && v > 0 ? v : 0);
|
|
@@ -166,24 +167,26 @@ export function codexFileSpend(file, since, until = Infinity) {
|
|
|
166
167
|
if (!Number.isFinite(ts) || ts < since || ts > until)
|
|
167
168
|
continue;
|
|
168
169
|
const u = openAIUsage(r.u);
|
|
169
|
-
out.push(priced({ tool: "codex", ts, project: cwd ? projectName(cwd) : "codex", session: basename(file, ".jsonl"), ...(model ? { 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) }, u));
|
|
170
|
+
out.push(priced({ tool: "codex", ts, project: cwd ? projectName(cwd) : "codex", session: basename(file, ".jsonl"), ...(model ? { 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), ...(r.key ? { key: r.key } : {}) }, u));
|
|
170
171
|
}
|
|
171
172
|
return out;
|
|
172
173
|
}
|
|
173
174
|
/** Codex rollouts written since `since`: the live ones and the archived. */
|
|
174
175
|
export function codexFiles(since, home = homedir()) {
|
|
175
|
-
const roots = [codexSessionsRoot(home), join(home, "
|
|
176
|
+
const roots = [codexSessionsRoot(home), join(codexDir(home), "archived_sessions")];
|
|
176
177
|
return roots.filter((r) => existsSync(r)).flatMap((r) => rolloutFiles(r, since));
|
|
177
178
|
}
|
|
179
|
+
/** Every Codex request in the window, once: a forked rollout's copy of its parent's (codexEventKey) counts at the earliest time met. */
|
|
178
180
|
export function codexSpend(since, until = Infinity, home = homedir()) {
|
|
179
|
-
const
|
|
181
|
+
const all = [];
|
|
180
182
|
for (const f of codexFiles(since, home)) {
|
|
181
183
|
try {
|
|
182
|
-
|
|
184
|
+
all.push(...codexFileSpend(f, since, until));
|
|
183
185
|
}
|
|
184
186
|
catch { /* unreadable: skipped */ }
|
|
185
187
|
}
|
|
186
|
-
|
|
188
|
+
const seen = new Set();
|
|
189
|
+
return all.sort((a, b) => a.ts - b.ts).filter((it) => !it.key || (!seen.has(it.key) && Boolean(seen.add(it.key))));
|
|
187
190
|
}
|
|
188
191
|
// ---------------------------------------------------------------------------
|
|
189
192
|
// Gemini CLI
|
|
@@ -364,8 +367,15 @@ export function summarizeSpend(items, days, since, until, skipped = []) {
|
|
|
364
367
|
skipped,
|
|
365
368
|
};
|
|
366
369
|
}
|
|
370
|
+
/**
|
|
371
|
+
* The longest window: ten years, older than any history these tools keep.
|
|
372
|
+
* Unbounded, `--days 10000000` listed every empty day of it (51 s, and
|
|
373
|
+
* --json died on a string too long), and 1e9 days fell off the calendar.
|
|
374
|
+
*/
|
|
375
|
+
export const MAX_SPEND_DAYS = 3650;
|
|
367
376
|
/** The last `days` days, every tool on this machine. A tool with nothing on disk is just absent. */
|
|
368
377
|
export function spendReport(days = 30, opts = {}) {
|
|
378
|
+
days = Math.min(days, MAX_SPEND_DAYS);
|
|
369
379
|
const until = opts.now ?? Date.now();
|
|
370
380
|
const since = until - days * DAY;
|
|
371
381
|
const home = opts.home ?? homedir();
|
|
@@ -402,7 +412,8 @@ export function renderSpend(r, top = 8) {
|
|
|
402
412
|
lines.push("─".repeat(60));
|
|
403
413
|
for (const t of r.tools) {
|
|
404
414
|
const unit = t.tool === "cursor" ? "replies" : "requests";
|
|
405
|
-
const
|
|
415
|
+
const notes = [t.estimate ? "estimate, no cache split" : t.subagentUsd ? `subagents ${usd(t.subagentUsd)}` : "", t.unpriced ? `${t.unpriced.toLocaleString("en-US")} not priced` : ""].filter(Boolean);
|
|
416
|
+
const note = notes.length ? ` ${notes.join(", ")}` : "";
|
|
406
417
|
lines.push(`${t.name.padEnd(14)}${`${t.estimate ? "~" : ""}${usd(t.usd)}`.padStart(11)} ${`${t.requests.toLocaleString("en-US")} ${unit}`.padEnd(16)}${note}`);
|
|
407
418
|
}
|
|
408
419
|
if (r.tools.length > 1)
|
|
@@ -416,7 +427,9 @@ export function renderSpend(r, top = 8) {
|
|
|
416
427
|
};
|
|
417
428
|
const toolsOf = (byTool) => (r.tools.length > 1 ? TOOLS.filter((t) => (byTool[t] ?? 0) > 0).map((t) => TOOL_NAME[t]).join(", ") : undefined);
|
|
418
429
|
list("By project", r.projects.slice(0, top).map((p) => ({ name: p.project, usd: p.usd, tail: toolsOf(p.byTool) })), r.projects.length - top);
|
|
419
|
-
|
|
430
|
+
// A model with no list price reads "not priced", not a $0.00 that looks free.
|
|
431
|
+
const unpricedModels = new Set(r.tools.flatMap((t) => t.unpricedModels));
|
|
432
|
+
list("By model", r.models.slice(0, top).map((m) => ({ name: m.model, usd: m.usd, ...(m.usd === 0 && unpricedModels.has(m.model) ? { tail: `not priced, ${m.requests.toLocaleString("en-US")} ${m.requests === 1 ? "request" : "requests"}` } : {}) })), r.models.length - top);
|
|
420
433
|
// The last two weeks of the window, a bar each, scaled to the busiest.
|
|
421
434
|
const recent = r.daily.slice(-14);
|
|
422
435
|
const peak = Math.max(...recent.map((d) => d.usd), 0);
|
|
@@ -466,6 +479,10 @@ export function renderSpendShare(r) {
|
|
|
466
479
|
const claude = r.tools.find((t) => t.tool === "claude");
|
|
467
480
|
if (claude?.subagentUsd)
|
|
468
481
|
lines.push(`Claude Code subagents: ${usd(claude.subagentUsd)} of it.`);
|
|
482
|
+
// Requests on a model with no list price are not in the total: said, so the total is not read as all of it.
|
|
483
|
+
const unpriced = r.tools.reduce((n, t) => n + t.unpriced, 0);
|
|
484
|
+
if (unpriced)
|
|
485
|
+
lines.push(`Not in it: ${unpriced.toLocaleString("en-US")} ${unpriced === 1 ? "request" : "requests"} (${formatTokens(r.tools.reduce((n, t) => n + t.unpricedTokens, 0))} tokens) on models with no list price.`);
|
|
469
486
|
const parts = [["cache writes", r.parts.writeUsd], ["cache reads", r.parts.readUsd], ["output", r.parts.outputUsd], ["uncached input", r.parts.inputUsd]];
|
|
470
487
|
const [bigPart, bigUsd] = parts.sort((a, b) => b[1] - a[1])[0];
|
|
471
488
|
const busiest = [...r.daily].sort((a, b) => b.usd - a.usd)[0];
|
package/dist/subagentmodel.d.ts
CHANGED
|
@@ -11,7 +11,9 @@
|
|
|
11
11
|
* built-ins: Explore, Plan and fork say "inherit", claude-code-guide
|
|
12
12
|
* "haiku", statusline-setup "sonnet"; general-purpose and claude name
|
|
13
13
|
* none);
|
|
14
|
-
* 3. CLAUDE_CODE_SUBAGENT_MODEL, unless it is
|
|
14
|
+
* 3. CLAUDE_CODE_SUBAGENT_MODEL, unless it is empty or "inherit" (this
|
|
15
|
+
* function treats "default" as a model name; Claude Code's fallback
|
|
16
|
+
* chain treats it like "inherit");
|
|
15
17
|
* 4. the main conversation's model.
|
|
16
18
|
* So the variable moves only the agents whose definition names no model
|
|
17
19
|
* (general-purpose, claude, agents of your own without `model:`).
|
|
@@ -49,6 +51,12 @@ export interface AgentDefinition {
|
|
|
49
51
|
model?: string;
|
|
50
52
|
where: string;
|
|
51
53
|
}
|
|
54
|
+
/**
|
|
55
|
+
* The agent definitions Claude Code uses in `cwd`, as 2.1.309 merges them,
|
|
56
|
+
* lowest first: the user's (~/.claude/agents), the project's (outer folders
|
|
57
|
+
* first), then managed. Plugin agents are not read.
|
|
58
|
+
*/
|
|
59
|
+
export declare function agentDefinitions(cwd: string | undefined, home?: string, env?: NodeJS.ProcessEnv): Map<string, AgentDefinition>;
|
|
52
60
|
/** How a type's model is chosen: whether CLAUDE_CODE_SUBAGENT_MODEL moves it, and why not. */
|
|
53
61
|
export declare function variableMoves(type: string, defs: Map<string, AgentDefinition>, force?: boolean): {
|
|
54
62
|
moves: boolean;
|
|
@@ -77,8 +85,15 @@ export interface SubagentModelReplay {
|
|
|
77
85
|
atCandidateUsd: number;
|
|
78
86
|
/** billed - at candidate. */
|
|
79
87
|
savedUsd: number;
|
|
80
|
-
/** The moved requests' bill by the model they ran on
|
|
88
|
+
/** The moved requests' bill by the model they ran on (the names in the plan's title). */
|
|
81
89
|
movedFrom: Record<string, number>;
|
|
90
|
+
/**
|
|
91
|
+
* Every request of the types the variable moves, Sonnet-or-cheaper ones
|
|
92
|
+
* included, by the model it ran on, weighted by its tokens (priced at the
|
|
93
|
+
* candidate's rates): the mix "saved since" prices those types at after
|
|
94
|
+
* the change, when every one of them is on the candidate.
|
|
95
|
+
*/
|
|
96
|
+
before: Record<string, number>;
|
|
82
97
|
/** Requests on models with no price (left out of the dollars). */
|
|
83
98
|
unpriced: number;
|
|
84
99
|
byType: TypeReplay[];
|
|
@@ -91,7 +106,7 @@ export interface SubagentModelOptions {
|
|
|
91
106
|
candidate?: string;
|
|
92
107
|
/** CLAUDE_CODE_SUBAGENT_MODEL_FORCE is on: the variable moves every type but forks. */
|
|
93
108
|
force?: boolean;
|
|
94
|
-
/** Agent definitions (default:
|
|
109
|
+
/** Agent definitions for every subagent (default: per subagent's folder, as agentDefinitions merges them). */
|
|
95
110
|
definitions?: Map<string, AgentDefinition>;
|
|
96
111
|
home?: string;
|
|
97
112
|
/** Price every moved request at this mix of models (shares adding to 1) instead of the candidate: "saved since". */
|
|
@@ -109,7 +124,7 @@ export declare function agentTypeOf(transcript: string): string;
|
|
|
109
124
|
export declare function replaySubagentModels(opts: SubagentModelOptions): SubagentModelReplay;
|
|
110
125
|
/** The models the moved requests ran on, for people: the one or two that carry 10%+ of the bill ("Fable 5.1 or Opus 5.5"). */
|
|
111
126
|
export declare function movedFromNames(movedFrom: Record<string, number>): string | undefined;
|
|
112
|
-
/** Each model's share of a
|
|
127
|
+
/** Each model's share of a total by model (a fix record keeps the shares of `before` as the baseline). */
|
|
113
128
|
export declare function shares(byModel: Record<string, number>): Record<string, number>;
|
|
114
129
|
/** A model id for people: "claude-opus-5-5" as "Opus 5.5". */
|
|
115
130
|
export declare function modelName(model: string | undefined): string;
|
package/dist/subagentmodel.js
CHANGED
|
@@ -11,7 +11,9 @@
|
|
|
11
11
|
* built-ins: Explore, Plan and fork say "inherit", claude-code-guide
|
|
12
12
|
* "haiku", statusline-setup "sonnet"; general-purpose and claude name
|
|
13
13
|
* none);
|
|
14
|
-
* 3. CLAUDE_CODE_SUBAGENT_MODEL, unless it is
|
|
14
|
+
* 3. CLAUDE_CODE_SUBAGENT_MODEL, unless it is empty or "inherit" (this
|
|
15
|
+
* function treats "default" as a model name; Claude Code's fallback
|
|
16
|
+
* chain treats it like "inherit");
|
|
15
17
|
* 4. the main conversation's model.
|
|
16
18
|
* So the variable moves only the agents whose definition names no model
|
|
17
19
|
* (general-purpose, claude, agents of your own without `model:`).
|
|
@@ -28,14 +30,15 @@
|
|
|
28
30
|
* tokenizes differently and may take more or fewer steps for the same task.
|
|
29
31
|
* Requests on a model no pricier than the candidate stay as billed.
|
|
30
32
|
*/
|
|
31
|
-
import { readdirSync, readFileSync } from "node:fs";
|
|
33
|
+
import { existsSync, readdirSync, readFileSync, realpathSync, statSync } from "node:fs";
|
|
32
34
|
import { homedir } from "node:os";
|
|
33
|
-
import {
|
|
35
|
+
import { dirname, join, resolve } from "node:path";
|
|
34
36
|
import { pick, rowsOf, slimUsage } from "./scan.js";
|
|
35
37
|
import { pricingFor, usageCost } from "./pricing.js";
|
|
36
38
|
import { realModel } from "./tokens.js";
|
|
37
39
|
import { claudeDir } from "./claudedir.js";
|
|
38
40
|
import { subagentTranscripts } from "./cachettl.js";
|
|
41
|
+
import { managedDir } from "./effective.js";
|
|
39
42
|
import { SUBAGENT_CANDIDATE, SUBAGENT_CANDIDATE_NAME } from "./subagentpay.js";
|
|
40
43
|
export { SUBAGENT_CANDIDATE, SUBAGENT_CANDIDATE_NAME };
|
|
41
44
|
/** The environment variable the lever writes. */
|
|
@@ -100,19 +103,51 @@ export const SUBAGENT_ROWS = {
|
|
|
100
103
|
out.push({ t: "r", ...pick(e, ["uuid", "timestamp"]), id, model: m.model, usage: slimUsage(m.usage) });
|
|
101
104
|
},
|
|
102
105
|
};
|
|
103
|
-
/** `
|
|
104
|
-
function
|
|
105
|
-
let
|
|
106
|
+
/** The `.md` files under `dir`, subfolders included (Claude Code reads agent folders recursively). */
|
|
107
|
+
function markdownUnder(dir, out = [], seen = new Set()) {
|
|
108
|
+
let real;
|
|
109
|
+
try {
|
|
110
|
+
real = realpathSync(dir);
|
|
111
|
+
}
|
|
112
|
+
catch {
|
|
113
|
+
return out;
|
|
114
|
+
}
|
|
115
|
+
if (seen.has(real))
|
|
116
|
+
return out;
|
|
117
|
+
seen.add(real);
|
|
118
|
+
let entries;
|
|
106
119
|
try {
|
|
107
|
-
|
|
120
|
+
entries = readdirSync(dir).sort();
|
|
108
121
|
}
|
|
109
122
|
catch {
|
|
110
|
-
return;
|
|
123
|
+
return out;
|
|
124
|
+
}
|
|
125
|
+
for (const e of entries) {
|
|
126
|
+
const p = join(dir, e);
|
|
127
|
+
let st;
|
|
128
|
+
try {
|
|
129
|
+
st = statSync(p);
|
|
130
|
+
}
|
|
131
|
+
catch {
|
|
132
|
+
continue;
|
|
133
|
+
}
|
|
134
|
+
if (st.isDirectory())
|
|
135
|
+
markdownUnder(p, out, seen);
|
|
136
|
+
else if (st.isFile() && e.endsWith(".md"))
|
|
137
|
+
out.push(p);
|
|
111
138
|
}
|
|
112
|
-
|
|
139
|
+
return out;
|
|
140
|
+
}
|
|
141
|
+
/**
|
|
142
|
+
* `name:` and `model:` from the frontmatter of the agent files under `dir`,
|
|
143
|
+
* over what `into` holds (a later folder wins). Like Claude Code, a file
|
|
144
|
+
* without a `name` or a `description` is not an agent.
|
|
145
|
+
*/
|
|
146
|
+
function definitionsIn(dir, into) {
|
|
147
|
+
for (const path of markdownUnder(dir)) {
|
|
113
148
|
let text;
|
|
114
149
|
try {
|
|
115
|
-
text = readFileSync(
|
|
150
|
+
text = readFileSync(path, "utf8");
|
|
116
151
|
}
|
|
117
152
|
catch {
|
|
118
153
|
continue;
|
|
@@ -121,10 +156,49 @@ function definitionsIn(dir, into) {
|
|
|
121
156
|
if (fm === undefined)
|
|
122
157
|
continue;
|
|
123
158
|
const field = (k) => new RegExp(`^${k}:[ \\t]*(.*)$`, "m").exec(fm)?.[1].trim().replace(/^["']|["']$/g, "") || undefined;
|
|
124
|
-
const name = field("name")
|
|
125
|
-
if (!
|
|
126
|
-
|
|
159
|
+
const name = field("name");
|
|
160
|
+
if (!name || !field("description"))
|
|
161
|
+
continue;
|
|
162
|
+
into.set(name, { model: field("model"), where: path });
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
/**
|
|
166
|
+
* The project folders whose `.claude/agents` apply in `cwd`, outermost
|
|
167
|
+
* first: `cwd` and its parents up to the git root, never the home folder
|
|
168
|
+
* or above it (the 2.1.309 binary: closer folders win over outer ones).
|
|
169
|
+
*/
|
|
170
|
+
function projectAgentDirs(cwd, home) {
|
|
171
|
+
const dirs = [];
|
|
172
|
+
let d = resolve(cwd);
|
|
173
|
+
const h = resolve(home);
|
|
174
|
+
for (;;) {
|
|
175
|
+
if (d === h)
|
|
176
|
+
break;
|
|
177
|
+
dirs.push(join(d, ".claude", "agents"));
|
|
178
|
+
if (existsSync(join(d, ".git")))
|
|
179
|
+
break;
|
|
180
|
+
const up = dirname(d);
|
|
181
|
+
if (up === d)
|
|
182
|
+
break;
|
|
183
|
+
d = up;
|
|
127
184
|
}
|
|
185
|
+
return dirs.reverse();
|
|
186
|
+
}
|
|
187
|
+
/**
|
|
188
|
+
* The agent definitions Claude Code uses in `cwd`, as 2.1.309 merges them,
|
|
189
|
+
* lowest first: the user's (~/.claude/agents), the project's (outer folders
|
|
190
|
+
* first), then managed. Plugin agents are not read.
|
|
191
|
+
*/
|
|
192
|
+
export function agentDefinitions(cwd, home = homedir(), env = process.env) {
|
|
193
|
+
const defs = new Map();
|
|
194
|
+
definitionsIn(join(claudeDir(home, env), "agents"), defs);
|
|
195
|
+
if (cwd)
|
|
196
|
+
for (const d of projectAgentDirs(cwd, home))
|
|
197
|
+
definitionsIn(d, defs);
|
|
198
|
+
const managed = managedDir(env);
|
|
199
|
+
if (managed)
|
|
200
|
+
definitionsIn(join(managed, ".claude", "agents"), defs);
|
|
201
|
+
return defs;
|
|
128
202
|
}
|
|
129
203
|
/** How a type's model is chosen: whether CLAUDE_CODE_SUBAGENT_MODEL moves it, and why not. */
|
|
130
204
|
export function variableMoves(type, defs, force = false) {
|
|
@@ -138,7 +212,7 @@ export function variableMoves(type, defs, force = false) {
|
|
|
138
212
|
}
|
|
139
213
|
const d = defs.get(type);
|
|
140
214
|
if (!d)
|
|
141
|
-
return { moves: false, why: "its agent file was not found here" };
|
|
215
|
+
return { moves: false, why: type === "unknown" ? "no agent type recorded beside it (an older Claude Code)" : "its agent file was not found here" };
|
|
142
216
|
if (!d.model)
|
|
143
217
|
return { moves: true };
|
|
144
218
|
return { moves: false, why: `its file says model: ${d.model}` };
|
|
@@ -180,12 +254,23 @@ export function replaySubagentModels(opts) {
|
|
|
180
254
|
const haiku = pricingFor(HAIKU);
|
|
181
255
|
const base = opts.baseline ? blend(opts.baseline) : undefined;
|
|
182
256
|
const until = opts.until ?? Infinity;
|
|
183
|
-
const
|
|
184
|
-
const
|
|
185
|
-
|
|
186
|
-
|
|
257
|
+
const home = opts.home ?? homedir();
|
|
258
|
+
const paths = opts.paths ?? subagentTranscripts(opts.since, home);
|
|
259
|
+
// Each project's agents, read the first time a subagent of that folder is met.
|
|
260
|
+
const defsByCwd = new Map();
|
|
261
|
+
const defsFor = (cwd) => {
|
|
262
|
+
if (opts.definitions)
|
|
263
|
+
return opts.definitions;
|
|
264
|
+
const key = typeof cwd === "string" ? cwd : "";
|
|
265
|
+
let d = defsByCwd.get(key);
|
|
266
|
+
if (!d)
|
|
267
|
+
defsByCwd.set(key, (d = agentDefinitions(key || undefined, home)));
|
|
268
|
+
return d;
|
|
269
|
+
};
|
|
187
270
|
const types = new Map();
|
|
188
271
|
const movedBy = new Map();
|
|
272
|
+
const beforeBy = new Map();
|
|
273
|
+
const add = (m, k, v) => m.set(k, (m.get(k) ?? 0) + v);
|
|
189
274
|
const seen = new Set();
|
|
190
275
|
let unpriced = 0;
|
|
191
276
|
for (const p of paths) {
|
|
@@ -196,13 +281,12 @@ export function replaySubagentModels(opts) {
|
|
|
196
281
|
catch {
|
|
197
282
|
continue;
|
|
198
283
|
}
|
|
199
|
-
const cwd = rows.find((r) => r?.t === "c")?.cwd;
|
|
200
|
-
// A project's own agents, looked up the first time a subagent of that project is met.
|
|
201
|
-
if (typeof cwd === "string" && !opts.definitions)
|
|
202
|
-
definitionsIn(join(cwd, ".claude", "agents"), defs);
|
|
203
284
|
const type = agentTypeOf(p);
|
|
204
|
-
const how = variableMoves(type,
|
|
285
|
+
const how = variableMoves(type, defsFor(rows.find((r) => r?.t === "c")?.cwd), opts.force);
|
|
205
286
|
const t = types.get(type) ?? types.set(type, { type, agents: 0, requests: 0, billedUsd: 0, atCandidateUsd: 0, atHaikuUsd: 0, over100k: 0, moves: how.moves, why: how.why, readOnly: READ_ONLY.has(type) }).get(type);
|
|
287
|
+
// One project's file may name a model where another's does not: the type moves where any of its runs does.
|
|
288
|
+
if (how.moves)
|
|
289
|
+
t.moves = true;
|
|
206
290
|
// Per reply of this file: the prices its output top-ups are charged at.
|
|
207
291
|
const priced = new Map();
|
|
208
292
|
let counted = false;
|
|
@@ -214,6 +298,8 @@ export function replaySubagentModels(opts) {
|
|
|
214
298
|
t.billedUsd += (r.more * q.billed.outputPerM) / 1e6;
|
|
215
299
|
t.atCandidateUsd += (r.more * q.other.outputPerM) / 1e6;
|
|
216
300
|
t.atHaikuUsd += (r.more * haiku.outputPerM) / 1e6;
|
|
301
|
+
if (how.moves)
|
|
302
|
+
add(beforeBy, q.model, (r.more * cand.outputPerM) / 1e6);
|
|
217
303
|
continue;
|
|
218
304
|
}
|
|
219
305
|
if (r?.t !== "r")
|
|
@@ -248,17 +334,19 @@ export function replaySubagentModels(opts) {
|
|
|
248
334
|
if (promptTokens(u) > HAIKU_TIER)
|
|
249
335
|
t.over100k++;
|
|
250
336
|
if (move)
|
|
251
|
-
movedBy
|
|
337
|
+
add(movedBy, model, billed);
|
|
338
|
+
if (how.moves)
|
|
339
|
+
add(beforeBy, model, usageCost(u, cand).totalUsd);
|
|
252
340
|
if (r.id)
|
|
253
|
-
priced.set(r.id, { billed: price, other });
|
|
341
|
+
priced.set(r.id, { billed: price, other, model });
|
|
254
342
|
}
|
|
255
343
|
if (counted)
|
|
256
344
|
t.agents++;
|
|
257
345
|
}
|
|
258
346
|
const byType = [...types.values()].filter((t) => t.requests > 0).sort((a, b) => b.billedUsd - a.billedUsd);
|
|
259
347
|
const sum = (k) => byType.reduce((s, t) => s + t[k], 0);
|
|
260
|
-
const
|
|
261
|
-
return { candidate, agents: sum("agents"), requests: sum("requests"), billedUsd: sum("billedUsd"), atCandidateUsd: sum("atCandidateUsd"), savedUsd: sum("billedUsd") - sum("atCandidateUsd"), movedFrom, unpriced, byType };
|
|
348
|
+
const sorted = (m) => Object.fromEntries([...m.entries()].sort((a, b) => b[1] - a[1]));
|
|
349
|
+
return { candidate, agents: sum("agents"), requests: sum("requests"), billedUsd: sum("billedUsd"), atCandidateUsd: sum("atCandidateUsd"), savedUsd: sum("billedUsd") - sum("atCandidateUsd"), movedFrom: sorted(movedBy), before: sorted(beforeBy), unpriced, byType };
|
|
262
350
|
}
|
|
263
351
|
/** The models the moved requests ran on, for people: the one or two that carry 10%+ of the bill ("Fable 5.1 or Opus 5.5"). */
|
|
264
352
|
export function movedFromNames(movedFrom) {
|
|
@@ -267,7 +355,7 @@ export function movedFromNames(movedFrom) {
|
|
|
267
355
|
const names = [...new Set(all.filter(([, v]) => v >= 0.1 * total).slice(0, 2).map(([m]) => modelName(m)))];
|
|
268
356
|
return names.length ? names.join(" or ") : undefined;
|
|
269
357
|
}
|
|
270
|
-
/** Each model's share of a
|
|
358
|
+
/** Each model's share of a total by model (a fix record keeps the shares of `before` as the baseline). */
|
|
271
359
|
export function shares(byModel) {
|
|
272
360
|
const total = Object.values(byModel).reduce((s, v) => s + v, 0);
|
|
273
361
|
return total > 0 ? Object.fromEntries(Object.entries(byModel).map(([m, v]) => [m, v / total])) : {};
|
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Long tool output: what it costs to keep in the context, and what a lower
|
|
3
|
+
* cap would save. The `tool-output` lever of `fix`.
|
|
4
|
+
*
|
|
5
|
+
* A tool result stays in the conversation, and every later request re-reads
|
|
6
|
+
* it (at the cache-read rate, or the write rate when the cache went cold)
|
|
7
|
+
* until a compaction. Claude Code caps it when it arrives. Read from the
|
|
8
|
+
* 2.1.309 binary and its docs (code.claude.com/docs/en/tools-reference,
|
|
9
|
+
* settings-reference, mcp, env-vars):
|
|
10
|
+
* - a successful Bash or PowerShell result over `bashOutputMaxChars`
|
|
11
|
+
* (settings, any scope; default 30,000 characters, clamped to
|
|
12
|
+
* 4,000-128,000; Claude Code 2.1.261+) is saved to a file, and the model
|
|
13
|
+
* receives the path and a preview of the first 2,000 characters
|
|
14
|
+
* (`<persisted-output>`). Set, it also replaces BASH_MAX_OUTPUT_LENGTH,
|
|
15
|
+
* which on its own sizes only the read-back window, not what the model
|
|
16
|
+
* receives. A failed command gets a head-and-tail excerpt of ~10,000
|
|
17
|
+
* characters instead, with no file, whatever the setting;
|
|
18
|
+
* - an MCP text result over MAX_MCP_OUTPUT_TOKENS (environment; default
|
|
19
|
+
* 25,000 tokens) is saved to a file and replaced by a message naming the
|
|
20
|
+
* path, with no preview; one over 50,000 characters is saved to a file
|
|
21
|
+
* whatever the variable says (with the same 2,000-character preview as
|
|
22
|
+
* Bash), unless the tool raises its own limit.
|
|
23
|
+
* Anthropic can also set a tool's threshold server-side (a remote flag the
|
|
24
|
+
* binary reads per tool name); that is not visible here.
|
|
25
|
+
*
|
|
26
|
+
* The replay reads each transcript's requests and its Bash and MCP results
|
|
27
|
+
* in order. For a candidate cap, a successful text result longer than the
|
|
28
|
+
* cap would have been the preview instead: the tokens past it are priced at
|
|
29
|
+
* the first request after the result (the cache write, at the session's own
|
|
30
|
+
* write price) and at every later request until a compaction (a cache read,
|
|
31
|
+
* or a write when that request found the cache cold: over 60% of its context
|
|
32
|
+
* written again). Token counts are estimates from the text's length, at the
|
|
33
|
+
* ratio measured on the growth of the billed prompt between consecutive
|
|
34
|
+
* calls (tokens.ts). Not counted: the model opening the file afterwards, or
|
|
35
|
+
* running the command again. Each such request costs about the context it
|
|
36
|
+
* re-reads, so the replay prices one per moved result and reports how many
|
|
37
|
+
* of them the saving still covers.
|
|
38
|
+
*/
|
|
39
|
+
import { type Extractor } from "./scan.js";
|
|
40
|
+
/** The settings key the lever writes. */
|
|
41
|
+
export declare const BASH_OUTPUT_KEY = "bashOutputMaxChars";
|
|
42
|
+
/** The environment variable the setting replaces (a value the user set there is theirs). */
|
|
43
|
+
export declare const BASH_OUTPUT_ENV = "BASH_MAX_OUTPUT_LENGTH";
|
|
44
|
+
/** Claude Code's inline ceiling for a successful command, unset. */
|
|
45
|
+
export declare const BASH_OUTPUT_DEFAULT = 30000;
|
|
46
|
+
/** What Claude Code clamps the setting to. */
|
|
47
|
+
export declare const BASH_OUTPUT_MIN = 4000;
|
|
48
|
+
export declare const BASH_OUTPUT_MAX = 128000;
|
|
49
|
+
/** The caps the replay tries, smallest first; under 8,000 the 2,000-character preview is most of the output. */
|
|
50
|
+
export declare const BASH_OUTPUT_CAPS: number[];
|
|
51
|
+
/** The MCP cap the replay tries, in tokens: the size at which Claude Code already warns. */
|
|
52
|
+
export declare const MCP_OUTPUT_CAP = 10000;
|
|
53
|
+
export declare const TOOL_OUTPUT_ROWS: Extractor<{
|
|
54
|
+
ids: Record<string, number>;
|
|
55
|
+
calls: Record<string, string>;
|
|
56
|
+
}>;
|
|
57
|
+
/** A result: its length (or the size Claude Code saved), as code or prose, the model's tokenizer. */
|
|
58
|
+
interface Res {
|
|
59
|
+
k: "b" | "m";
|
|
60
|
+
n: number;
|
|
61
|
+
c: number;
|
|
62
|
+
p?: number;
|
|
63
|
+
model?: string;
|
|
64
|
+
}
|
|
65
|
+
/** Which results a cap moves to a file, and the tokens the model would no longer carry. */
|
|
66
|
+
type Mover = (r: Res) => number;
|
|
67
|
+
/** A candidate cap for Bash: a successful result longer than it, still inline, becomes the preview. */
|
|
68
|
+
export declare const bashCap: (cap: number) => Mover;
|
|
69
|
+
/** Since a cap was set: the results Claude Code moved that the cap before would have left inline. */
|
|
70
|
+
export declare const bashMovedSince: (previous: number) => Mover;
|
|
71
|
+
/** MAX_MCP_OUTPUT_TOKENS at `tokens`: a longer text result becomes a message naming the file. */
|
|
72
|
+
export declare const mcpCap: (tokens: number) => Mover;
|
|
73
|
+
export interface CapReplay {
|
|
74
|
+
/** Results the cap moves to a file, of the ones it applies to. */
|
|
75
|
+
moved: number;
|
|
76
|
+
results: number;
|
|
77
|
+
/** Tokens it keeps out of the context, summed over the requests that re-read them. */
|
|
78
|
+
tokens: number;
|
|
79
|
+
savedUsd: number;
|
|
80
|
+
/** One more request at each moved result's context: what opening the file (or running the command again) costs a time. */
|
|
81
|
+
openUsd: number;
|
|
82
|
+
}
|
|
83
|
+
export interface ToolOutputReplay {
|
|
84
|
+
/** Transcripts read (main conversations and subagents). */
|
|
85
|
+
transcripts: number;
|
|
86
|
+
requests: number;
|
|
87
|
+
/** Input billed over the same requests (prompt only), the share's base. */
|
|
88
|
+
billedUsd: number;
|
|
89
|
+
/** Successful Bash results Claude Code already saved to a file (over 30,000 characters or the cap set). */
|
|
90
|
+
alreadyMoved: number;
|
|
91
|
+
bash: Array<CapReplay & {
|
|
92
|
+
cap: number;
|
|
93
|
+
}>;
|
|
94
|
+
/** MAX_MCP_OUTPUT_TOKENS at MCP_OUTPUT_CAP: measured, not offered (the model gets no preview). */
|
|
95
|
+
mcp: CapReplay & {
|
|
96
|
+
cap: number;
|
|
97
|
+
};
|
|
98
|
+
/** The cap `fix` offers: the most saved among those that cover the model opening at least half the files. */
|
|
99
|
+
recommended?: number;
|
|
100
|
+
}
|
|
101
|
+
/** The share of moved results the model could open before the cap stops paying (each opening costs openUsd / moved and loses that result's saving). */
|
|
102
|
+
export declare function breakEven(r: CapReplay): number;
|
|
103
|
+
export interface ToolOutputOptions {
|
|
104
|
+
since: number;
|
|
105
|
+
until?: number;
|
|
106
|
+
/** Transcripts (default: Claude Code's main conversations and subagents written since `since`). */
|
|
107
|
+
paths?: string[];
|
|
108
|
+
caps?: number[];
|
|
109
|
+
}
|
|
110
|
+
/** Claude Code transcripts written since `since`, subagents included: every place a tool result is re-read. */
|
|
111
|
+
export declare function toolOutputTranscripts(since: number): string[];
|
|
112
|
+
/** Replay every Bash and MCP result in [since, until) at each candidate cap. */
|
|
113
|
+
export declare function replayToolOutput(opts: ToolOutputOptions): ToolOutputReplay;
|
|
114
|
+
/** What a cap set at `since` saved: the results it moved that the cap before (`previous`) left inline, re-read no more. */
|
|
115
|
+
export declare function toolOutputSavedSince(since: number, previous: number, paths?: string[]): CapReplay;
|
|
116
|
+
/** The lines under the lever in `fix`: each cap tried, and MCP's. */
|
|
117
|
+
export declare function renderToolOutputCaps(r: ToolOutputReplay): string[];
|
|
118
|
+
export {};
|