context-doctor 0.50.0 → 0.51.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 +10 -9
- package/dist/apptools.d.ts +89 -0
- package/dist/apptools.js +203 -0
- package/dist/appwindow.d.ts +6 -0
- package/dist/appwindow.js +15 -1
- package/dist/budget.d.ts +20 -2
- package/dist/budget.js +43 -3
- package/dist/cachemisses.d.ts +70 -0
- package/dist/cachemisses.js +126 -0
- package/dist/cli.js +20 -8
- package/dist/credits.d.ts +64 -2
- package/dist/credits.js +88 -3
- package/dist/doctor.d.ts +18 -6
- package/dist/doctor.js +56 -11
- package/dist/fileparams.js +15 -3
- package/dist/fix.d.ts +11 -2
- package/dist/fix.js +53 -18
- package/dist/limits.d.ts +44 -3
- package/dist/limits.js +210 -22
- package/dist/mcp.js +68 -68
- package/dist/mod/api.d.ts +1 -1
- package/dist/mod/logic.d.ts +46 -1
- package/dist/mod/logic.js +76 -4
- package/dist/mod/register.d.ts +13 -3
- package/dist/mod/register.js +39 -9
- package/dist/modelids.d.ts +15 -0
- package/dist/modelids.js +33 -0
- package/dist/modmeasure.d.ts +7 -0
- package/dist/modmeasure.js +9 -0
- package/dist/overhead.js +8 -2
- package/dist/progresssummaries.d.ts +85 -2
- package/dist/progresssummaries.js +169 -23
- package/dist/proxy.d.ts +1 -1
- package/dist/proxy.js +1 -1
- package/dist/spend.d.ts +4 -2
- package/dist/spend.js +33 -4
- package/dist/starts.d.ts +7 -0
- package/dist/starts.js +7 -3
- package/dist/usagepane.js +1 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -30,7 +30,7 @@ Pick where you work. Each takes about a minute and is fully reversible.
|
|
|
30
30
|
| **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)) |
|
|
31
31
|
| **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)) |
|
|
32
32
|
| **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) |
|
|
33
|
-
| **GitHub pull requests** | `uses: KushalP1/context-doctor@v0.
|
|
33
|
+
| **GitHub pull requests** | `uses: KushalP1/context-doctor@v0.51.0` comments how much a PR grows CLAUDE.md, AGENTS.md and rules, and can fail over a budget ([setup](./docs/ci.md)) |
|
|
34
34
|
|
|
35
35
|
## What it does
|
|
36
36
|
|
|
@@ -40,7 +40,7 @@ Pick where you work. Each takes about a minute and is fully reversible.
|
|
|
40
40
|
- `overhead`: what every request re-reads before your message (system prompt, tools, MCP servers, CLAUDE.md, rules, memory), each file priced per month.
|
|
41
41
|
- `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.
|
|
42
42
|
- `cache-misses`: requests that re-wrote the prompt cache while it should still have been warm, priced, by model and context size, with the cause where the transcript shows one. And the cold returns (back after the cache expired): each one as billed, compacted on return, and kept warm by a cache read every 55 minutes, by how long you were away; what keeping warm for up to 1-8 hours would have netted; and a compacted segment the Desktop app put back ([#107157](https://github.com/anthropics/claude-code/issues/107157)).
|
|
43
|
-
- `limits`: your plan's weekly and 5-hour windows (Claude Pro, Max and Ultra, which has no 5-hour window; recorded by the plugin's mod, the status line or the proxy) and Codex's, the pace and when each runs out, what 1M tokens of each kind cost in % of the limit, and for each weekly window the API-equivalent dollars and tokens per 1%, by entrypoint and model, with every move in that figure dated, and, when a limit ran out and Claude Code kept going on usage credits, when and about how much. `limits --report` prints it as a block to paste into a bug report, with no prompts, paths or ids.
|
|
43
|
+
- `limits`: your plan's weekly and 5-hour windows (Claude Pro, Max and Ultra, which has no 5-hour window; recorded by the plugin's mod, the status line or the proxy) and Codex's, the pace and when each runs out, what 1M tokens of each kind cost in % of the limit, and for each weekly window the API-equivalent dollars and tokens per 1%, by entrypoint and model, with every move in that figure dated and checked against the model mix (a week moved to a model that uses the limit faster per dollar is said to be the mix, not the limit draining faster), and, when a limit ran out and Claude Code kept going on usage credits, when and about how much (or, with extra usage on and the weekly limit on pace to run out early, about how much the hours until the reset would cost). `limits --report` prints it as a block to paste into a bug report, with no prompts, paths or ids.
|
|
44
44
|
- `cache-plan <request.json>`: where an Anthropic API request should carry `cache_control`, and what it saves over N calls.
|
|
45
45
|
- `session`, `watch`, `analyze`, `report`, `dashboard`: token breakdown and wasted-context findings for any session, conversation file or agent trace.
|
|
46
46
|
|
|
@@ -107,7 +107,7 @@ On a Claude subscription you do not pay list price; the same tokens come out of
|
|
|
107
107
|
| Where you work | Automatic, every request | What you get on top |
|
|
108
108
|
|---|---|---|
|
|
109
109
|
| **Claude Code** in the terminal, VS Code or JetBrains | **Autopilot** clears stale tool output (cold cache only, never more expensive). **Hook** on every prompt: real context size, largest waste, and a `/compact` offer when you return to a large session after the cache expired. **Compaction hook** on every compaction. **`compact-window`**, if you set one | Install via npm or as a **plugin**. Status bar context meter, `/context-doctor:savings`, `session`, `watch`, `report`, dashboard, MCP tools |
|
|
110
|
-
| **Claude Code** in the desktop app's Code tab | **Hooks**, as above, the cold-resume `/compact` offer shown to you as well as the model. **`compact-window`**, if you set one: Claude Code compacts earlier by itself. Not autopilot: the app sets its own API address and ignores the one in settings | Same as above, and the plugin's mod: `/context-doctor-usage`, the usage view the app dropped (context ring, limit windows, tokens and dollars by model for today, 7 and 30 days, running subagents), `/context-doctor-fix`, and, once you apply `fix --apply desktop-tools-defer`, the app's own browser, session, preview and terminal tools kept behind tool search in new sessions (Claude Code 2.1.326
|
|
110
|
+
| **Claude Code** in the desktop app's Code tab | **Hooks**, as above, the cold-resume `/compact` offer shown to you as well as the model. **`compact-window`**, if you set one: Claude Code compacts earlier by itself. Not autopilot: the app sets its own API address and ignores the one in settings | Same as above, and the plugin's mod: `/context-doctor-usage`, the usage view the app dropped (context ring, how long the cache stays warm and what the next message costs now and after, limit windows, tokens and dollars by model for today, 7 and 30 days, running subagents), `/context-doctor-fix`, and, once you apply `fix --apply desktop-tools-defer`, the app's own browser, session, preview and terminal tools kept behind tool search in new sessions (Claude Code 2.1.326+; `fix` and `doctor` first confirm from your own Desktop sessions that it reaches them) ([Desktop](./docs/desktop.md)) |
|
|
111
111
|
| **Cursor** (agent) | A native **after-tool-call hook** (`~/.cursor/hooks.json`): in a heavy chat the agent gets the same hygiene guidance and the largest waste, once per 40% of growth. (Cursor's prompt hook can only allow or block a prompt, so this is the event where guidance reaches the model) | MCP tools, editor status bar extension, `cursor` profiler. With your own OpenAI key, autopilot too via a tokened tunnel ([how](./docs/proxy.md#putting-the-proxy-on-a-public-url-cursor-with-your-own-openai-key-remote-apps)) |
|
|
112
112
|
| **Codex** (ChatGPT app's Codex tab, IDE extension, CLI) | Every-prompt hook with the API's own token counts | MCP tools, skill, `session` reads Codex rollouts. Codex 0.171+: a footer status line from the MCP server (context, the session's cost, the plan's limits), once you turn on Codex's Custom status line experiment and pick it ([how](./docs/editor-and-statusline.md#codexs-footer-codex-0171)). On an API key, autopilot too (`autopilot on` sets `openai_base_url` in `~/.codex/config.toml`; Codex no longer reads `OPENAI_BASE_URL`) |
|
|
113
113
|
| **Gemini CLI** | Every-prompt hook (`BeforeAgent`) with the API's own token counts. On an API key, autopilot too: `GOOGLE_GEMINI_BASE_URL` set to the proxy on `127.0.0.1:8787`, plain HTTP (Google sign-in traffic goes elsewhere) | MCP tools, `session` and `watch` read its chats, `overhead` sizes GEMINI.md |
|
|
@@ -136,9 +136,9 @@ Rules 1-4 end exactly at character 512, the part ChatGPT's guide says must stand
|
|
|
136
136
|
|---|---|
|
|
137
137
|
| `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)) |
|
|
138
138
|
| `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, MCP servers set to load up front, the Desktop app's own tools kept behind tool search through the plugin's mod, unused servers, the subagents' model, long Bash output to a file, Codex's auto-compact limit, subagent progress summaries), with what each costs in quality; applies one only on a yes (the subagents' model and the two MCP deferrals only when named), `fix undo` reverts exactly what it changed, later runs show what each saved since ([details](./docs/fix.md)) |
|
|
139
|
-
| `context-doctor spend [--days n] [--by repo\|branch] [--share] [--export]`, `spend merge <folder>` | One bill across every tool on this machine: Claude Code (main conversation and subagents), Codex, Gemini CLI, Cursor (an estimate: no cache split), Copilot CLI (with the AI credits it counted), OpenCode and Cline, by tool, project (or repository or branch), model and day; `--export` writes a file of totals (no prompt or path) and `spend merge` adds up a team's files, with a month-end forecast, with what drives it, and Claude Code's own figure (its `cost-state`) beside ours with what the gap is made of: its side requests, prompt suggestions and requests that hung and were sent again, named; subagent output Claude Code 2.1.284-2.1.299 never settled in its rows, estimated from the content and counted; subagent progress summaries estimated beside the total (from Claude Code 2.1.328, short notes on Haiku 5.5). When a plan limit ran out and requests kept going (extra usage), Claude Code's dollars split into past the limit, on usage credits, and inside the plan (at API list prices, an estimate) ([docs](./docs/spend.md)) |
|
|
140
|
-
| `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)) |
|
|
141
|
-
| `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,
|
|
139
|
+
| `context-doctor spend [--days n] [--by repo\|branch] [--share] [--export]`, `spend merge <folder>` | One bill across every tool on this machine: Claude Code (main conversation and subagents), Codex, Gemini CLI, Cursor (an estimate: no cache split), Copilot CLI (with the AI credits it counted), OpenCode and Cline, by tool, project (or repository or branch), model and day; `--export` writes a file of totals (no prompt or path) and `spend merge` adds up a team's files, with a month-end forecast, with what drives it, and Claude Code's own figure (its `cost-state`) beside ours with what the gap is made of: its side requests, prompt suggestions and requests that hung and were sent again, named; subagent output Claude Code 2.1.284-2.1.299 never settled in its rows, estimated from the content and counted; subagent progress summaries estimated beside the total (from Claude Code 2.1.328, short notes on Haiku 5.5 on the Anthropic API; the subagent's own model on Bedrock, Vertex or Foundry; its whole context with the small model overridden or through a proxy such as autopilot's on a Claude sign-in; a range where that cannot be told). When a plan limit ran out and requests kept going (extra usage), Claude Code's dollars split into past the limit, on usage credits, and inside the plan (at API list prices, an estimate) ([docs](./docs/spend.md)) |
|
|
140
|
+
| `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; past your plan's limit, the line and `budget` say how much was paid from usage credits, and `budget` what running out before the weekly reset would cost on them ([docs](./docs/spend.md#a-budget-the-hook-applies-context-doctor-budget)) |
|
|
141
|
+
| `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, whether extra usage (usage credits past a plan's limit) is on, which Claude Code versions sent requests the prompt cache never saw in the last 30 days and what they cost, what you answered the Desktop app's own auto-compact offer, when there is an answer on file, and which MCP servers your newest Desktop session handed the mod (their type, and whether `fix --apply desktop-tools-defer` reaches them) |
|
|
142
142
|
| `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 (the main conversations' input: `spend` has the whole bill, output and subagents included). `--share` prints totals only (no project names or paths) to post. A bare `context-doctor` in a terminal shows `fix`'s plan instead, with one question for the fixes that cost nothing in quality |
|
|
143
143
|
| `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)) |
|
|
144
144
|
| `context-doctor proxy --autopilot` | Local proxy for your own Anthropic, OpenAI and Gemini API apps: clears stale tool output only when the prompt cache is cold, so it never costs more. Plain `proxy` runs the optimizing strategies (dedupe, trim, strip base64), which can cost more on cached traffic. `--token` for a public URL; `/stats` for cumulative savings ([details](./docs/proxy.md)) |
|
|
@@ -154,7 +154,7 @@ Rules 1-4 end exactly at character 512, the part ChatGPT's guide says must stand
|
|
|
154
154
|
| `context-doctor analyze <file>` | Profile a conversation: token breakdown, findings, cost + latency estimates. `--exact` adds a true count; `--fail-over-budget` exits 1 on a breach, for CI |
|
|
155
155
|
| `context-doctor optimize <file>` | Apply the safe fixes; add `--strategy trim-tool-calls` for big inline file writes, `--strategy prune-history` for consented lossy compaction ([what each does](./docs/detectors.md)) |
|
|
156
156
|
| `context-doctor diff <before> <after>` | Compare two profiles: what moved by category, which findings were resolved or introduced, and what it saves in money and latency |
|
|
157
|
-
| `context-doctor overhead [--days n] [--mcp]` | What every request re-reads before your message: measured first-request size (Claude Code, Codex and Gemini CLI sessions), each memory file (CLAUDE.md and imports, rules, auto memory, AGENTS.md, Cursor rules, GEMINI.md) priced per month, MCP calls per server; each session's and subagent's start per entrypoint (Desktop app, terminal, SDK) and subagent type, priced over the period, with the MCP tool definitions sent whole and whether any setting defers them; `--mcp` sizes each configured server's tool definitions and flags unused ones |
|
|
157
|
+
| `context-doctor overhead [--days n] [--mcp]` | What every request re-reads before your message: measured first-request size (Claude Code, Codex and Gemini CLI sessions), each memory file (CLAUDE.md and imports, rules, auto memory, AGENTS.md, Cursor rules, GEMINI.md) priced per month, MCP calls per server; each session's and subagent's start per entrypoint (Desktop app, terminal, SDK) and subagent type, priced over the period as billed (the headline's one total is their sum), with the MCP tool definitions sent whole and whether any setting defers them; `--mcp` sizes each configured server's tool definitions and flags unused ones |
|
|
158
158
|
| `context-doctor overhead prune [--days n] [--write] [--undo]` | Per project, the MCP servers and skills its sessions never used in n days; `--write` switches them off for this folder's project in its `.claude/settings.local.json` (backup kept, every entry recorded), `--undo` takes exactly those out. Never the app's connectors, plugins, or context-doctor itself |
|
|
159
159
|
| `context-doctor overhead split <file> [--min-tokens n] [--write]` | Move a memory file's big or code-heavy sections word for word to `<name>.reference.md`, leaving pointers; indexes stay. A plan until `--write`, which backs up first |
|
|
160
160
|
| `context-doctor pack <files\|dirs\|-> -q "…"` | Only the chunks of big documents, logs or code a question needs, ranked and fit to `--max-tokens` (default 4000). No query: an outline; `--ids a#2,b#5` picks chunks from it. `--semantic` also ranks by meaning with a local Ollama model. Offline, no key |
|
|
@@ -163,8 +163,8 @@ Rules 1-4 end exactly at character 512, the part ChatGPT's guide says must stand
|
|
|
163
163
|
| `context-doctor reads [--days n] [--limit n]` | Files read into session after session: reads, tokens, cost, and whether a CLAUDE.md summary or `pack` pays |
|
|
164
164
|
| `context-doctor subagents [--days n]` | Which subagents paid for themselves: each one's bill vs the same steps run in the parent session (read through the transcript cache: 15 s to 0.3 s warm on the author's machine) |
|
|
165
165
|
| `context-doctor compactions [--days n]` | Do sessions work worse right after compacting? Re-reads, tool errors and your corrections, before vs after each compaction |
|
|
166
|
-
| `context-doctor cache-misses [--days n]` | Requests that re-wrote the prompt cache within its lifetime (no compaction between, previous context over 20k, over 60% of it written again): priced above the cache-read rate, by model and context size, with the cause where visible and the model versions that miss less; by Claude Code version, with step changes after an upgrade flagged (the 1-hour cache share, the first request's size, a model's miss rate). Then the cold returns, each replayed as billed, compacted on return and kept warm (a cache read every 55 min while away, 4.5 on a 5-minute cache), by time away (<1h to >8h); keeping warm for up to 1, 2, 4 and 8 hours priced with every ping a timer would send;
|
|
167
|
-
| `context-doctor limits [--days n] [--report [--copy]]` | Your plan's limits in their own unit: each window's %, pace (from the window's reset when it began within the last hour, or day for a weekly one) and run-out time (Claude's weekly and 5-hour windows, from the readings the plugin's mod, the status line or the proxy record; Ultra has no 5-hour window; Codex's from its rollouts), and % of the limit per 1M tokens of input, cache read, cache write and output, fitted on your readings with the fit's error; too-thin data is said to be thin, never quoted. Each weekly window, reset to reset: API-equivalent $ and tokens per 1%, split by entrypoint (`cli`, `claude-desktop`, `sdk-cli`) and model, and where that moved, by how much and on what date. When a limit ran out and Claude Code kept going on usage credits (extra usage), one line says when, how many requests and about how much at API list prices (an estimate), from the API's own headers where the proxy read them, else inferred from a 100% reading and said to be. `--report`: the same as a block to paste into a GitHub issue (no prompts, paths, session or account ids) |
|
|
166
|
+
| `context-doctor cache-misses [--days n]` | Requests that re-wrote the prompt cache within its lifetime (no compaction between, previous context over 20k, over 60% of it written again): priced above the cache-read rate, by model and context size, with the cause where visible and the model versions that miss less; by Claude Code version, with step changes after an upgrade flagged (the 1-hour cache share, the first request's size, a model's miss rate). Then the cold returns, each replayed as billed, compacted on return and kept warm (a cache read every 55 min while away, 4.5 on a 5-minute cache), by time away (<1h to >8h); keeping warm for up to 1, 2, 4 and 8 hours priced with every ping a timer would send; #107157's re-added compacted segment with its re-write; and requests the cache never saw (no cache write, most of the prompt billed as new input, [#111948](https://github.com/anthropics/claude-code/issues/111948)) by Claude Code version, priced against a working cache; `--json` per model and version |
|
|
167
|
+
| `context-doctor limits [--days n] [--report [--copy]]` | Your plan's limits in their own unit: each window's %, pace (from the window's reset when it began within the last hour, or day for a weekly one) and run-out time (Claude's weekly and 5-hour windows, from the readings the plugin's mod, the status line or the proxy record; Ultra has no 5-hour window; Codex's from its rollouts), and % of the limit per 1M tokens of input, cache read, cache write and output, fitted on your readings with the fit's error; too-thin data is said to be thin, never quoted. Each weekly window, reset to reset: API-equivalent $ and tokens per 1%, split by entrypoint (`cli`, `claude-desktop`, `sdk-cli`) and model, and where that moved, by how much and on what date, checked against the model mix (a move the mix explains is said to be the mix, not the limit draining faster). With extra usage on and the weekly limit on pace to run out before its reset, one line says about how many dollars the hours until the reset would go on usage credits (at the last 24 hours' pace, list prices, an estimate). When a limit ran out and Claude Code kept going on usage credits (extra usage), one line says when, how many requests and about how much at API list prices (an estimate), from the API's own headers where the proxy read them, else inferred from a 100% reading and said to be. `--report`: the same as a block to paste into a GitHub issue (no prompts, paths, session or account ids) |
|
|
168
168
|
| `context-doctor cache-plan <request.json> [--calls n] [--out file] [--explicit]` | Where an Anthropic API request should carry `cache_control` (top-level automatic caching for the moving end, unless `--explicit`), and what it saves over n calls; `--out` writes it applied |
|
|
169
169
|
| `context-doctor accuracy` | How much of what you are billed for is visible in your transcript (the fixed harness baseline, per-turn injected content), plus a tokenizer check: real chars/token per model from the API's own counts, next to the ratio the estimator uses |
|
|
170
170
|
| `context-doctor report` | Machine-wide impact report (proxy savings persist across restarts): exact proxy savings, hook activity, how often the cold-resume `/compact` offer was followed by a compaction, recoverable waste in recent sessions |
|
|
@@ -183,6 +183,7 @@ Rules 1-4 end exactly at character 512, the part ChatGPT's guide says must stand
|
|
|
183
183
|
|
|
184
184
|
## What's new
|
|
185
185
|
|
|
186
|
+
- **0.51 Limits that tell the model mix from the limit, proof before a lever, and the cache in the usage pane**: `limits` no longer reads a switch to a hungrier model as the limit draining faster: it says when the move comes from your model mix, and claims a drain only when what is left is 1.5x or more. `limits` and `budget` say when the weekly limit would run out at your current pace and, with extra usage on, about what would go on usage credits before the reset; `budget` counts what credits already paid. The mod records which tools the Desktop app hands over, so `fix` and `doctor` confirm or withdraw `desktop-tools-defer` before you apply it. The `/context-doctor-usage` pane shows how long the cache stays warm and what your next message costs now and after it expires. `cache-misses` and `doctor` count requests the cache never saw (claude-code #111948). Progress summaries are priced in the form Claude Code really sends on your setup; `overhead` gives one total; `doctor` shows the Desktop app's auto-compact offer. Fixes: "1000k" for a 1M window, a flaky download-budget test, the ledger path `doctor` names ([details](./ROADMAP.md#shipped-in-0510-limits-that-tell-the-model-mix-from-the-limit-proof-before-a-lever-and-the-cache-in-the-usage-pane)).
|
|
186
187
|
- **0.50 The Desktop app's own tools, money past the limit, a Codex status line, and two audits**: `fix --apply desktop-tools-defer` has the mod keep the Desktop app's own tools (browser, terminal, sessions, visualize) behind tool search until a session needs them (about $70 a month on the author's history; opt-in, undo with `fix undo`). `limits` says when a plan limit ran out and usage credits paid, `spend` splits dollars inside the plan and past it, `doctor` says whether extra usage is on. `compact-window` and `fix` read the window the Desktop app offered and your answer. Progress summaries are priced on the small model Claude Code 2.1.328 uses. Codex users can turn on a status line served by the MCP server. Gemini 4 Neon is priced. Two audits fixed 14 issues: a crash on a bad date, `limits` reading pace from a burst after a reset, subagent counts that disagreed, a false "contracted rates" warning, and more ([details](./ROADMAP.md#shipped-in-0500-the-desktop-apps-own-tools-money-past-the-limit-a-codex-status-line-and-two-audits)).
|
|
187
188
|
- **0.49.1 The Desktop band off by default, and the rest of Claude Code's figure explained**: the band above the prompt in the Desktop app no longer shows unless `CONTEXT_DOCTOR_MOD_BAND=cold` (a cold return, with **Compact first**) or `always`; the mod still records limits and cost. Subagent replies Claude Code 2.1.284-2.1.299 never finished writing are counted, and the gap to Claude Code's own cost names its prompt suggestions and requests that hung ([details](./ROADMAP.md#shipped-in-0491-the-desktop-band-off-by-default-and-the-rest-of-claude-codes-figure-explained)).
|
|
188
189
|
- **0.49 Count what Claude Code counts, cold returns, limits you can paste, a Desktop usage pane, and teams**: `spend` and `doctor` show Claude Code's own cost (its `cost-state`) beside ours, 2% apart on the author's 30 days, and count the advisor's calls and replies a server-side fallback replaced. `cache-misses` replays every return after the cache expired three ways (as billed, compacted, kept warm) by time away (the author's: $894 in 183 returns), and the mod's `/context-doctor-keep-warm` keeps it warm on request only, capped in hours and dollars. `overhead` prices every session's and subagent's start ($455 a month here) and `fix` gains `mcp-defer`. `limits` gives dollars per 1% per weekly reset with the moves dated, `limits --report` a block for a bug report, and handles Ultra (no 5-hour window). `/context-doctor-usage` is a usage pane in the Desktop app. `spend` reads Copilot CLI, OpenCode and Cline, splits `--by repo|branch`, and `--export` / `spend merge` add up a team's totals with no prompt or path ([details](./ROADMAP.md#shipped-in-0490-count-what-claude-code-counts-cold-returns-limits-you-can-paste-a-desktop-usage-pane-and-teams)).
|
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Which MCP servers Claude Code hands context-doctor's mod, and how
|
|
3
|
+
* (ROADMAP H3): the evidence `fix`'s desktop-tools-defer and `doctor` read
|
|
4
|
+
* before anyone applies the lever.
|
|
5
|
+
*
|
|
6
|
+
* The mod's `tool.describe` hook (Claude Code 2.1.326+) sees each tool once
|
|
7
|
+
* per session with its server's transport (`mcpServer.type`) and whether the
|
|
8
|
+
* engine already lists it behind tool search (`isDeferred`). It keeps that in
|
|
9
|
+
* memory, per server, and hands it to `context-doctor mod measure` after the
|
|
10
|
+
* turn (the CLI it already runs), which appends one line per session here,
|
|
11
|
+
* changes only: a second measure of the same session with the same servers
|
|
12
|
+
* writes nothing. The mod draws nothing and moves nothing for this; with
|
|
13
|
+
* CONTEXT_DOCTOR_DEFER_MCP unset it only watches.
|
|
14
|
+
*
|
|
15
|
+
* `~/.claude/.context-doctor-tools.jsonl` (beside the session-cost ledger),
|
|
16
|
+
* capped as that one is: past 128 KB it keeps its newest 96 KB (a line is
|
|
17
|
+
* ~400 bytes: months of sessions). Off: CONTEXT_DOCTOR_NO_COST_LOG=1, as the
|
|
18
|
+
* session-cost ledger.
|
|
19
|
+
*/
|
|
20
|
+
/** One server as the mod saw it in a session. */
|
|
21
|
+
export interface ToolServerSeen {
|
|
22
|
+
server: string;
|
|
23
|
+
/** `mcpServer.type`: stdio, http, sse, ws, sdk (in-process, the Desktop app's own), sse-ide, ws-ide, claudeai-proxy. */
|
|
24
|
+
type: string;
|
|
25
|
+
/** Its tools the engine described in that session. */
|
|
26
|
+
tools: number;
|
|
27
|
+
/** Every one of them came already behind tool search (the engine's own rule). */
|
|
28
|
+
deferredByHost: boolean;
|
|
29
|
+
/** The mod put them behind tool search (CONTEXT_DOCTOR_DEFER_MCP named the server). */
|
|
30
|
+
movedByUs: boolean;
|
|
31
|
+
}
|
|
32
|
+
/** One session's servers. */
|
|
33
|
+
export interface ToolsLine {
|
|
34
|
+
ts: number;
|
|
35
|
+
sid: string;
|
|
36
|
+
/** `session.start`'s surface: desktop, terminal, vscode; absent when the engine gave none. */
|
|
37
|
+
surface?: string;
|
|
38
|
+
servers: ToolServerSeen[];
|
|
39
|
+
}
|
|
40
|
+
export declare function toolsLogPath(): string;
|
|
41
|
+
/** The servers as the mod sent them, cleaned: valid names and types only, each once, sorted by name. */
|
|
42
|
+
export declare function cleanServers(list: unknown): ToolServerSeen[];
|
|
43
|
+
/**
|
|
44
|
+
* Append a session's servers, unless its last line says the same (the mod
|
|
45
|
+
* sends them again only when they changed, and a second window of the same
|
|
46
|
+
* session may send them too). Never throws. True when a line was written.
|
|
47
|
+
*/
|
|
48
|
+
export declare function recordToolServers(line: {
|
|
49
|
+
ts: number;
|
|
50
|
+
sid: string;
|
|
51
|
+
surface?: string;
|
|
52
|
+
servers: unknown;
|
|
53
|
+
}, path?: string): boolean;
|
|
54
|
+
/** Every line since `since`, each session's last only (a session's servers grow as they connect). */
|
|
55
|
+
export declare function readToolLines(since?: number, path?: string): ToolsLine[];
|
|
56
|
+
/** A Desktop session: the surface says so, or (no surface given) the app's own servers are in it. */
|
|
57
|
+
export declare function isDesktopLine(l: ToolsLine): boolean;
|
|
58
|
+
/** The newest Desktop session the mod recorded, or undefined. */
|
|
59
|
+
export declare function newestDesktop(lines: ToolsLine[]): ToolsLine | undefined;
|
|
60
|
+
/**
|
|
61
|
+
* What the newest Desktop session says of the servers the lever would name:
|
|
62
|
+
* those that arrive whole (the setting reaches them), those Claude Code
|
|
63
|
+
* already keeps behind tool search (nothing to do), those the mod was never
|
|
64
|
+
* shown (the setting would not reach them). Undefined with no Desktop session
|
|
65
|
+
* on record: not yet known.
|
|
66
|
+
*/
|
|
67
|
+
export interface AppToolsVerdict {
|
|
68
|
+
at: number;
|
|
69
|
+
reach: ToolServerSeen[];
|
|
70
|
+
hostDefers: ToolServerSeen[];
|
|
71
|
+
unseen: string[];
|
|
72
|
+
}
|
|
73
|
+
export declare function appToolsVerdict(lines: ToolsLine[], servers: readonly string[]): AppToolsVerdict | undefined;
|
|
74
|
+
/** The verdict's sentences, for fix's lines. */
|
|
75
|
+
export declare function verdictLines(v: AppToolsVerdict): string[];
|
|
76
|
+
/** Sessions in which the mod moved a server's tools behind tool search, and the first of them. */
|
|
77
|
+
export declare function movedSessions(lines: ToolsLine[]): {
|
|
78
|
+
sessions: number;
|
|
79
|
+
since?: number;
|
|
80
|
+
servers: string[];
|
|
81
|
+
};
|
|
82
|
+
/**
|
|
83
|
+
* `doctor`'s line: the servers the newest Desktop session handed the mod,
|
|
84
|
+
* their type, and what desktop-tools-defer would do with them. A fact, not a
|
|
85
|
+
* fault. Undefined when the mod recorded no Desktop session.
|
|
86
|
+
*/
|
|
87
|
+
export declare function appToolsCheckText(lines: ToolsLine[]): string | undefined;
|
|
88
|
+
/** The ledger's lines of the last `days`, never throwing. */
|
|
89
|
+
export declare function recentToolLines(days?: number, now?: number, path?: string): ToolsLine[];
|
package/dist/apptools.js
ADDED
|
@@ -0,0 +1,203 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Which MCP servers Claude Code hands context-doctor's mod, and how
|
|
3
|
+
* (ROADMAP H3): the evidence `fix`'s desktop-tools-defer and `doctor` read
|
|
4
|
+
* before anyone applies the lever.
|
|
5
|
+
*
|
|
6
|
+
* The mod's `tool.describe` hook (Claude Code 2.1.326+) sees each tool once
|
|
7
|
+
* per session with its server's transport (`mcpServer.type`) and whether the
|
|
8
|
+
* engine already lists it behind tool search (`isDeferred`). It keeps that in
|
|
9
|
+
* memory, per server, and hands it to `context-doctor mod measure` after the
|
|
10
|
+
* turn (the CLI it already runs), which appends one line per session here,
|
|
11
|
+
* changes only: a second measure of the same session with the same servers
|
|
12
|
+
* writes nothing. The mod draws nothing and moves nothing for this; with
|
|
13
|
+
* CONTEXT_DOCTOR_DEFER_MCP unset it only watches.
|
|
14
|
+
*
|
|
15
|
+
* `~/.claude/.context-doctor-tools.jsonl` (beside the session-cost ledger),
|
|
16
|
+
* capped as that one is: past 128 KB it keeps its newest 96 KB (a line is
|
|
17
|
+
* ~400 bytes: months of sessions). Off: CONTEXT_DOCTOR_NO_COST_LOG=1, as the
|
|
18
|
+
* session-cost ledger.
|
|
19
|
+
*/
|
|
20
|
+
import { appendFileSync, closeSync, existsSync, mkdirSync, openSync, readFileSync, readSync, statSync, writeFileSync } from "node:fs";
|
|
21
|
+
import { dirname, join } from "node:path";
|
|
22
|
+
import { statePath } from "./ledger.js";
|
|
23
|
+
import { APP_TOOL_SERVERS } from "./mod/logic.js";
|
|
24
|
+
export function toolsLogPath() {
|
|
25
|
+
return join(dirname(statePath()), ".context-doctor-tools.jsonl");
|
|
26
|
+
}
|
|
27
|
+
const ROTATE_AT = 128 * 1024;
|
|
28
|
+
const KEEP_BYTES = 96 * 1024;
|
|
29
|
+
const MAX_SERVERS = 60;
|
|
30
|
+
const NAME = /^[A-Za-z0-9_.-]{1,80}$/;
|
|
31
|
+
const TYPE = /^[a-z-]{1,20}$/;
|
|
32
|
+
/** The servers as the mod sent them, cleaned: valid names and types only, each once, sorted by name. */
|
|
33
|
+
export function cleanServers(list) {
|
|
34
|
+
if (!Array.isArray(list))
|
|
35
|
+
return [];
|
|
36
|
+
const out = new Map();
|
|
37
|
+
for (const s of list) {
|
|
38
|
+
if (!s || typeof s !== "object")
|
|
39
|
+
continue;
|
|
40
|
+
const { server, type, tools, deferredByHost, movedByUs } = s;
|
|
41
|
+
if (typeof server !== "string" || !NAME.test(server) || typeof type !== "string" || !TYPE.test(type) || out.has(server))
|
|
42
|
+
continue;
|
|
43
|
+
const n = typeof tools === "number" && Number.isFinite(tools) && tools >= 0 ? Math.min(10_000, Math.round(tools)) : 0;
|
|
44
|
+
out.set(server, { server, type, tools: n, deferredByHost: deferredByHost === true, movedByUs: movedByUs === true });
|
|
45
|
+
if (out.size >= MAX_SERVERS)
|
|
46
|
+
break;
|
|
47
|
+
}
|
|
48
|
+
return [...out.values()].sort((a, b) => (a.server < b.server ? -1 : a.server > b.server ? 1 : 0));
|
|
49
|
+
}
|
|
50
|
+
function parseLine(line) {
|
|
51
|
+
let e;
|
|
52
|
+
try {
|
|
53
|
+
e = JSON.parse(line);
|
|
54
|
+
}
|
|
55
|
+
catch {
|
|
56
|
+
return undefined;
|
|
57
|
+
}
|
|
58
|
+
if (!e || typeof e !== "object" || typeof e.ts !== "number" || !Number.isFinite(e.ts) || typeof e.sid !== "string")
|
|
59
|
+
return undefined;
|
|
60
|
+
const servers = cleanServers(e.servers);
|
|
61
|
+
if (!servers.length)
|
|
62
|
+
return undefined;
|
|
63
|
+
return { ts: e.ts, sid: e.sid, ...(typeof e.surface === "string" && TYPE.test(e.surface) ? { surface: e.surface } : {}), servers };
|
|
64
|
+
}
|
|
65
|
+
function tail(path, bytes) {
|
|
66
|
+
const size = statSync(path).size;
|
|
67
|
+
const n = Math.min(size, bytes);
|
|
68
|
+
const fd = openSync(path, "r");
|
|
69
|
+
try {
|
|
70
|
+
const buf = Buffer.alloc(n);
|
|
71
|
+
readSync(fd, buf, 0, n, size - n);
|
|
72
|
+
return buf.toString("utf8");
|
|
73
|
+
}
|
|
74
|
+
finally {
|
|
75
|
+
closeSync(fd);
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
/**
|
|
79
|
+
* Append a session's servers, unless its last line says the same (the mod
|
|
80
|
+
* sends them again only when they changed, and a second window of the same
|
|
81
|
+
* session may send them too). Never throws. True when a line was written.
|
|
82
|
+
*/
|
|
83
|
+
export function recordToolServers(line, path = toolsLogPath()) {
|
|
84
|
+
if (!/^[\w.-]{1,100}$/.test(line.sid))
|
|
85
|
+
return false;
|
|
86
|
+
const servers = cleanServers(line.servers);
|
|
87
|
+
if (!servers.length)
|
|
88
|
+
return false;
|
|
89
|
+
const out = { ts: line.ts, sid: line.sid, ...(line.surface && TYPE.test(line.surface) ? { surface: line.surface } : {}), servers };
|
|
90
|
+
try {
|
|
91
|
+
if (existsSync(path)) {
|
|
92
|
+
let last;
|
|
93
|
+
for (const l of tail(path, 32 * 1024).split("\n")) {
|
|
94
|
+
const p = parseLine(l);
|
|
95
|
+
if (p && p.sid === out.sid)
|
|
96
|
+
last = p;
|
|
97
|
+
}
|
|
98
|
+
if (last && JSON.stringify(last.servers) === JSON.stringify(out.servers))
|
|
99
|
+
return false;
|
|
100
|
+
}
|
|
101
|
+
mkdirSync(dirname(path), { recursive: true });
|
|
102
|
+
if (existsSync(path) && statSync(path).size > ROTATE_AT) {
|
|
103
|
+
const text = tail(path, KEEP_BYTES);
|
|
104
|
+
writeFileSync(path, text.slice(text.indexOf("\n") + 1));
|
|
105
|
+
}
|
|
106
|
+
appendFileSync(path, JSON.stringify(out) + "\n");
|
|
107
|
+
return true;
|
|
108
|
+
}
|
|
109
|
+
catch {
|
|
110
|
+
return false;
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
/** Every line since `since`, each session's last only (a session's servers grow as they connect). */
|
|
114
|
+
export function readToolLines(since = 0, path = toolsLogPath()) {
|
|
115
|
+
let text;
|
|
116
|
+
try {
|
|
117
|
+
text = readFileSync(path, "utf8");
|
|
118
|
+
}
|
|
119
|
+
catch {
|
|
120
|
+
return [];
|
|
121
|
+
}
|
|
122
|
+
const bySid = new Map();
|
|
123
|
+
for (const l of text.split("\n")) {
|
|
124
|
+
const p = parseLine(l);
|
|
125
|
+
if (p && p.ts >= since)
|
|
126
|
+
bySid.set(p.sid, p);
|
|
127
|
+
}
|
|
128
|
+
return [...bySid.values()].sort((a, b) => a.ts - b.ts);
|
|
129
|
+
}
|
|
130
|
+
/** A Desktop session: the surface says so, or (no surface given) the app's own servers are in it. */
|
|
131
|
+
export function isDesktopLine(l) {
|
|
132
|
+
return l.surface === "desktop" || (l.surface === undefined && l.servers.some((s) => APP_TOOL_SERVERS.includes(s.server)));
|
|
133
|
+
}
|
|
134
|
+
/** The newest Desktop session the mod recorded, or undefined. */
|
|
135
|
+
export function newestDesktop(lines) {
|
|
136
|
+
return [...lines].reverse().find(isDesktopLine);
|
|
137
|
+
}
|
|
138
|
+
const day = (ts) => new Date(ts).toISOString().slice(0, 10);
|
|
139
|
+
/** "Claude_Browser (sdk, 12 tools)". */
|
|
140
|
+
const seenText = (s) => `${s.server} (${s.type}, ${s.tools} tool${s.tools === 1 ? "" : "s"})`;
|
|
141
|
+
const list = (names) => (names.length <= 1 ? names.join("") : `${names.slice(0, -1).join(", ")} and ${names[names.length - 1]}`);
|
|
142
|
+
export function appToolsVerdict(lines, servers) {
|
|
143
|
+
const d = newestDesktop(lines);
|
|
144
|
+
if (!d)
|
|
145
|
+
return undefined;
|
|
146
|
+
const reach = [], hostDefers = [], unseen = [];
|
|
147
|
+
for (const name of servers) {
|
|
148
|
+
const s = d.servers.find((x) => x.server === name);
|
|
149
|
+
if (!s)
|
|
150
|
+
unseen.push(name);
|
|
151
|
+
else if (s.deferredByHost)
|
|
152
|
+
hostDefers.push(s);
|
|
153
|
+
else
|
|
154
|
+
reach.push(s);
|
|
155
|
+
}
|
|
156
|
+
return { at: d.ts, reach, hostDefers, unseen };
|
|
157
|
+
}
|
|
158
|
+
/** The verdict's sentences, for fix's lines. */
|
|
159
|
+
export function verdictLines(v) {
|
|
160
|
+
const out = [];
|
|
161
|
+
const when = `your Desktop session of ${day(v.at)}`;
|
|
162
|
+
if (v.reach.length)
|
|
163
|
+
out.push(`Seen in ${when}: ${list(v.reach.map(seenText))} ${v.reach.length === 1 ? "arrives" : "arrive"} whole${v.reach.every((s) => s.type === "sdk") ? " as in-process (sdk) servers" : ""}, and Claude Code tells context-doctor's mod which server each tool is from, so this setting reaches ${v.reach.length === 1 ? "it" : "them"}.`);
|
|
164
|
+
if (v.hostDefers.length)
|
|
165
|
+
out.push(`Claude Code already keeps ${list(v.hostDefers.map((s) => s.server))} behind tool search (${when}): nothing to move there.`);
|
|
166
|
+
if (v.unseen.length)
|
|
167
|
+
out.push(`Claude Code did not show context-doctor's mod ${list(v.unseen)}'s tools in ${when}, so the setting would not reach ${v.unseen.length === 1 ? "it" : "them"} there.`);
|
|
168
|
+
return out;
|
|
169
|
+
}
|
|
170
|
+
/** Sessions in which the mod moved a server's tools behind tool search, and the first of them. */
|
|
171
|
+
export function movedSessions(lines) {
|
|
172
|
+
const moved = lines.filter((l) => l.servers.some((s) => s.movedByUs));
|
|
173
|
+
const servers = [...new Set(moved.flatMap((l) => l.servers.filter((s) => s.movedByUs).map((s) => s.server)))].sort();
|
|
174
|
+
return { sessions: moved.length, ...(moved.length ? { since: moved[0].ts } : {}), servers };
|
|
175
|
+
}
|
|
176
|
+
/**
|
|
177
|
+
* `doctor`'s line: the servers the newest Desktop session handed the mod,
|
|
178
|
+
* their type, and what desktop-tools-defer would do with them. A fact, not a
|
|
179
|
+
* fault. Undefined when the mod recorded no Desktop session.
|
|
180
|
+
*/
|
|
181
|
+
export function appToolsCheckText(lines) {
|
|
182
|
+
const d = newestDesktop(lines);
|
|
183
|
+
if (!d)
|
|
184
|
+
return undefined;
|
|
185
|
+
const parts = d.servers.map((s) => `${seenText(s)}${s.movedByUs ? ", moved behind tool search by context-doctor" : s.deferredByHost ? ", behind tool search already" : ", sent whole"}`);
|
|
186
|
+
const whole = d.servers.filter((s) => !s.deferredByHost && !s.movedByUs && APP_TOOL_SERVERS.includes(s.server)).map((s) => s.server);
|
|
187
|
+
const moved = movedSessions(lines);
|
|
188
|
+
const tail = moved.sessions
|
|
189
|
+
? `; moved behind tool search in ${moved.sessions} session${moved.sessions === 1 ? "" : "s"} since ${day(moved.since)}`
|
|
190
|
+
: whole.length
|
|
191
|
+
? `; context-doctor fix --apply desktop-tools-defer would move ${list(whole)} (it reaches them)`
|
|
192
|
+
: "";
|
|
193
|
+
return `your Desktop session of ${day(d.ts)} handed context-doctor's mod ${parts.join("; ")}${tail}`;
|
|
194
|
+
}
|
|
195
|
+
/** The ledger's lines of the last `days`, never throwing. */
|
|
196
|
+
export function recentToolLines(days = 30, now = Date.now(), path = toolsLogPath()) {
|
|
197
|
+
try {
|
|
198
|
+
return readToolLines(now - days * 86_400_000, path);
|
|
199
|
+
}
|
|
200
|
+
catch {
|
|
201
|
+
return [];
|
|
202
|
+
}
|
|
203
|
+
}
|
package/dist/appwindow.d.ts
CHANGED
|
@@ -62,6 +62,12 @@ export declare const hasAppWindows: (a: AppWindows | undefined) => a is AppWindo
|
|
|
62
62
|
export declare function modelKey(model: string): string;
|
|
63
63
|
/** Whether a transcript's model is the one an answer names ("opus" and the like match their family). */
|
|
64
64
|
export declare function sameModel(answer: string, model: string): boolean;
|
|
65
|
+
/**
|
|
66
|
+
* `doctor`'s one line: each answer on file, in plain words ("on 2026-11-18
|
|
67
|
+
* the Desktop app offered a 400k auto-compact window for Opus 5.5 and you
|
|
68
|
+
* accepted it"). Undefined when there is none.
|
|
69
|
+
*/
|
|
70
|
+
export declare function appAnswerText(a: AppWindows): string | undefined;
|
|
65
71
|
/**
|
|
66
72
|
* The lines `compact-window` and `fix` say about it (none when nothing is on
|
|
67
73
|
* file). `left`: the sessions the replay left as they ran, when known.
|
package/dist/appwindow.js
CHANGED
|
@@ -112,9 +112,23 @@ export function sameModel(answer, model) {
|
|
|
112
112
|
return m.includes(a);
|
|
113
113
|
return a === m;
|
|
114
114
|
}
|
|
115
|
-
|
|
115
|
+
/** A window in tokens: "300k", "1M", "1.5M" (a 1M window read "1000k"). */
|
|
116
|
+
const k = (n) => (n >= 999_500 ? `${Number((n / 1_000_000).toFixed(1))}M` : `${Math.round(n / 1000)}k`);
|
|
116
117
|
const day = (ms) => new Date(ms).toISOString().slice(0, 10);
|
|
117
118
|
const nameOf = (m) => modelName(m) === m ? m : modelName(m);
|
|
119
|
+
/**
|
|
120
|
+
* `doctor`'s one line: each answer on file, in plain words ("on 2026-11-18
|
|
121
|
+
* the Desktop app offered a 400k auto-compact window for Opus 5.5 and you
|
|
122
|
+
* accepted it"). Undefined when there is none.
|
|
123
|
+
*/
|
|
124
|
+
export function appAnswerText(a) {
|
|
125
|
+
if (!a.answers.length)
|
|
126
|
+
return undefined;
|
|
127
|
+
const one = (x) => x.choice === "accept" ? `on ${day(x.at)} the Desktop app offered a ${k(x.tokens)} auto-compact window for ${nameOf(x.model)} and you accepted it`
|
|
128
|
+
: x.choice === "keep" ? `on ${day(x.at)} the Desktop app offered a lower auto-compact window for ${nameOf(x.model)} and you kept yours (${k(x.tokens)})`
|
|
129
|
+
: `on ${day(x.at)} you undid the lower auto-compact window the Desktop app had set for ${nameOf(x.model)} (on record: ${k(x.tokens)})`;
|
|
130
|
+
return a.answers.map(one).join("; ");
|
|
131
|
+
}
|
|
118
132
|
/**
|
|
119
133
|
* The lines `compact-window` and `fix` say about it (none when nothing is on
|
|
120
134
|
* file). `left`: the sessions the replay left as they ran, when known.
|
package/dist/budget.d.ts
CHANGED
|
@@ -23,6 +23,7 @@
|
|
|
23
23
|
* replies count once. Measured on the author's history: docs/spend.md.
|
|
24
24
|
*/
|
|
25
25
|
import { type Tool } from "./spend.js";
|
|
26
|
+
import { type CreditsAhead, type CreditsSummary } from "./credits.js";
|
|
26
27
|
import { type CompactTrack } from "./compactcost.js";
|
|
27
28
|
export type Period = "day" | "week";
|
|
28
29
|
export interface Budget {
|
|
@@ -155,6 +156,19 @@ export declare function periodSpend(period: Period, now?: number, home?: string,
|
|
|
155
156
|
export declare const THRESHOLDS: readonly [50, 80, 100];
|
|
156
157
|
/** The highest threshold `usd` has reached of `budget` (0 below the first). */
|
|
157
158
|
export declare function levelOf(usd: number, budget: number): number;
|
|
159
|
+
/**
|
|
160
|
+
* Claude Code's part of the period that ran past the plan's limit, paid from
|
|
161
|
+
* usage credits (credits.ts): already in the period's dollars, said apart.
|
|
162
|
+
* Reads the limits ledger, and the transcripts only when the ledger says a
|
|
163
|
+
* limit ran out or credits were in use. Undefined when nothing was; never
|
|
164
|
+
* throws (a damaged ledger must not cost the budget its line).
|
|
165
|
+
*/
|
|
166
|
+
export declare function periodCredits(start: number, now?: number, home?: string): CreditsSummary | undefined;
|
|
167
|
+
/**
|
|
168
|
+
* "$4.20 of this was paid from usage credits, past your plan's limit (37
|
|
169
|
+
* requests, at API list prices, an estimate)." Inferred ones say so.
|
|
170
|
+
*/
|
|
171
|
+
export declare function creditsLine(c: CreditsSummary | undefined): string | undefined;
|
|
158
172
|
export interface BudgetVerdict {
|
|
159
173
|
/** A line for the user, once per threshold per period. */
|
|
160
174
|
message?: string;
|
|
@@ -170,7 +184,11 @@ export interface BudgetVerdict {
|
|
|
170
184
|
export declare function budgetVerdict(now?: number, home?: string): BudgetVerdict | undefined;
|
|
171
185
|
/** The status line's part: "$12/$50 today", or undefined with no budget set. */
|
|
172
186
|
export declare function budgetStatus(now?: number, home?: string): string | undefined;
|
|
173
|
-
/**
|
|
174
|
-
|
|
187
|
+
/**
|
|
188
|
+
* `budget` with no argument, and after setting one: the budget and where the
|
|
189
|
+
* period stands. `ahead`: the weekly limit running out before its reset with
|
|
190
|
+
* extra usage on (credits.ts creditsAheadNow), said in one line.
|
|
191
|
+
*/
|
|
192
|
+
export declare function renderBudgetStatus(b: Budget | undefined, s: PeriodSpend | undefined, hookInstalled: boolean, credits?: CreditsSummary, ahead?: CreditsAhead, now?: number): string;
|
|
175
193
|
/** Our every-prompt hook in Claude Code, Codex or Gemini CLI, or the plugin's. */
|
|
176
194
|
export declare function promptHookInstalled(home?: string): boolean;
|
package/dist/budget.js
CHANGED
|
@@ -34,6 +34,7 @@ import { subagentFiles } from "./subagents.js";
|
|
|
34
34
|
import { codexFileSpend, codexFiles, geminiFileSpend, geminiFiles, TOOL_NAME } from "./spend.js";
|
|
35
35
|
import { billedCost, isUnbilledModel, priceChangedText, priceTableKey, requestCost } from "./pricing.js";
|
|
36
36
|
import { orgRates, orgRatesLine } from "./orgrates.js";
|
|
37
|
+
import { creditsAheadLine, creditsSince } from "./credits.js";
|
|
37
38
|
import { anchorOf, rowsOf } from "./scan.js";
|
|
38
39
|
import { realModel } from "./tokens.js";
|
|
39
40
|
import { isCompactionRow, isTrack, newTrack, trackCompaction } from "./compactcost.js";
|
|
@@ -683,6 +684,33 @@ function resets(p) {
|
|
|
683
684
|
function raised(b, spent) {
|
|
684
685
|
return Math.ceil(Math.max(b.usd * 1.5, spent * 1.2) / 5) * 5;
|
|
685
686
|
}
|
|
687
|
+
/**
|
|
688
|
+
* Claude Code's part of the period that ran past the plan's limit, paid from
|
|
689
|
+
* usage credits (credits.ts): already in the period's dollars, said apart.
|
|
690
|
+
* Reads the limits ledger, and the transcripts only when the ledger says a
|
|
691
|
+
* limit ran out or credits were in use. Undefined when nothing was; never
|
|
692
|
+
* throws (a damaged ledger must not cost the budget its line).
|
|
693
|
+
*/
|
|
694
|
+
export function periodCredits(start, now = Date.now(), home) {
|
|
695
|
+
try {
|
|
696
|
+
return creditsSince(start, { now, ...(home ? { home } : {}) });
|
|
697
|
+
}
|
|
698
|
+
catch {
|
|
699
|
+
return undefined;
|
|
700
|
+
}
|
|
701
|
+
}
|
|
702
|
+
/**
|
|
703
|
+
* "$4.20 of this was paid from usage credits, past your plan's limit (37
|
|
704
|
+
* requests, at API list prices, an estimate)." Inferred ones say so.
|
|
705
|
+
*/
|
|
706
|
+
export function creditsLine(c) {
|
|
707
|
+
if (!c || !c.requests)
|
|
708
|
+
return undefined;
|
|
709
|
+
const n = `${c.requests.toLocaleString("en-US")} request${c.requests === 1 ? "" : "s"}`;
|
|
710
|
+
const how = c.inferred && !c.fromHeaders ? "was most likely paid" : "was paid";
|
|
711
|
+
const why = !c.inferred ? "" : !c.fromHeaders ? "; inferred: they went through after a limit read 100%" : `; ${c.inferred.toLocaleString("en-US")} of them inferred from a limit at 100%`;
|
|
712
|
+
return `${money(c.usd)} of this ${how} from usage credits, past your plan's limit (${n}, at API list prices, an estimate${why}).`;
|
|
713
|
+
}
|
|
686
714
|
/**
|
|
687
715
|
* The hook's check: undefined with no budget set (one failed read: the hot
|
|
688
716
|
* path stays a stat), otherwise the spend so far and what to say or do.
|
|
@@ -704,9 +732,12 @@ export function budgetVerdict(now = Date.now(), home = homedir()) {
|
|
|
704
732
|
const unpriced = spend.unpricedNew && spend.unpriced ? unpricedText(spend.unpriced) : undefined;
|
|
705
733
|
if (!spend.warn)
|
|
706
734
|
return unpriced ? { spend, budget: b, message: `context-doctor: ${unpriced}` } : { spend, budget: b };
|
|
707
|
-
const
|
|
735
|
+
const base = spend.warn >= 100
|
|
708
736
|
? `${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.`
|
|
709
737
|
: `${head}${byToolText(spend.byTool)}: ${pct}% of your ${amount(b.usd)}/${per(b.period)} budget.`;
|
|
738
|
+
// Once per threshold, so the ledger (and the transcripts only past a limit) is read only then.
|
|
739
|
+
const credits = creditsLine(periodCredits(spend.start, now, home));
|
|
740
|
+
const message = credits ? `${base} ${credits}` : base;
|
|
710
741
|
return { spend, budget: b, message: unpriced ? `${message} ${unpriced}` : message };
|
|
711
742
|
}
|
|
712
743
|
/** The status line's part: "$12/$50 today", or undefined with no budget set. */
|
|
@@ -718,14 +749,23 @@ export function budgetStatus(now = Date.now(), home = homedir()) {
|
|
|
718
749
|
const short = (n) => (n >= 10 ? `$${Math.round(n).toLocaleString("en-US")}` : `$${n.toFixed(2)}`);
|
|
719
750
|
return `${short(s.usd)}/${amount(b.usd)} ${span(b.period)}${s.usd >= b.usd ? " ⚠" : ""}`;
|
|
720
751
|
}
|
|
721
|
-
/**
|
|
722
|
-
|
|
752
|
+
/**
|
|
753
|
+
* `budget` with no argument, and after setting one: the budget and where the
|
|
754
|
+
* period stands. `ahead`: the weekly limit running out before its reset with
|
|
755
|
+
* extra usage on (credits.ts creditsAheadNow), said in one line.
|
|
756
|
+
*/
|
|
757
|
+
export function renderBudgetStatus(b, s, hookInstalled, credits, ahead, now = Date.now()) {
|
|
723
758
|
if (!b || !s)
|
|
724
759
|
return "No spend budget set. Set one: context-doctor budget 50/day (or 200/week; --block to hold prompts over it).";
|
|
725
760
|
const lines = [
|
|
726
761
|
`Budget: ${amount(b.usd)} a ${per(b.period)}, across Claude Code, Codex and Gemini CLI${b.block ? "; prompts over it are held" : ""}.`,
|
|
727
762
|
`${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)}`,
|
|
728
763
|
];
|
|
764
|
+
const paid = creditsLine(credits);
|
|
765
|
+
if (paid)
|
|
766
|
+
lines.push(paid);
|
|
767
|
+
if (ahead)
|
|
768
|
+
lines.push(creditsAheadLine(ahead, now));
|
|
729
769
|
const org = orgRatesLine();
|
|
730
770
|
if (org)
|
|
731
771
|
lines.push(org);
|