context-doctor 0.40.0 → 0.41.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -9,6 +9,7 @@ AI agents re-send their whole context on every message: old tool output, pasted
9
9
  ```bash
10
10
  npx context-doctor savings # what your recent sessions cost, and what each fix would have saved
11
11
  npx context-doctor fix # the fixes ranked by dollars; applies only the ones you say yes to
12
+ npx context-doctor spend # one bill across Claude Code, Codex, Gemini CLI and Cursor
12
13
  ```
13
14
 
14
15
  <img src="https://raw.githubusercontent.com/KushalP1/context-doctor/main/assets/savings.svg" alt="npx context-doctor savings: input billed, what /compact at cold resumes, autopilot and an earlier auto-compact window would have saved" width="640">
@@ -27,11 +28,12 @@ Pick where you work. Each takes about a minute and is fully reversible.
27
28
  | **claude.ai, ChatGPT, phone apps** | `npx context-doctor instructions --copy`, then paste into the app's personal preferences (it tells you where). ChatGPT can also reach the MCP server at a URL ([how](./docs/chat-apps.md#chatgpt)) |
28
29
  | **Your own app on an LLM API** | Run `npx context-doctor proxy --autopilot` and point `ANTHROPIC_BASE_URL`, `OPENAI_BASE_URL` (add `/v1`) or `GOOGLE_GEMINI_BASE_URL` at the proxy on `127.0.0.1:8787`, plain HTTP ([exact values](./docs/proxy.md)). No proxy possible? Wrap the SDK client: `withContextDoctor(new Anthropic())` ([library](./docs/library.md)) |
29
30
  | **Python / RAG pipelines** | `pip install "git+https://github.com/KushalP1/context-doctor#subdirectory=python"` (PyPI release coming), then `pack_documents(retrieved_docs, question, budget=4000)` trims LangChain or LlamaIndex results to the chunks that matter. [Python README](./python/README.md) |
30
- | **GitHub pull requests** | `uses: KushalP1/context-doctor@v0.40.0` comments how much a PR grows CLAUDE.md, AGENTS.md and rules, and can fail over a budget ([setup](./docs/ci.md)) |
31
+ | **GitHub pull requests** | `uses: KushalP1/context-doctor@v0.41.0` comments how much a PR grows CLAUDE.md, AGENTS.md and rules, and can fail over a budget ([setup](./docs/ci.md)) |
31
32
 
32
33
  ## What it does
33
34
 
34
35
  **Measure, in dollars, on your own history** ([profiling](./docs/profiling.md))
36
+ - `spend`: one bill across Claude Code (subagents included), Codex, Gemini CLI and Cursor, by tool, project, model and day, at list prices ([spend and budget](./docs/spend.md)).
35
37
  - `savings`: what your recent Claude Code sessions cost and what each fix below would have saved, replayed request by request against what you were billed.
36
38
  - `overhead`: what every request re-reads before your message (system prompt, tools, MCP servers, CLAUDE.md, rules, memory), each file priced per month.
37
39
  - `tasks`, `reads`, `subagents`, `compactions`: cost per commit; files read into session after session; whether each subagent was cheaper than the same steps in the parent; whether sessions work worse after compacting.
@@ -51,6 +53,7 @@ Pick where you work. Each takes about a minute and is fully reversible.
51
53
  - A subagent price (`PreToolUse` on the Agent tool) shows what a subagent costs before it starts, at your own median for that type (the author's: $3.99 for general-purpose, $1.43 for Explore, 422 runs in 30 days), with the Sonnet price where it would run on Opus or Fable, and a total when launches bunch up. It never blocks.
52
54
  - A compaction hook (`PreCompact`) tells each Claude Code compaction what the session cannot lose (files changed, open tasks, your instructions, failing tests), so compacting saves tokens without losing the thread.
53
55
  - An every-prompt hook (Claude Code, Codex, Gemini CLI; Cursor after each tool call) tells the model its real context size and the largest waste, and offers `/compact` when you return to a big session after the cache expired.
56
+ - `budget 50/day` (or `/week`): the every-prompt hook in Claude Code, Codex and Gemini CLI says when today's spend passes 50%, 80% and 100% of it, and with `--block` holds prompts over budget; the status line shows `$12/$50 today`.
54
57
  - `compact-window`: sets Claude Code's own auto-compact window, measured on your history first. Works in the desktop app too.
55
58
  - `cache-ttl`: replays your own pauses at a 5-minute and a 1-hour prompt cache and sets Claude Code's `promptCacheTtl` to the cheaper one (the author's: 7% less main-conversation input at 1 hour; 22% less than the 5-minute default an API key gets). Same content either way, so no quality cost ([fixes](./docs/fix.md)).
56
59
  - [Autopilot](./docs/autopilot.md): a local proxy (or SDK wrapper) that clears stale tool output only when the prompt cache is cold, so a request never costs more.
@@ -130,6 +133,8 @@ Rules 1-4 end exactly at character 512, the part ChatGPT's guide says must stand
130
133
  |---|---|
131
134
  | `context-doctor install` / `uninstall` | Wire (or remove) everything it finds: the MCP server for Claude Desktop, Claude Code, Cursor, Codex, Gemini CLI, Google Antigravity and GitHub Copilot; the Agent Skill (Claude Code, Codex, Antigravity); the every-prompt hook (Claude Code, Codex, Gemini CLI's `BeforeAgent`, Cursor's `postToolUse`, `postToolUseFailure` and `sessionStart`); Claude Code's `PreCompact`, `SessionStart`, `PreToolUse` (the subagent price) and, on 2.1.251+, `PreModelSwitch` hooks; Copilot's `sessionStart` (the standing rules). `--statusline` adds the status bar line ([details](./docs/install.md)) |
132
135
  | `context-doctor fix [--apply ids\|all] [--share]` / `fix undo` | Every lever ranked by what it would have saved on your last 30 days (compact earlier, the cache lifetime, autopilot, MCP tool search, unused servers), with what each costs in quality; applies one only on a yes, `fix undo` reverts exactly what it changed, later runs show what each saved since ([details](./docs/fix.md)) |
136
+ | `context-doctor spend [--days n] [--share]` | One bill across every tool on this machine: Claude Code (main conversation and subagents), Codex, Gemini CLI and Cursor (an estimate: no cache split), by tool, project, model and day, with what drives it ([docs](./docs/spend.md)) |
137
+ | `context-doctor budget [<$>/day\|<$>/week [--block]\|off]` | A spend budget the every-prompt hook applies: a line at 50%, 80% and 100%, and with `--block` prompts over it are held until you raise it or turn it off ([docs](./docs/spend.md#a-budget-the-hook-applies-context-doctor-budget)) |
133
138
  | `context-doctor doctor` | Self-check the whole installation — one pasteable ✓/✗ diagnosis with fixes, including which surfaces autopilot can reach and any other program on its port |
134
139
  | `context-doctor savings [--days n] [--share [--copy]]` | What your recent Claude Code sessions cost, and what `/compact` at cold resumes, autopilot and an earlier auto-compact window would save, replayed through the shipped code against your actual billed usage. `--share` prints totals only (no project names or paths) to post. A bare `context-doctor` in a terminal shows the same |
135
140
  | `context-doctor autopilot on\|off\|pause\|resume\|status` | Every new Claude Code session started in a terminal or IDE goes through the local proxy, which clears stale tool output only when the prompt cache is cold: measured 12.7% less input cost, no session worse ([details](./docs/autopilot.md)) |
@@ -175,6 +180,7 @@ Rules 1-4 end exactly at character 512, the part ChatGPT's guide says must stand
175
180
 
176
181
  ## What's new
177
182
 
183
+ - **0.41 One bill, a budget, and the subagents' model**: `context-doctor spend` puts Claude Code (subagents included), Codex, Gemini CLI and Cursor on one bill by tool, project, model and day. `context-doctor budget 50/day` has the every-prompt hook tell you at 50%, 80% and 100%, and with `--block` holds prompts over budget; the status line shows `$12/$50 today`, at about 5 ms a prompt. `fix` gains `subagent-model`: subagents run on your main conversation's model (Opus or Fable included), and `CLAUDE_CODE_SUBAGENT_MODEL` set to Sonnet 5.5 would have cost the author $632 less (38% of $1,658) in 30 days; it changes the model, so it is applied only when you name it, and `fix undo` reverts it.
178
184
  - **0.40 Reports in under a second**: `fix`, `savings`, `compact-window`, `cache-ttl`, `cache-misses` and `overhead` read each transcript once and keep what they took from it in `~/.cache/context-doctor`, so a second run reads only what was appended: `fix` 23.5 s → 0.4 s, `savings` 41 s → 0.6 s on the author's 2.7 GB history, every figure unchanged ([details](./docs/performance.md#the-transcript-cache)). Also from a QA pass on 0.39: `install` then `uninstall` gives every config back byte for byte, and `doctor` warns about an out-of-date skill.
179
185
  - **0.39 `fix`, the cache lifetime, the cache clock, and Antigravity**: `context-doctor fix` turns the measurements into changes: every lever ranked by what it would have saved on your own sessions, with what each costs in quality, applied only on a yes, undone with `fix undo`, and re-measured afterwards (`/context-doctor:fix` in the plugin). `cache-ttl` replays your pauses at a 5-minute and a 1-hour prompt cache and sets Claude Code's `promptCacheTtl` to the cheaper one, a price-only change. On Claude Code 2.1.251+ the status line says until when the cache is warm and what going cold costs, `cache-misses` explains misses in Claude Code's own words, and `install` wires Google Antigravity.
180
186
  - **0.38 Your limits in their own unit, regressions after upgrades, recall, and a subagent price**: `context-doctor limits` shows each plan window's %, pace and run-out time (Claude Pro/Max through the status line, Codex from its rollouts) and what 1M tokens cost in % of it, fitted on your readings with the error; `savings` then speaks in your limit too. `cache-misses` flags step changes after a Claude Code upgrade, `recall` searches the session's own transcript (compacted turns included), a hook prices a subagent before it starts (never blocking), and `overhead prune` switches off unused MCP servers and skills per project, reversibly. OpenAI caches count as warm for up to 24 hours. An independent QA pass's findings were fixed before the release.
@@ -186,7 +192,8 @@ Every release, with the details: [docs/whats-new.md](./docs/whats-new.md).
186
192
 
187
193
  - [What `install` does](./docs/install.md): every file it writes, what runs in each session after, and when you need MCP
188
194
  - [Autopilot](./docs/autopilot.md): how it clears stale tool output, and why it never costs more
189
- - [Fixes](./docs/fix.md): `fix` (one plan, applied with consent, undone in one step, re-measured) and `cache-ttl`
195
+ - [Fixes](./docs/fix.md): `fix` (one plan, applied with consent, undone in one step, re-measured), `cache-ttl` and the subagents' model
196
+ - [Spend and budget](./docs/spend.md): one bill across every tool, and a budget the every-prompt hook applies
190
197
  - [The proxy](./docs/proxy.md): autopilot and the optimizing mode for your API apps, `/stats`, cache advice, a public URL for Cursor
191
198
  - [Chat apps](./docs/chat-apps.md): Claude Desktop, ChatGPT, claude.ai and the phone apps; what acts by itself and what only nudges; the MCP tools, prompts and resources
192
199
  - [Handoff](./docs/handoff.md): continue a long chat in a new one from a ≤400-token brief
@@ -0,0 +1,91 @@
1
+ /**
2
+ * `context-doctor budget`: a spend budget the every-prompt hook enforces.
3
+ *
4
+ * `budget 50/day` (or `200/week`) is kept in ~/.claude/.context-doctor-budget.json.
5
+ * Before each prompt the hook (Claude Code's UserPromptSubmit, Codex's
6
+ * UserPromptSubmit, Gemini CLI's BeforeAgent) adds up what today (or this
7
+ * week, from Monday) has cost across Claude Code, Codex and Gemini CLI, as
8
+ * `spend` prices it, and says so to the user once per threshold: at 50%, 80%
9
+ * and 100%. With `--block`, over the budget it holds the prompt in each
10
+ * host's documented way (`decision: "block"` with a reason in Claude Code and
11
+ * Codex, `decision: "deny"` in Gemini CLI), saying how to lift it. Cursor is
12
+ * not counted: its history is a database too slow to read on every prompt,
13
+ * and its prompt hook cannot add a line.
14
+ *
15
+ * The hook must stay fast, so the period's spend is a ledger
16
+ * (~/.claude/.context-doctor-budget-state.json): per transcript, its size,
17
+ * time and inode when last read, and the period's requests in it (a short
18
+ * key and the dollars). A transcript met for the first time in a period is
19
+ * read through the shared scan (scan.ts), as `spend` reads it; after that a
20
+ * prompt reads only what was appended to the transcripts that changed, a
21
+ * few kilobytes, without loading the scan's records for a whole transcript
22
+ * (megabytes for a long one). The keys let a fork's copy of its parent's
23
+ * replies count once. Measured on the author's history: docs/spend.md.
24
+ */
25
+ import { type Tool } from "./spend.js";
26
+ export type Period = "day" | "week";
27
+ export interface Budget {
28
+ usd: number;
29
+ period: Period;
30
+ /** Over the budget, hold the prompt instead of only saying so. */
31
+ block: boolean;
32
+ /** When it was set, ms. */
33
+ at: number;
34
+ }
35
+ /** Beside the hook state and the ledger: ~/.claude/.context-doctor-budget.json. */
36
+ export declare function budgetPath(): string;
37
+ /** The period's spend ledger and what was said: ~/.claude/.context-doctor-budget-state.json. */
38
+ export declare function budgetStatePath(): string;
39
+ /** "50/day", "$200/week", "7.5/d", "100/wk": a budget, or an error to show. */
40
+ export declare function parseBudget(arg: string): {
41
+ usd: number;
42
+ period: Period;
43
+ } | {
44
+ error: string;
45
+ };
46
+ export declare function readBudget(): Budget | undefined;
47
+ export declare function writeBudget(b: Budget): void;
48
+ /** Remove the budget and its ledger. True when there was one. */
49
+ export declare function clearBudget(): boolean;
50
+ /** The start of the period holding `now`: local midnight, or Monday's for a week. */
51
+ export declare function periodStart(period: Period, now?: number): number;
52
+ /** When the period holding `now` ends (the next one starts). */
53
+ export declare function periodEnd(period: Period, now?: number): number;
54
+ export interface PeriodSpend {
55
+ start: number;
56
+ end: number;
57
+ usd: number;
58
+ byTool: Partial<Record<Tool, number>>;
59
+ }
60
+ /**
61
+ * What the period holding `now` has cost so far, across Claude Code, Codex
62
+ * and Gemini CLI. Re-reads only the transcripts that changed since the last
63
+ * call (any process's), then writes the ledger back. `warn` (the hook's) is
64
+ * the threshold reached, recorded as said, when it is one not said yet.
65
+ */
66
+ export declare function periodSpend(period: Period, now?: number, home?: string, warnAt?: (usd: number, warned: number) => number): PeriodSpend & {
67
+ warn?: number;
68
+ };
69
+ /** The thresholds the hook speaks at. */
70
+ export declare const THRESHOLDS: readonly [50, 80, 100];
71
+ /** The highest threshold `usd` has reached of `budget` (0 below the first). */
72
+ export declare function levelOf(usd: number, budget: number): number;
73
+ export interface BudgetVerdict {
74
+ /** A line for the user, once per threshold per period. */
75
+ message?: string;
76
+ /** Over the budget with --block: why the prompt is held, and how to lift it. */
77
+ block?: string;
78
+ spend: PeriodSpend;
79
+ budget: Budget;
80
+ }
81
+ /**
82
+ * The hook's check: undefined with no budget set (one failed read: the hot
83
+ * path stays a stat), otherwise the spend so far and what to say or do.
84
+ */
85
+ export declare function budgetVerdict(now?: number, home?: string): BudgetVerdict | undefined;
86
+ /** The status line's part: "$12/$50 today", or undefined with no budget set. */
87
+ export declare function budgetStatus(now?: number, home?: string): string | undefined;
88
+ /** `budget` with no argument, and after setting one: the budget and where the period stands. */
89
+ export declare function renderBudgetStatus(b: Budget | undefined, s: PeriodSpend | undefined, hookInstalled: boolean): string;
90
+ /** Our every-prompt hook in Claude Code, Codex or Gemini CLI, or the plugin's. */
91
+ export declare function promptHookInstalled(home?: string): boolean;
package/dist/budget.js ADDED
@@ -0,0 +1,428 @@
1
+ /**
2
+ * `context-doctor budget`: a spend budget the every-prompt hook enforces.
3
+ *
4
+ * `budget 50/day` (or `200/week`) is kept in ~/.claude/.context-doctor-budget.json.
5
+ * Before each prompt the hook (Claude Code's UserPromptSubmit, Codex's
6
+ * UserPromptSubmit, Gemini CLI's BeforeAgent) adds up what today (or this
7
+ * week, from Monday) has cost across Claude Code, Codex and Gemini CLI, as
8
+ * `spend` prices it, and says so to the user once per threshold: at 50%, 80%
9
+ * and 100%. With `--block`, over the budget it holds the prompt in each
10
+ * host's documented way (`decision: "block"` with a reason in Claude Code and
11
+ * Codex, `decision: "deny"` in Gemini CLI), saying how to lift it. Cursor is
12
+ * not counted: its history is a database too slow to read on every prompt,
13
+ * and its prompt hook cannot add a line.
14
+ *
15
+ * The hook must stay fast, so the period's spend is a ledger
16
+ * (~/.claude/.context-doctor-budget-state.json): per transcript, its size,
17
+ * time and inode when last read, and the period's requests in it (a short
18
+ * key and the dollars). A transcript met for the first time in a period is
19
+ * read through the shared scan (scan.ts), as `spend` reads it; after that a
20
+ * prompt reads only what was appended to the transcripts that changed, a
21
+ * few kilobytes, without loading the scan's records for a whole transcript
22
+ * (megabytes for a long one). The keys let a fork's copy of its parent's
23
+ * replies count once. Measured on the author's history: docs/spend.md.
24
+ */
25
+ import { closeSync, existsSync, fstatSync, mkdirSync, openSync, readdirSync, readFileSync, readSync, renameSync, rmSync, statSync, unlinkSync, writeFileSync } from "node:fs";
26
+ import { randomBytes } from "node:crypto";
27
+ import { homedir } from "node:os";
28
+ import { dirname, join } from "node:path";
29
+ import { statePath } from "./ledger.js";
30
+ import { claudeDir } from "./claudedir.js";
31
+ import { claudeFileUsage, claudeUsageFiles } from "./limits.js";
32
+ import { codexFileSpend, codexFiles, geminiFileSpend, geminiFiles, TOOL_NAME } from "./spend.js";
33
+ import { pricingFor, usageCost } from "./pricing.js";
34
+ import { realModel } from "./tokens.js";
35
+ /** Beside the hook state and the ledger: ~/.claude/.context-doctor-budget.json. */
36
+ export function budgetPath() {
37
+ return join(dirname(statePath()), ".context-doctor-budget.json");
38
+ }
39
+ /** The period's spend ledger and what was said: ~/.claude/.context-doctor-budget-state.json. */
40
+ export function budgetStatePath() {
41
+ return join(dirname(statePath()), ".context-doctor-budget-state.json");
42
+ }
43
+ /** "50/day", "$200/week", "7.5/d", "100/wk": a budget, or an error to show. */
44
+ export function parseBudget(arg) {
45
+ const m = /^\$?(\d+(?:\.\d+)?)\s*\/\s*(day|d|daily|week|w|wk|weekly)$/i.exec(arg.trim());
46
+ const usd = m ? Number(m[1]) : Number.NaN;
47
+ if (!m || !(usd > 0) || usd > 1_000_000)
48
+ return { error: `"${arg}" is not a budget: give dollars per day or per week, e.g. 50/day or 200/week.` };
49
+ return { usd, period: /^d/i.test(m[2]) ? "day" : "week" };
50
+ }
51
+ export function readBudget() {
52
+ try {
53
+ const b = JSON.parse(readFileSync(budgetPath(), "utf8"));
54
+ if (typeof b?.usd === "number" && b.usd > 0 && (b.period === "day" || b.period === "week"))
55
+ return { usd: b.usd, period: b.period, block: b.block === true, at: Number(b.at) || 0 };
56
+ }
57
+ catch {
58
+ /* none set, or damaged: no budget */
59
+ }
60
+ return undefined;
61
+ }
62
+ /** A whole file renamed into place, so two prompts at once never read half of one. */
63
+ function writeWhole(path, value) {
64
+ const tmp = `${path}.${process.pid}.${randomBytes(4).toString("hex")}.tmp`;
65
+ try {
66
+ mkdirSync(dirname(path), { recursive: true });
67
+ writeFileSync(tmp, JSON.stringify(value), { mode: 0o600 });
68
+ renameSync(tmp, path);
69
+ }
70
+ catch (e) {
71
+ try {
72
+ unlinkSync(tmp);
73
+ }
74
+ catch { /* never written */ }
75
+ throw e;
76
+ }
77
+ }
78
+ export function writeBudget(b) {
79
+ writeWhole(budgetPath(), b);
80
+ // A new budget starts its thresholds afresh; the ledger stays (same period, same spend).
81
+ const st = readState();
82
+ if (st)
83
+ writeWhole(budgetStatePath(), { ...st, warned: 0 });
84
+ }
85
+ /** Remove the budget and its ledger. True when there was one. */
86
+ export function clearBudget() {
87
+ const had = existsSync(budgetPath());
88
+ rmSync(budgetPath(), { force: true });
89
+ rmSync(budgetStatePath(), { force: true });
90
+ return had;
91
+ }
92
+ /** The start of the period holding `now`: local midnight, or Monday's for a week. */
93
+ export function periodStart(period, now = Date.now()) {
94
+ const d = new Date(now);
95
+ const start = new Date(d.getFullYear(), d.getMonth(), d.getDate());
96
+ if (period === "week")
97
+ start.setDate(start.getDate() - ((start.getDay() + 6) % 7));
98
+ return start.getTime();
99
+ }
100
+ /** When the period holding `now` ends (the next one starts). */
101
+ export function periodEnd(period, now = Date.now()) {
102
+ const s = new Date(periodStart(period, now));
103
+ s.setDate(s.getDate() + (period === "week" ? 7 : 1));
104
+ return s.getTime();
105
+ }
106
+ /** Replies remembered per transcript, to tell a later row of one from a new reply. */
107
+ const RECENT_REPLIES = 64;
108
+ function readState() {
109
+ try {
110
+ const s = JSON.parse(readFileSync(budgetStatePath(), "utf8"));
111
+ if (typeof s?.start === "number" && s.files && typeof s.files === "object")
112
+ return { start: s.start, files: s.files, warned: Number(s.warned) || 0, usd: Number(s.usd) || 0, byTool: s.byTool ?? {} };
113
+ }
114
+ catch {
115
+ /* none yet, or damaged: start afresh */
116
+ }
117
+ return undefined;
118
+ }
119
+ /**
120
+ * Write the ledger. Another prompt or the status line may have written it
121
+ * meanwhile: a threshold it already said stays said.
122
+ */
123
+ function saveState(st) {
124
+ const disk = readState();
125
+ if (disk?.start === st.start)
126
+ st.warned = Math.max(st.warned, disk.warned);
127
+ try {
128
+ writeWhole(budgetStatePath(), st);
129
+ }
130
+ catch { /* a read-only folder: worked out again next time */ }
131
+ }
132
+ /** Claude Code's main transcripts written since `since`, without listing Codex's or Gemini's too. */
133
+ function claudeTops(since) {
134
+ const root = join(claudeDir(), "projects");
135
+ const out = [];
136
+ let dirs;
137
+ try {
138
+ dirs = readdirSync(root);
139
+ }
140
+ catch {
141
+ return out;
142
+ }
143
+ for (const d of dirs) {
144
+ let names;
145
+ try {
146
+ names = readdirSync(join(root, d));
147
+ }
148
+ catch {
149
+ continue;
150
+ }
151
+ for (const n of names) {
152
+ if (!n.endsWith(".jsonl"))
153
+ continue;
154
+ try {
155
+ if (statSync(join(root, d, n)).mtimeMs >= since)
156
+ out.push(join(root, d, n));
157
+ }
158
+ catch { /* vanished */ }
159
+ }
160
+ }
161
+ return out;
162
+ }
163
+ /** 12 hex digits of a row's uuid: enough to tell a fork's copy, a third of the bytes. */
164
+ const keyOf = (uuid) => (uuid ? uuid.slice(0, 13) : "");
165
+ /** The offset just after the last newline before `size`: where a whole-line read resumes. */
166
+ function lineStart(fd, size) {
167
+ const buf = Buffer.alloc(64 * 1024);
168
+ for (let end = size; end > 0;) {
169
+ const from = Math.max(0, end - buf.length);
170
+ const n = readSync(fd, buf, 0, end - from, from);
171
+ const nl = buf.subarray(0, n).lastIndexOf(10);
172
+ if (nl >= 0)
173
+ return from + nl + 1;
174
+ end = from;
175
+ }
176
+ return 0;
177
+ }
178
+ /**
179
+ * The requests of one transcript in the period, read in full (through the
180
+ * shared scan, so only what it has not cached), as the ledger keeps them.
181
+ */
182
+ function readFile(tool, file, since, size) {
183
+ const k = [], d = [];
184
+ if (tool !== "claude") {
185
+ for (const r of tool === "codex" ? codexFileSpend(file, since) : geminiFileSpend(file, since)) {
186
+ k.push("");
187
+ d.push(r.usd);
188
+ }
189
+ return { k, d };
190
+ }
191
+ const reqs = claudeFileUsage(file, since);
192
+ const r = [];
193
+ reqs.forEach((q, i) => {
194
+ k.push(keyOf(q.uuid));
195
+ d.push(q.usd);
196
+ if (q.id)
197
+ r.push([q.id, i, q.output, pricingFor(q.model)?.outputPerM ?? 0]);
198
+ });
199
+ const fd = openSync(file, "r");
200
+ try {
201
+ return { k, d, o: lineStart(fd, size), r: r.slice(-RECENT_REPLIES) };
202
+ }
203
+ finally {
204
+ closeSync(fd);
205
+ }
206
+ }
207
+ /**
208
+ * A Claude Code transcript that grew: the whole lines after `e.o`, each
209
+ * reply counted as claudeFileUsage counts it (once, its output settled on
210
+ * its later rows, priced with usageCost), into `e`.
211
+ */
212
+ function readAppended(e, file, since) {
213
+ const fd = openSync(file, "r");
214
+ try {
215
+ const size = fstatSync(fd).size;
216
+ const from = e.o ?? 0;
217
+ const buf = Buffer.alloc(size - from);
218
+ const n = readSync(fd, buf, 0, buf.length, from);
219
+ const end = buf.subarray(0, n).lastIndexOf(10);
220
+ if (end < 0)
221
+ return;
222
+ const recent = e.r ?? [];
223
+ for (const line of buf.subarray(0, end).toString("utf8").split("\n")) {
224
+ if (!line.includes('"usage"'))
225
+ continue;
226
+ let row;
227
+ try {
228
+ row = JSON.parse(line);
229
+ }
230
+ catch {
231
+ continue;
232
+ }
233
+ const m = row?.message;
234
+ if (row?.type !== "assistant" || !m?.usage)
235
+ continue;
236
+ const u = m.usage;
237
+ const out = Number(u.output_tokens) > 0 ? Number(u.output_tokens) : 0;
238
+ const known = typeof m.id === "string" ? recent.find((x) => x[0] === m.id) : undefined;
239
+ if (known) {
240
+ // A later row of a reply already met: only output it settles on is new.
241
+ if (out > known[2]) {
242
+ if (known[1] >= 0)
243
+ e.d[known[1]] += ((out - known[2]) * known[3]) / 1e6;
244
+ known[2] = out;
245
+ }
246
+ continue;
247
+ }
248
+ const ts = Date.parse(String(row.timestamp ?? ""));
249
+ const tokens = [u.input_tokens, u.cache_read_input_tokens, u.cache_creation_input_tokens].reduce((t, v) => t + (Number(v) > 0 ? Number(v) : 0), 0);
250
+ const price = pricingFor(realModel(m.model));
251
+ let index = -1;
252
+ if (Number.isFinite(ts) && ts >= since && tokens > 0) {
253
+ index = e.k.length;
254
+ e.k.push(keyOf(typeof row.uuid === "string" ? row.uuid : undefined));
255
+ e.d.push(price ? usageCost(u, price).totalUsd : 0);
256
+ }
257
+ if (typeof m.id === "string")
258
+ recent.push([m.id, index, out, price?.outputPerM ?? 0]);
259
+ }
260
+ e.r = recent.slice(-RECENT_REPLIES);
261
+ e.o = from + end + 1;
262
+ }
263
+ finally {
264
+ closeSync(fd);
265
+ }
266
+ }
267
+ /**
268
+ * What the period holding `now` has cost so far, across Claude Code, Codex
269
+ * and Gemini CLI. Re-reads only the transcripts that changed since the last
270
+ * call (any process's), then writes the ledger back. `warn` (the hook's) is
271
+ * the threshold reached, recorded as said, when it is one not said yet.
272
+ */
273
+ export function periodSpend(period, now = Date.now(), home = homedir(), warnAt) {
274
+ const start = periodStart(period, now);
275
+ const prev = readState();
276
+ const fresh = !prev || prev.start !== start;
277
+ const st = fresh ? { start, files: {}, warned: 0, usd: 0, byTool: {} } : prev;
278
+ const files = [
279
+ ...claudeUsageFiles(start, claudeTops(start)).map((f) => ["claude", f.file]),
280
+ ...codexFiles(start, home).map((f) => ["codex", f]),
281
+ ...geminiFiles(start, home).map((f) => ["gemini", f]),
282
+ ];
283
+ let changed = fresh;
284
+ const kept = {};
285
+ for (const [tool, file] of files) {
286
+ let s;
287
+ try {
288
+ s = statSync(file);
289
+ }
290
+ catch {
291
+ continue;
292
+ }
293
+ const e = st.files[file];
294
+ if (e && e.t === tool && e.s === s.size && e.m === s.mtimeMs && e.i === s.ino) {
295
+ kept[file] = e;
296
+ continue;
297
+ }
298
+ try {
299
+ // Claude Code appends: a transcript that only grew is read from where the last read stopped.
300
+ if (e && tool === "claude" && e.o !== undefined && e.i === s.ino && s.size >= e.s) {
301
+ readAppended(e, file, start);
302
+ kept[file] = { ...e, s: s.size, m: s.mtimeMs };
303
+ }
304
+ else
305
+ kept[file] = { t: tool, s: s.size, m: s.mtimeMs, i: s.ino, ...readFile(tool, file, start, s.size) };
306
+ }
307
+ catch {
308
+ continue; // unreadable now: left out, read again next time
309
+ }
310
+ changed = true;
311
+ }
312
+ if (Object.keys(st.files).some((f) => !(f in kept)))
313
+ changed = true;
314
+ // Each reply once: a fork's copy shares its key with the reply it copied.
315
+ const seen = new Set();
316
+ let usd = 0;
317
+ const byTool = {};
318
+ for (const file of Object.keys(kept).sort()) {
319
+ const e = kept[file];
320
+ e.k.forEach((key, i) => {
321
+ if (key) {
322
+ if (seen.has(key))
323
+ return;
324
+ seen.add(key);
325
+ }
326
+ usd += e.d[i];
327
+ byTool[e.t] = (byTool[e.t] ?? 0) + e.d[i];
328
+ });
329
+ }
330
+ const level = warnAt ? warnAt(usd, st.warned) : 0;
331
+ const warn = level > st.warned ? level : undefined;
332
+ if (warn) {
333
+ st.warned = warn;
334
+ changed = true;
335
+ }
336
+ if (changed)
337
+ saveState({ ...st, files: kept, usd, byTool });
338
+ return { start, end: periodEnd(period, now), usd, byTool, ...(warn ? { warn } : {}) };
339
+ }
340
+ // ---------------------------------------------------------------------------
341
+ // What the hook, the status line and `budget` say
342
+ // ---------------------------------------------------------------------------
343
+ /** "$12.30", "$1,234": dollars as the budget lines show them. */
344
+ const money = (n) => (n >= 1000 ? `$${Math.round(n).toLocaleString("en-US")}` : `$${n.toFixed(2)}`);
345
+ /** "$50", "$7.50": the budget itself. */
346
+ const amount = (n) => (Number.isInteger(n) ? `$${n.toLocaleString("en-US")}` : `$${n.toFixed(2)}`);
347
+ const per = (p) => (p === "day" ? "day" : "week");
348
+ const span = (p) => (p === "day" ? "today" : "this week");
349
+ /** The thresholds the hook speaks at. */
350
+ export const THRESHOLDS = [50, 80, 100];
351
+ /** The highest threshold `usd` has reached of `budget` (0 below the first). */
352
+ export function levelOf(usd, budget) {
353
+ const pct = (usd / budget) * 100;
354
+ return [...THRESHOLDS].reverse().find((t) => pct >= t) ?? 0;
355
+ }
356
+ function byToolText(byTool) {
357
+ const parts = Object.keys(byTool).filter((t) => (byTool[t] ?? 0) >= 0.005).sort((a, b) => byTool[b] - byTool[a]).map((t) => `${TOOL_NAME[t]} ${money(byTool[t])}`);
358
+ return parts.length > 1 ? ` (${parts.join(", ")})` : "";
359
+ }
360
+ /** When the period resets, in words. */
361
+ function resets(p) {
362
+ return p === "day" ? "It resets at midnight." : "It resets on Monday.";
363
+ }
364
+ /** A higher budget to suggest: half again, or a fifth over what was spent, rounded up to $5. */
365
+ function raised(b, spent) {
366
+ return Math.ceil(Math.max(b.usd * 1.5, spent * 1.2) / 5) * 5;
367
+ }
368
+ /**
369
+ * The hook's check: undefined with no budget set (one failed read: the hot
370
+ * path stays a stat), otherwise the spend so far and what to say or do.
371
+ */
372
+ export function budgetVerdict(now = Date.now(), home = homedir()) {
373
+ const b = readBudget();
374
+ if (!b)
375
+ return undefined;
376
+ const spend = periodSpend(b.period, now, home, (usd) => levelOf(usd, b.usd));
377
+ const pct = Math.round((spend.usd / b.usd) * 100);
378
+ const head = `context-doctor: ${money(spend.usd)} spent ${span(b.period)}`;
379
+ if (b.block && spend.usd >= b.usd) {
380
+ return {
381
+ spend, budget: b,
382
+ block: `${head}${byToolText(spend.byTool)}, over your ${amount(b.usd)}/${per(b.period)} budget, so this prompt was held. To go on, turn it off (context-doctor budget off) or raise it (context-doctor budget ${raised(b, spend.usd)}/${per(b.period)}). ${resets(b.period)}`,
383
+ };
384
+ }
385
+ if (!spend.warn)
386
+ return { spend, budget: b };
387
+ const message = spend.warn >= 100
388
+ ? `${head}${byToolText(spend.byTool)}: over your ${amount(b.usd)}/${per(b.period)} budget (${pct}%). Raise it with context-doctor budget ${raised(b, spend.usd)}/${per(b.period)}, or add --block to hold prompts over it.`
389
+ : `${head}${byToolText(spend.byTool)}: ${pct}% of your ${amount(b.usd)}/${per(b.period)} budget.`;
390
+ return { spend, budget: b, message };
391
+ }
392
+ /** The status line's part: "$12/$50 today", or undefined with no budget set. */
393
+ export function budgetStatus(now = Date.now(), home = homedir()) {
394
+ const b = readBudget();
395
+ if (!b)
396
+ return undefined;
397
+ const s = periodSpend(b.period, now, home);
398
+ const short = (n) => (n >= 10 ? `$${Math.round(n).toLocaleString("en-US")}` : `$${n.toFixed(2)}`);
399
+ return `${short(s.usd)}/${amount(b.usd)} ${span(b.period)}${s.usd >= b.usd ? " ⚠" : ""}`;
400
+ }
401
+ /** `budget` with no argument, and after setting one: the budget and where the period stands. */
402
+ export function renderBudgetStatus(b, s, hookInstalled) {
403
+ if (!b || !s)
404
+ return "No spend budget set. Set one: context-doctor budget 50/day (or 200/week; --block to hold prompts over it).";
405
+ const lines = [
406
+ `Budget: ${amount(b.usd)} a ${per(b.period)}, across Claude Code, Codex and Gemini CLI${b.block ? "; prompts over it are held" : ""}.`,
407
+ `${span(b.period) === "today" ? "Today" : "This week"}: ${money(s.usd)} so far, ${Math.round((s.usd / b.usd) * 100)}%${byToolText(s.byTool)}. ${resets(b.period)}`,
408
+ ];
409
+ lines.push(hookInstalled
410
+ ? `The every-prompt hook says so at ${THRESHOLDS.join("%, ").replace(/, (\d+)$/, " and $1")}%${b.block ? ", and holds prompts over it" : ""}. Cursor is not counted (context-doctor spend shows it).`
411
+ : "No every-prompt hook is installed, so nothing will say so: run context-doctor install.");
412
+ lines.push(`Off: context-doctor budget off`);
413
+ return lines.join("\n");
414
+ }
415
+ /** Our every-prompt hook in Claude Code, Codex or Gemini CLI, or the plugin's. */
416
+ export function promptHookInstalled(home = homedir()) {
417
+ const has = (path, pick) => {
418
+ try {
419
+ return JSON.stringify(pick(JSON.parse(readFileSync(path, "utf8"))) ?? "").includes("context-doctor");
420
+ }
421
+ catch {
422
+ return false;
423
+ }
424
+ };
425
+ return has(join(claudeDir(), "settings.json"), (j) => [j?.hooks?.UserPromptSubmit, j?.enabledPlugins]) ||
426
+ has(join(home, ".codex", "hooks.json"), (j) => j?.hooks?.UserPromptSubmit) ||
427
+ has(join(home, ".gemini", "settings.json"), (j) => j?.hooks?.BeforeAgent);
428
+ }