context-doctor 0.42.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.
@@ -0,0 +1,216 @@
1
+ /**
2
+ * A session's own price, said once while it runs.
3
+ *
4
+ * The budget counts a day across tools; one session can cost $2,000 on its
5
+ * own without anyone noticing that each message now re-reads ~470k tokens
6
+ * (the author's `gantry-ai` audit: 2,795 requests, 1.3B cached tokens read).
7
+ * So before each prompt (Claude Code's and Codex's UserPromptSubmit, Gemini
8
+ * CLI's BeforeAgent) the hook adds up what this session has cost, subagents
9
+ * included (they bill to it), and when it passes $25, $100 and $500 says so
10
+ * to the user once: the cost so far, what each message of the main
11
+ * conversation now costs at the model's cache-read rate (or, after an idle
12
+ * that expired the cache, the re-write this message pays), and that
13
+ * /compact or a handoff to a new session cuts it.
14
+ *
15
+ * To the user, not the model: compacting or moving to a new session is the
16
+ * person's decision about their money, and only they can run /compact. The
17
+ * cold-resume offer measured how a model-delivered offer fares (acted on 1
18
+ * time in 33 before it got a line of its own), and a note in the model's
19
+ * context costs every later request and can pull it off the task. The
20
+ * heavy-context note already asks the model to offer a compaction.
21
+ *
22
+ * Fast and quiet. The cost is the budget ledger's per-transcript entry
23
+ * (budget.ts refreshEntry), with the period starting at 0: a prompt reads
24
+ * only what was appended since the last read. The entries are kept beside
25
+ * the hook's per-session state, but written only once enough was read to be
26
+ * worth keeping (SAVE_BYTES) or a threshold was said, so a session below
27
+ * the first threshold costs a read of its last turns and writes nothing.
28
+ * Each threshold is claimed by creating a file that must not exist yet
29
+ * (`wx`), which exactly one of several hooks running at once can do. Once
30
+ * the top threshold is said, the check is one stat.
31
+ *
32
+ * Thresholds: CONTEXT_DOCTOR_SESSION_PRICE (dollars, e.g. "50,200");
33
+ * off: CONTEXT_DOCTOR_NO_SESSION_PRICE=1.
34
+ */
35
+ import { existsSync, mkdirSync, readdirSync, readFileSync, writeFileSync } from "node:fs";
36
+ import { createHash } from "node:crypto";
37
+ import { basename, dirname, join } from "node:path";
38
+ import { statePath } from "./ledger.js";
39
+ import { refreshEntry, wellFormed, writeWhole } from "./budget.js";
40
+ import { codexFileSpend, geminiFileSpend } from "./spend.js";
41
+ import { isGeminiChat } from "./gemini.js";
42
+ import { subagentDir } from "./subagents.js";
43
+ import { tailUsage } from "./statusline.js";
44
+ import { autoCompactsAt, detectColdResume, withResumeVerdict } from "./coldresume.js";
45
+ import { formatUsd, pricingFor } from "./pricing.js";
46
+ import { formatTokens } from "./tokens.js";
47
+ /** Where the hook speaks unless CONTEXT_DOCTOR_SESSION_PRICE says otherwise. */
48
+ export const SESSION_PRICE_THRESHOLDS = [25, 100, 500];
49
+ /**
50
+ * The entries are written once a prompt has read this much: below it, the
51
+ * next prompt reading the same bytes again costs a few milliseconds, less
52
+ * than a write.
53
+ */
54
+ const SAVE_BYTES = 512 * 1024;
55
+ /** The thresholds in force, ascending; none when switched off. */
56
+ export function sessionPriceThresholds(env = process.env) {
57
+ if (env.CONTEXT_DOCTOR_NO_SESSION_PRICE === "1")
58
+ return [];
59
+ const raw = env.CONTEXT_DOCTOR_SESSION_PRICE?.trim();
60
+ if (!raw)
61
+ return SESSION_PRICE_THRESHOLDS;
62
+ const set = raw.split(/[\s,]+/).map((v) => Number(v.replace(/^\$/, ""))).filter((v) => Number.isFinite(v) && v > 0);
63
+ // A value that is not a list of dollars is not a reason to go quiet: the defaults.
64
+ return set.length ? [...new Set(set)].sort((a, b) => a - b) : SESSION_PRICE_THRESHOLDS;
65
+ }
66
+ /** This session's files beside the hook's own state: one hash per session, as hook.ts and fanout.ts name them. */
67
+ function base(sessionId) {
68
+ return join(statePath().replace(/\.json$/, "") + ".d", createHash("sha1").update(sessionId).digest("hex").slice(0, 16));
69
+ }
70
+ const ledgerFile = (b) => `${b}.price.json`;
71
+ const claimFile = (b, usd) => `${b}.price-${usd}`;
72
+ /** True for exactly one caller per path: the file is created only if it is not there. */
73
+ function claim(path) {
74
+ for (let attempt = 0; attempt < 2; attempt++) {
75
+ try {
76
+ writeFileSync(path, "", { flag: "wx", mode: 0o600 });
77
+ return true;
78
+ }
79
+ catch (e) {
80
+ if (e.code !== "ENOENT" || attempt)
81
+ return false;
82
+ mkdirSync(dirname(path), { recursive: true });
83
+ }
84
+ }
85
+ return false;
86
+ }
87
+ /** The app a transcript belongs to. */
88
+ function appOf(transcript, event) {
89
+ if (event === "BeforeAgent" || isGeminiChat(transcript))
90
+ return "gemini";
91
+ return /^rollout-.*\.jsonl$/.test(basename(transcript)) ? "codex" : "claude";
92
+ }
93
+ /**
94
+ * The threshold this prompt is the first to pass, with what to say about
95
+ * it, or undefined (below the first, said already, or anything unreadable).
96
+ * Claims the threshold: a second call for the same one gets undefined.
97
+ */
98
+ export function sessionPriceDue(input, now = Date.now(), env = process.env) {
99
+ const thresholds = sessionPriceThresholds(env);
100
+ if (!thresholds.length)
101
+ return undefined;
102
+ const b = base(input.sessionId);
103
+ // Everything said: one stat from now on.
104
+ if (existsSync(claimFile(b, thresholds[thresholds.length - 1])))
105
+ return undefined;
106
+ const app = appOf(input.transcript, input.event);
107
+ const files = [[input.transcript, false]];
108
+ if (app === "claude") {
109
+ // Subagents bill to the session that started them.
110
+ const dir = subagentDir(input.transcript);
111
+ try {
112
+ for (const f of readdirSync(dir))
113
+ if (f.endsWith(".jsonl"))
114
+ files.push([join(dir, f), true]);
115
+ }
116
+ catch { /* no subagents */ }
117
+ }
118
+ let saved = {};
119
+ try {
120
+ const raw = JSON.parse(readFileSync(ledgerFile(b), "utf8"))?.f;
121
+ if (raw && typeof raw === "object")
122
+ saved = raw;
123
+ }
124
+ catch { /* none yet, or damaged: read again */ }
125
+ const kept = {};
126
+ let read = 0;
127
+ for (const [file] of files) {
128
+ const prev = saved[file];
129
+ const r = refreshEntry(app, file, wellFormed(prev) && prev.t === app ? prev : undefined, 0, true);
130
+ if (!r)
131
+ continue;
132
+ kept[file] = r.e;
133
+ // Only a Claude Code entry saves a read: Codex's and Gemini's are read whole on a change (through the scan's cache).
134
+ if (app === "claude")
135
+ read += Math.max(0, r.read);
136
+ }
137
+ // Each reply once: a fork's copy shares its key with the reply it copied.
138
+ const seen = new Set();
139
+ let usd = 0, subagentUsd = 0;
140
+ for (const [file, sub] of files) {
141
+ const e = kept[file];
142
+ if (!e)
143
+ continue;
144
+ e.k.forEach((key, i) => {
145
+ if (key) {
146
+ if (seen.has(key))
147
+ return;
148
+ seen.add(key);
149
+ }
150
+ usd += e.d[i];
151
+ if (sub)
152
+ subagentUsd += e.d[i];
153
+ });
154
+ }
155
+ const save = () => { try {
156
+ writeWhole(ledgerFile(b), { f: kept });
157
+ }
158
+ catch { /* read again next time */ } };
159
+ const passed = thresholds.filter((t) => usd >= t);
160
+ const top = passed[passed.length - 1];
161
+ if (top === undefined || existsSync(claimFile(b, top)) || !claim(claimFile(b, top))) {
162
+ if (read >= SAVE_BYTES)
163
+ save();
164
+ return undefined;
165
+ }
166
+ // Passed two at once (a first look at a long session): said once, for the higher.
167
+ for (const t of passed.slice(0, -1))
168
+ claim(claimFile(b, t));
169
+ save();
170
+ return { app, threshold: top, usd, subagentUsd, ...perMessage(app, input, now) };
171
+ }
172
+ /** The main conversation's context now, and what the next message pays for it. */
173
+ function perMessage(app, input, now) {
174
+ try {
175
+ if (app !== "claude") {
176
+ // Codex and Gemini CLI: the last request's prompt, at the cached rate.
177
+ const items = app === "codex" ? codexFileSpend(input.transcript, 0) : geminiFileSpend(input.transcript, 0);
178
+ const last = items[items.length - 1];
179
+ const model = last?.model ?? input.model;
180
+ const p = pricingFor(model);
181
+ if (!last || !p)
182
+ return {};
183
+ const tokens = last.input + last.read + last.write;
184
+ return { tokens, model, readUsd: (tokens * p.cacheReadPerM) / 1e6 };
185
+ }
186
+ // Undefined right after a compaction: the new size is not known yet.
187
+ const live = tailUsage(input.transcript);
188
+ if (!live)
189
+ return {};
190
+ const model = live.model ?? input.model;
191
+ const p = pricingFor(model);
192
+ // Claude Code compacts this very prompt itself: the figure is about to be wrong.
193
+ if (!p || live.tokens >= (autoCompactsAt(model) ?? Infinity))
194
+ return {};
195
+ const cold = withResumeVerdict(detectColdResume(input.transcript, now, undefined, 0), input.rv?.(), now);
196
+ return { tokens: live.tokens, model, readUsd: (live.tokens * p.cacheReadPerM) / 1e6, ...(cold?.resumeUsd !== undefined ? { coldUsd: cold.resumeUsd } : {}) };
197
+ }
198
+ catch {
199
+ return {};
200
+ }
201
+ }
202
+ /** "$112", "$1,240", "$25.40": a session's cost as the line shows it. */
203
+ const dollars = (n) => (n >= 100 ? `$${Math.round(n).toLocaleString("en-US")}` : `$${n.toFixed(2)}`);
204
+ /** The line for the user (the hook's systemMessage). */
205
+ export function renderSessionPrice(p) {
206
+ const subs = p.subagentUsd >= 0.005 ? ` (${dollars(p.subagentUsd)} of it subagents)` : "";
207
+ const head = `context-doctor: this session has cost ${dollars(p.usd)} so far${subs}`;
208
+ if (p.tokens === undefined || p.readUsd === undefined)
209
+ return `${head}.`;
210
+ const compact = p.app === "gemini" ? "/compress" : "/compact";
211
+ const ctx = `~${formatTokens(p.tokens)} tokens`;
212
+ const each = p.coldUsd !== undefined
213
+ ? `the cache expired while it was idle, so this message re-writes its ${ctx} (~${formatUsd(p.coldUsd)}), and each one after re-reads them (~${formatUsd(p.readUsd)})`
214
+ : `each message now re-reads ${ctx} (~${formatUsd(p.readUsd)})`;
215
+ return `${head}; ${each}. ${compact}, or a handoff to a new session, cuts that.`;
216
+ }
@@ -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 {};