context-doctor 0.51.0 → 0.52.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
@@ -7,30 +7,34 @@
7
7
  AI agents re-send their whole context on every message: old tool output, pasted files, long instructions. A 500k-token session pays for all of it again each time, and at full price after a coffee break, when the prompt cache has expired. context-doctor measures that waste on your own sessions, in dollars, and removes it at the moments it pays: before it enters the context, while it sits there, and on every request. It runs on your machine, needs no API key, sends no telemetry, and works with **Claude Code** (terminal, IDE, desktop app), **Claude Desktop, ChatGPT, Codex, Cursor, Gemini CLI, GitHub Copilot**, any app on the **Anthropic, OpenAI or Gemini API**, and **CI**. MIT licensed, Node 20+, macOS, Linux and Windows.
8
8
 
9
9
  ```bash
10
- npx context-doctor savings # what your recent sessions cost, and what each fix would have saved
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, Cursor, Copilot CLI, OpenCode and Cline
10
+ npx context-doctor savings
13
11
  ```
14
12
 
13
+ What your recent Claude Code sessions cost, and what each fix would have saved: replayed request by request against what you were billed, never modelled, and with nothing to measure it says so. Nothing to measure yet? `npx context-doctor savings --sample` runs the same report on generated example sessions, labelled SAMPLE.
14
+
15
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">
16
16
 
17
+ *Measured on the author's own sessions, priced the way the prompt cache billed them; `savings` replays yours the same way and, with nothing to measure, says so.*
18
+
17
19
  > **Which context-doctor is this?** Several projects share the name. This one is [`context-doctor` on npm](https://www.npmjs.com/package/context-doctor) and `io.github.KushalP1/context-doctor` in the official MCP Registry ([see the entry](https://registry.modelcontextprotocol.io/v0/servers/io.github.KushalP1%2Fcontext-doctor/versions/latest)). The registry is a service, not a list in a GitHub repo: the `modelcontextprotocol/servers` repository holds only reference servers and points to the registry for the rest. Built and maintained by [gAI Ventures](https://gai.ventures).
18
20
 
19
21
  ## Quick start
20
22
 
21
23
  **See it first, nothing installed:** in a terminal, `npx context-doctor` reads your last 30 days of Claude Code sessions on this machine and shows what the fixes with no quality cost would have saved, as one total, then asks once: `y` applies them all, `npx context-doctor fix undo` puts them back. The fixes that trade something (compacting earlier, the subagents' model) are listed with their dollars and the command for each.
22
24
 
23
- Pick where you work. Each takes about a minute and is fully reversible.
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`.
26
+
27
+ **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`.
28
+
29
+ Each takes about a minute and is fully reversible. Work somewhere else? Same idea, other surfaces:
24
30
 
25
31
  | You use | Do this |
26
32
  |---|---|
27
- | **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` |
28
- | **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` |
29
33
  | **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"]}}}` |
30
34
  | **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
35
  | **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
36
  | **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.51.0` comments how much a PR grows CLAUDE.md, AGENTS.md and rules, and can fail over a budget ([setup](./docs/ci.md)) |
37
+ | **GitHub pull requests** | `uses: KushalP1/context-doctor@v0.52.0` comments how much a PR grows CLAUDE.md, AGENTS.md and rules, and can fail over a budget ([setup](./docs/ci.md)) |
34
38
 
35
39
  ## What it does
36
40
 
@@ -63,36 +67,37 @@ Pick where you work. Each takes about a minute and is fully reversible.
63
67
 
64
68
  ## What it saves
65
69
 
66
- Measured, not modelled, on every Claude Code session on the author's machine (mostly Opus 5 and Fable 5 with the 1M window), priced the way the prompt cache bills it (cached reads at each model's read rate, 2.5-10% of input; writes 1.25x input for the 5-minute cache, 2x for the hour) at API list prices. Re-measured on 2026-10-13 with each request at its own model and current prices (Opus 5.5 is $4 per million input tokens with $0.20 reads). `context-doctor savings` runs the same measurement on yours.
70
+ Measured, not modelled, on every Claude Code session on the author's machine (mostly Opus 5.5 and the Fable 5 models with the 1M window), priced the way the prompt cache bills it (cached reads at each model's read rate, 2.5-10% of input; writes 1.25x input for the 5-minute cache, 2x for the hour) at API list prices. Re-measured on 2026-11-24 with each request at its own model and current prices (Opus 5.5 is $4 per million input tokens with $0.20 reads). `context-doctor savings` runs the same measurement on yours.
67
71
 
68
- **1. Compacting when you come back** (every Claude Code surface, desktop app included). 133 days, 479 returns to a session over 150k tokens after its prompt cache expired (65 idle minutes on the 1-hour cache, 10 on the 5-minute one that Claude Code 2.1.295 often writes); median context at the return, 522k tokens.
72
+ **1. Compacting when you come back** (every Claude Code surface, desktop app included). 146 days, 729 returns to a session over 150k tokens after its prompt cache expired (65 idle minutes on the 1-hour cache, 10 on the 5-minute one that Claude Code 2.1.295 often writes); median context at the return, 497k tokens.
69
73
 
70
74
  | | |
71
75
  |---|---|
72
- | Net saving had you run `/compact` after the first reply | **$2,993 (about $675 a month)** |
73
- | Returns where it paid off | 342 of 479 |
76
+ | Net saving had you run `/compact` after the first reply | **$3,554 (about $740 a month)** |
77
+ | Returns where it paid off | about 2 in 3 |
74
78
  | Worst single case | −$1.79 (a session left a few messages later) |
75
79
 
76
80
  Each return counts only the messages up to the next return, and the compaction request is charged as a cost. Not counted: files the model may re-read after compacting, and what the summary leaves out. That is why this is advice with the numbers attached, not something done for you.
77
81
 
78
- **2. Autopilot** (Claude Code in a terminal or IDE, API apps). 133 days, 67 sessions, replayed through the shipped autopilot code with real timestamps:
82
+ **2. Autopilot** (Claude Code in a terminal or IDE, API apps). 146 days, 108 sessions, replayed through the shipped autopilot code with real timestamps:
79
83
 
80
84
  | | Without autopilot | With autopilot | Saved |
81
85
  |---|---|---|---|
82
- | Input cost at API list price | $11,347 | $9,905 | **$1,442 (12.7%, about $325 a month)** |
83
- | Sessions made more expensive | | | **0 of 67** |
86
+ | Input cost at API list price | $14,318 | $12,561 | **$1,757 (12.3%, about $365 a month)** |
87
+ | Sessions made more expensive | | | **0 of 108** |
84
88
 
85
- 30 of 67 sessions save something, the best 34.9%: long sessions that go idle are where the money is. These sessions ran in the desktop app, which autopilot cannot reach, so for the author this is what the same sessions would have saved in a terminal; `context-doctor savings` separates the two for you. [How it works →](./docs/autopilot.md)
89
+ 43 of 108 sessions save something, the best 41.6%: long sessions that go idle are where the money is. These sessions ran in the desktop app, which autopilot cannot reach, so for the author this is what the same sessions would have saved in a terminal; `context-doctor savings` separates the two for you. [How it works →](./docs/autopilot.md)
86
90
 
87
91
  **3. Compacting earlier** <a id="3-compacting-earlier-automatic"></a>(automatic, every Claude Code surface, desktop app included). The offer in 1 is advice, and on the author's machine it was followed 1 time in 33. Claude Code has a native setting that needs nobody to follow anything: `autoCompactWindow` in `~/.claude/settings.json` makes it compact as if the window were that size. `context-doctor compact-window` replays each session request by request at several sizes, priced as the cache bills (each simulated compaction pays its own request and a 20k-token summary at the output rate), and changes nothing until you pick one:
88
92
 
89
93
  | Window | Input cost, last 30 days | Saved | Compactions a week |
90
94
  |---|---|---|---|
91
- | as now (~970k) | $3,648 | | 4.7 |
92
- | 600k | $2,242 | $1,405 (39%) | 6.5 |
93
- | **400k** | **$1,814** | **$1,833 (50%)** | **14.2** |
94
- | 300k | $1,664 | $1,983 (54%) | 25.2 |
95
- | 200k | $1,501 | $2,146 (59%) | 48.1 |
95
+ | as now (not set) | $1,680 | | 8.6 |
96
+ | 800k | $1,532 | $149 (9%) | 8.6 |
97
+ | 600k | $1,324 | $357 (21%) | 8.9 |
98
+ | **400k** | **$1,053** | **$628 (37%)** | **11.9** |
99
+ | 300k | $958 | $723 (43%) | 17.0 |
100
+ | 200k | $881 | $799 (48%) | 30.6 |
96
101
 
97
102
  41 sessions. The cost is real: each compaction replaces the session's history with a summary, so a smaller window trades detail for money. That is why the command shows the table first and sets a window only when you name one (`context-doctor compact-window 400k`; `off` undoes it, and a backup of settings.json is kept).
98
103
 
@@ -140,7 +145,7 @@ Rules 1-4 end exactly at character 512, the part ChatGPT's guide says must stand
140
145
  | `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
146
  | `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
147
  | `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
- | `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)) |
148
+ | `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.3% less input cost, no session worse ([details](./docs/autopilot.md)) |
144
149
  | `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)) |
145
150
  | `context-doctor compact-window [status\|off\|<size>]` | Replay your last 30 days at auto-compact windows from 200k to 800k: input cost, saving, and how many more compactions each means. `400k` (or `250000`, `0.4m`) sets Claude Code's `autoCompactWindow`, with a backup; `off` removes it. Works in every Claude Code surface, the desktop app included. When you answered the Desktop app's own window offer, it says what the app offered and what you chose, and leaves that model's sessions out of the replay ([docs](./docs/fix.md#the-desktop-apps-own-window-offer-compact-window)) |
146
151
  | `context-doctor cache-ttl [status\|1h\|5m\|off] [--subagents]` | The main conversation's (or subagents') prompt cache lifetime: what 5 minutes and 1 hour would each have cost on your last 30 days, then set or remove `promptCacheTtl` / `subagentPromptCacheTtl` (Claude Code 2.1.243+, every surface). Price only: the same content is sent ([details](./docs/fix.md)) |
@@ -183,6 +188,7 @@ Rules 1-4 end exactly at character 512, the part ChatGPT's guide says must stand
183
188
 
184
189
  ## What's new
185
190
 
191
+ - **0.52 An honest empty state, a sample report, and one command up front**: with nothing of yours to replay, `savings` says so, offers `savings --sample`, the same report on generated example sessions, labelled SAMPLE, and says when to run it again; the measured report's footer says it too. `doctor` no longer says "All good" when nothing is protected: the verdict distinguishes no supported app, installed-but-not-wired ("not actively protecting any workflow") and wired. The README leads with one audience and one command, the savings figure captioned as measured on the author's own sessions, the other surfaces in a table. A new bug-report template asks for `doctor` output and `limits --report`, never transcripts; security reports go through private advisories ([details](./ROADMAP.md#shipped-in-0520-an-honest-empty-state-a-sample-report-and-one-command-up-front)).
186
192
  - **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)).
187
193
  - **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)).
188
194
  - **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)).
@@ -190,15 +196,6 @@ Rules 1-4 end exactly at character 512, the part ChatGPT's guide says must stand
190
196
  - **0.48 Directory-ready, quality on your own plan, and MCP SDK v2**: a build of the plugin for Anthropic's directory (strict-clean, with and without the mod); `ab --via claude-code` measures the subagent lever on your own sign-in, no API key; the price check covers OpenAI, Google, Codex and Gemini CLI and warns before a price ends; the MCP server speaks protocol 2026-07-28 to Claude Code and the old handshake to everyone else. Fixed: installing the plugin from the marketplace no longer pulls 80 MB of build tools into Claude Code's cache ([details](./ROADMAP.md#shipped-in-0480-a-directory-ready-plugin-quality-on-your-own-plan-prices-that-change-under-us-and-mcp-sdk-v2)).
191
197
  - **0.47 One keystroke to a saving, the mod through `install`, a weekly live check, and an audit of 0.46**: a bare `context-doctor` in a terminal shows the fixes that cost no quality as one monthly total and asks once (the author's: $469 a month: long Bash output to a file, the 1-hour cache). On Claude Code 2.1.286+, `install` enables the plugin, so npm users get the mod too (limit readings and Claude Code's own cost after each turn, Compact first, `/context-doctor-fix`). A weekly canary runs the plugin and mod in the newest Claude Code against a local mock API. `spend` estimates compaction requests and, for terminal sessions, subagent progress summaries, and `fix` can switch the summaries off. An audit fixed, among others, the GitHub Action's YAML (it could not load), programs planted in a cloned repository running on Windows, `pack_context` opening network shares, a re-pricing gap after upgrades, and a test that would have failed from 2026-12-16 ([details](./ROADMAP.md#shipped-in-0470-one-keystroke-the-mod-through-install-a-weekly-live-check-and-an-audit-of-046)).
192
198
  - **0.46 Fable 5.2, the Desktop app, and an audit**: Claude Fable 5.2 is priced (0.45 read it 1.5x too high); managed `modelPricing` is honoured; a check catches new models without a price. The plugin's new mod brings limit readings, Claude Code's own cost and `/context-doctor-fix` with Apply and Undo buttons to the Desktop app, VS Code and the terminal, and a cache-expiry band with **Compact first** to the Desktop app and the terminal (Claude Code draws a mod's band on no other surface) ([Desktop](./docs/desktop.md), [details](./ROADMAP.md#shipped-in-0460-fable-52-the-desktop-app-and-an-audit-of-045)).
193
- - **0.45 Price what is billed, and a security pass**: fast mode, US-only inference, Haiku 5.5's long-prompt rates, web searches and OpenAI's and Gemini's long-prompt tiers are priced per request in every report, and prices that end on a known day say so. A security pass fixed a cloned repository approving its own MCP servers for `overhead --mcp`, a PDF's name running as a command through `pack` on macOS, the agents' API-key configs being packed, and the proxy answering a DNS-rebinding page ([details](./ROADMAP.md#shipped-in-0450-price-what-is-billed-and-a-security-pass-on-044)).
194
- - **0.44 Workflow agents on the bill, current prices, and an audit**: Claude Code's workflow agents were in no report: on the author's last 30 days $1,494 of $5,542. `spend`, the budget, a session's price, `subagents` and `fix` now count them, and `spend` equals an independent sum of every transcript to the cent. Prices re-read from each provider (Sonnet 5.5's cache read $0.10, gpt-5.5 $5/$30, the gpt-6 family); estimates are labelled. An audit fixed `overhead --mcp` launching a cloned repository's unapproved MCP servers, `pack_context` returning the agents' sign-in files, and more ([details](./ROADMAP.md#shipped-in-0440-workflow-agents-on-the-bill-current-prices-and-an-audit-of-043)).
195
- - **0.43 Long tool output, `fix` for Codex, and a session's price**: every Bash result stays in the conversation and is re-read on every later message until a compaction; `fix` now replays them at lower caps and, on a yes, sets Claude Code's `bashOutputMaxChars`, so longer output goes to a file the model can still open after a 2,000-character preview (the author's 30 days: $323 less at 8k, 9% of input). `fix` also works for Codex: it replays your rollouts at earlier auto-compact limits and sets `model_auto_compact_token_limit` in `config.toml`, on a machine with only Codex too. And the every-prompt hook now tells you once when a session passes $25, $100 and $500, with what each message costs from there (the author's: 15 sessions passed $25 in 30 days and spent $3,369 after).
196
- - **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)).
197
- - **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.
198
- - **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.
199
- - **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.
200
- - **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.
201
- - **0.37 Desktop chat apps: a handoff, uploads, compact results, and a security pass**: a chat app's history cannot be edited, so the `handoff` prompt (Claude Desktop's **+** menu) has the model write a ≤400-token brief and save it with `save_handoff` (secrets masked, `handoff://latest` to attach in the next chat, the per-turn saving reported: a 52k-token chat drops to ~600). `ask_file` answers from a big file through `pack_context`, which over `--http` also takes ChatGPT uploads; ChatGPT gets compact results. An independent QA pass's eleven findings were fixed with tests; **behind a tunnel, `--http` now needs `--allowed-hosts <tunnel host>`** ([handoff](./docs/handoff.md)).
202
199
 
203
200
  Every release, with the details: [docs/whats-new.md](./docs/whats-new.md).
204
201
 
package/dist/cli.js CHANGED
@@ -27,7 +27,8 @@ import { latestModelComparison } from "./abstore.js";
27
27
  import { buildImpactReport } from "./impact.js";
28
28
  import { measureTokenizer, renderTokenizer } from "./tokenizer-measure.js";
29
29
  import { autopilotOff, autopilotOn, autopilotPauseResult, autopilotPaths, autopilotStatus, DEFAULT_AUTOPILOT_PORT } from "./autopilot.js";
30
- import { estimateSavings, renderSavings, renderShare, savingsRows } from "./savings.js";
30
+ import { estimateSavings, renderSampleSavings, renderSavings, renderShare, savingsRows } from "./savings.js";
31
+ import { writeSampleHistory } from "./sample.js";
31
32
  import { prescan } from "./scan.js";
32
33
  import { REQUEST_ROWS } from "./coldresume.js";
33
34
  import { coldReturns } from "./coldreturns.js";
@@ -125,7 +126,7 @@ Start here:
125
126
  Cursor's postToolUse), Claude Code's PreCompact
126
127
  hook, which tells each compaction what to keep,
127
128
  and Copilot's sessionStart (the standing rules)
128
- context-doctor savings [--days n] [--share [--copy]]
129
+ context-doctor savings [--days n] [--share [--copy]] [--sample]
129
130
  What your recent Claude Code sessions cost, and what
130
131
  /compact at cold resumes, autopilot and an earlier
131
132
  auto-compact window would save, replayed and priced
@@ -618,6 +619,7 @@ const FLAGS = [
618
619
  { names: ["--dry-run"], set: (a) => { a.dryRun = true; } },
619
620
  { names: ["--copy"], set: (a) => { a.copy = true; } },
620
621
  { names: ["--share"], set: (a) => { a.share = true; } },
622
+ { names: ["--sample"], set: (a) => { a.sample = true; } },
621
623
  { names: ["--report"], set: (a) => { a.report = true; } },
622
624
  { names: ["--by"], value: "text", set: (a, v) => { a.by = v; } },
623
625
  { names: ["--export"], set: (a) => { a.exportSpend = true; } },
@@ -1186,6 +1188,8 @@ async function main() {
1186
1188
  if (args.command === "savings" || (!args.command && process.stdout.isTTY && hasClaudeSessions())) {
1187
1189
  // `savings`, and a bare `context-doctor --json` or `--share` in a terminal
1188
1190
  // with Claude Code history (what a bare run printed before the one-question screen).
1191
+ if (args.sample && (args.json || args.share))
1192
+ usageError("--sample is a demonstration for the terminal; it does not go with --json or --share.");
1189
1193
  const replaying = progressLine("Replaying your Claude Code sessions through autopilot");
1190
1194
  // Each transcript read once for every report below; what an earlier run kept is not read again (scan.ts).
1191
1195
  prescan([
@@ -1194,6 +1198,19 @@ async function main() {
1194
1198
  ], replaying.tick);
1195
1199
  const report = estimateSavings(args.days ?? 30, {}, undefined, replaying.tick);
1196
1200
  replaying.clear();
1201
+ // --sample: the real report on a generated history, said to be a sample.
1202
+ // Never substituted for the real one: with no history the empty report
1203
+ // says so and offers this flag (renderSavings' empty branch).
1204
+ if (args.sample) {
1205
+ const demo = writeSampleHistory();
1206
+ try {
1207
+ console.log(renderSampleSavings(estimateSavings(30, {}, demo.paths)));
1208
+ }
1209
+ finally {
1210
+ demo.cleanup();
1211
+ }
1212
+ return;
1213
+ }
1197
1214
  const setWindow = currentCompactWindow();
1198
1215
  const measuring = progressLine("Measuring your compactions");
1199
1216
  const reread = compactionQuality(60, undefined, measuring.tick).extraRereadTokensPerCompaction;
package/dist/doctor.js CHANGED
@@ -1092,12 +1092,35 @@ export async function runDoctor() {
1092
1092
  const warns = checks.filter((c) => c.status === "warn");
1093
1093
  if (fails.length > 0)
1094
1094
  process.exitCode = 1;
1095
+ // "All good" must mean something is actually protected. A clean bill on an
1096
+ // empty machine is not that: say what is missing instead of reassuring.
1097
+ // Presence is what each section above already decides: the app's config or
1098
+ // home folder, its binary. (The app rows cannot be re-read for this — the
1099
+ // Claude Code row watches ~/.claude.json while the app lives in ~/.claude.)
1100
+ const home = homedir();
1101
+ const appsDetected = existsSync(claudeDesktopConfigPath()) ||
1102
+ claudeCodePresent() ||
1103
+ existsSync(join(claudeDir(), "settings.json")) ||
1104
+ existsSync(join(home, ".cursor")) ||
1105
+ existsSync(codexDir()) ||
1106
+ geminiCliPresent() ||
1107
+ antigravityPresent() ||
1108
+ copilotPresent() ||
1109
+ devinCheck(home).status !== "skip";
1110
+ // An ok that means a workflow is protected, not internal plumbing (the
1111
+ // ledger, the MCP handshake with itself, optional config files existing).
1112
+ const INTERNAL_OK = new Set(["Ledger", "MCP server handshake", "Project config", "Spend budget", "Desktop chat tool use", "Extra usage", "Desktop app tools", "Desktop compact offer", "Autopilot port"]);
1113
+ const protecting = checks.filter((c) => c.status === "ok" && !INTERNAL_OK.has(c.label));
1095
1114
  console.log("");
1096
1115
  console.log(fails.length > 0
1097
1116
  ? `${fails.length} issue(s) found — fixes suggested above.`
1098
- : warns.length > 0
1099
- ? `No problems; ${warns.length} note(s) marked ! above.`
1100
- : "All good.");
1117
+ : protecting.length === 0
1118
+ ? !appsDetected
1119
+ ? withInvocation("Installed and healthy, but no supported AI app was found on this machine: nothing is being measured or protected yet. On a machine with Claude Code, Cursor, Codex or Gemini CLI, `context-doctor install` wires it (`context-doctor uninstall` removes it).")
1120
+ : withInvocation("Installed and healthy, but nothing is wired up yet: context-doctor is not actively protecting any workflow. `context-doctor install` wires the apps on this machine (`context-doctor uninstall` removes it).")
1121
+ : warns.length > 0
1122
+ ? `No problems; ${warns.length} note(s) marked ! above.`
1123
+ : "All good.");
1101
1124
  }
1102
1125
  /** "3.18.25" >= major.minor. */
1103
1126
  function versionAtLeast(v, major, minor) {
package/dist/mcp.js CHANGED
@@ -112,7 +112,7 @@ data:
112
112
  Put it behind your tunnel's or reverse proxy's authentication unless only you can reach this address.`}function UC(e,t=8808){let r=Number(e);return e!==void 0&&e.trim()!==""&&Number.isInteger(r)&&r>=0&&r<=65535?r:t}function h0(e,t){if(e.hosts!=="*"){let o=au(String(t.host??""));if(!o)return"the request has no Host header";if(!e.hosts.has(o)&&!(e.ipLiterals&&K6(o)))return`Host "${o}" is not one this server answers to. Behind a tunnel or under a host name, start it with --allowed-hosts ${o}`}let r=t.origin;if(r!==void 0){let o=String(r).toLowerCase().replace(/\/+$/,"");if(e.origins.has(o))return;let n;try{n=new URL(o)}catch{return`Origin "${o}" is not allowed`}let i=au(n.host);if(!(jC.includes(i)||e.hosts!=="*"&&e.hosts.has(i)))return`Origin "${o}" is not allowed. To let a web page call this server, start it with --allowed-origins ${o}`}}function DC(e,t=NC.bodyBytes,r=NC.bodyMs){return new Promise(o=>{let n=!1,i=setTimeout(()=>{n||(n=!0,o({status:408,code:-32600,message:`the request body did not arrive within ${Math.round(r/1e3)} s`}))},r),s=d=>{clearTimeout(i),o(d)},a={status:413,code:-32600,message:`request body over ${Math.round(t/1024/1024)} MB`},c=Number(e.headers["content-length"]);if(Number.isFinite(c)&&c>t)return e.resume(),s(a);let u=[],l=0;e.on("data",d=>{if(!n){if(l+=d.length,l>t)return n=!0,u.length=0,e.resume(),s(a);u.push(d)}}),e.on("end",()=>{if(!n){n=!0;try{s({value:JSON.parse(Buffer.concat(u).toString("utf8"))})}catch{s({status:400,code:-32700,message:"Parse error: the body is not JSON"})}}}),e.on("error",()=>{n||(n=!0,s({status:400,code:-32700,message:"the request body could not be read"}))})})}var NC,G6,jC,g0=V(()=>{"use strict";NC={bodyBytes:10*1024*1024,bodyMs:3e4},G6=["https://chatgpt.com","https://chat.openai.com"],jC=["localhost","127.0.0.1","::1"]});import{closeSync as X6,existsSync as uK,openSync as Y6,readdirSync as lK,readFileSync as Q6,readSync as eF,statSync as dK}from"node:fs";function y0(e){if(!/\.jsonl?$/.test(e))return!1;try{let t=Buffer.alloc(4096),r=Y6(e,"r"),o=eF(r,t,0,4096,0);X6(r);let n=t.subarray(0,o).toString("utf8");return/"projectHash"\s*:/.test(n)&&/"sessionId"\s*:/.test(n)}catch{return!1}}function LC(e){let t=[],r=new Map,o=0,n=a=>{let c=typeof a.id=="string"?a.id:`anon-${o++}`;r.has(c)||t.push(c),r.set(c,a)},i=Q6(e,"utf8"),s=i.trimStart();if(s.startsWith("{")&&!s.includes(`
113
113
  {`))try{let a=JSON.parse(i);for(let c of a.messages??[])n(c);return t.map(c=>r.get(c))}catch{}return Fo(e,a=>{if(!a.trim())return;let c;try{c=JSON.parse(a)}catch{return}if(!(!c||typeof c!="object")){if(typeof c.$rewindTo=="string"){let u=t.indexOf(c.$rewindTo);if(u>=0)for(let l of t.splice(u))r.delete(l);return}typeof c.type=="string"&&("content"in c||"toolCalls"in c)&&n(c)}}),t.map(a=>r.get(a))}var Gm=V(()=>{"use strict";Vo()});import{readdirSync as vK,readFileSync as _K,statSync as $K,existsSync as SK,openSync as nF,readSync as rF,closeSync as oF}from"node:fs";import{StringDecoder as iF}from"node:string_decoder";import{homedir as sF}from"node:os";import{join as aF}from"node:path";function qC(e,t=sF()){return aF(St(t),"projects",e.replace(/[^A-Za-z0-9]/g,"-"))}function Fo(e,t){let r=nF(e,"r"),o=new iF("utf8"),n=Buffer.allocUnsafe(4*1024*1024),i="";try{for(;;){let s=rF(r,n,0,n.length,null);if(s===0)break;i+=o.write(n.subarray(0,s));let a;for(;(a=i.indexOf(`
114
114
  `))!==-1;)t(i.slice(0,a)),i=i.slice(a+1)}i+=o.end(),i&&t(i)}finally{oF(r)}}function Xm(e){let t=new Set;return r=>{let o=r?.message?.id;if(typeof o=="string"){if(t.has(o))return"repeat";t.add(o)}let n=r?.uuid;if(e&&typeof n=="string"){if(e.has(n))return"copy";e.add(n)}return"new"}}function v0(){let e=new Map;return(t,r)=>{let o=Number(t?.message?.usage?.output_tokens),n=Number.isFinite(o)&&o>0?o:0,i=t?.message?.id;if(typeof i!="string")return r?n:0;if(r)return e.set(i,n),n;let s=e.get(i);return s===void 0||n<=s?0:(e.set(i,n),n-s)}}function Ym(e){return typeof e=="string"?e:Array.isArray(e)?e.map(t=>typeof t=="string"?t:typeof t?.text=="string"?t.text:"").filter(Boolean).join(`
115
- `):""}var Vo=V(()=>{"use strict";Ze();Xe();Yr();Gm();mn()});import{readdirSync as b0,readFileSync as LK,statSync as $F}from"node:fs";import{basename as FK,join as uu}from"node:path";function SF(e){return uu(e.replace(/\.jsonl$/,""),"subagents")}function lu(e,t=-1/0){let r=SF(e),o=[],n=(a,c)=>{try{(t===-1/0||$F(a).mtimeMs>=t)&&o.push(c?{file:a,run:c}:{file:a})}catch{}},i;try{i=b0(r)}catch{return o}for(let a of i)a.endsWith(".jsonl")&&n(uu(r,a));if(!i.includes("workflows"))return o;let s;try{s=b0(uu(r,"workflows"))}catch{return o}for(let a of s){let c;try{c=b0(uu(r,"workflows",a))}catch{continue}for(let u of c)u.endsWith(".jsonl")&&n(uu(r,"workflows",a,u),a)}return o}var zs=V(()=>{"use strict";Ze();Xe();Qc();Vo();Ze()});var YC=V(()=>{"use strict";Ze()});var QC=V(()=>{"use strict";Ze();Xe()});var eO=V(()=>{"use strict"});var mG,w0,hG,k0=V(()=>{"use strict";Jb();YC();Ze();Xe();sr();QC();eO();g0();mG=100*1024*1024,w0="0.51.0",hG=["7d-utilization","5h-utilization","overage-status","overage-in-use"].map(e=>`anthropic-ratelimit-unified-${e}`)});import{closeSync as T0,existsSync as bF,fstatSync as wF,mkdirSync as iO,openSync as P0,readdirSync as x0,readFileSync as C0,readSync as O0,renameSync as kF,rmSync as xF,statSync as z0,unlinkSync as R0,utimesSync as zF,writeFileSync as sO}from"node:fs";import{createHash as A0,randomBytes as RF}from"node:crypto";import{homedir as IF}from"node:os";import{isAbsolute as EF,join as Cn}from"node:path";function cO(e=process.env){if(e.CONTEXT_DOCTOR_CACHE_DIR)return e.CONTEXT_DOCTOR_CACHE_DIR;let t=e.XDG_CACHE_HOME&&EF(e.XDG_CACHE_HOME)?e.XDG_CACHE_HOME:Cn(IF(),".cache");return Cn(t,"context-doctor")}function CF(e,t){if(!nh())try{let r=JSON.parse(C0(lO(t.path,t.id),"utf8"));if(r?.path===t.path&&r.off===t.off&&r.anchor===t.anchor)return e.load(r.state)}catch{}}function M0(e){try{let t=z0(e);return{size:t.size,mtimeMs:t.mtimeMs,ino:t.ino}}catch{return}}function dO(e,t){if(!(t>N0))try{return A0("sha1").update(C0(e)).digest("hex")}catch{return}}function tO(e,t,r,o){return OF(e,t)?t.size>N0?!0:(o.done||(o.v=dO(r,t.size),o.done=!0),e.fp!==void 0&&e.fp===o.v):!1}function AF(e,t){if(!nh())try{let r=JSON.parse(C0(j0(e,t),"utf8"));if(r&&r.path===e&&r.id===t&&Array.isArray(r.rows)&&Array.isArray(r.tail)&&typeof r.off=="number")return r}catch{}}function rO(e,t=j0(e.path,e.id)){if(nh())return;let r=`${t}.${process.pid}.${RF(4).toString("hex")}.tmp`;try{iO(Cn(t,".."),{recursive:!0,mode:448}),sO(r,JSON.stringify(e),{mode:384}),kF(r,t),nO||(nO=!0,jF())}catch{try{R0(r)}catch{}}}function Ho(e,t){let r=A0("sha1"),o=(n,i)=>{let s=Buffer.alloc(i),a=O0(e,s,0,i,n);r.update(s.subarray(0,a))};return o(0,Math.min(Rs,t)),t>Rs&&o(Math.max(Rs,t-Rs),Math.min(Rs,t-Rs)),r.update(String(t)),r.digest("hex")}function NF(e,t,r){let o=Buffer.allocUnsafe(4194304),n=t,i=t,s=[];for(;;){let a=O0(e,o,0,o.length,n);if(a===0)break;let c=0;for(;;){let u=o.indexOf(10,c);if(u===-1||u>=a)break;let l=o.subarray(c,u),d=s.length?Buffer.concat([...s,l]).toString("utf8"):l.toString("utf8");s=[];let f=i;i=n+u+1,r(d,f,!0),c=u+1}c<a&&s.push(Buffer.from(o.subarray(c,a))),n+=a}return s.length&&r(Buffer.concat(s).toString("utf8"),i,!1),{off:i,end:n}}function oO(e,t,r=!1){let o=M0(e);if(!o)return[];let n=[],i=[],s={};for(let c of t){if(r){n.push({ex:c,from:0,state:c.init(),rows:[],tail:[]});continue}let u=E0(e,c.id),l=th.get(u);if(l&&tO(l,o,e,s))continue;let d=AF(e,c.id);if(d&&tO(d,o,e,s)){th.set(u,d);continue}let f=[d,l].find(h=>h&&c.resumable!==!1&&h.ino===o.ino&&o.size>h.size&&h.off<=o.size),p=f&&c.save?CF(c,f):f?.state;n.push(f&&p!==void 0?{ex:c,from:f.off,state:p,rows:f.rows,tail:[],prior:f}:{ex:c,from:0,state:c.init(),rows:[],tail:[]})}if(n.length===0)return i;let a;try{a=P0(e,"r")}catch{return i}try{for(let g of n)g.prior&&(g.prior.off===0||Ho(a,g.prior.off)!==g.prior.anchor)&&Object.assign(g,{from:0,state:g.ex.init(),rows:[],prior:void 0}),g.prior&&Object.assign(g,{state:g.ex.save?g.state:structuredClone(g.state),rows:g.rows.slice()});let c=Math.min(...n.map(g=>g.from)),u,{off:l,end:d}=NF(a,c,(g,m,_)=>{let y,b,R=!1,z=()=>{if(!R){R=!0;try{y=JSON.parse(g)}catch(w){b=w??new SyntaxError("not JSON")}}if(b!==void 0)throw b;return y};if(_){for(let w of n)m>=w.from&&w.ex.line(g,z,w.rows,w.state);return}u=n.map(w=>w.ex.resumable===!1?w.state:PF(w.ex,w.state)),n.forEach((w,x)=>{m>=w.from&&w.ex.line(g,z,w.ex.resumable===!1?w.rows:w.tail,u[x])})}),f;try{let g=wF(a);f={size:g.size,mtimeMs:g.mtimeMs,ino:g.ino}}catch{}let p=f!==void 0&&f.size===d,h=n.some(g=>g.ex.resumable!==!1)?Ho(a,l):"",v=p&&d<=N0?dO(e,d):void 0;n.forEach((g,m)=>{let _=g.ex.resumable!==!1;g.ex.end&&g.ex.end(_?g.tail:g.rows,u?u[m]:g.state);let y={path:e,id:g.ex.id,size:d,mtimeMs:p?f.mtimeMs:-1,ino:f?.ino??o.ino,off:_?l:d,anchor:_?h:"",state:_&&!g.ex.save?g.state:null,rows:g.rows,tail:g.tail,...v!==void 0?{fp:v}:{}};i.push(y),!r&&(th.set(E0(e,g.ex.id),y),p&&(rO(y),_&&g.ex.save&&Date.now()-f.mtimeMs<aO&&rO({path:e,off:l,anchor:h,state:g.ex.save(g.state)},lO(e,g.ex.id))))})}finally{T0(a)}return i}function On(e,t,r={}){let o=M0(e),n=r.keep===!1?oO(e,[t],!0)[0]:(oO(e,[t]),th.get(E0(e,t.id)));if(!o||!n)throw T0(P0(e,"r")),new Error(`unreadable transcript: ${e}`);return n.tail.length?n.rows.concat(n.tail):n.rows}function jF(e=Date.now(),t=!1){if(nh())return;let r=Cn(cO(),"transcripts"),o=Cn(r,".pruned");try{if(!t&&e-z0(o).mtimeMs<I0)return}catch{}try{iO(r,{recursive:!0,mode:448}),sO(o,""),zF(o,e/1e3,e/1e3);let n=uO();for(let c of x0(r))c.startsWith(".")||Cn(r,c)!==n&&xF(Cn(r,c),{recursive:!0,force:!0});if(!bF(n))return;let i=(Number(process.env.CONTEXT_DOCTOR_CACHE_MAX_MB)>0?Number(process.env.CONTEXT_DOCTOR_CACHE_MAX_MB):256)*1024*1024,s=[];for(let c of x0(n)){let u=Cn(n,c),l;try{l=x0(u)}catch{continue}for(let d of l){let f=Cn(u,d),p;try{p=z0(f)}catch{continue}let h=()=>{try{R0(f)}catch{}};if(d.endsWith(".tmp")){e-p.mtimeMs>36e5&&h();continue}if(d.endsWith(".state.json")&&e-p.mtimeMs>aO){h();continue}let v=MF(f),g=v?M0(v):void 0;if(!g||e-g.mtimeMs>120*I0){h();continue}s.push({file:f,size:p.size,mtimeMs:p.mtimeMs})}}let a=s.reduce((c,u)=>c+u.size,0);if(a<=i)return;for(let c of s.sort((u,l)=>u.mtimeMs-l.mtimeMs)){if(a<=i*.8)break;try{R0(c.file),a-=c.size}catch{}}}catch{}}function MF(e){try{let t=P0(e,"r");try{let r=Buffer.alloc(8192),o=O0(t,r,0,r.length,0),n=/^\{"path":("(?:[^"\\]|\\.)*")/.exec(r.subarray(0,o).toString("utf8"));return n?JSON.parse(n[1]):void 0}finally{T0(t)}}catch{return}}function Zt(e,t){if(!e||typeof e!="object"||Array.isArray(e))return e;let r={};for(let o of t)e[o]!==void 0&&(r[o]=e[o]);return r}var TF,I0,Rs,N0,aO,th,E0,nh,uO,j0,lO,PF,OF,nO,UF,rh,DF,ur=V(()=>{"use strict";k0();Xe();TF=1,I0=864e5,Rs=64*1024,N0=64*1024,aO=3*I0,th=new Map,E0=(e,t)=>`${t}\0${e}`;nh=()=>process.env.CONTEXT_DOCTOR_NO_CACHE==="1",uO=()=>Cn(cO(),"transcripts",`v${TF}-${w0}`),j0=(e,t)=>Cn(uO(),t.replace(/[^\w.-]/g,"_"),`${A0("sha1").update(e).digest("hex")}.json`),lO=(e,t)=>j0(e,t).replace(/\.json$/,".state.json"),PF=(e,t)=>e.save?e.load(JSON.parse(JSON.stringify(e.save(t)))):structuredClone(t);OF=(e,t)=>e.size===t.size&&e.mtimeMs===t.mtimeMs&&e.ino===t.ino;nO=!1;UF=["input_tokens","cache_creation_input_tokens","cache_read_input_tokens","output_tokens","cache_creation","output_tokens_details","context_management"],rh=(e,t={})=>{let r=Zt(e,UF);if(!r||typeof r!="object"||Array.isArray(r))return r;e.speed==="fast"&&(r.speed="fast"),e.inference_geo==="us"&&(r.inference_geo="us");let o=e.server_tool_use?.web_search_requests;return typeof o=="number"&&o>0&&(r.server_tool_use={web_search_requests:o}),t.iterations&&ru(e).length&&(r.iterations=e.iterations.map(n=>Zt(n,DF))),r},DF=["type","model","input_tokens","cache_creation_input_tokens","cache_read_input_tokens","output_tokens","cache_creation"]});function fO(e){if(typeof e!="string")return!1;let t=e.split(/[.-]/).map(o=>parseInt(o,10)||0),r=o=>{let n=o.split(".").map(Number);for(let i=0;i<3;i++)if((t[i]??0)!==n[i])return(t[i]??0)-n[i];return 0};return r(LF)>=0&&r(qF)<=0}function pO(e){if(!Array.isArray(e))return 0;let t=0,r=0;for(let o of e)!o||typeof o!="object"||(o.type==="text"&&typeof o.text=="string"?t+=o.text.length:o.type==="tool_use"?t+=JSON.stringify(o.input??{}).length+String(o.name??"").length:o.type==="thinking"&&(t+=typeof o.thinking=="string"?o.thinking.length:0,r+=typeof o.signature=="string"?o.signature.length:0));return Math.round(t*FF+r*VF)}var LF,qF,FF,VF,U0=V(()=>{"use strict";Xe();Ze();LF="2.1.284",qF="2.1.299";FF=.4,VF=.26});function mO(e,t){if(e?.type!=="cost-state"||typeof e.totalCostUSD!="number"||!Number.isFinite(e.totalCostUSD))return;let r={},o=e.modelUsage&&typeof e.modelUsage=="object"&&!Array.isArray(e.modelUsage)?e.modelUsage:{};for(let[n,i]of Object.entries(o).slice(0,40)){if(!i||typeof i!="object")continue;let s=i;r[n.slice(0,100)]={usd:lr(s.costUSD),input:lr(s.inputTokens),output:lr(s.outputTokens),read:lr(s.cacheReadInputTokens),write:lr(s.cacheCreationInputTokens),write1h:lr(s.cacheCreationEphemeral1hInputTokens),write5m:lr(s.cacheCreationEphemeral5mInputTokens),searches:lr(s.webSearchRequests)}}return{type:"cost-state",usd:Math.max(0,e.totalCostUSD),...lr(e.startTime)?{start:e.startTime}:{},models:r,...e.hasUnknownModelCost===!0?{unknown:!0}:{},...t?{version:t}:{}}}function hO(e){if(!(e?.type!=="system"||e.subtype!=="model_refusal_fallback"||typeof e.originalModel!="string"))return{type:"refusal",model:e.originalModel.slice(0,100),...typeof e.timestamp=="string"?{timestamp:e.timestamp}:{}}}var lr,D0=V(()=>{"use strict";Xe();Ze();ur();Zo();zs();U0();lr=e=>typeof e=="number"&&Number.isFinite(e)&&e>0?e:0});function vO(e){return!!e&&typeof e=="object"&&!!e.t&&typeof e.t=="object"}function oh(e){return e.includes('"compact_boundary"')||e.includes('"isCompactSummary"')}function q0(e,t){let r=e.p;if(e.p=void 0,!r)return;let o=e.t[r.th];if(!o?.m||!(r.pre>0))return;let n=o.ttl??yO,i=o.at!==void 0&&r.at-o.at<=n,s={input_tokens:0,cache_read_input_tokens:r.pre,cache_creation_input_tokens:0,output_tokens:t,...o.b},a=wt(o.m,s,r.at);if(a)return{...r.u?{uuid:r.u}:{},...r.s?{sessionId:r.s}:{},sidechain:r.th==="1",ts:r.at,model:o.m,usage:s,cost:a,warm:i}}function pu(e,t){if(!(!t||typeof t!="object")){if(t.type==="system"&&t.subtype==="compact_boundary"){let r=e.p?q0(e,gO):void 0,o=Date.parse(String(t.timestamp??"")),n=Number(t.compactMetadata?.preTokens);return Number.isFinite(o)&&Number.isFinite(n)&&n>0&&(e.p={at:o,pre:n,th:L0(t),...typeof t.uuid=="string"?{u:t.uuid}:{},...typeof t.sessionId=="string"?{s:t.sessionId}:{}}),r}if(t.type==="user"&&t.isCompactSummary===!0){if(!e.p)return;let r=typeof t.n=="number"?t.n:Ym(t.message?.content).length,o=e.t[e.p.th]?.m;return q0(e,Math.max(1,Rb(r,!1,o)))}if(t.type==="assistant"&&t.message?.usage){let r=e.p&&e.p.th===L0(t)?q0(e,gO):void 0,o=$t(t.message.model);if(!o)return r;let n=t.message.usage,i=e.t[L0(t)]??={};i.m=o;let s=Date.parse(String(t.timestamp??""));Number.isFinite(s)&&(i.at=s);let a=n.cache_creation;a&&(a.ephemeral_1h_input_tokens??0)>0?i.ttl=yO:a&&(a.ephemeral_5m_input_tokens??0)>0&&(i.ttl=BF);let c={...n.speed==="fast"?{speed:"fast"}:{},...n.inference_geo==="us"?{inference_geo:"us"}:{}};return Object.keys(c).length?i.b=c:delete i.b,r}}}function _O(e){return{type:"user",isCompactSummary:!0,n:Ym(e?.message?.content).length,...e?.isSidechain===!0?{isSidechain:!0}:{}}}var yO,BF,gO,fu,L0,F0=V(()=>{"use strict";Xe();Vo();Ze();yO=36e5,BF=3e5,gO=2e4,fu=()=>({t:{}});L0=e=>e?.isSidechain===!0?"1":"0"});import{appendFileSync as VG,closeSync as BG,existsSync as HG,mkdirSync as ZG,openSync as JG,readdirSync as ZF,readFileSync as WG,readSync as KG,statSync as $O,writeFileSync as GG}from"node:fs";import{homedir as JF}from"node:os";import{dirname as QG,join as xO}from"node:path";function mu(e=JF()){return xO(Bt(e),"sessions")}function ih(e,t){let r=[],o=(n,i)=>{let s;try{s=ZF(n,{withFileTypes:!0})}catch{return}for(let a of s){let c=xO(n,a.name),u=a.isDirectory();if(a.isSymbolicLink())try{u=$O(c).isDirectory()}catch{continue}if(u)i<3&&o(c,i+1);else if(a.name.endsWith(".jsonl"))try{$O(c).mtimeMs>=t&&r.push(c)}catch{}}};return o(e,0),r}function RO(e,t){if(!e||typeof e!="object"||!t||typeof t!="object")return"";let r=e,o=t;return jt(r.total_tokens)?`cx:${SO.map(n=>jt(r[n])).join(",")}/${SO.map(n=>jt(o[n])).join(",")}`:""}function bO(e,t){if(typeof e.stop_reason=="string"&&e.stop_reason)return{stop_reason:e.stop_reason.slice(0,40)};if(!fO(t))return{};let r=pO(e.content);return r>0?{oc:r}:{}}function KF(e){let t=e.usage;return{ts:e.ts,app:"claude",model:e.model,input:jt(t.input_tokens),read:jt(t.cache_read_input_tokens),write:jt(t.cache_creation_input_tokens),output:jt(t.output_tokens),usd:e.cost.totalUsd,promptUsd:e.cost.promptUsd,rates:e.cost.rates,modifiers:e.cost.modifiers,compaction:!0,...e.uuid?{uuid:e.uuid}:{},...e.sidechain?{sidechain:!0}:{},...e.cost.estimated?{estimated:!0}:{},...e.cost.changedOn?{changedOn:e.cost.changedOn}:{}}}function wO(e,t,r){return ru(t).map(o=>{let n=$t(o.model??e),i=wt(n,o.usage,r);return{type:o.type,...n?{model:n}:{},input:jt(o.usage.input_tokens),read:jt(o.usage.cache_read_input_tokens),write:jt(o.usage.cache_creation_input_tokens),output:jt(o.usage.output_tokens),usd:i?.totalUsd??0,promptUsd:i?.promptUsd??0,priced:!!i,modifiers:i?i.modifiers:{...nu},...i?.estimated?{estimated:!0}:{},...i?.changedOn?{changedOn:i.changedOn}:{}}})}function kO(e,t){for(let r of e.extra??[])e.usd-=r.usd,e.promptUsd-=r.promptUsd,Lo(e.modifiers,GF(r.modifiers));t.length?e.extra=t:delete e.extra;for(let r of t)e.usd+=r.usd,e.promptUsd+=r.promptUsd,Lo(e.modifiers,r.modifiers)}function B0(e,t,r=1/0,o){let n=[],i=Xm(o),s=v0(),a=new Map,c=new Map,u=fu();On(e,du).forEach(l=>{let d=pu(u,l);d&&d.ts>=t&&d.ts<=r&&n.push(KF(d));let f=l?.message;if(l?.type!=="assistant"||!f?.usage)return;if(typeof f.id=="string"){let y=c.get(f.id)??c.set(f.id,{stop:!1,oc:0}).get(f.id);f.stop_reason&&(y.stop=!0),y.oc+=typeof f.oc=="number"?f.oc:0}let p=i(l);if(p==="repeat"){let y=typeof f.id=="string"?a.get(f.id):void 0,b=s(l,!1);if(y&&b){let R=y.point;if(R.output+=b,R.rates&&(R.usd+=b*R.rates.outputPerM/1e6,R.modifiers.fastUsd||R.modifiers.geoUsd||R.modifiers.longUsd)){R.modifiers={...wt(R.model,{...y.u,output_tokens:R.output},R.ts).modifiers};for(let z of R.extra??[])Lo(R.modifiers,z.modifiers)}}if(y&&f.usage.iterations){let R=wO(y.point.model,{...y.u,iterations:f.usage.iterations},y.point.ts);JSON.stringify(R)!==JSON.stringify(y.point.extra??[])&&kO(y.point,R)}return}if(p!=="new"||(s(l,!0),Kr(f.model)))return;let h=Date.parse(String(l.timestamp??""));if(!Number.isFinite(h)||h<t||h>r)return;let v=f.usage,g={ts:h,app:"claude",model:$t(f.model),input:jt(v.input_tokens),read:jt(v.cache_read_input_tokens),write:jt(v.cache_creation_input_tokens),output:jt(v.output_tokens),usd:0,promptUsd:0,modifiers:{...nu}};if(g.input+g.read+g.write===0)return;typeof l.uuid=="string"&&(g.uuid=l.uuid),typeof f.id=="string"&&(g.id=f.id),l.isSidechain===!0&&(g.sidechain=!0);let m=wt(g.model,v,h);m&&(g.usd=m.totalUsd,g.promptUsd=m.promptUsd,g.rates=m.rates,g.modifiers=m.modifiers,m.estimated&&(g.estimated=!0),m.changedOn&&(g.changedOn=m.changedOn));let _=wO(g.model,v,h);_.length&&kO(g,_),n.push(g),typeof f.id=="string"&&a.set(f.id,{point:g,u:v})});for(let[l,d]of c){let f=a.get(l);if(d.stop||!f||d.oc<=f.point.output)continue;let p=f.point,h=d.oc-p.output;if(p.output+=h,p.unsettled=h,p.rates&&(p.usd+=h*p.rates.outputPerM/1e6,p.modifiers.fastUsd||p.modifiers.geoUsd||p.modifiers.longUsd)){p.modifiers={...wt(p.model,{...f.u,output_tokens:p.output},p.ts).modifiers};for(let v of p.extra??[])Lo(p.modifiers,v.modifiers)}}return n}var V0,zO,WF,d8,f8,p8,m8,jt,SO,du,GF,XF,h8,Zo=V(()=>{"use strict";Yr();sr();Vo();zs();ur();D0();Xe();Ze();F0();k0();U0();V0=6e4,zO=60*V0,WF=24*zO,d8=15*V0,f8=2*1024*1024,p8=1536*1024,m8=10*V0;jt=e=>typeof e=="number"&&Number.isFinite(e)&&e>0?e:0,SO=["input_tokens","cached_input_tokens","output_tokens","reasoning_output_tokens","total_tokens"];du={id:"usage.6",init:()=>({ids:{}}),line(e,t,r,o){let n=oh(e),i=!n&&e.startsWith('{"type":"cost-state"'),s=!n&&!i&&e.includes('"model_refusal_fallback"'),a=!n&&!i&&e.startsWith('{"type":"api-request",'),c=!n&&!i&&!a&&e.includes('"subtype":"api_error"');if(!n&&!i&&!s&&!a&&!c&&!e.includes('"usage"'))return;let u;try{u=t()}catch{return}if(a){u?.type==="api-request"&&typeof u.id=="string"&&r.push({type:"api-request",id:u.id,...typeof u.base=="string"?{base:u.base}:{},t:Array.isArray(u.tail)?u.tail.length:0,timestamp:u.timestamp});return}if(c){u?.type==="system"&&u.subtype==="api_error"&&r.push({type:"system",subtype:"api_error",timestamp:u.timestamp,code:String(u.error?.connection?.code??u.error?.status??"").slice(0,40)});return}if(i||s){let d=i?mO(u,o.v):hO(u);if(d&&r.push(d),i||d)return}if(n&&u?.type==="system"&&u.subtype==="compact_boundary"){r.push(Zt({...u,isSidechain:u.isSidechain===!0||void 0,compactMetadata:Zt(u.compactMetadata??{},["preTokens"])},["type","subtype","uuid","sessionId","timestamp","isSidechain","compactMetadata"]));return}if(n&&u?.type==="user"&&u.isCompactSummary===!0){r.push(_O(u));return}let l=u?.message;if(!(u?.type!=="assistant"||!l?.usage)){if(typeof u.version=="string"&&(o.v=u.version.slice(0,40)),typeof l.id=="string"){if(o.ids[l.id]){let d=rh(l.usage,{iterations:!0});r.push({type:"assistant",message:{id:l.id,usage:{...Zt(l.usage,["output_tokens"]),...d?.iterations?{iterations:d.iterations}:{}},...bO(l,u.version)}});return}o.ids[l.id]=1}r.push(Zt({...u,isSidechain:u.isSidechain===!0||void 0,message:{...Zt({...l,usage:rh(l.usage,{iterations:!0})},["id","model","usage"]),...bO(l,u.version)}},["type","uuid","timestamp","isSidechain","entrypoint","requestRef","message"]))}}};GF=e=>({fastUsd:-e.fastUsd,geoUsd:-e.geoUsd,longUsd:-e.longUsd,webSearchUsd:-e.webSearchUsd,webSearches:-e.webSearches});XF=2*864e5,h8=7*WF-zO});var _8,$8,YF,S8,IO=V(()=>{"use strict";sr();Xe();_8=1024*1024,$8=768*1024,YF="unseen",S8={tools_changed:{label:"tool definitions changed",fix:"an MCP server connected late, reconnected or changed its tools mid-session; `overhead --mcp` flags servers whose tool list is unstable, `overhead prune` drops unused ones"},system_prompt_changed:{label:"system prompt changed",fix:"CLAUDE.md, memory, an output style or a skill changed mid-session; edit them between sessions"},model_changed:{label:"model changed",fix:"each model has its own cache; switch models at the start of a session (the PreModelSwitch hook prices it)"},messages_rewritten:{label:"earlier messages changed",fix:"something rewrote history (a proxy, a rewind, a hook): if it is autopilot, it acts only when the cache is cold"},ttl_expired_5m:{label:"idle past the 5m TTL",fix:"a pause over 5 minutes; the status line shows until when the cache is warm"},ttl_expired_1h:{label:"idle past the 1h TTL",fix:"a pause over an hour, or a loop waking just after it; keep wake-ups under 55 minutes"},likely_server_side:{label:"prompt unchanged, likely server-side",fix:"nothing changed on this machine: the provider dropped the cache; nothing to fix locally"},fast_mode_changed:{label:"fast mode toggled"},cache_scope_or_ttl_changed:{label:"cache scope or TTL changed"},betas_changed:{label:"beta headers changed"},effort_changed:{label:"effort changed",fix:"/effort mid-session re-writes the cache; set it at the start"},thinking_mode_changed:{label:"thinking toggled"},thinking_display_changed:{label:"thinking display changed"},auto_mode_changed:{label:"auto mode toggled"},overage_changed:{label:"usage-limit state changed"},extra_body_changed:{label:"extra request fields changed"},defer_loading_changed:{label:"deferred tool loading changed"},unknown:{label:"unknown"},[YF]:{label:"not seen: two misses between status line runs"}}});import{closeSync as QF,openSync as eV,readSync as tV,statSync as nV}from"node:fs";function H0(e,t=256*1024){try{let r=nV(e).size,o=Math.min(r,t),n=eV(e,"r"),i=Buffer.alloc(o);try{tV(n,i,0,o,r-o)}finally{QF(n)}for(let s of i.toString("utf8").split(`
115
+ `):""}var Vo=V(()=>{"use strict";Ze();Xe();Yr();Gm();mn()});import{readdirSync as b0,readFileSync as LK,statSync as $F}from"node:fs";import{basename as FK,join as uu}from"node:path";function SF(e){return uu(e.replace(/\.jsonl$/,""),"subagents")}function lu(e,t=-1/0){let r=SF(e),o=[],n=(a,c)=>{try{(t===-1/0||$F(a).mtimeMs>=t)&&o.push(c?{file:a,run:c}:{file:a})}catch{}},i;try{i=b0(r)}catch{return o}for(let a of i)a.endsWith(".jsonl")&&n(uu(r,a));if(!i.includes("workflows"))return o;let s;try{s=b0(uu(r,"workflows"))}catch{return o}for(let a of s){let c;try{c=b0(uu(r,"workflows",a))}catch{continue}for(let u of c)u.endsWith(".jsonl")&&n(uu(r,"workflows",a,u),a)}return o}var zs=V(()=>{"use strict";Ze();Xe();Qc();Vo();Ze()});var YC=V(()=>{"use strict";Ze()});var QC=V(()=>{"use strict";Ze();Xe()});var eO=V(()=>{"use strict"});var mG,w0,hG,k0=V(()=>{"use strict";Jb();YC();Ze();Xe();sr();QC();eO();g0();mG=100*1024*1024,w0="0.52.0",hG=["7d-utilization","5h-utilization","overage-status","overage-in-use"].map(e=>`anthropic-ratelimit-unified-${e}`)});import{closeSync as T0,existsSync as bF,fstatSync as wF,mkdirSync as iO,openSync as P0,readdirSync as x0,readFileSync as C0,readSync as O0,renameSync as kF,rmSync as xF,statSync as z0,unlinkSync as R0,utimesSync as zF,writeFileSync as sO}from"node:fs";import{createHash as A0,randomBytes as RF}from"node:crypto";import{homedir as IF}from"node:os";import{isAbsolute as EF,join as Cn}from"node:path";function cO(e=process.env){if(e.CONTEXT_DOCTOR_CACHE_DIR)return e.CONTEXT_DOCTOR_CACHE_DIR;let t=e.XDG_CACHE_HOME&&EF(e.XDG_CACHE_HOME)?e.XDG_CACHE_HOME:Cn(IF(),".cache");return Cn(t,"context-doctor")}function CF(e,t){if(!nh())try{let r=JSON.parse(C0(lO(t.path,t.id),"utf8"));if(r?.path===t.path&&r.off===t.off&&r.anchor===t.anchor)return e.load(r.state)}catch{}}function M0(e){try{let t=z0(e);return{size:t.size,mtimeMs:t.mtimeMs,ino:t.ino}}catch{return}}function dO(e,t){if(!(t>N0))try{return A0("sha1").update(C0(e)).digest("hex")}catch{return}}function tO(e,t,r,o){return OF(e,t)?t.size>N0?!0:(o.done||(o.v=dO(r,t.size),o.done=!0),e.fp!==void 0&&e.fp===o.v):!1}function AF(e,t){if(!nh())try{let r=JSON.parse(C0(j0(e,t),"utf8"));if(r&&r.path===e&&r.id===t&&Array.isArray(r.rows)&&Array.isArray(r.tail)&&typeof r.off=="number")return r}catch{}}function rO(e,t=j0(e.path,e.id)){if(nh())return;let r=`${t}.${process.pid}.${RF(4).toString("hex")}.tmp`;try{iO(Cn(t,".."),{recursive:!0,mode:448}),sO(r,JSON.stringify(e),{mode:384}),kF(r,t),nO||(nO=!0,jF())}catch{try{R0(r)}catch{}}}function Ho(e,t){let r=A0("sha1"),o=(n,i)=>{let s=Buffer.alloc(i),a=O0(e,s,0,i,n);r.update(s.subarray(0,a))};return o(0,Math.min(Rs,t)),t>Rs&&o(Math.max(Rs,t-Rs),Math.min(Rs,t-Rs)),r.update(String(t)),r.digest("hex")}function NF(e,t,r){let o=Buffer.allocUnsafe(4194304),n=t,i=t,s=[];for(;;){let a=O0(e,o,0,o.length,n);if(a===0)break;let c=0;for(;;){let u=o.indexOf(10,c);if(u===-1||u>=a)break;let l=o.subarray(c,u),d=s.length?Buffer.concat([...s,l]).toString("utf8"):l.toString("utf8");s=[];let f=i;i=n+u+1,r(d,f,!0),c=u+1}c<a&&s.push(Buffer.from(o.subarray(c,a))),n+=a}return s.length&&r(Buffer.concat(s).toString("utf8"),i,!1),{off:i,end:n}}function oO(e,t,r=!1){let o=M0(e);if(!o)return[];let n=[],i=[],s={};for(let c of t){if(r){n.push({ex:c,from:0,state:c.init(),rows:[],tail:[]});continue}let u=E0(e,c.id),l=th.get(u);if(l&&tO(l,o,e,s))continue;let d=AF(e,c.id);if(d&&tO(d,o,e,s)){th.set(u,d);continue}let f=[d,l].find(h=>h&&c.resumable!==!1&&h.ino===o.ino&&o.size>h.size&&h.off<=o.size),p=f&&c.save?CF(c,f):f?.state;n.push(f&&p!==void 0?{ex:c,from:f.off,state:p,rows:f.rows,tail:[],prior:f}:{ex:c,from:0,state:c.init(),rows:[],tail:[]})}if(n.length===0)return i;let a;try{a=P0(e,"r")}catch{return i}try{for(let g of n)g.prior&&(g.prior.off===0||Ho(a,g.prior.off)!==g.prior.anchor)&&Object.assign(g,{from:0,state:g.ex.init(),rows:[],prior:void 0}),g.prior&&Object.assign(g,{state:g.ex.save?g.state:structuredClone(g.state),rows:g.rows.slice()});let c=Math.min(...n.map(g=>g.from)),u,{off:l,end:d}=NF(a,c,(g,m,_)=>{let y,b,R=!1,z=()=>{if(!R){R=!0;try{y=JSON.parse(g)}catch(w){b=w??new SyntaxError("not JSON")}}if(b!==void 0)throw b;return y};if(_){for(let w of n)m>=w.from&&w.ex.line(g,z,w.rows,w.state);return}u=n.map(w=>w.ex.resumable===!1?w.state:PF(w.ex,w.state)),n.forEach((w,x)=>{m>=w.from&&w.ex.line(g,z,w.ex.resumable===!1?w.rows:w.tail,u[x])})}),f;try{let g=wF(a);f={size:g.size,mtimeMs:g.mtimeMs,ino:g.ino}}catch{}let p=f!==void 0&&f.size===d,h=n.some(g=>g.ex.resumable!==!1)?Ho(a,l):"",v=p&&d<=N0?dO(e,d):void 0;n.forEach((g,m)=>{let _=g.ex.resumable!==!1;g.ex.end&&g.ex.end(_?g.tail:g.rows,u?u[m]:g.state);let y={path:e,id:g.ex.id,size:d,mtimeMs:p?f.mtimeMs:-1,ino:f?.ino??o.ino,off:_?l:d,anchor:_?h:"",state:_&&!g.ex.save?g.state:null,rows:g.rows,tail:g.tail,...v!==void 0?{fp:v}:{}};i.push(y),!r&&(th.set(E0(e,g.ex.id),y),p&&(rO(y),_&&g.ex.save&&Date.now()-f.mtimeMs<aO&&rO({path:e,off:l,anchor:h,state:g.ex.save(g.state)},lO(e,g.ex.id))))})}finally{T0(a)}return i}function On(e,t,r={}){let o=M0(e),n=r.keep===!1?oO(e,[t],!0)[0]:(oO(e,[t]),th.get(E0(e,t.id)));if(!o||!n)throw T0(P0(e,"r")),new Error(`unreadable transcript: ${e}`);return n.tail.length?n.rows.concat(n.tail):n.rows}function jF(e=Date.now(),t=!1){if(nh())return;let r=Cn(cO(),"transcripts"),o=Cn(r,".pruned");try{if(!t&&e-z0(o).mtimeMs<I0)return}catch{}try{iO(r,{recursive:!0,mode:448}),sO(o,""),zF(o,e/1e3,e/1e3);let n=uO();for(let c of x0(r))c.startsWith(".")||Cn(r,c)!==n&&xF(Cn(r,c),{recursive:!0,force:!0});if(!bF(n))return;let i=(Number(process.env.CONTEXT_DOCTOR_CACHE_MAX_MB)>0?Number(process.env.CONTEXT_DOCTOR_CACHE_MAX_MB):256)*1024*1024,s=[];for(let c of x0(n)){let u=Cn(n,c),l;try{l=x0(u)}catch{continue}for(let d of l){let f=Cn(u,d),p;try{p=z0(f)}catch{continue}let h=()=>{try{R0(f)}catch{}};if(d.endsWith(".tmp")){e-p.mtimeMs>36e5&&h();continue}if(d.endsWith(".state.json")&&e-p.mtimeMs>aO){h();continue}let v=MF(f),g=v?M0(v):void 0;if(!g||e-g.mtimeMs>120*I0){h();continue}s.push({file:f,size:p.size,mtimeMs:p.mtimeMs})}}let a=s.reduce((c,u)=>c+u.size,0);if(a<=i)return;for(let c of s.sort((u,l)=>u.mtimeMs-l.mtimeMs)){if(a<=i*.8)break;try{R0(c.file),a-=c.size}catch{}}}catch{}}function MF(e){try{let t=P0(e,"r");try{let r=Buffer.alloc(8192),o=O0(t,r,0,r.length,0),n=/^\{"path":("(?:[^"\\]|\\.)*")/.exec(r.subarray(0,o).toString("utf8"));return n?JSON.parse(n[1]):void 0}finally{T0(t)}}catch{return}}function Zt(e,t){if(!e||typeof e!="object"||Array.isArray(e))return e;let r={};for(let o of t)e[o]!==void 0&&(r[o]=e[o]);return r}var TF,I0,Rs,N0,aO,th,E0,nh,uO,j0,lO,PF,OF,nO,UF,rh,DF,ur=V(()=>{"use strict";k0();Xe();TF=1,I0=864e5,Rs=64*1024,N0=64*1024,aO=3*I0,th=new Map,E0=(e,t)=>`${t}\0${e}`;nh=()=>process.env.CONTEXT_DOCTOR_NO_CACHE==="1",uO=()=>Cn(cO(),"transcripts",`v${TF}-${w0}`),j0=(e,t)=>Cn(uO(),t.replace(/[^\w.-]/g,"_"),`${A0("sha1").update(e).digest("hex")}.json`),lO=(e,t)=>j0(e,t).replace(/\.json$/,".state.json"),PF=(e,t)=>e.save?e.load(JSON.parse(JSON.stringify(e.save(t)))):structuredClone(t);OF=(e,t)=>e.size===t.size&&e.mtimeMs===t.mtimeMs&&e.ino===t.ino;nO=!1;UF=["input_tokens","cache_creation_input_tokens","cache_read_input_tokens","output_tokens","cache_creation","output_tokens_details","context_management"],rh=(e,t={})=>{let r=Zt(e,UF);if(!r||typeof r!="object"||Array.isArray(r))return r;e.speed==="fast"&&(r.speed="fast"),e.inference_geo==="us"&&(r.inference_geo="us");let o=e.server_tool_use?.web_search_requests;return typeof o=="number"&&o>0&&(r.server_tool_use={web_search_requests:o}),t.iterations&&ru(e).length&&(r.iterations=e.iterations.map(n=>Zt(n,DF))),r},DF=["type","model","input_tokens","cache_creation_input_tokens","cache_read_input_tokens","output_tokens","cache_creation"]});function fO(e){if(typeof e!="string")return!1;let t=e.split(/[.-]/).map(o=>parseInt(o,10)||0),r=o=>{let n=o.split(".").map(Number);for(let i=0;i<3;i++)if((t[i]??0)!==n[i])return(t[i]??0)-n[i];return 0};return r(LF)>=0&&r(qF)<=0}function pO(e){if(!Array.isArray(e))return 0;let t=0,r=0;for(let o of e)!o||typeof o!="object"||(o.type==="text"&&typeof o.text=="string"?t+=o.text.length:o.type==="tool_use"?t+=JSON.stringify(o.input??{}).length+String(o.name??"").length:o.type==="thinking"&&(t+=typeof o.thinking=="string"?o.thinking.length:0,r+=typeof o.signature=="string"?o.signature.length:0));return Math.round(t*FF+r*VF)}var LF,qF,FF,VF,U0=V(()=>{"use strict";Xe();Ze();LF="2.1.284",qF="2.1.299";FF=.4,VF=.26});function mO(e,t){if(e?.type!=="cost-state"||typeof e.totalCostUSD!="number"||!Number.isFinite(e.totalCostUSD))return;let r={},o=e.modelUsage&&typeof e.modelUsage=="object"&&!Array.isArray(e.modelUsage)?e.modelUsage:{};for(let[n,i]of Object.entries(o).slice(0,40)){if(!i||typeof i!="object")continue;let s=i;r[n.slice(0,100)]={usd:lr(s.costUSD),input:lr(s.inputTokens),output:lr(s.outputTokens),read:lr(s.cacheReadInputTokens),write:lr(s.cacheCreationInputTokens),write1h:lr(s.cacheCreationEphemeral1hInputTokens),write5m:lr(s.cacheCreationEphemeral5mInputTokens),searches:lr(s.webSearchRequests)}}return{type:"cost-state",usd:Math.max(0,e.totalCostUSD),...lr(e.startTime)?{start:e.startTime}:{},models:r,...e.hasUnknownModelCost===!0?{unknown:!0}:{},...t?{version:t}:{}}}function hO(e){if(!(e?.type!=="system"||e.subtype!=="model_refusal_fallback"||typeof e.originalModel!="string"))return{type:"refusal",model:e.originalModel.slice(0,100),...typeof e.timestamp=="string"?{timestamp:e.timestamp}:{}}}var lr,D0=V(()=>{"use strict";Xe();Ze();ur();Zo();zs();U0();lr=e=>typeof e=="number"&&Number.isFinite(e)&&e>0?e:0});function vO(e){return!!e&&typeof e=="object"&&!!e.t&&typeof e.t=="object"}function oh(e){return e.includes('"compact_boundary"')||e.includes('"isCompactSummary"')}function q0(e,t){let r=e.p;if(e.p=void 0,!r)return;let o=e.t[r.th];if(!o?.m||!(r.pre>0))return;let n=o.ttl??yO,i=o.at!==void 0&&r.at-o.at<=n,s={input_tokens:0,cache_read_input_tokens:r.pre,cache_creation_input_tokens:0,output_tokens:t,...o.b},a=wt(o.m,s,r.at);if(a)return{...r.u?{uuid:r.u}:{},...r.s?{sessionId:r.s}:{},sidechain:r.th==="1",ts:r.at,model:o.m,usage:s,cost:a,warm:i}}function pu(e,t){if(!(!t||typeof t!="object")){if(t.type==="system"&&t.subtype==="compact_boundary"){let r=e.p?q0(e,gO):void 0,o=Date.parse(String(t.timestamp??"")),n=Number(t.compactMetadata?.preTokens);return Number.isFinite(o)&&Number.isFinite(n)&&n>0&&(e.p={at:o,pre:n,th:L0(t),...typeof t.uuid=="string"?{u:t.uuid}:{},...typeof t.sessionId=="string"?{s:t.sessionId}:{}}),r}if(t.type==="user"&&t.isCompactSummary===!0){if(!e.p)return;let r=typeof t.n=="number"?t.n:Ym(t.message?.content).length,o=e.t[e.p.th]?.m;return q0(e,Math.max(1,Rb(r,!1,o)))}if(t.type==="assistant"&&t.message?.usage){let r=e.p&&e.p.th===L0(t)?q0(e,gO):void 0,o=$t(t.message.model);if(!o)return r;let n=t.message.usage,i=e.t[L0(t)]??={};i.m=o;let s=Date.parse(String(t.timestamp??""));Number.isFinite(s)&&(i.at=s);let a=n.cache_creation;a&&(a.ephemeral_1h_input_tokens??0)>0?i.ttl=yO:a&&(a.ephemeral_5m_input_tokens??0)>0&&(i.ttl=BF);let c={...n.speed==="fast"?{speed:"fast"}:{},...n.inference_geo==="us"?{inference_geo:"us"}:{}};return Object.keys(c).length?i.b=c:delete i.b,r}}}function _O(e){return{type:"user",isCompactSummary:!0,n:Ym(e?.message?.content).length,...e?.isSidechain===!0?{isSidechain:!0}:{}}}var yO,BF,gO,fu,L0,F0=V(()=>{"use strict";Xe();Vo();Ze();yO=36e5,BF=3e5,gO=2e4,fu=()=>({t:{}});L0=e=>e?.isSidechain===!0?"1":"0"});import{appendFileSync as VG,closeSync as BG,existsSync as HG,mkdirSync as ZG,openSync as JG,readdirSync as ZF,readFileSync as WG,readSync as KG,statSync as $O,writeFileSync as GG}from"node:fs";import{homedir as JF}from"node:os";import{dirname as QG,join as xO}from"node:path";function mu(e=JF()){return xO(Bt(e),"sessions")}function ih(e,t){let r=[],o=(n,i)=>{let s;try{s=ZF(n,{withFileTypes:!0})}catch{return}for(let a of s){let c=xO(n,a.name),u=a.isDirectory();if(a.isSymbolicLink())try{u=$O(c).isDirectory()}catch{continue}if(u)i<3&&o(c,i+1);else if(a.name.endsWith(".jsonl"))try{$O(c).mtimeMs>=t&&r.push(c)}catch{}}};return o(e,0),r}function RO(e,t){if(!e||typeof e!="object"||!t||typeof t!="object")return"";let r=e,o=t;return jt(r.total_tokens)?`cx:${SO.map(n=>jt(r[n])).join(",")}/${SO.map(n=>jt(o[n])).join(",")}`:""}function bO(e,t){if(typeof e.stop_reason=="string"&&e.stop_reason)return{stop_reason:e.stop_reason.slice(0,40)};if(!fO(t))return{};let r=pO(e.content);return r>0?{oc:r}:{}}function KF(e){let t=e.usage;return{ts:e.ts,app:"claude",model:e.model,input:jt(t.input_tokens),read:jt(t.cache_read_input_tokens),write:jt(t.cache_creation_input_tokens),output:jt(t.output_tokens),usd:e.cost.totalUsd,promptUsd:e.cost.promptUsd,rates:e.cost.rates,modifiers:e.cost.modifiers,compaction:!0,...e.uuid?{uuid:e.uuid}:{},...e.sidechain?{sidechain:!0}:{},...e.cost.estimated?{estimated:!0}:{},...e.cost.changedOn?{changedOn:e.cost.changedOn}:{}}}function wO(e,t,r){return ru(t).map(o=>{let n=$t(o.model??e),i=wt(n,o.usage,r);return{type:o.type,...n?{model:n}:{},input:jt(o.usage.input_tokens),read:jt(o.usage.cache_read_input_tokens),write:jt(o.usage.cache_creation_input_tokens),output:jt(o.usage.output_tokens),usd:i?.totalUsd??0,promptUsd:i?.promptUsd??0,priced:!!i,modifiers:i?i.modifiers:{...nu},...i?.estimated?{estimated:!0}:{},...i?.changedOn?{changedOn:i.changedOn}:{}}})}function kO(e,t){for(let r of e.extra??[])e.usd-=r.usd,e.promptUsd-=r.promptUsd,Lo(e.modifiers,GF(r.modifiers));t.length?e.extra=t:delete e.extra;for(let r of t)e.usd+=r.usd,e.promptUsd+=r.promptUsd,Lo(e.modifiers,r.modifiers)}function B0(e,t,r=1/0,o){let n=[],i=Xm(o),s=v0(),a=new Map,c=new Map,u=fu();On(e,du).forEach(l=>{let d=pu(u,l);d&&d.ts>=t&&d.ts<=r&&n.push(KF(d));let f=l?.message;if(l?.type!=="assistant"||!f?.usage)return;if(typeof f.id=="string"){let y=c.get(f.id)??c.set(f.id,{stop:!1,oc:0}).get(f.id);f.stop_reason&&(y.stop=!0),y.oc+=typeof f.oc=="number"?f.oc:0}let p=i(l);if(p==="repeat"){let y=typeof f.id=="string"?a.get(f.id):void 0,b=s(l,!1);if(y&&b){let R=y.point;if(R.output+=b,R.rates&&(R.usd+=b*R.rates.outputPerM/1e6,R.modifiers.fastUsd||R.modifiers.geoUsd||R.modifiers.longUsd)){R.modifiers={...wt(R.model,{...y.u,output_tokens:R.output},R.ts).modifiers};for(let z of R.extra??[])Lo(R.modifiers,z.modifiers)}}if(y&&f.usage.iterations){let R=wO(y.point.model,{...y.u,iterations:f.usage.iterations},y.point.ts);JSON.stringify(R)!==JSON.stringify(y.point.extra??[])&&kO(y.point,R)}return}if(p!=="new"||(s(l,!0),Kr(f.model)))return;let h=Date.parse(String(l.timestamp??""));if(!Number.isFinite(h)||h<t||h>r)return;let v=f.usage,g={ts:h,app:"claude",model:$t(f.model),input:jt(v.input_tokens),read:jt(v.cache_read_input_tokens),write:jt(v.cache_creation_input_tokens),output:jt(v.output_tokens),usd:0,promptUsd:0,modifiers:{...nu}};if(g.input+g.read+g.write===0)return;typeof l.uuid=="string"&&(g.uuid=l.uuid),typeof f.id=="string"&&(g.id=f.id),l.isSidechain===!0&&(g.sidechain=!0);let m=wt(g.model,v,h);m&&(g.usd=m.totalUsd,g.promptUsd=m.promptUsd,g.rates=m.rates,g.modifiers=m.modifiers,m.estimated&&(g.estimated=!0),m.changedOn&&(g.changedOn=m.changedOn));let _=wO(g.model,v,h);_.length&&kO(g,_),n.push(g),typeof f.id=="string"&&a.set(f.id,{point:g,u:v})});for(let[l,d]of c){let f=a.get(l);if(d.stop||!f||d.oc<=f.point.output)continue;let p=f.point,h=d.oc-p.output;if(p.output+=h,p.unsettled=h,p.rates&&(p.usd+=h*p.rates.outputPerM/1e6,p.modifiers.fastUsd||p.modifiers.geoUsd||p.modifiers.longUsd)){p.modifiers={...wt(p.model,{...f.u,output_tokens:p.output},p.ts).modifiers};for(let v of p.extra??[])Lo(p.modifiers,v.modifiers)}}return n}var V0,zO,WF,d8,f8,p8,m8,jt,SO,du,GF,XF,h8,Zo=V(()=>{"use strict";Yr();sr();Vo();zs();ur();D0();Xe();Ze();F0();k0();U0();V0=6e4,zO=60*V0,WF=24*zO,d8=15*V0,f8=2*1024*1024,p8=1536*1024,m8=10*V0;jt=e=>typeof e=="number"&&Number.isFinite(e)&&e>0?e:0,SO=["input_tokens","cached_input_tokens","output_tokens","reasoning_output_tokens","total_tokens"];du={id:"usage.6",init:()=>({ids:{}}),line(e,t,r,o){let n=oh(e),i=!n&&e.startsWith('{"type":"cost-state"'),s=!n&&!i&&e.includes('"model_refusal_fallback"'),a=!n&&!i&&e.startsWith('{"type":"api-request",'),c=!n&&!i&&!a&&e.includes('"subtype":"api_error"');if(!n&&!i&&!s&&!a&&!c&&!e.includes('"usage"'))return;let u;try{u=t()}catch{return}if(a){u?.type==="api-request"&&typeof u.id=="string"&&r.push({type:"api-request",id:u.id,...typeof u.base=="string"?{base:u.base}:{},t:Array.isArray(u.tail)?u.tail.length:0,timestamp:u.timestamp});return}if(c){u?.type==="system"&&u.subtype==="api_error"&&r.push({type:"system",subtype:"api_error",timestamp:u.timestamp,code:String(u.error?.connection?.code??u.error?.status??"").slice(0,40)});return}if(i||s){let d=i?mO(u,o.v):hO(u);if(d&&r.push(d),i||d)return}if(n&&u?.type==="system"&&u.subtype==="compact_boundary"){r.push(Zt({...u,isSidechain:u.isSidechain===!0||void 0,compactMetadata:Zt(u.compactMetadata??{},["preTokens"])},["type","subtype","uuid","sessionId","timestamp","isSidechain","compactMetadata"]));return}if(n&&u?.type==="user"&&u.isCompactSummary===!0){r.push(_O(u));return}let l=u?.message;if(!(u?.type!=="assistant"||!l?.usage)){if(typeof u.version=="string"&&(o.v=u.version.slice(0,40)),typeof l.id=="string"){if(o.ids[l.id]){let d=rh(l.usage,{iterations:!0});r.push({type:"assistant",message:{id:l.id,usage:{...Zt(l.usage,["output_tokens"]),...d?.iterations?{iterations:d.iterations}:{}},...bO(l,u.version)}});return}o.ids[l.id]=1}r.push(Zt({...u,isSidechain:u.isSidechain===!0||void 0,message:{...Zt({...l,usage:rh(l.usage,{iterations:!0})},["id","model","usage"]),...bO(l,u.version)}},["type","uuid","timestamp","isSidechain","entrypoint","requestRef","message"]))}}};GF=e=>({fastUsd:-e.fastUsd,geoUsd:-e.geoUsd,longUsd:-e.longUsd,webSearchUsd:-e.webSearchUsd,webSearches:-e.webSearches});XF=2*864e5,h8=7*WF-zO});var _8,$8,YF,S8,IO=V(()=>{"use strict";sr();Xe();_8=1024*1024,$8=768*1024,YF="unseen",S8={tools_changed:{label:"tool definitions changed",fix:"an MCP server connected late, reconnected or changed its tools mid-session; `overhead --mcp` flags servers whose tool list is unstable, `overhead prune` drops unused ones"},system_prompt_changed:{label:"system prompt changed",fix:"CLAUDE.md, memory, an output style or a skill changed mid-session; edit them between sessions"},model_changed:{label:"model changed",fix:"each model has its own cache; switch models at the start of a session (the PreModelSwitch hook prices it)"},messages_rewritten:{label:"earlier messages changed",fix:"something rewrote history (a proxy, a rewind, a hook): if it is autopilot, it acts only when the cache is cold"},ttl_expired_5m:{label:"idle past the 5m TTL",fix:"a pause over 5 minutes; the status line shows until when the cache is warm"},ttl_expired_1h:{label:"idle past the 1h TTL",fix:"a pause over an hour, or a loop waking just after it; keep wake-ups under 55 minutes"},likely_server_side:{label:"prompt unchanged, likely server-side",fix:"nothing changed on this machine: the provider dropped the cache; nothing to fix locally"},fast_mode_changed:{label:"fast mode toggled"},cache_scope_or_ttl_changed:{label:"cache scope or TTL changed"},betas_changed:{label:"beta headers changed"},effort_changed:{label:"effort changed",fix:"/effort mid-session re-writes the cache; set it at the start"},thinking_mode_changed:{label:"thinking toggled"},thinking_display_changed:{label:"thinking display changed"},auto_mode_changed:{label:"auto mode toggled"},overage_changed:{label:"usage-limit state changed"},extra_body_changed:{label:"extra request fields changed"},defer_loading_changed:{label:"deferred tool loading changed"},unknown:{label:"unknown"},[YF]:{label:"not seen: two misses between status line runs"}}});import{closeSync as QF,openSync as eV,readSync as tV,statSync as nV}from"node:fs";function H0(e,t=256*1024){try{let r=nV(e).size,o=Math.min(r,t),n=eV(e,"r"),i=Buffer.alloc(o);try{tV(n,i,0,o,r-o)}finally{QF(n)}for(let s of i.toString("utf8").split(`
116
116
  `).reverse()){let a;try{a=JSON.parse(s)}catch{continue}if(a.type==="system"&&a.subtype==="compact_boundary"||a.isCompactSummary)return;if(a.isSidechain)continue;let c=a.type==="assistant"?a.message?.usage:void 0;if(!c)continue;let u=c.cache_read_input_tokens??0,l=(c.input_tokens??0)+u+(c.cache_creation_input_tokens??0);if(l>0){let d=rV(c);return{tokens:l,cacheShare:u/l,model:a.message?.model,...d?{billing:d}:{}}}}}catch{}}var rV,P8,Z0=V(()=>{"use strict";Ze();Xe();Zo();IO();J0();rV=e=>e&&(e.speed==="fast"||e.inference_geo==="us")?{...e.speed==="fast"?{speed:"fast"}:{},...e.inference_geo==="us"?{inference_geo:"us"}:{}}:void 0;P8=2*3600});var EO=V(()=>{"use strict";Xe();Ze();Z0()});var TO=V(()=>{"use strict";ur();mn();Pb();Xe();Ze();zs();EO()});import{createRequire as oV}from"node:module";var t7,W0=V(()=>{"use strict";jm();ur();t7=oV(import.meta.url)});var PO=V(()=>{"use strict";ur()});var CO=V(()=>{"use strict"});var OO=V(()=>{"use strict";W0()});var AO=V(()=>{"use strict"});var K0,NO,S7,b7,w7,k7,G0=V(()=>{"use strict";mn();Zo();K0=6e4,NO=60*K0,S7=24*NO,b7=16*K0,w7=10*K0,k7=5*NO});var jO=V(()=>{"use strict"});import{basename as Jo,dirname as Q0,join as X0}from"node:path";import{homedir as aV}from"node:os";import{closeSync as cV,existsSync as rX,openSync as uV,readdirSync as lV,readSync as dV,statSync as sh}from"node:fs";function fV(e){return e.replace(/^(?:[A-Za-z]-)?-(?:Users|home)-[^-]+-/,"").replace(/^-root-/,"").replace(/^-/,"")||e}function pV(e){return fV(e.replace(/[^A-Za-z0-9]/g,"-"))}function hV(e,t){return t.estimated&&(e.estimated=!0),t.changedOn&&(e.changedOn=t.changedOn),mV(t.modifiers)&&(e.modifiers=t.modifiers),e}function MO(e,t,r=e.model){let o=wt(r,t,e.ts);return o?hV({...e,usd:o.totalUsd,inputUsd:o.inputUsd,writeUsd:o.writeUsd,readUsd:o.readUsd,outputUsd:o.outputUsd,priced:!0},o):{...e,usd:0,inputUsd:0,writeUsd:0,readUsd:0,outputUsd:0,priced:!1}}function UO(e){let t=e.parent_thread_id??e.source?.subagent?.thread_spawn?.parent_thread_id;return typeof t=="string"&&t?t:void 0}function ah(e,t,r=1/0){let o=[],n,i,s,a=-1;for(let c of On(e,gV)){if(c.k==="meta")continue;if(c.k==="branch"){s=s??c.branch;continue}if(c.k==="cwd"){i=i??c.cwd;continue}if(c.k==="model"){n=c.model;continue}let u=xt(c.total);if(xt(c.u?.input_tokens)===0||u!==0&&u===a)continue;a=u;let l=Date.parse(c.ts);if(!Number.isFinite(l)||l<t||l>r||Kr(n))continue;let d=_s(c.u);o.push(MO({tool:"codex",ts:l,project:i?pV(i):"codex",session:Jo(e,".jsonl"),...n?{model:n}:{},input:xt(d.input_tokens),read:xt(d.cache_read_input_tokens),write:xt(d.cache_creation_input_tokens),output:xt(d.output_tokens),...c.key?{key:c.key}:{},...i?{cwd:i}:{},...s?{branch:s}:{}},d))}return o}function vV(e,t=16*1024){let r=uV(e,"r");try{let o=Buffer.alloc(t),n=dV(r,o,0,t,0),i=o.subarray(0,n).toString("utf8"),s=i.indexOf(`
117
117
  `);return s>=0?i.slice(0,s):i}finally{cV(r)}}function _V(e){let t=vV(e);try{let r=JSON.parse(t)?.payload??{};return{id:typeof r.id=="string"?r.id:void 0,parent:UO(r)}}catch{return{id:/"id":"([^"]+)"/.exec(t)?.[1],parent:/"parent_thread_id":"([^"]+)"/.exec(t)?.[1]}}}function DO(e,t=Date.now(),r=aV(),o){let n=yV(e);if(!n)return[];let i;try{i=sh(e).birthtimeMs||sh(e).mtimeMs}catch{return[]}let s=/rollout-(\d{4})-(\d{2})-(\d{2})T(\d{2})-(\d{2})-(\d{2})/.exec(Jo(e));s&&(i=Math.min(i,new Date(+s[1],+s[2]-1,+s[3],+s[4],+s[5],+s[6]).getTime()));let a=mu(r),c=new Set([Q0(e),X0(Bt(r),"archived_sessions")]);for(let p=Math.max(i,t-90*Y0)-Y0;p<=t+Y0;p+=36e5){let h=new Date(p);for(let[v,g,m]of[[h.getFullYear(),h.getMonth()+1,h.getDate()],[h.getUTCFullYear(),h.getUTCMonth()+1,h.getUTCDate()]])c.add(X0(a,String(v),String(g).padStart(2,"0"),String(m).padStart(2,"0")))}let u=new Map,l={};for(let p of c){let h;try{h=lV(p)}catch{continue}for(let v of h){let g=X0(p,v);if(!v.startsWith("rollout-")||!v.endsWith(".jsonl")||g===e||u.has(g))continue;let m=o?.heads[v];if(Array.isArray(m)&&typeof m[0]=="string"){u.set(g,{id:m[0],...typeof m[1]=="string"?{parent:m[1]}:{}}),l[v]=m;continue}try{if(sh(g).mtimeMs<i)continue;let _=_V(g);u.set(g,_),o&&_.id&&(l[v]=_.parent?[_.id,_.parent]:[_.id],o.changed=!0)}catch{}}}o&&(Object.keys(o.heads).some(p=>!(p in l))&&(o.changed=!0),o.heads=l);let d=new Set([n]),f=[];for(let p=!0;p;){p=!1;for(let[h,v]of u)!v.parent||!d.has(v.parent)||!v.id||d.has(v.id)||(d.add(v.id),f.push(h),p=!0)}return f.sort((p,h)=>Jo(p).localeCompare(Jo(h)))}function SV(e){let t=xt(e.input),r=Math.min(t,xt(e.cached));return{input_tokens:t-r,cache_read_input_tokens:r,cache_creation_input_tokens:0,output_tokens:xt(e.output)+xt(e.thoughts)}}function ch(e,t,r=1/0){let o=new Map,n=0;if(e.endsWith(".jsonl"))for(let u of On(e,$V))o.set(u.id??`anon-${n++}`,u);else{let u="";for(let l of LC(e))typeof l?.timestamp=="string"&&(u=l.timestamp),l?.type==="gemini"&&l.tokens&&typeof l.tokens=="object"&&o.set(typeof l.id=="string"?l.id:`anon-${n++}`,{ts:u,t:l.tokens,model:typeof l.model=="string"?l.model:void 0})}let i=Jo(Q0(Q0(e))),s=[],a,c;for(let u of o.values()){a=u.model??a;let l=Date.parse(u.ts)||(c??=sh(e).mtimeMs);if(l<t||l>r||Kr(a))continue;let d=SV(u.t);xt(d.input_tokens)+xt(d.cache_read_input_tokens)+xt(d.output_tokens)!==0&&s.push(MO({tool:"gemini",ts:l,project:/^[0-9a-f]{40,}$/.test(i)?i.slice(0,8):i,session:Jo(e).replace(/\.jsonl?$/,""),...a?{model:a}:{},input:xt(d.input_tokens),read:xt(d.cache_read_input_tokens),write:0,output:xt(d.output_tokens)},d))}return s}var Y0,mV,gV,xt,yV,$V,ew=V(()=>{"use strict";Yr();Zo();TO();Gm();W0();PO();CO();OO();AO();Xe();Qc();D0();G0();ur();Ze();jO();Y0=864e5;mV=e=>!!(e&&(e.fastUsd||e.geoUsd||e.longUsd||e.webSearchUsd||e.webSearches));gV={id:"codex-spend.4",init:()=>({}),line(e,t,r,o){if(!e.includes('"token_count"')&&!e.includes('"turn_context"')&&!e.includes('"session_meta"'))return;let n;try{n=t()}catch{return}let i=n?.payload;if(!i||typeof i!="object")return;if(n.type==="session_meta"&&!o.m){o.m=1;let c=UO(i);typeof i.id=="string"&&r.push({k:"meta",id:i.id,...c?{parent:c}:{}}),typeof i.git?.branch=="string"&&i.git.branch&&r.push({k:"branch",branch:i.git.branch})}if(n.type==="session_meta"||n.type==="turn_context"){typeof i.cwd=="string"&&r.push({k:"cwd",cwd:i.cwd}),n.type==="turn_context"&&typeof i.model=="string"&&r.push({k:"model",model:i.model});return}if(n.type!=="event_msg"||i.type!=="token_count")return;let s=i.info?.last_token_usage;if(!s||typeof s!="object")return;let a=i.info?.total_token_usage?.total_tokens;r.push({k:"t",ts:String(n.timestamp??""),total:typeof a=="number"?a:0,key:RO(i.info?.total_token_usage,s),u:Zt(s,["input_tokens","cached_input_tokens","cache_write_input_tokens","output_tokens","input_tokens_details","prompt_tokens","prompt_tokens_details","completion_tokens"])})}},xt=e=>typeof e=="number"&&Number.isFinite(e)&&e>0?e:0;yV=e=>/([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})\.jsonl$/i.exec(Jo(e))?.[1];$V={id:"gemini-spend.1",init:()=>({ts:""}),line(e,t,r,o){if(!e.includes('"tokens"')&&!e.includes('"timestamp"')&&!e.includes('"startTime"'))return;let n;try{n=t()}catch{return}if(!n||typeof n!="object")return;let i=typeof n.timestamp=="string"?n.timestamp:typeof n.startTime=="string"?n.startTime:"";if(i&&(o.ts=i),n.type!=="gemini"||!n.tokens||typeof n.tokens!="object")return;let s={ts:o.ts,t:Zt(n.tokens,["input","output","cached","thoughts"])};typeof n.id=="string"&&(s.id=n.id),typeof n.model=="string"&&(s.model=n.model),r.push(s)}}});import{closeSync as nw,existsSync as RX,fstatSync as bV,mkdirSync as wV,openSync as rw,readdirSync as IX,readFileSync as EX,readSync as qO,renameSync as kV,rmdirSync as TX,rmSync as PX,statSync as xV,unlinkSync as zV,writeFileSync as RV}from"node:fs";import{createHash as IV,randomBytes as EV}from"node:crypto";import{dirname as TV,join as AX}from"node:path";function ow(e,t){let r=`${e}.${process.pid}.${EV(4).toString("hex")}.tmp`;try{wV(TV(e),{recursive:!0}),RV(r,JSON.stringify(t),{mode:384}),kV(r,e)}catch(o){try{zV(r)}catch{}throw o}}function CV(e,t){let r=Buffer.alloc(65536);for(let o=t;o>0;){let n=Math.max(0,o-r.length),i=qO(e,r,0,o-n,n),s=r.subarray(0,i).lastIndexOf(10);if(s>=0)return n+s+1;o=n}return 0}function OV(e,t,r,o){let n=[],i=[],s=[],a=[],c=[],u=(m,_)=>{_.priced?_.changedOn?c.push([m,_.model??"unknown",_.changedOn]):_.estimated&&a.push([m,_.model??"unknown"]):s.push([m,_.model??"unknown"])},l=()=>({...s.length?{x:s}:{},...a.length?{y:a}:{},...c.length?{z:c}:{}});if(e!=="claude"){for(let m of e==="codex"?ah(t,r):ch(t,r))u(n.length,m),n.push(m.key?IV("sha1").update(m.key).digest("hex").slice(0,12):""),i.push(m.usd);return{k:n,d:i,...l()}}let d=B0(t,r),f=new Map;d.forEach((m,_)=>{u(_,{...m,priced:m.rates!==void 0}),n.push(tw(m.uuid)),i.push(m.usd),m.id&&f.set(m.id,_)});let p=new Map,h=fu();for(let m of On(t,du)){pu(h,m);let _=m?.message;if(m?.type!=="assistant"||typeof _?.id!="string")continue;let y=Number(_.usage?.output_tokens)>0?Number(_.usage.output_tokens):0,b=p.get(_.id);if(b){b[2]=Math.max(b[2],y);continue}let R=f.get(_.id)??-1;p.set(_.id,[_.id,R,y,(R>=0?d[R].rates:wt($t(_.model),_.usage,Date.parse(String(m.timestamp??"")))?.rates)?.outputPerM??0,R>=0?(d[R].extra??[]).reduce((z,w)=>z+w.usd,0):0]),p.size>hu&&p.delete(p.keys().next().value)}let v=[...p.values()],g=rw(t,"r");try{let m=CV(g,o);return{k:n,d:i,o:m,a:Ho(g,m),r:v.slice(-hu),c:h,...l()}}finally{nw(g)}}function LO(e,t,r,o){let n=rw(t,"r");try{let i=bV(n).size,s=e.o??0;if(e.a===void 0||e.r===void 0||i<s||Ho(n,s)!==e.a)return!1;let a=e.r,c=s,u=Buffer.alloc(0);for(;c<i;){let l=Buffer.alloc(Math.min(AV,i-c)),d=qO(n,l,0,l.length,c);if(d<=0)break;c+=d;let f=u.length?Buffer.concat([u,l.subarray(0,d)]):l.subarray(0,d),p=f.lastIndexOf(10);if(p<0){u=f;continue}u=f.subarray(p+1),NV(e,a,f.subarray(0,p).toString("utf8"),r,o)}return e.r=a.slice(-hu),e.o=c-u.length,e.a=Ho(n,e.o),!0}finally{nw(n)}}function NV(e,t,r,o,n){for(let i of r.split(`
118
118
  `)){if(t.length>2*hu&&t.splice(0,t.length-hu),!oh(i)&&!i.includes('"usage"'))continue;let a;try{a=JSON.parse(i)}catch{continue}vO(e.c)||(e.c=fu());let c=pu(e.c,a);if(c&&(Number.isFinite(c.ts)?c.ts>=o:o<=0)&&!(n!==void 0&&c.sessionId!==void 0&&c.sessionId!==n)){let y=e.k.length;c.cost.changedOn?(e.z??=[]).push([y,c.model,c.cost.changedOn]):c.cost.estimated&&(e.y??=[]).push([y,c.model]),e.k.push(tw(c.uuid)),e.d.push(c.cost.totalUsd)}let u=a?.message;if(a?.type!=="assistant"||!u?.usage)continue;let l=u.usage,d=Number(l.output_tokens)>0?Number(l.output_tokens):0,f=typeof u.id=="string"?t.find(y=>y[0]===u.id):void 0;if(f){if(d>f[2]&&(f[1]>=0&&(e.d[f[1]]+=(d-f[2])*f[3]/1e6),f[2]=d),l.iterations){let y=Am($t(u.model),l,Date.parse(String(a.timestamp??"")))?.extra?.usd??0;y>f[4]&&(f[1]>=0&&(e.d[f[1]]+=y-f[4]),f[4]=y)}continue}let p=Date.parse(String(a.timestamp??"")),h=[l.input_tokens,l.cache_read_input_tokens,l.cache_creation_input_tokens].reduce((y,b)=>y+(Number(b)>0?Number(b):0),0),v=$t(u.model),g=Am(v,l,p),m=-1,_=n!==void 0&&typeof a.sessionId=="string"&&a.sessionId!==n;(Number.isFinite(p)?p>=o:o<=0)&&h>0&&!Kr(u.model)&&!_&&(m=e.k.length,g?g.changedOn?(e.z??=[]).push([m,v??"unknown",g.changedOn]):g.estimated&&(e.y??=[]).push([m,v??"unknown"]):(e.x??=[]).push([m,v??"unknown"]),e.k.push(tw(typeof a.uuid=="string"?a.uuid:void 0)),e.d.push(g?g.totalUsd:0)),typeof u.id=="string"&&t.push([u.id,m,d,g?.rates.outputPerM??0,g?.extra?.usd??0])}}function iw(e){return!!e&&typeof e=="object"&&Array.isArray(e.k)&&Array.isArray(e.d)&&e.k.length===e.d.length&&e.k.every(t=>typeof t=="string")&&e.d.every(t=>typeof t=="number"&&Number.isFinite(t))&&(e.a===void 0||typeof e.a=="string")&&(e.x===void 0||Array.isArray(e.x)&&e.x.every(t=>Array.isArray(t)&&typeof t[0]=="number"))&&(e.y===void 0||Array.isArray(e.y)&&e.y.every(t=>Array.isArray(t)&&typeof t[0]=="number"))&&(e.r===void 0||Array.isArray(e.r)&&e.r.every(t=>Array.isArray(t)&&t.length===5))&&(e.z===void 0||Array.isArray(e.z)&&e.z.every(t=>Array.isArray(t)&&typeof t[0]=="number"&&typeof t[2]=="string"))}function FO(e,t,r,o,n=!1,i){let s;try{s=xV(t)}catch{return}let a=Yc()?.key,c=`${PV}.${lP()}${a?` ${a}`:""}`,u=iw(r)&&r.p===c?r:void 0;if(u&&u.t===e&&u.s===s.size&&u.m===s.mtimeMs&&u.i===s.ino)return{e:u,read:-1};try{if(u&&e==="claude"&&u.o!==void 0&&u.i===s.ino&&s.size>=u.s){let l=u.o;if(LO(u,t,o,n?i:void 0))return{e:{...u,s:s.size,m:s.mtimeMs},read:s.size-l}}if(n&&e==="claude"){let l=rw(t,"r"),d;try{d=Ho(l,0)}finally{nw(l)}let f={t:e,s:0,m:0,i:s.ino,k:[],d:[],o:0,a:d,r:[],p:c};if(LO(f,t,o,i))return{e:{...f,s:s.size,m:s.mtimeMs},read:s.size}}return{e:{t:e,s:s.size,m:s.mtimeMs,i:s.ino,...OV(e,t,o,s.size),p:c},read:s.size}}catch{return}}var PV,hu,JX,tw,AV,J0=V(()=>{"use strict";Yr();sr();mn();Zo();zs();ew();Xe();Qc();G0();ur();Ze();F0();PV=3,hu=64,JX=5*6e4,tw=e=>e?e.slice(0,13):"";AV=8*1024*1024});import{closeSync as jV,openSync as MV,readFileSync as UV,readSync as DV,statSync as LV}from"node:fs";import{homedir as qV}from"node:os";import{join as FV}from"node:path";function BV(e){return e?.type==="system"&&typeof e.content=="string"&&e.content.startsWith(VV)}function BO(e,t=qV(),r=process.env){if(r.DISABLE_AUTO_COMPACT||r.DISABLE_COMPACT)return;let o={};try{o=JSON.parse(UV(FV(St(t),"settings.json"),"utf8"))??{}}catch{}if(o.autoCompactEnabled===!1)return;let n=Mo(e),i=Number(r.CLAUDE_CODE_AUTO_COMPACT_WINDOW),s=i>0?i:typeof o.autoCompactWindow=="number"&&o.autoCompactWindow>0?o.autoCompactWindow:void 0;return s!==void 0?Math.min(n??s,s):n}function VO(e){let t=e?.cache_creation;if(t){if((t.ephemeral_1h_input_tokens??0)>0)return sw;if((t.ephemeral_5m_input_tokens??0)>0)return HO}}function ZO(e,t,r=Date.now()){return!e||!t||Math.abs(e.lastReplyAt-t.replyAt)>5e3?e:t.expired?t.usd!==void 0?{...e,resumeUsd:t.usd,claudeCodePriced:!0}:e:r-t.at<HO?void 0:e}function JO(e,t=256*1024){let r=LV(e).size,o=Math.min(r,t),n=MV(e,"r"),i=Buffer.alloc(o);try{DV(n,i,0,o,r-o)}finally{jV(n)}return i.toString("utf8").split(`
@@ -158,7 +158,7 @@ Put it behind your tunnel's or reverse proxy's authentication unless only you ca
158
158
  ${s.text.slice(-t)}`,masked:r.count+s.count+n}}function BC(e,t){let r=t??{},o=["command","file_path","path","pattern","url","query","cmd","description","prompt"].find(i=>typeof r[i]=="string"),n=o?String(r[o]):typeof t=="string"?t:JSON.stringify(t??"");return`${e}: ${n.slice(0,2e3)}`}function gF(e,t=pF){let r=[],o=0,n=0,i=0,s=0,a=/[\\/]subagents[\\/]agent-[^\\/]*\.jsonl$/.test(e)||void 0,c=new Map,u=(f,p,h)=>{let v=h.trim();if(!v)return;i++;let g=mF(v);for(r.push({n:i,at:typeof f=="string"?f:void 0,kind:p,raw:g,compactedBy:0,c:s}),n+=VC(g);n>t&&o<r.length-1;)n-=VC(r[o].raw),r[o].raw={whole:""},o++;o>1024&&(r.splice(0,o),o=0),c.size>1e5&&c.clear()};Fo(e,f=>{let p;try{p=JSON.parse(f)}catch{return}if(!p||typeof p!="object")return;if(p.payload&&typeof p.payload=="object"&&typeof p.type=="string"&&!p.message){let g=p.payload;if(p.type==="compacted"||g.type==="context_compacted"){s++;return}if(p.type!=="response_item")return;if(g.type==="message"&&(g.role==="user"||g.role==="assistant"))return u(p.timestamp,g.role,_0(g.content));if(g.type==="function_call"||g.type==="custom_tool_call"||g.type==="local_shell_call"){let m=String(g.name??(g.type==="local_shell_call"?"shell":g.type));typeof g.call_id=="string"&&c.set(g.call_id,m);let _=g.arguments??g.input??g.action;if(typeof _=="string")try{_=JSON.parse(_)}catch{}return u(p.timestamp,"tool call",BC(m,_))}return/_call_output$/.test(String(g.type))?u(p.timestamp,`tool output (${c.get(g.call_id)??"tool"})`,_0(g.output)):void 0}if(p.type==="system"&&p.subtype==="compact_boundary"){s++;return}if(p.isCompactSummary)return;let h=p.message;if(!h||(a===void 0&&(a=p.isSidechain===!0),p.isSidechain&&!a))return;let v=h.content;if(p.type==="user"){if(typeof v=="string")return u(p.timestamp,"user",v);if(!Array.isArray(v))return;for(let g of v)g?.type==="tool_result"?u(p.timestamp,`tool output (${c.get(g.tool_use_id)??"tool"})`,_0(g.content)):typeof g?.text=="string"&&u(p.timestamp,"user",g.text);return}if(p.type==="assistant"&&Array.isArray(v))for(let g of v)g?.type==="text"?u(p.timestamp,"assistant",String(g.text??"")):g?.type==="tool_use"&&(typeof g.id=="string"&&c.set(g.id,String(g.name??"tool")),u(p.timestamp,"tool call",BC(String(g.name??"tool"),g.input)))});let l=0;return{entries:r.slice(o).map(({c:f,raw:p,...h})=>{let v=hF(p);return l+=v.masked,{...h,text:v.text,compactedBy:s-f}}),total:i,compactions:s,masked:l}}function yF(e){try{let t=uF(e,"r");try{let r=Buffer.alloc(65536),o=lF(t,r,0,r.length,0),n=r.subarray(0,o).toString("utf8").split(`
159
159
  `)[0],i=JSON.parse(n)?.payload?.cwd;return typeof i=="string"?i:void 0}finally{cF(t)}}catch{return}}function HC(e){let t;try{for(let r of eh(e)){if(!r.endsWith(".jsonl"))continue;let o=Bo(e,r),n=$0(o).mtimeMs;(!t||n>t.at)&&(t={path:o,at:n})}}catch{}return t}function vF(e,t){let r=Bo(Bt(t),"sessions");if(!Qm(r))return;let o=Date.now()-7*864e5,n=[],i=(s,a)=>{let c;try{c=eh(s)}catch{return}for(let u of c){let l=Bo(s,u),d;try{d=$0(l)}catch{continue}d.isDirectory()?a<3&&i(l,a+1):u.endsWith(".jsonl")&&d.mtimeMs>=o&&n.push({path:l,at:d.mtimeMs})}};return i(r,0),n.sort((s,a)=>a.at-s.at).find(s=>yF(s.path)===JC(e))}function WC(e=process.env,t=process.cwd(),r=S0(),o={}){let n=e.CLAUDE_CODE_SESSION_ID?.trim();if(n&&/^[\w.-]+$/.test(n)){let a=_F(n,r);if(a&&a.endsWith(`${n}.jsonl`)){if(o.envMayBeStale){let c=HC(dF(a));if(c&&c.path!==a&&c.at>$0(a).mtimeMs)return{path:c.path,how:`the newest Claude Code session in this project (${ZC(c.path,".jsonl")}; CLAUDE_CODE_SESSION_ID still names ${n}, as after /clear)`}}return{path:a,how:`this Claude Code session (${n})`}}}let i=HC(qC(t,r)),s=vF(t,r);return s&&(!i||s.at>i.at)?{path:s.path,how:"the newest Codex session started in this folder"}:i?{path:i.path,how:"the newest Claude Code session in this folder"}:void 0}function _F(e,t=S0()){if((fF(e)||e.includes("/")||e.includes("\\"))&&Qm(e))return JC(e);if(!/^[\w.-]+$/.test(e))return;let r=Bo(St(t),"projects"),o=[];try{o=eh(r)}catch{}for(let a of o){let c=Bo(r,a,`${e}.jsonl`);if(Qm(c))return c}let n=Bo(Bt(t),"sessions"),i,s=(a,c)=>{if(i)return;let u;try{u=eh(a)}catch{return}for(let l of u){let d=Bo(a,l);if(l.endsWith(".jsonl")&&l.includes(e)){i=d;return}c<3&&!l.includes(".")&&s(d,c+1)}};return Qm(n)&&s(n,0),i}function KC(e,t,r={}){let o=gF(e),{entries:n,compactions:i}=o,s=new Map,a=n.map(p=>{let h=`#${p.n}`;return s.set(h,p),{name:h,text:p.text}}),c=Math.max(200,r.budget??2e3),u=cC(a,{query:t,budget:c,maxChunkTokens:300}),l=p=>p.compactedBy===0?"in context":`before compaction ${i-p.compactedBy+1} of ${i}`,d=[...u.selected].sort((p,h)=>h.score-p.score).map(p=>{let h=s.get(p.source);return{id:p.id,n:h.n,at:h.at,kind:h.kind,where:l(h),tokens:p.tokens,score:p.score,text:p.text}}),f=u.chunks.filter(p=>p.score>0&&!u.selected.includes(p)).length;return{path:e,how:r.how??"the session named",query:t,entries:o.total,compactions:i,totalTokens:u.totalTokens,hits:d,masked:o.masked,more:f,leftOut:o.total-n.length}}function GC(e,t=S0()){let r=ZC(e.path).replace(/\.jsonl$/,"").slice(0,48),o=[`RECALL from ${e.how}${e.how.includes(r)?"":` (${r})`}: ${e.entries} entries, ~${ie(e.totalTokens)} tokens, ${e.compactions} compaction${e.compactions===1?"":"s"}.`];if(!e.hits.length)return o.push(`Nothing in it matches "${e.query}". Try the words the output itself would use (a file name, an error, a command).`),o.join(`
160
160
  `);o.push(`Best ${e.hits.length} excerpt${e.hits.length===1?"":"s"} for "${e.query}", best first${e.more?` (${e.more} more matched; a narrower query or a larger max_tokens gets them)`:""}:`),e.masked&&o.push(`${e.masked} secret-looking string${e.masked===1?"":"s"} masked.`),e.leftOut&&o.push(`The oldest ${e.leftOut} entries were not searched: the transcript is that large.`);for(let n of e.hits){let i=n.at?n.at.slice(0,16).replace("T"," ")+" UTC":"time not recorded";o.push("",`\u2500\u2500 entry ${n.n} of ${e.entries} \xB7 ${i} \xB7 ${n.kind} \xB7 ${n.where} \xB7 ~${ie(n.tokens)}`,n.text)}return o.join(`
161
- `).replaceAll(t,"~")}Yr();Zo();Xe();Ze();import{existsSync as cB,readdirSync as uB}from"node:fs";import{homedir as lB}from"node:os";import{join as gu}from"node:path";var yu="ui://context-doctor/statusline",u1="com.openai/codex-statusline-state",l1={"openai/ui":{entrypoints:[{type:"statusline",resourceUri:yu}]}},cw="context-doctor/codex-statusline-price",dB=200,fB=3e4,pB=6e4,mB=3e3,dh={bytes:64*1024,nodes:256,depth:16,textBytes:16*1024};function hB(e){let t=Buffer.byteLength(e,"utf8"),r=0,o=0,n=0,i=(s,a)=>{if(s!=null){if(r++,o=Math.max(o,a),typeof s=="string"){n+=Buffer.byteLength(s,"utf8");return}for(let c of s.children??[])i(c,a+1)}};return i(JSON.parse(e),0),{ok:t<=dh.bytes&&r<=dh.nodes&&o<=dh.depth&&n<=dh.textBytes,bytes:t,nodes:r,depth:o,textBytes:n}}var to=e=>typeof e=="number"&&Number.isFinite(e),Is=e=>to(e)&&e>0;function gB(e){return e>=1e3?`$${Math.round(e).toLocaleString("en-US")}`:`$${e.toFixed(2)}`}function yB(e){if(Is(e))return e===300?"5h":e===10080?"weekly":e%1440===0?`${e/1440}d`:e%60===0?`${e/60}h`:`${e}m`}function vB(e,t){let r=new Date(e*1e3);if(!Number.isFinite(r.getTime())||r.getTime()<=t||r.getTime()>t+31*864e5)return;let o=`${String(r.getHours()).padStart(2,"0")}:${String(r.getMinutes()).padStart(2,"0")}`;return r.toDateString()===new Date(t).toDateString()?o:`${r.toLocaleDateString("en-US",{weekday:"short"})} ${o}`}function _B(e,t=Date.now()){let r=e.thread?.usage?.total,o=e.thread?.model?.id;if(!r||!o)return;let n=hn(o,void 0,t);if(!n)return;let i=_s({input_tokens:r.total_input_tokens,cached_input_tokens:r.cache_read_input_tokens,cache_write_input_tokens:r.cache_write_input_tokens,output_tokens:r.output_tokens}),s=eu(i,Ln(n,to(e.thread?.usage?.context?.used_tokens)?e.thread.usage.context.used_tokens:0)).totalUsd;return to(s)&&s>0?s:void 0}function $B(e,t,r=Date.now()){if(!e||typeof e!="object")return null;let o=[],n=(f,p)=>({type:"text",...p?{props:{color:p}}:{},children:[f]}),i=e.thread?.usage?.context,s=i?.used_tokens,a=i?.context_window_size;if(Is(s)){let f=to(i?.used_percentage)?i.used_percentage:Is(a)?s/a*100:void 0,p=Is(a)?` of ${ie(a)}`:"",h=f!==void 0?` (${Math.round(f)}%)`:"";o.push(n(`context ${ie(s)}${p}${h}${f!==void 0&&f>=70?" \u26A0":""}`,f!==void 0&&f>=70?"yellow":"status-usage"))}let c=e.thread?.usage?.cost?.total_cost_usd,u=Is(t)?t:_B(e,r)??(Is(c)?c:void 0);u!==void 0&&u>=.005&&o.push(n(`${gB(u)} this session`,"status-usage"));let l=[],d=0;for(let f of e.account?.rate_limits??[])if(!(f?.limit_id!==void 0&&f.limit_id!=="codex"))for(let p of[f?.primary_limit,f?.secondary_limit]){if(!p||!to(p.used_percent)||p.used_percent<0)continue;let h=yB(p.window_minutes);if(!h)continue;let v=Math.round(p.used_percent);d=Math.max(d,v);let g=v>=80&&to(p.resets_at)?vB(p.resets_at,r):void 0;l.push(`${h} ${v}%${g?` (resets ${g})`:""}`)}return l.length&&o.push(n(`limits: ${l.join(", ")}`,d>=90?"red":d>=70?"yellow":"status-limit")),o.length?{type:"row",props:{gap:3},children:o}:null}function SB(e){let t=/^([0-9a-f]{8})-([0-9a-f]{4})-7/i.exec(e);if(!t)return;let r=parseInt(t[1]+t[2],16);return Number.isFinite(r)&&r>0?r:void 0}function bB(e,t=lB()){if(!/^[0-9a-f-]{8,64}$/i.test(e))return;let r=`-${e}.jsonl`,o=mu(t),n=a=>{try{let c=uB(a).find(u=>u.startsWith("rollout-")&&u.endsWith(r));return c?gu(a,c):void 0}catch{return}},i=SB(e);if(i!==void 0){let a=new Set;for(let c of[0,-864e5,864e5]){let u=new Date(i+c);a.add(gu(String(u.getFullYear()),String(u.getMonth()+1).padStart(2,"0"),String(u.getDate()).padStart(2,"0"))),a.add(gu(String(u.getUTCFullYear()),String(u.getUTCMonth()+1).padStart(2,"0"),String(u.getUTCDate()).padStart(2,"0")))}for(let c of a){let u=n(gu(o,c));if(u)return u}}let s=n(gu(Bt(t),"archived_sessions"));if(s)return s;if(cB(o))return ih(o,0).find(a=>a.endsWith(r))}async function d1(){let{parentPort:e}=await import("node:worker_threads"),{sessionTotal:t}=await Promise.resolve().then(()=>(c1(),a1));if(!e)return;let r=new Map;e.on("message",o=>{let n={id:o.id};try{let i=r.get(o.thread)??bB(o.thread);if(i){r.set(o.thread,i);let s=t({sessionId:o.thread,transcript:i});to(s.usd)&&(n={id:o.id,usd:s.usd})}}catch{}e.postMessage(n)})}var fh=class{spawn;worker;broken=!1;next=1;waiting=new Map;inFlight=new Map;prices=new Map;lastGood=new Map;constructor(t){this.spawn=t}ask(t){if(!this.worker&&!this.broken&&this.spawn)try{let n=this.spawn();n.unref(),n.on("message",s=>{let a=this.waiting.get(s?.id);this.waiting.delete(s?.id),a?.(to(s?.usd)?s.usd:void 0)});let i=()=>{this.broken=!0,this.worker=void 0;for(let s of this.waiting.values())s(void 0);this.waiting.clear()};n.on("error",i),n.on("exit",i),this.worker=n}catch{this.broken=!0}let r=this.worker;if(!r)return Promise.resolve(void 0);let o=this.next++;return new Promise(n=>{this.waiting.set(o,n),setTimeout(()=>{this.waiting.delete(o)&&n(void 0)},pB).unref(),r.postMessage({id:o,thread:t})})}async price(t,r,o,n){let i=this.prices.get(t),s=Math.max(mB,(i?.tookMs??0)*10);if((!i||(i.key!==r||n-i.at>=fB)&&n-i.at>=s)&&!this.inFlight.has(t)){let u=Date.now(),l=this.ask(t).then(d=>{this.prices.set(t,{usd:d??i?.usd,at:Date.now(),key:r,tookMs:Date.now()-u}),this.inFlight.delete(t)});this.inFlight.set(t,l)}let c=this.inFlight.get(t);if(c&&!i){let u;await Promise.race([c,new Promise(l=>{u=setTimeout(l,o)})]),clearTimeout(u)}return this.prices.get(t)?.usd}async read(t,r=dB){let o=t&&typeof t=="object"?t:void 0,n=typeof o?.thread?.id=="string"?o.thread.id:"";try{let i=o?.thread?.usage?.total,s=i?`${i.total_input_tokens}/${i.output_tokens}`:"",a=n&&this.spawn?await this.price(n,s,r,Date.now()):void 0,c=JSON.stringify($B(o,a));return hB(c).ok?(this.lastGood.set(n,c),c):this.lastGood.get(n)??"null"}catch{return this.lastGood.get(n)??"null"}}async close(){let t=this.worker;this.worker=void 0,this.broken=!0,t&&await t.terminate()}};import{isMainThread as kB,Worker as xB,workerData as zB}from"node:worker_threads";import{fileURLToPath as RB}from"node:url";var IB=["dedupe","trim-tool-results","trim-tool-calls","strip-base64","prune-history"],EB={approx_tokens:1e7,approx_lines:1e6,approx_words:5e6,approx_chars:4e7};function uw(e,t,r){if(yC(e)==="full")return{content:[{type:"text",text:t}]};let o=r();return{content:[{type:"text",text:o.text}],structuredContent:o.structured,_meta:o.meta}}var ph={ttlMs:864e5,cacheScope:"private"},f1="consent",mh="the consent form failed, so nothing was assumed";function TB(e){return e.mcpReq.envelope?.["io.modelcontextprotocol/clientCapabilities"]}function p1(e,t){return e===void 0?!0:!e||typeof e!="object"||Array.isArray(e)?!1:Object.entries(e).every(([r,o])=>r in t&&typeof o=="boolean")}async function m1(e,t,r,o){if(t.mcpReq.envelope){if(!TB(t)?.elicitation?.form)return{asked:!1};let n=Vc(t.mcpReq.inputResponses,f1);return n.kind==="missing"?{pending:Fc({inputRequests:{[f1]:Fc.elicit({mode:"form",message:r,requestedSchema:{type:"object",properties:o}})}})}:n.kind!=="elicit"?{asked:!0,ok:!1,content:{},why:mh}:n.action==="accept"?p1(n.content,o)?{asked:!0,ok:!0,content:n.content??{}}:{asked:!0,ok:!1,content:{},why:mh}:{asked:!0,ok:!1,content:{},why:n.action==="decline"?"the user declined":"the user dismissed the prompt"}}if(!e.server.getClientCapabilities()?.elicitation?.form)return{asked:!1};try{let n=await t.mcpReq.elicitInput({mode:"form",message:r,requestedSchema:{type:"object",properties:o}},{timeout:12e4});return n.action==="accept"?p1(n.content,o)?{asked:!0,ok:!0,content:n.content??{}}:{asked:!0,ok:!1,content:{},why:mh}:{asked:!0,ok:!1,content:{},why:n.action==="decline"?"the user declined":"the user dismissed the prompt"}}catch(n){return n instanceof Se&&n.code===ke.RequestTimeout?{asked:!0,ok:!1,content:{},why:"no answer within two minutes"}:{asked:!0,ok:!1,content:{},why:mh}}}var PB=new fh(()=>new xB(RB(import.meta.url),{workerData:{role:cw}}));function CB(e,t){let o=t?.params?._meta?.["io.modelcontextprotocol/clientInfo"]?.name??e.server.getClientVersion()?.name;return typeof o=="string"&&/^codex/i.test(o)}function OB(e){let t=e.server._requestHandlers;if(!t)return;let r=[["tools/list","tools",o=>o.name==="statusline"],["resources/list","resources",o=>o.uri===yu]];for(let[o,n,i]of r){let s=t.get(o);s&&t.set(o,async(a,c)=>{let u=await s(a,c);return!CB(e,a)&&Array.isArray(u?.[n])&&(u[n]=u[n].filter(l=>!i(l))),u})}}function lw({http:e=!1,storeHandoffs:t=!e}={}){let r=!e,o=new nr({name:"context-doctor",version:"0.51.0"},{instructions:gC,maxToolInputElements:1e4,cacheHints:{"tools/list":ph,"prompts/list":ph,"resources/templates/list":ph,"server/discover":ph}});o.registerTool("profile_context",{description:"Profile a conversation's context: token breakdown, largest blocks, wasted context. Pass `conversation` (JSON or text) or, in a chat app, a `sketch` (~120 tokens). Call it when the user asks about tokens, cost, speed or limits, and once past ~30 turns or 3+ large pastes. Act on the top finding.",inputSchema:he.object({conversation:he.string().optional().describe("JSON or text; in a chat app pass `sketch`"),sketch:he.object({turns:he.number().int().nonnegative().describe("Exchanges so far"),model:he.string().optional(),blocks:he.array(he.object({turn:he.number().int().positive(),kind:he.enum(["paste","code","tool_result","image","base64","text"]),label:he.string().describe("Short name"),approx_tokens:he.number().optional(),approx_lines:he.number().optional(),approx_words:he.number().optional(),approx_chars:he.number().optional(),repeated:he.number().int().optional().describe("Times it appears (2+ = duplicate)"),stale:he.boolean().optional().describe("Acted on, no longer needed")})).describe("Only blocks over ~500 tokens, repeated, or images.")}).optional().describe("For chat apps. One size hint per block: lines for code, words for prose, chars for logs."),model:he.string().optional().describe("e.g. claude-sonnet-5")}),annotations:{title:"Profile context",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},async({conversation:s,sketch:a,model:c},u)=>{if(a){let f=g=>({isError:!0,content:[{type:"text",text:g}]});if(a.turns>1e5)return f(`sketch.turns is ${a.turns}; the most that makes sense is 100000.`);if(a.blocks.length>500)return f(`sketch.blocks has ${a.blocks.length} blocks; list at most 500 (only those over ~500 tokens, repeated, or images).`);for(let[g,m]of a.blocks.entries()){if(m.turn>1e5)return f(`sketch.blocks[${g}].turn is ${m.turn}; the most that makes sense is 100000.`);if(m.repeated!==void 0&&(m.repeated<1||m.repeated>1e3))return f(`sketch.blocks[${g}].repeated is ${m.repeated}; give 1 to 1000.`);for(let[_,y]of Object.entries(EB)){let b=m[_];if(typeof b=="number"&&!(b>0))return f(`sketch.blocks[${g}].${_} is ${b}; a size is above 0.`);if(typeof b=="number"&&b>y)return f(`sketch.blocks[${g}].${_} is ${b}; the most that makes sense is ${y}. Give a rough size of the block itself.`)}}let p=s?"Note: both `conversation` and `sketch` were passed; profiled the sketch only. Pass one.\n\n":"",h=AP({...a,model:a.model??c},{record:!e}),v=p+OP(h);return uw(u.mcpReq._meta,v,()=>{let g=_C(h,v);return{...g,text:p+g.text}})}if(!s)return{isError:!0,content:[{type:"text",text:"Pass either `conversation` (full JSON or text) or `sketch` (turns + large/repeated blocks). In a chat app, use `sketch`."}]};let l=xP(XT(s),c),d=TP(l);return uw(u.mcpReq._meta,d,()=>vC(l,d))}),o.registerTool("optimize_context",{description:"Rewrite a conversation to reclaim tokens (dedupe, trim stale tool results, strip base64; prune-history is lossy). Returns slimmed JSON and the savings. Use after profile_context finds waste the user wants fixed; prune-history only with the user's consent, then write the summary the result asks for.",inputSchema:he.object({conversation:he.string().describe("Conversation JSON"),strategies:he.array(he.enum(IB)).optional().describe("Default: dedupe, trim-tool-results, strip-base64"),keep_recent:he.number().int().nonnegative().optional().describe("Tail messages kept (default 6)"),max_tool_result_tokens:he.number().int().positive().optional().describe("Per trimmed result (default 300)")}),annotations:{title:"Optimize context",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},async({conversation:s,strategies:a,keep_recent:c,max_tool_result_tokens:u},l)=>{let d="";if(a?.includes("prune-history")){let _=await m1(o,l,`Prune old turns from this conversation? It is lossy: all but the last ${Math.max(2,c??6)} messages are replaced by a summary the assistant writes.`,{prune:{type:"boolean",title:"Replace old turns with a summary",default:!0}});if("pending"in _)return _.pending;_.asked&&(!_.ok||_.content.prune===!1)&&(a=a.filter(y=>y!=="prune-history"),d=`
161
+ `).replaceAll(t,"~")}Yr();Zo();Xe();Ze();import{existsSync as cB,readdirSync as uB}from"node:fs";import{homedir as lB}from"node:os";import{join as gu}from"node:path";var yu="ui://context-doctor/statusline",u1="com.openai/codex-statusline-state",l1={"openai/ui":{entrypoints:[{type:"statusline",resourceUri:yu}]}},cw="context-doctor/codex-statusline-price",dB=200,fB=3e4,pB=6e4,mB=3e3,dh={bytes:64*1024,nodes:256,depth:16,textBytes:16*1024};function hB(e){let t=Buffer.byteLength(e,"utf8"),r=0,o=0,n=0,i=(s,a)=>{if(s!=null){if(r++,o=Math.max(o,a),typeof s=="string"){n+=Buffer.byteLength(s,"utf8");return}for(let c of s.children??[])i(c,a+1)}};return i(JSON.parse(e),0),{ok:t<=dh.bytes&&r<=dh.nodes&&o<=dh.depth&&n<=dh.textBytes,bytes:t,nodes:r,depth:o,textBytes:n}}var to=e=>typeof e=="number"&&Number.isFinite(e),Is=e=>to(e)&&e>0;function gB(e){return e>=1e3?`$${Math.round(e).toLocaleString("en-US")}`:`$${e.toFixed(2)}`}function yB(e){if(Is(e))return e===300?"5h":e===10080?"weekly":e%1440===0?`${e/1440}d`:e%60===0?`${e/60}h`:`${e}m`}function vB(e,t){let r=new Date(e*1e3);if(!Number.isFinite(r.getTime())||r.getTime()<=t||r.getTime()>t+31*864e5)return;let o=`${String(r.getHours()).padStart(2,"0")}:${String(r.getMinutes()).padStart(2,"0")}`;return r.toDateString()===new Date(t).toDateString()?o:`${r.toLocaleDateString("en-US",{weekday:"short"})} ${o}`}function _B(e,t=Date.now()){let r=e.thread?.usage?.total,o=e.thread?.model?.id;if(!r||!o)return;let n=hn(o,void 0,t);if(!n)return;let i=_s({input_tokens:r.total_input_tokens,cached_input_tokens:r.cache_read_input_tokens,cache_write_input_tokens:r.cache_write_input_tokens,output_tokens:r.output_tokens}),s=eu(i,Ln(n,to(e.thread?.usage?.context?.used_tokens)?e.thread.usage.context.used_tokens:0)).totalUsd;return to(s)&&s>0?s:void 0}function $B(e,t,r=Date.now()){if(!e||typeof e!="object")return null;let o=[],n=(f,p)=>({type:"text",...p?{props:{color:p}}:{},children:[f]}),i=e.thread?.usage?.context,s=i?.used_tokens,a=i?.context_window_size;if(Is(s)){let f=to(i?.used_percentage)?i.used_percentage:Is(a)?s/a*100:void 0,p=Is(a)?` of ${ie(a)}`:"",h=f!==void 0?` (${Math.round(f)}%)`:"";o.push(n(`context ${ie(s)}${p}${h}${f!==void 0&&f>=70?" \u26A0":""}`,f!==void 0&&f>=70?"yellow":"status-usage"))}let c=e.thread?.usage?.cost?.total_cost_usd,u=Is(t)?t:_B(e,r)??(Is(c)?c:void 0);u!==void 0&&u>=.005&&o.push(n(`${gB(u)} this session`,"status-usage"));let l=[],d=0;for(let f of e.account?.rate_limits??[])if(!(f?.limit_id!==void 0&&f.limit_id!=="codex"))for(let p of[f?.primary_limit,f?.secondary_limit]){if(!p||!to(p.used_percent)||p.used_percent<0)continue;let h=yB(p.window_minutes);if(!h)continue;let v=Math.round(p.used_percent);d=Math.max(d,v);let g=v>=80&&to(p.resets_at)?vB(p.resets_at,r):void 0;l.push(`${h} ${v}%${g?` (resets ${g})`:""}`)}return l.length&&o.push(n(`limits: ${l.join(", ")}`,d>=90?"red":d>=70?"yellow":"status-limit")),o.length?{type:"row",props:{gap:3},children:o}:null}function SB(e){let t=/^([0-9a-f]{8})-([0-9a-f]{4})-7/i.exec(e);if(!t)return;let r=parseInt(t[1]+t[2],16);return Number.isFinite(r)&&r>0?r:void 0}function bB(e,t=lB()){if(!/^[0-9a-f-]{8,64}$/i.test(e))return;let r=`-${e}.jsonl`,o=mu(t),n=a=>{try{let c=uB(a).find(u=>u.startsWith("rollout-")&&u.endsWith(r));return c?gu(a,c):void 0}catch{return}},i=SB(e);if(i!==void 0){let a=new Set;for(let c of[0,-864e5,864e5]){let u=new Date(i+c);a.add(gu(String(u.getFullYear()),String(u.getMonth()+1).padStart(2,"0"),String(u.getDate()).padStart(2,"0"))),a.add(gu(String(u.getUTCFullYear()),String(u.getUTCMonth()+1).padStart(2,"0"),String(u.getUTCDate()).padStart(2,"0")))}for(let c of a){let u=n(gu(o,c));if(u)return u}}let s=n(gu(Bt(t),"archived_sessions"));if(s)return s;if(cB(o))return ih(o,0).find(a=>a.endsWith(r))}async function d1(){let{parentPort:e}=await import("node:worker_threads"),{sessionTotal:t}=await Promise.resolve().then(()=>(c1(),a1));if(!e)return;let r=new Map;e.on("message",o=>{let n={id:o.id};try{let i=r.get(o.thread)??bB(o.thread);if(i){r.set(o.thread,i);let s=t({sessionId:o.thread,transcript:i});to(s.usd)&&(n={id:o.id,usd:s.usd})}}catch{}e.postMessage(n)})}var fh=class{spawn;worker;broken=!1;next=1;waiting=new Map;inFlight=new Map;prices=new Map;lastGood=new Map;constructor(t){this.spawn=t}ask(t){if(!this.worker&&!this.broken&&this.spawn)try{let n=this.spawn();n.unref(),n.on("message",s=>{let a=this.waiting.get(s?.id);this.waiting.delete(s?.id),a?.(to(s?.usd)?s.usd:void 0)});let i=()=>{this.broken=!0,this.worker=void 0;for(let s of this.waiting.values())s(void 0);this.waiting.clear()};n.on("error",i),n.on("exit",i),this.worker=n}catch{this.broken=!0}let r=this.worker;if(!r)return Promise.resolve(void 0);let o=this.next++;return new Promise(n=>{this.waiting.set(o,n),setTimeout(()=>{this.waiting.delete(o)&&n(void 0)},pB).unref(),r.postMessage({id:o,thread:t})})}async price(t,r,o,n){let i=this.prices.get(t),s=Math.max(mB,(i?.tookMs??0)*10);if((!i||(i.key!==r||n-i.at>=fB)&&n-i.at>=s)&&!this.inFlight.has(t)){let u=Date.now(),l=this.ask(t).then(d=>{this.prices.set(t,{usd:d??i?.usd,at:Date.now(),key:r,tookMs:Date.now()-u}),this.inFlight.delete(t)});this.inFlight.set(t,l)}let c=this.inFlight.get(t);if(c&&!i){let u;await Promise.race([c,new Promise(l=>{u=setTimeout(l,o)})]),clearTimeout(u)}return this.prices.get(t)?.usd}async read(t,r=dB){let o=t&&typeof t=="object"?t:void 0,n=typeof o?.thread?.id=="string"?o.thread.id:"";try{let i=o?.thread?.usage?.total,s=i?`${i.total_input_tokens}/${i.output_tokens}`:"",a=n&&this.spawn?await this.price(n,s,r,Date.now()):void 0,c=JSON.stringify($B(o,a));return hB(c).ok?(this.lastGood.set(n,c),c):this.lastGood.get(n)??"null"}catch{return this.lastGood.get(n)??"null"}}async close(){let t=this.worker;this.worker=void 0,this.broken=!0,t&&await t.terminate()}};import{isMainThread as kB,Worker as xB,workerData as zB}from"node:worker_threads";import{fileURLToPath as RB}from"node:url";var IB=["dedupe","trim-tool-results","trim-tool-calls","strip-base64","prune-history"],EB={approx_tokens:1e7,approx_lines:1e6,approx_words:5e6,approx_chars:4e7};function uw(e,t,r){if(yC(e)==="full")return{content:[{type:"text",text:t}]};let o=r();return{content:[{type:"text",text:o.text}],structuredContent:o.structured,_meta:o.meta}}var ph={ttlMs:864e5,cacheScope:"private"},f1="consent",mh="the consent form failed, so nothing was assumed";function TB(e){return e.mcpReq.envelope?.["io.modelcontextprotocol/clientCapabilities"]}function p1(e,t){return e===void 0?!0:!e||typeof e!="object"||Array.isArray(e)?!1:Object.entries(e).every(([r,o])=>r in t&&typeof o=="boolean")}async function m1(e,t,r,o){if(t.mcpReq.envelope){if(!TB(t)?.elicitation?.form)return{asked:!1};let n=Vc(t.mcpReq.inputResponses,f1);return n.kind==="missing"?{pending:Fc({inputRequests:{[f1]:Fc.elicit({mode:"form",message:r,requestedSchema:{type:"object",properties:o}})}})}:n.kind!=="elicit"?{asked:!0,ok:!1,content:{},why:mh}:n.action==="accept"?p1(n.content,o)?{asked:!0,ok:!0,content:n.content??{}}:{asked:!0,ok:!1,content:{},why:mh}:{asked:!0,ok:!1,content:{},why:n.action==="decline"?"the user declined":"the user dismissed the prompt"}}if(!e.server.getClientCapabilities()?.elicitation?.form)return{asked:!1};try{let n=await t.mcpReq.elicitInput({mode:"form",message:r,requestedSchema:{type:"object",properties:o}},{timeout:12e4});return n.action==="accept"?p1(n.content,o)?{asked:!0,ok:!0,content:n.content??{}}:{asked:!0,ok:!1,content:{},why:mh}:{asked:!0,ok:!1,content:{},why:n.action==="decline"?"the user declined":"the user dismissed the prompt"}}catch(n){return n instanceof Se&&n.code===ke.RequestTimeout?{asked:!0,ok:!1,content:{},why:"no answer within two minutes"}:{asked:!0,ok:!1,content:{},why:mh}}}var PB=new fh(()=>new xB(RB(import.meta.url),{workerData:{role:cw}}));function CB(e,t){let o=t?.params?._meta?.["io.modelcontextprotocol/clientInfo"]?.name??e.server.getClientVersion()?.name;return typeof o=="string"&&/^codex/i.test(o)}function OB(e){let t=e.server._requestHandlers;if(!t)return;let r=[["tools/list","tools",o=>o.name==="statusline"],["resources/list","resources",o=>o.uri===yu]];for(let[o,n,i]of r){let s=t.get(o);s&&t.set(o,async(a,c)=>{let u=await s(a,c);return!CB(e,a)&&Array.isArray(u?.[n])&&(u[n]=u[n].filter(l=>!i(l))),u})}}function lw({http:e=!1,storeHandoffs:t=!e}={}){let r=!e,o=new nr({name:"context-doctor",version:"0.52.0"},{instructions:gC,maxToolInputElements:1e4,cacheHints:{"tools/list":ph,"prompts/list":ph,"resources/templates/list":ph,"server/discover":ph}});o.registerTool("profile_context",{description:"Profile a conversation's context: token breakdown, largest blocks, wasted context. Pass `conversation` (JSON or text) or, in a chat app, a `sketch` (~120 tokens). Call it when the user asks about tokens, cost, speed or limits, and once past ~30 turns or 3+ large pastes. Act on the top finding.",inputSchema:he.object({conversation:he.string().optional().describe("JSON or text; in a chat app pass `sketch`"),sketch:he.object({turns:he.number().int().nonnegative().describe("Exchanges so far"),model:he.string().optional(),blocks:he.array(he.object({turn:he.number().int().positive(),kind:he.enum(["paste","code","tool_result","image","base64","text"]),label:he.string().describe("Short name"),approx_tokens:he.number().optional(),approx_lines:he.number().optional(),approx_words:he.number().optional(),approx_chars:he.number().optional(),repeated:he.number().int().optional().describe("Times it appears (2+ = duplicate)"),stale:he.boolean().optional().describe("Acted on, no longer needed")})).describe("Only blocks over ~500 tokens, repeated, or images.")}).optional().describe("For chat apps. One size hint per block: lines for code, words for prose, chars for logs."),model:he.string().optional().describe("e.g. claude-sonnet-5")}),annotations:{title:"Profile context",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},async({conversation:s,sketch:a,model:c},u)=>{if(a){let f=g=>({isError:!0,content:[{type:"text",text:g}]});if(a.turns>1e5)return f(`sketch.turns is ${a.turns}; the most that makes sense is 100000.`);if(a.blocks.length>500)return f(`sketch.blocks has ${a.blocks.length} blocks; list at most 500 (only those over ~500 tokens, repeated, or images).`);for(let[g,m]of a.blocks.entries()){if(m.turn>1e5)return f(`sketch.blocks[${g}].turn is ${m.turn}; the most that makes sense is 100000.`);if(m.repeated!==void 0&&(m.repeated<1||m.repeated>1e3))return f(`sketch.blocks[${g}].repeated is ${m.repeated}; give 1 to 1000.`);for(let[_,y]of Object.entries(EB)){let b=m[_];if(typeof b=="number"&&!(b>0))return f(`sketch.blocks[${g}].${_} is ${b}; a size is above 0.`);if(typeof b=="number"&&b>y)return f(`sketch.blocks[${g}].${_} is ${b}; the most that makes sense is ${y}. Give a rough size of the block itself.`)}}let p=s?"Note: both `conversation` and `sketch` were passed; profiled the sketch only. Pass one.\n\n":"",h=AP({...a,model:a.model??c},{record:!e}),v=p+OP(h);return uw(u.mcpReq._meta,v,()=>{let g=_C(h,v);return{...g,text:p+g.text}})}if(!s)return{isError:!0,content:[{type:"text",text:"Pass either `conversation` (full JSON or text) or `sketch` (turns + large/repeated blocks). In a chat app, use `sketch`."}]};let l=xP(XT(s),c),d=TP(l);return uw(u.mcpReq._meta,d,()=>vC(l,d))}),o.registerTool("optimize_context",{description:"Rewrite a conversation to reclaim tokens (dedupe, trim stale tool results, strip base64; prune-history is lossy). Returns slimmed JSON and the savings. Use after profile_context finds waste the user wants fixed; prune-history only with the user's consent, then write the summary the result asks for.",inputSchema:he.object({conversation:he.string().describe("Conversation JSON"),strategies:he.array(he.enum(IB)).optional().describe("Default: dedupe, trim-tool-results, strip-base64"),keep_recent:he.number().int().nonnegative().optional().describe("Tail messages kept (default 6)"),max_tool_result_tokens:he.number().int().positive().optional().describe("Per trimmed result (default 300)")}),annotations:{title:"Optimize context",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},async({conversation:s,strategies:a,keep_recent:c,max_tool_result_tokens:u},l)=>{let d="";if(a?.includes("prune-history")){let _=await m1(o,l,`Prune old turns from this conversation? It is lossy: all but the last ${Math.max(2,c??6)} messages are replaced by a summary the assistant writes.`,{prune:{type:"boolean",title:"Replace old turns with a summary",default:!0}});if("pending"in _)return _.pending;_.asked&&(!_.ok||_.content.prune===!1)&&(a=a.filter(y=>y!=="prune-history"),d=`
162
162
  prune-history skipped: ${_.ok?"the user unticked it":_.why}.`)}let f=Zb(s,{strategies:a,keepRecent:c,maxToolResultTokens:u}),p=f.tokensBefore-f.tokensAfter;p>0&&!e&&ou({ev:"optimize",src:"mcp",saved:p,model:f.conversation?.model});let h=`Saved ~${ie(p)} tokens (${ie(f.tokensBefore)} \u2192 ${ie(f.tokensAfter)}) via ${f.applied.length} change(s):
163
163
  `+f.applied.map(_=>`- [${_.strategy}] message #${_.messageIndex}: ${_.note} (~${ie(_.tokensSaved)})`).join(`
164
164
  `)+d,v=1e5,g=JSON.stringify(f.conversation),m=[{type:"text",text:h},g.length<=v?{type:"text",text:g}:{type:"text",text:`[optimized conversation is ${g.length} chars \u2014 too large to echo into this context. Tell the user the savings above and that \`npx context-doctor optimize <file> --out slim.json\` produces the file directly.]`}];return f.prunedDigest&&m.push({type:"text",text:`ACTION REQUIRED (you, the assistant calling this tool): the pruned turns are digested below. Write a dense factual summary of them (\u2264150 tokens: decisions, current state, open items, key identifiers) and replace the '[context-doctor: ... pruned]' stub message in the conversation above with your summary before presenting the result.
package/dist/proxy.d.ts CHANGED
@@ -83,7 +83,7 @@ export interface ProxyOptions extends OptimizeOptions {
83
83
  /** Default request body cap: far above any real request (a 1M-token context is ~4 MB of JSON, images aside). */
84
84
  export declare const DEFAULT_MAX_BODY_BYTES: number;
85
85
  /** Reported by /health so `autopilot status` can tell an outdated service from a current one. */
86
- export declare const PROXY_VERSION = "0.51.0";
86
+ export declare const PROXY_VERSION = "0.52.0";
87
87
  /**
88
88
  * Remove a leading `/t/<token>` from a request path, or return undefined when
89
89
  * the prefix is absent or the token differs. The comparison is constant time
package/dist/proxy.js CHANGED
@@ -25,7 +25,7 @@ import { makeGuard, refusal } from "./httpguard.js";
25
25
  /** Default request body cap: far above any real request (a 1M-token context is ~4 MB of JSON, images aside). */
26
26
  export const DEFAULT_MAX_BODY_BYTES = 100 * 1024 * 1024;
27
27
  /** Reported by /health so `autopilot status` can tell an outdated service from a current one. */
28
- export const PROXY_VERSION = "0.51.0";
28
+ export const PROXY_VERSION = "0.52.0";
29
29
  /** Connection-level headers that must not be forwarded. */
30
30
  const SKIP_REQUEST_HEADERS = new Set(["host", "content-length", "connection", "transfer-encoding", "accept-encoding", "expect"]);
31
31
  /** A reply carrying any of these has something for the limits ledger: a plan window, or the usage-credits state. */
@@ -0,0 +1,8 @@
1
+ export interface SampleHistory {
2
+ /** Transcript paths, ready for estimateSavings(days, {}, paths). */
3
+ paths: string[];
4
+ /** Delete the temp folder. Call it in a finally. */
5
+ cleanup: () => void;
6
+ }
7
+ /** Two synthetic sessions: one with a cold return past the prompt cache, one without. */
8
+ export declare function writeSampleHistory(now?: number): SampleHistory;
package/dist/sample.js ADDED
@@ -0,0 +1,86 @@
1
+ /**
2
+ * `savings --sample`: a demonstration report. The sessions are synthetic,
3
+ * written to a temp folder here and deleted right after; the report is the
4
+ * real replay pipeline (replaySession, estimateSavings) run over them, so
5
+ * every dollar is the product's own arithmetic on generated data. Nothing is
6
+ * measured on the user's machine and no usage is invented for them: the
7
+ * output says SAMPLE and says the data is generated. It is never substituted
8
+ * for the real report: with no history, `savings` says so and offers the flag.
9
+ *
10
+ * Deterministic apart from the anchor time: contents come from a seeded
11
+ * generator, timestamps are relative to `now` so the sessions always fall
12
+ * inside the report's 30-day window.
13
+ */
14
+ import { mkdtempSync, rmSync, utimesSync, writeFileSync } from "node:fs";
15
+ import { tmpdir } from "node:os";
16
+ import { join } from "node:path";
17
+ const MIN = 60_000;
18
+ const DAY = 86_400_000;
19
+ function rng(seed) {
20
+ return () => {
21
+ seed |= 0;
22
+ seed = (seed + 0x6d2b79f5) | 0;
23
+ let t = Math.imul(seed ^ (seed >>> 15), 1 | seed);
24
+ t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
25
+ return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
26
+ };
27
+ }
28
+ /** A Read result, big enough to matter once it goes stale. */
29
+ const BIG_READ = "const value = compute(input, options); // step\n".repeat(400);
30
+ function sessionRows(s) {
31
+ const r = rng(s.seed);
32
+ const rows = [];
33
+ let t = s.start;
34
+ const iso = (ms) => new Date(ms).toISOString();
35
+ rows.push(JSON.stringify({ type: "user", cwd: "/work/app", sessionId: s.id, version: "2.1.300", entrypoint: "cli", uuid: `${s.id}-q0`, timestamp: iso(t), message: { role: "user", content: "Work through the backlog in src/, and run the tests as you go." } }));
36
+ const PROMPTS = ["Fix the failing test", "Now the next ticket", "That broke the build, revert it", "Add the retry and run the suite again", "Looks right, continue"];
37
+ const breakAt = new Map((s.breaks ?? []).map((b) => [b.at, b.hours]));
38
+ let prompt = s.promptStart;
39
+ for (let i = 0; i < s.requests; i++) {
40
+ const brk = breakAt.get(i);
41
+ t += brk !== undefined ? brk * 60 * MIN : 30_000 + Math.floor(r() * 60_000);
42
+ // Each request starts with what the person typed, as real transcripts do;
43
+ // the return after a long break always does.
44
+ if (i > 0 && (brk !== undefined || r() < 0.5)) {
45
+ rows.push(JSON.stringify({ type: "user", cwd: "/work/app", sessionId: s.id, version: "2.1.300", entrypoint: "cli", uuid: `${s.id}-u${i}`, timestamp: iso(t - 2_000), message: { role: "user", content: PROMPTS[Math.floor(r() * PROMPTS.length)] } }));
46
+ }
47
+ const usage = {
48
+ input_tokens: 5 + Math.floor(r() * 20),
49
+ cache_read_input_tokens: prompt,
50
+ cache_creation_input_tokens: s.promptStep,
51
+ output_tokens: 100 + Math.floor(r() * 400),
52
+ cache_creation: { ephemeral_5m_input_tokens: 0, ephemeral_1h_input_tokens: s.promptStep },
53
+ service_tier: "standard",
54
+ };
55
+ const toolId = `toolu_${s.id}_${i}`;
56
+ rows.push(JSON.stringify({
57
+ type: "assistant", cwd: "/work/app", sessionId: s.id, version: "2.1.300", entrypoint: "cli", uuid: `${s.id}-a${i}`, timestamp: iso(t),
58
+ message: { id: `msg_${s.id}_${i}`, type: "message", role: "assistant", model: s.model, content: [{ type: "tool_use", id: toolId, name: "Read", input: { file_path: `/work/app/src/file${i % 7}.ts` } }], usage },
59
+ }));
60
+ rows.push(JSON.stringify({
61
+ type: "user", cwd: "/work/app", sessionId: s.id, version: "2.1.300", entrypoint: "cli", uuid: `${s.id}-r${i}`, timestamp: iso(t + 1_000),
62
+ message: { role: "user", content: [{ type: "tool_result", tool_use_id: toolId, content: BIG_READ }] },
63
+ }));
64
+ prompt += s.promptStep;
65
+ }
66
+ return { rows, end: t + 2_000 };
67
+ }
68
+ /** Two synthetic sessions: one with a cold return past the prompt cache, one without. */
69
+ export function writeSampleHistory(now = Date.now()) {
70
+ const dir = mkdtempSync(join(tmpdir(), "context-doctor-sample-"));
71
+ const specs = [
72
+ // A big session, come back to twice after the cache expired: both levers show.
73
+ { id: "sample-a", start: now - 6 * DAY, requests: 40, seed: 42, model: "claude-opus-5-5", promptStart: 200_000, promptStep: 15_000, breaks: [{ at: 12, hours: 3 }, { at: 26, hours: 26 }] },
74
+ // A smaller session without a cold return: not every session has one.
75
+ { id: "sample-b", start: now - 2 * DAY, requests: 14, seed: 7, model: "claude-opus-5-5", promptStart: 60_000, promptStep: 8_000 },
76
+ ];
77
+ const paths = [];
78
+ for (const s of specs) {
79
+ const { rows, end } = sessionRows(s);
80
+ const p = join(dir, `${s.id}.jsonl`);
81
+ writeFileSync(p, rows.join("\n") + "\n");
82
+ utimesSync(p, end / 1000, end / 1000);
83
+ paths.push(p);
84
+ }
85
+ return { paths, cleanup: () => rmSync(dir, { recursive: true, force: true }) };
86
+ }
package/dist/savings.d.ts CHANGED
@@ -94,7 +94,14 @@ export declare function renderSavings(r: SavingsReport, autopilotOn?: boolean, c
94
94
  hours: number;
95
95
  netUsd: number;
96
96
  pingUsd: number;
97
- }): string;
97
+ }, sample?: boolean): string;
98
+ /**
99
+ * The demonstration report: the real replay over the synthetic history from
100
+ * sample.ts, said to be a sample in its first and last lines. Shown only by
101
+ * `savings --sample`; without it, no history stays an honest empty report
102
+ * that offers the flag.
103
+ */
104
+ export declare function renderSampleSavings(r: SavingsReport): string;
98
105
  /**
99
106
  * `savings --share`: a few lines people can paste or screenshot. Totals only:
100
107
  * no project names, paths or session ids, so sharing it leaks nothing.
package/dist/savings.js CHANGED
@@ -354,10 +354,11 @@ export function estimateSavings(days = 30, options = {}, paths, onProgress, repl
354
354
  }
355
355
  const tokens = (n) => (n >= 1e9 ? `${(n / 1e9).toFixed(1)}B` : formatTokens(n));
356
356
  const usd = (n) => (n >= 100 ? `$${Math.round(n).toLocaleString("en-US")}` : `$${n.toFixed(2)}`);
357
- export function renderSavings(r, autopilotOn = false, cw, missLines, limitLines, lensLines, keepWarm) {
357
+ export function renderSavings(r, autopilotOn = false, cw, missLines, limitLines, lensLines, keepWarm, sample = false) {
358
358
  const lines = [];
359
359
  if (r.sessions.length === 0) {
360
- lines.push(`No Claude Code sessions with 10+ requests in the last ${r.days} days to replay.`);
360
+ lines.push(`No Claude Code sessions with 10+ requests in the last ${r.days} days to replay: nothing of yours was measured.`);
361
+ lines.push("See the same report on generated example sessions: `context-doctor savings --sample`.");
361
362
  lines.push("Use Claude Code for a while, then run this again: `context-doctor savings`.");
362
363
  return withInvocation(lines.join("\n"));
363
364
  }
@@ -365,9 +366,11 @@ export function renderSavings(r, autopilotOn = false, cw, missLines, limitLines,
365
366
  const allDesktop = r.unreachableSessions === n;
366
367
  const pct = (x) => (r.billedUsd > 0 ? ` (${Math.round((x / r.billedUsd) * 100)}%)` : "");
367
368
  // Kept within 80 columns: this is most people's first screen of the tool.
368
- lines.push("What context-doctor finds in your Claude Code sessions");
369
+ lines.push(sample ? "SAMPLE: what context-doctor finds in Claude Code sessions" : "What context-doctor finds in your Claude Code sessions");
369
370
  // The same count, said the same way, as compact-window's.
370
- lines.push(`Last ${r.days} days, ${sessionsLabel(n, r.transcripts ?? n)}, ${priceBasis()}`);
371
+ lines.push(sample
372
+ ? `Generated example sessions (no real history here), ${priceBasis()}`
373
+ : `Last ${r.days} days, ${sessionsLabel(n, r.transcripts ?? n)}, ${priceBasis()}`);
371
374
  lines.push("─".repeat(60));
372
375
  lines.push(`Input in your main conversations ${usd(r.billedUsd).padStart(9)} from your transcripts' usage`);
373
376
  // spend's total is larger: it adds output and the subagents. Said here, so the two do not look like they disagree.
@@ -424,12 +427,34 @@ export function renderSavings(r, autopilotOn = false, cw, missLines, limitLines,
424
427
  lines.push(...missLines);
425
428
  }
426
429
  lines.push("");
427
- lines.push("Replayed request by request through the shipped code and priced as the");
428
- lines.push("prompt cache bills. On a subscription the same tokens come out of your");
429
- lines.push("usage limit instead. Share yours: context-doctor savings --share");
430
+ if (sample) {
431
+ lines.push("Replayed request by request through the shipped code, on sessions");
432
+ lines.push("generated for this demonstration. Nothing was measured on this machine.");
433
+ }
434
+ else {
435
+ lines.push("Replayed request by request through the shipped code and priced as the");
436
+ lines.push("prompt cache bills. On a subscription the same tokens come out of your");
437
+ lines.push("usage limit instead. Share yours: context-doctor savings --share");
438
+ lines.push("Run it again after a week of use: the report re-measures on what");
439
+ lines.push("changed, and `fix` shows what each applied fix has saved since.");
440
+ }
430
441
  // Hints as the user can type them: `npx context-doctor …` after an npx run.
431
442
  return withInvocation(lines.join("\n"));
432
443
  }
444
+ /**
445
+ * The demonstration report: the real replay over the synthetic history from
446
+ * sample.ts, said to be a sample in its first and last lines. Shown only by
447
+ * `savings --sample`; without it, no history stays an honest empty report
448
+ * that offers the flag.
449
+ */
450
+ export function renderSampleSavings(r) {
451
+ const body = renderSavings(r, false, undefined, undefined, undefined, undefined, undefined, true);
452
+ if (r.sessions.length === 0)
453
+ return body;
454
+ return body + "\n\n" + withInvocation("This is a demonstration on generated data, not your usage. Once this\n" +
455
+ "machine has real Claude Code sessions, `context-doctor savings` replays\n" +
456
+ "them the same way. See this sample again: `context-doctor savings --sample`.");
457
+ }
433
458
  /**
434
459
  * `savings --share`: a few lines people can paste or screenshot. Totals only:
435
460
  * no project names, paths or session ids, so sharing it leaks nothing.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "context-doctor",
3
- "version": "0.51.0",
3
+ "version": "0.52.0",
4
4
  "description": "Context and token optimizer for LLM agents: see where Claude Code, Cursor, Codex and Gemini CLI tokens go, then cut them: an every-prompt hook, smarter compaction, an autopilot proxy that edits history only when the prompt cache is cold, RAG chunk packing and an MCP server. Local, no API key. By gAI Ventures.",
5
5
  "keywords": [
6
6
  "agent",