context-doctor 0.40.0 → 0.42.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 +12 -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 +102 -0
- package/dist/budget.js +550 -0
- package/dist/cachettl.js +12 -9
- package/dist/claudedir.d.ts +8 -0
- package/dist/claudedir.js +19 -0
- package/dist/cli.js +145 -15
- 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.d.ts +23 -0
- package/dist/cursor.js +140 -6
- package/dist/doctor.d.ts +9 -0
- package/dist/doctor.js +49 -12
- 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 +23 -2
- package/dist/fix.js +86 -10
- package/dist/hook.js +45 -7
- package/dist/install.js +108 -47
- package/dist/ledger.d.ts +15 -0
- package/dist/ledger.js +30 -1
- package/dist/limits.d.ts +53 -6
- package/dist/limits.js +152 -77
- 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 +10 -0
- package/dist/scan.js +23 -1
- package/dist/session.js +2 -1
- package/dist/settingsedit.d.ts +4 -0
- package/dist/settingsedit.js +61 -3
- package/dist/spend.d.ts +183 -0
- package/dist/spend.js +493 -0
- package/dist/statusline.d.ts +9 -2
- package/dist/statusline.js +20 -4
- package/dist/subagentmodel.d.ts +141 -0
- package/dist/subagentmodel.js +408 -0
- package/dist/subagentpay.d.ts +11 -0
- package/dist/subagentpay.js +23 -4
- package/package.json +1 -1
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">
|
|
@@ -21,17 +22,18 @@ Pick where you work. Each takes about a minute and is fully reversible.
|
|
|
21
22
|
|
|
22
23
|
| You use | Do this |
|
|
23
24
|
|---|---|
|
|
24
|
-
| **Claude Code** (terminal, IDE, desktop app) | Inside Claude Code: `/plugin marketplace add KushalP1/context-doctor`, then `/plugin install context-doctor@context-doctor`. You get the every-prompt check, the compaction hook, the MCP tools and `/context-doctor:fix`, `:savings`, `:checkup`, `:overhead`, `:pack`, `:autopilot`, `:compact-window` |
|
|
25
|
+
| **Claude Code** (terminal, IDE, desktop app) | Inside Claude Code: `/plugin marketplace add KushalP1/context-doctor`, then `/plugin install context-doctor@context-doctor`. You get the every-prompt check, the compaction hook, the MCP tools and `/context-doctor:fix`, `:spend`, `:savings`, `:checkup`, `:overhead`, `:pack`, `:autopilot`, `:compact-window` |
|
|
25
26
|
| **Everything on this machine at once** | `npm install -g context-doctor && context-doctor install` wires Claude Code, Claude Desktop, Cursor, Codex, Gemini CLI, Google Antigravity and GitHub Copilot: MCP server, skill and hooks ([what it writes](./docs/install.md)). `context-doctor doctor` checks it; `context-doctor uninstall` removes it. Then, for Claude Code in a terminal or IDE, `context-doctor autopilot on` |
|
|
26
27
|
| **Claude Desktop, Cursor or any MCP client** | Add the server to the client's MCP config (or install the one-click `.mcpb` from the [latest release](https://github.com/KushalP1/context-doctor/releases/latest) in Claude Desktop):<br>`{"mcpServers": {"context-doctor": {"command": "npx", "args": ["-y", "context-doctor", "mcp"]}}}` |
|
|
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.
|
|
31
|
+
| **GitHub pull requests** | `uses: KushalP1/context-doctor@v0.42.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.
|
|
@@ -129,7 +132,9 @@ Rules 1-4 end exactly at character 512, the part ChatGPT's guide says must stand
|
|
|
129
132
|
| Command | What it does |
|
|
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
|
-
| `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)) |
|
|
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, the subagents' model), with what each costs in quality; applies one only on a yes (the subagents' model only when named), `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,8 @@ 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.42 An audit of 0.41**: each Codex request counts once (forks repeat their parent's), the budget no longer double-counts a reply streamed across midnight, unpriced models show as such instead of $0, Cursor is read after it quits, and `CODEX_HOME` is followed everywhere. `fix`'s subagent lever reads agent files the way Claude Code merges them, and every writer of `settings.json` takes one lock, so concurrent runs lose nothing ([details](./ROADMAP.md#shipped-in-0420-an-audit-of-041)).
|
|
184
|
+
- **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 in 30 days (38% of the subagents' $1,658); it changes the model, so it is applied only when you name it, and `fix undo` reverts it.
|
|
178
185
|
- **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
186
|
- **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
187
|
- **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 +193,8 @@ Every release, with the details: [docs/whats-new.md](./docs/whats-new.md).
|
|
|
186
193
|
|
|
187
194
|
- [What `install` does](./docs/install.md): every file it writes, what runs in each session after, and when you need MCP
|
|
188
195
|
- [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)
|
|
196
|
+
- [Fixes](./docs/fix.md): `fix` (one plan, applied with consent, undone in one step, re-measured), `cache-ttl` and the subagents' model
|
|
197
|
+
- [Spend and budget](./docs/spend.md): one bill across every tool, and a budget the every-prompt hook applies
|
|
190
198
|
- [The proxy](./docs/proxy.md): autopilot and the optimizing mode for your API apps, `/stats`, cache advice, a public URL for Cursor
|
|
191
199
|
- [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
200
|
- [Handoff](./docs/handoff.md): continue a long chat in a new one from a ≤400-token brief
|
package/dist/ab.js
CHANGED
|
@@ -170,7 +170,9 @@ function killLeftovers(root) {
|
|
|
170
170
|
}
|
|
171
171
|
}
|
|
172
172
|
else {
|
|
173
|
-
|
|
173
|
+
// lsof walks every process's open files: ~0.5 s here, several on a loaded machine. Cut off
|
|
174
|
+
// early, it found nothing and the leftover lived on, so it gets time.
|
|
175
|
+
const r = spawnSync("lsof", ["-t", "+D", root], { encoding: "utf8", timeout: 30_000 });
|
|
174
176
|
for (const line of (r.stdout ?? "").split("\n"))
|
|
175
177
|
if (/^\d+$/.test(line.trim()))
|
|
176
178
|
pids.add(Number(line.trim()));
|
package/dist/autopilot.d.ts
CHANGED
|
@@ -118,4 +118,4 @@ export declare function autopilotStatus(paths?: AutopilotPaths): Promise<string[
|
|
|
118
118
|
* Called by the every-prompt hook: if autopilot is on and the proxy is down,
|
|
119
119
|
* start it before the prompt's request goes out. Returns quickly either way.
|
|
120
120
|
*/
|
|
121
|
-
export declare function ensureProxyUp(paths?: AutopilotPaths, exec?: ServiceExec): Promise<void>;
|
|
121
|
+
export declare function ensureProxyUp(paths?: AutopilotPaths, exec?: ServiceExec, healthMs?: number): Promise<void>;
|
package/dist/autopilot.js
CHANGED
|
@@ -24,6 +24,7 @@ import { homedir, platform } from "node:os";
|
|
|
24
24
|
import { dirname, join } from "node:path";
|
|
25
25
|
import { fileURLToPath } from "node:url";
|
|
26
26
|
import { isEphemeralPath, readJson, writeJsonWithBackup } from "./install.js";
|
|
27
|
+
import { withSettingsLock } from "./settingsedit.js";
|
|
27
28
|
import { formatTokens } from "./tokens.js";
|
|
28
29
|
import { codexAuthMode, codexHomeIn, codexRouting, routeCodex, unrouteCodex } from "./codexroute.js";
|
|
29
30
|
import { claudeDir } from "./claudedir.js";
|
|
@@ -210,14 +211,17 @@ function migrateToolSearch(paths, cfg) {
|
|
|
210
211
|
if (cfg.setToolSearch !== undefined)
|
|
211
212
|
return;
|
|
212
213
|
try {
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
214
|
+
// Under the settings lock (fix, cache-ttl, compact-window take it too), waiting briefly: a prompt is waiting.
|
|
215
|
+
withSettingsLock(paths.settings, () => {
|
|
216
|
+
const settings = readJson(paths.settings);
|
|
217
|
+
const env = settings.env;
|
|
218
|
+
if (!env || env.ANTHROPIC_BASE_URL !== proxyUrl(cfg.port))
|
|
219
|
+
return;
|
|
220
|
+
const set = keepToolSearch(env);
|
|
221
|
+
if (set)
|
|
222
|
+
writeJsonWithBackup(paths.settings, settings);
|
|
223
|
+
writeFileSync(paths.config, JSON.stringify({ ...cfg, setToolSearch: set }, null, 2));
|
|
224
|
+
}, 500);
|
|
221
225
|
}
|
|
222
226
|
catch {
|
|
223
227
|
/* the self-heal must never disturb a prompt */
|
|
@@ -535,15 +539,19 @@ export async function autopilotOn(port = DEFAULT_AUTOPILOT_PORT, paths = autopil
|
|
|
535
539
|
return { ok: false, lines: [`✗ The proxy did not come up on port ${port} (log: ${paths.log}). Nothing was changed in Claude Code's settings.`] };
|
|
536
540
|
}
|
|
537
541
|
lines.push(`✓ Proxy running with autopilot on ${proxyUrl(port)} (${how})`);
|
|
538
|
-
|
|
539
|
-
const
|
|
540
|
-
|
|
542
|
+
// Read and written under the settings lock fix, cache-ttl and compact-window take: no concurrent key is lost.
|
|
543
|
+
const { previousBaseUrl, setToolSearch } = withSettingsLock(paths.settings, () => {
|
|
544
|
+
const settings = readJson(paths.settings);
|
|
545
|
+
const env = (settings.env ??= {});
|
|
546
|
+
const previousBaseUrl = baseUrlToRestore(paths, port, env.ANTHROPIC_BASE_URL ?? null);
|
|
547
|
+
env.ANTHROPIC_BASE_URL = proxyUrl(port);
|
|
548
|
+
const setToolSearch = keepToolSearch(env);
|
|
549
|
+
writeJsonWithBackup(paths.settings, settings);
|
|
550
|
+
return { previousBaseUrl, setToolSearch };
|
|
551
|
+
});
|
|
541
552
|
if (previousBaseUrl && previousBaseUrl !== proxyUrl(port)) {
|
|
542
553
|
lines.push(`! settings.json already routed Claude Code to ${previousBaseUrl}; autopilot forwards to api.anthropic.com instead. \`autopilot off\` restores it.`);
|
|
543
554
|
}
|
|
544
|
-
env.ANTHROPIC_BASE_URL = proxyUrl(port);
|
|
545
|
-
const setToolSearch = keepToolSearch(env);
|
|
546
|
-
writeJsonWithBackup(paths.settings, settings);
|
|
547
555
|
// Codex on an API key: its address is openai_base_url in config.toml.
|
|
548
556
|
let codex = { routed: false };
|
|
549
557
|
try {
|
|
@@ -569,13 +577,16 @@ export async function autopilotOn(port = DEFAULT_AUTOPILOT_PORT, paths = autopil
|
|
|
569
577
|
export async function autopilotOff(paths = autopilotPaths(), exec = tryRun) {
|
|
570
578
|
const lines = [];
|
|
571
579
|
const cfg = readConfig(paths);
|
|
572
|
-
|
|
573
|
-
const
|
|
574
|
-
|
|
575
|
-
|
|
576
|
-
|
|
577
|
-
|
|
578
|
-
|
|
580
|
+
// Read and written under the settings lock fix, cache-ttl and compact-window take.
|
|
581
|
+
const unrouted = withSettingsLock(paths.settings, () => {
|
|
582
|
+
const settings = readJson(paths.settings);
|
|
583
|
+
const env = settings.env;
|
|
584
|
+
// With the config damaged its port is unknown; the proxy URL in settings
|
|
585
|
+
// must still go, or every new Claude Code session points at a proxy whose
|
|
586
|
+
// service is being removed.
|
|
587
|
+
const ours = env?.ANTHROPIC_BASE_URL ? isOurProxyUrl(env.ANTHROPIC_BASE_URL, cfg?.port, paths) : false;
|
|
588
|
+
if (!env || !ours)
|
|
589
|
+
return false;
|
|
579
590
|
const restore = cfg?.previousBaseUrl && !isOurProxyUrl(cfg.previousBaseUrl, cfg.port, paths) ? cfg.previousBaseUrl : undefined;
|
|
580
591
|
if (restore)
|
|
581
592
|
env.ANTHROPIC_BASE_URL = restore;
|
|
@@ -586,8 +597,10 @@ export async function autopilotOff(paths = autopilotPaths(), exec = tryRun) {
|
|
|
586
597
|
if (Object.keys(env).length === 0)
|
|
587
598
|
delete settings.env;
|
|
588
599
|
writeJsonWithBackup(paths.settings, settings);
|
|
600
|
+
return true;
|
|
601
|
+
});
|
|
602
|
+
if (unrouted)
|
|
589
603
|
lines.push("✓ Claude Code no longer routed through the proxy (new sessions)");
|
|
590
|
-
}
|
|
591
604
|
// Our address in Codex's config.toml goes too, whether or not we recorded it.
|
|
592
605
|
try {
|
|
593
606
|
if (unrouteCodex(homeOf(paths), isOurCodexUrl(cfg?.port, paths)))
|
|
@@ -682,7 +695,7 @@ export async function autopilotStatus(paths = autopilotPaths()) {
|
|
|
682
695
|
* Called by the every-prompt hook: if autopilot is on and the proxy is down,
|
|
683
696
|
* start it before the prompt's request goes out. Returns quickly either way.
|
|
684
697
|
*/
|
|
685
|
-
export async function ensureProxyUp(paths = autopilotPaths(), exec = tryRun) {
|
|
698
|
+
export async function ensureProxyUp(paths = autopilotPaths(), exec = tryRun, healthMs = 300) {
|
|
686
699
|
const cfg = readConfig(paths);
|
|
687
700
|
if (!cfg)
|
|
688
701
|
return;
|
|
@@ -696,7 +709,8 @@ export async function ensureProxyUp(paths = autopilotPaths(), exec = tryRun) {
|
|
|
696
709
|
}
|
|
697
710
|
catch { /* never fail a prompt over this */ }
|
|
698
711
|
}
|
|
699
|
-
|
|
712
|
+
// 300 ms: a prompt is waiting. (Tests that are not about a slow proxy pass more.)
|
|
713
|
+
const h = await health(cfg.port, healthMs);
|
|
700
714
|
if (h.ok) {
|
|
701
715
|
// A service keeps running the code it started with: after an update it
|
|
702
716
|
// answers fine but is still the old version (seen: 0.25 serving for days
|
package/dist/budget.d.ts
ADDED
|
@@ -0,0 +1,102 @@
|
|
|
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
|
+
/**
|
|
40
|
+
* "50/day", "$200/week", "7.5/d", "100/wk", "50/days": a budget, or an
|
|
41
|
+
* error to show. Dollars are kept to the cent (50.555 was stored as given
|
|
42
|
+
* and shown as $50.55); `note` says so when the amount was rounded.
|
|
43
|
+
*/
|
|
44
|
+
export declare function parseBudget(arg: string): {
|
|
45
|
+
usd: number;
|
|
46
|
+
period: Period;
|
|
47
|
+
note?: string;
|
|
48
|
+
} | {
|
|
49
|
+
error: string;
|
|
50
|
+
};
|
|
51
|
+
export declare function readBudget(): Budget | undefined;
|
|
52
|
+
export declare function writeBudget(b: Budget): void;
|
|
53
|
+
/** Remove the budget and its ledger. True when there was one. */
|
|
54
|
+
export declare function clearBudget(): boolean;
|
|
55
|
+
/** The start of the period holding `now`: local midnight, or Monday's for a week. */
|
|
56
|
+
export declare function periodStart(period: Period, now?: number): number;
|
|
57
|
+
/** When the period holding `now` ends (the next one starts). */
|
|
58
|
+
export declare function periodEnd(period: Period, now?: number): number;
|
|
59
|
+
export interface PeriodSpend {
|
|
60
|
+
start: number;
|
|
61
|
+
end: number;
|
|
62
|
+
usd: number;
|
|
63
|
+
byTool: Partial<Record<Tool, number>>;
|
|
64
|
+
/** Requests on a model with no list price: counted here, not in `usd`. */
|
|
65
|
+
unpriced?: {
|
|
66
|
+
requests: number;
|
|
67
|
+
models: string[];
|
|
68
|
+
};
|
|
69
|
+
}
|
|
70
|
+
/**
|
|
71
|
+
* What the period holding `now` has cost so far, across Claude Code, Codex
|
|
72
|
+
* and Gemini CLI. Re-reads only the transcripts that changed since the last
|
|
73
|
+
* call (any process's), then writes the ledger back. `warn` (the hook's) is
|
|
74
|
+
* the threshold reached, recorded as said, when it is one not said yet.
|
|
75
|
+
*/
|
|
76
|
+
export declare function periodSpend(period: Period, now?: number, home?: string, warnAt?: (usd: number, warned: number) => number): PeriodSpend & {
|
|
77
|
+
warn?: number;
|
|
78
|
+
unpricedNew?: boolean;
|
|
79
|
+
};
|
|
80
|
+
/** The thresholds the hook speaks at. */
|
|
81
|
+
export declare const THRESHOLDS: readonly [50, 80, 100];
|
|
82
|
+
/** The highest threshold `usd` has reached of `budget` (0 below the first). */
|
|
83
|
+
export declare function levelOf(usd: number, budget: number): number;
|
|
84
|
+
export interface BudgetVerdict {
|
|
85
|
+
/** A line for the user, once per threshold per period. */
|
|
86
|
+
message?: string;
|
|
87
|
+
/** Over the budget with --block: why the prompt is held, and how to lift it. */
|
|
88
|
+
block?: string;
|
|
89
|
+
spend: PeriodSpend;
|
|
90
|
+
budget: Budget;
|
|
91
|
+
}
|
|
92
|
+
/**
|
|
93
|
+
* The hook's check: undefined with no budget set (one failed read: the hot
|
|
94
|
+
* path stays a stat), otherwise the spend so far and what to say or do.
|
|
95
|
+
*/
|
|
96
|
+
export declare function budgetVerdict(now?: number, home?: string): BudgetVerdict | undefined;
|
|
97
|
+
/** The status line's part: "$12/$50 today", or undefined with no budget set. */
|
|
98
|
+
export declare function budgetStatus(now?: number, home?: string): string | undefined;
|
|
99
|
+
/** `budget` with no argument, and after setting one: the budget and where the period stands. */
|
|
100
|
+
export declare function renderBudgetStatus(b: Budget | undefined, s: PeriodSpend | undefined, hookInstalled: boolean): string;
|
|
101
|
+
/** Our every-prompt hook in Claude Code, Codex or Gemini CLI, or the plugin's. */
|
|
102
|
+
export declare function promptHookInstalled(home?: string): boolean;
|