context-doctor 0.41.0 → 0.43.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (54) hide show
  1. package/README.md +7 -4
  2. package/dist/ab.js +3 -1
  3. package/dist/autopilot.d.ts +1 -1
  4. package/dist/autopilot.js +38 -24
  5. package/dist/budget.d.ts +54 -1
  6. package/dist/budget.js +207 -53
  7. package/dist/cachettl.js +12 -9
  8. package/dist/claudedir.d.ts +8 -0
  9. package/dist/claudedir.js +19 -0
  10. package/dist/cli.js +90 -15
  11. package/dist/codexcompact.d.ts +116 -0
  12. package/dist/codexcompact.js +415 -0
  13. package/dist/codexdir.d.ts +11 -0
  14. package/dist/codexdir.js +20 -0
  15. package/dist/codexroute.d.ts +1 -0
  16. package/dist/codexroute.js +3 -1
  17. package/dist/compactwindow.js +12 -9
  18. package/dist/cursor.js +20 -5
  19. package/dist/doctor.d.ts +9 -0
  20. package/dist/doctor.js +42 -14
  21. package/dist/effective.d.ts +18 -0
  22. package/dist/effective.js +39 -4
  23. package/dist/extract.d.ts +12 -3
  24. package/dist/extract.js +39 -12
  25. package/dist/fileparams.d.ts +1 -1
  26. package/dist/fileparams.js +8 -8
  27. package/dist/fix.d.ts +33 -4
  28. package/dist/fix.js +221 -19
  29. package/dist/hook.js +35 -5
  30. package/dist/install.js +106 -47
  31. package/dist/ledger.d.ts +17 -1
  32. package/dist/ledger.js +31 -1
  33. package/dist/limits.d.ts +15 -1
  34. package/dist/limits.js +71 -28
  35. package/dist/mcp.js +58 -58
  36. package/dist/overhead.js +2 -1
  37. package/dist/pack.js +3 -2
  38. package/dist/proxy.d.ts +1 -1
  39. package/dist/proxy.js +1 -1
  40. package/dist/recall.js +3 -2
  41. package/dist/scan.d.ts +2 -0
  42. package/dist/scan.js +2 -1
  43. package/dist/session.js +2 -1
  44. package/dist/sessionprice.d.ts +71 -0
  45. package/dist/sessionprice.js +216 -0
  46. package/dist/settingsedit.d.ts +4 -0
  47. package/dist/settingsedit.js +61 -3
  48. package/dist/spend.d.ts +8 -1
  49. package/dist/spend.js +27 -10
  50. package/dist/subagentmodel.d.ts +19 -4
  51. package/dist/subagentmodel.js +116 -28
  52. package/dist/tooloutput.d.ts +118 -0
  53. package/dist/tooloutput.js +355 -0
  54. package/package.json +1 -1
package/README.md CHANGED
@@ -22,13 +22,13 @@ Pick where you work. Each takes about a minute and is fully reversible.
22
22
 
23
23
  | You use | Do this |
24
24
  |---|---|
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`, `:savings`, `:checkup`, `:overhead`, `:pack`, `:autopilot`, `:compact-window` |
25
+ | **Claude Code** (terminal, IDE, desktop app) | Inside Claude Code: `/plugin marketplace add KushalP1/context-doctor`, then `/plugin install context-doctor@context-doctor`. You get the every-prompt check, the compaction hook, the MCP tools and `/context-doctor:fix`, `:spend`, `:savings`, `:checkup`, `:overhead`, `:pack`, `:autopilot`, `:compact-window` |
26
26
  | **Everything on this machine at once** | `npm install -g context-doctor && context-doctor install` wires Claude Code, Claude Desktop, Cursor, Codex, Gemini CLI, Google Antigravity and GitHub Copilot: MCP server, skill and hooks ([what it writes](./docs/install.md)). `context-doctor doctor` checks it; `context-doctor uninstall` removes it. Then, for Claude Code in a terminal or IDE, `context-doctor autopilot on` |
27
27
  | **Claude Desktop, Cursor or any MCP client** | Add the server to the client's MCP config (or install the one-click `.mcpb` from the [latest release](https://github.com/KushalP1/context-doctor/releases/latest) in Claude Desktop):<br>`{"mcpServers": {"context-doctor": {"command": "npx", "args": ["-y", "context-doctor", "mcp"]}}}` |
28
28
  | **claude.ai, ChatGPT, phone apps** | `npx context-doctor instructions --copy`, then paste into the app's personal preferences (it tells you where). ChatGPT can also reach the MCP server at a URL ([how](./docs/chat-apps.md#chatgpt)) |
29
29
  | **Your own app on an LLM API** | Run `npx context-doctor proxy --autopilot` and point `ANTHROPIC_BASE_URL`, `OPENAI_BASE_URL` (add `/v1`) or `GOOGLE_GEMINI_BASE_URL` at the proxy on `127.0.0.1:8787`, plain HTTP ([exact values](./docs/proxy.md)). No proxy possible? Wrap the SDK client: `withContextDoctor(new Anthropic())` ([library](./docs/library.md)) |
30
30
  | **Python / RAG pipelines** | `pip install "git+https://github.com/KushalP1/context-doctor#subdirectory=python"` (PyPI release coming), then `pack_documents(retrieved_docs, question, budget=4000)` trims LangChain or LlamaIndex results to the chunks that matter. [Python README](./python/README.md) |
31
- | **GitHub pull requests** | `uses: KushalP1/context-doctor@v0.41.0` comments how much a PR grows CLAUDE.md, AGENTS.md and rules, and can fail over a budget ([setup](./docs/ci.md)) |
31
+ | **GitHub pull requests** | `uses: KushalP1/context-doctor@v0.43.0` comments how much a PR grows CLAUDE.md, AGENTS.md and rules, and can fail over a budget ([setup](./docs/ci.md)) |
32
32
 
33
33
  ## What it does
34
34
 
@@ -53,6 +53,7 @@ Pick where you work. Each takes about a minute and is fully reversible.
53
53
  - A subagent price (`PreToolUse` on the Agent tool) shows what a subagent costs before it starts, at your own median for that type (the author's: $3.99 for general-purpose, $1.43 for Explore, 422 runs in 30 days), with the Sonnet price where it would run on Opus or Fable, and a total when launches bunch up. It never blocks.
54
54
  - A compaction hook (`PreCompact`) tells each Claude Code compaction what the session cannot lose (files changed, open tasks, your instructions, failing tests), so compacting saves tokens without losing the thread.
55
55
  - An every-prompt hook (Claude Code, Codex, Gemini CLI; Cursor after each tool call) tells the model its real context size and the largest waste, and offers `/compact` when you return to a big session after the cache expired.
56
+ - A session's own price: once a session passes $25, $100 and $500 (subagents included), the every-prompt hook tells you what it has cost and what each message now costs, and that `/compact` or a fresh session cuts it ([docs](./docs/spend.md#a-sessions-own-price-while-it-runs)).
56
57
  - `budget 50/day` (or `/week`): the every-prompt hook in Claude Code, Codex and Gemini CLI says when today's spend passes 50%, 80% and 100% of it, and with `--block` holds prompts over budget; the status line shows `$12/$50 today`.
57
58
  - `compact-window`: sets Claude Code's own auto-compact window, measured on your history first. Works in the desktop app too.
58
59
  - `cache-ttl`: replays your own pauses at a 5-minute and a 1-hour prompt cache and sets Claude Code's `promptCacheTtl` to the cheaper one (the author's: 7% less main-conversation input at 1 hour; 22% less than the 5-minute default an API key gets). Same content either way, so no quality cost ([fixes](./docs/fix.md)).
@@ -132,7 +133,7 @@ Rules 1-4 end exactly at character 512, the part ChatGPT's guide says must stand
132
133
  | Command | What it does |
133
134
  |---|---|
134
135
  | `context-doctor install` / `uninstall` | Wire (or remove) everything it finds: the MCP server for Claude Desktop, Claude Code, Cursor, Codex, Gemini CLI, Google Antigravity and GitHub Copilot; the Agent Skill (Claude Code, Codex, Antigravity); the every-prompt hook (Claude Code, Codex, Gemini CLI's `BeforeAgent`, Cursor's `postToolUse`, `postToolUseFailure` and `sessionStart`); Claude Code's `PreCompact`, `SessionStart`, `PreToolUse` (the subagent price) and, on 2.1.251+, `PreModelSwitch` hooks; Copilot's `sessionStart` (the standing rules). `--statusline` adds the status bar line ([details](./docs/install.md)) |
135
- | `context-doctor fix [--apply ids\|all] [--share]` / `fix undo` | Every lever ranked by what it would have saved on your last 30 days (compact earlier, the cache lifetime, autopilot, MCP tool search, unused servers), with what each costs in quality; applies one only on a yes, `fix undo` reverts exactly what it changed, later runs show what each saved since ([details](./docs/fix.md)) |
136
+ | `context-doctor fix [--apply ids\|all] [--share]` / `fix undo` | Every lever ranked by what it would have saved on your last 30 days (compact earlier, the cache lifetime, autopilot, MCP tool search, unused servers, the subagents' model, long Bash output to a file, Codex's auto-compact limit), with what each costs in quality; applies one only on a yes (the subagents' model only when named), `fix undo` reverts exactly what it changed, later runs show what each saved since ([details](./docs/fix.md)) |
136
137
  | `context-doctor spend [--days n] [--share]` | One bill across every tool on this machine: Claude Code (main conversation and subagents), Codex, Gemini CLI and Cursor (an estimate: no cache split), by tool, project, model and day, with what drives it ([docs](./docs/spend.md)) |
137
138
  | `context-doctor budget [<$>/day\|<$>/week [--block]\|off]` | A spend budget the every-prompt hook applies: a line at 50%, 80% and 100%, and with `--block` prompts over it are held until you raise it or turn it off ([docs](./docs/spend.md#a-budget-the-hook-applies-context-doctor-budget)) |
138
139
  | `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 |
@@ -180,7 +181,9 @@ Rules 1-4 end exactly at character 512, the part ChatGPT's guide says must stand
180
181
 
181
182
  ## What's new
182
183
 
183
- - **0.41 One bill, a budget, and the subagents' model**: `context-doctor spend` puts Claude Code (subagents included), Codex, Gemini CLI and Cursor on one bill by tool, project, model and day. `context-doctor budget 50/day` has the every-prompt hook tell you at 50%, 80% and 100%, and with `--block` holds prompts over budget; the status line shows `$12/$50 today`, at about 5 ms a prompt. `fix` gains `subagent-model`: subagents run on your main conversation's model (Opus or Fable included), and `CLAUDE_CODE_SUBAGENT_MODEL` set to Sonnet 5.5 would have cost the author $632 less (38% of $1,658) in 30 days; it changes the model, so it is applied only when you name it, and `fix undo` reverts it.
184
+ - **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).
185
+ - **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)).
186
+ - **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.
184
187
  - **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.
185
188
  - **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.
186
189
  - **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.
package/dist/ab.js CHANGED
@@ -170,7 +170,9 @@ function killLeftovers(root) {
170
170
  }
171
171
  }
172
172
  else {
173
- const r = spawnSync("lsof", ["-t", "+D", root], { encoding: "utf8", timeout: 5000 });
173
+ // lsof walks every process's open files: ~0.5 s here, several on a loaded machine. Cut off
174
+ // early, it found nothing and the leftover lived on, so it gets time.
175
+ const r = spawnSync("lsof", ["-t", "+D", root], { encoding: "utf8", timeout: 30_000 });
174
176
  for (const line of (r.stdout ?? "").split("\n"))
175
177
  if (/^\d+$/.test(line.trim()))
176
178
  pids.add(Number(line.trim()));
@@ -118,4 +118,4 @@ export declare function autopilotStatus(paths?: AutopilotPaths): Promise<string[
118
118
  * Called by the every-prompt hook: if autopilot is on and the proxy is down,
119
119
  * start it before the prompt's request goes out. Returns quickly either way.
120
120
  */
121
- export declare function ensureProxyUp(paths?: AutopilotPaths, exec?: ServiceExec): Promise<void>;
121
+ export declare function ensureProxyUp(paths?: AutopilotPaths, exec?: ServiceExec, healthMs?: number): Promise<void>;
package/dist/autopilot.js CHANGED
@@ -24,6 +24,7 @@ import { homedir, platform } from "node:os";
24
24
  import { dirname, join } from "node:path";
25
25
  import { fileURLToPath } from "node:url";
26
26
  import { isEphemeralPath, readJson, writeJsonWithBackup } from "./install.js";
27
+ import { withSettingsLock } from "./settingsedit.js";
27
28
  import { formatTokens } from "./tokens.js";
28
29
  import { codexAuthMode, codexHomeIn, codexRouting, routeCodex, unrouteCodex } from "./codexroute.js";
29
30
  import { claudeDir } from "./claudedir.js";
@@ -210,14 +211,17 @@ function migrateToolSearch(paths, cfg) {
210
211
  if (cfg.setToolSearch !== undefined)
211
212
  return;
212
213
  try {
213
- const settings = readJson(paths.settings);
214
- const env = settings.env;
215
- if (!env || env.ANTHROPIC_BASE_URL !== proxyUrl(cfg.port))
216
- return;
217
- const set = keepToolSearch(env);
218
- if (set)
219
- writeJsonWithBackup(paths.settings, settings);
220
- writeFileSync(paths.config, JSON.stringify({ ...cfg, setToolSearch: set }, null, 2));
214
+ // Under the settings lock (fix, cache-ttl, compact-window take it too), waiting briefly: a prompt is waiting.
215
+ withSettingsLock(paths.settings, () => {
216
+ const settings = readJson(paths.settings);
217
+ const env = settings.env;
218
+ if (!env || env.ANTHROPIC_BASE_URL !== proxyUrl(cfg.port))
219
+ return;
220
+ const set = keepToolSearch(env);
221
+ if (set)
222
+ writeJsonWithBackup(paths.settings, settings);
223
+ writeFileSync(paths.config, JSON.stringify({ ...cfg, setToolSearch: set }, null, 2));
224
+ }, 500);
221
225
  }
222
226
  catch {
223
227
  /* the self-heal must never disturb a prompt */
@@ -535,15 +539,19 @@ export async function autopilotOn(port = DEFAULT_AUTOPILOT_PORT, paths = autopil
535
539
  return { ok: false, lines: [`✗ The proxy did not come up on port ${port} (log: ${paths.log}). Nothing was changed in Claude Code's settings.`] };
536
540
  }
537
541
  lines.push(`✓ Proxy running with autopilot on ${proxyUrl(port)} (${how})`);
538
- const settings = readJson(paths.settings);
539
- const env = (settings.env ??= {});
540
- const previousBaseUrl = baseUrlToRestore(paths, port, env.ANTHROPIC_BASE_URL ?? null);
542
+ // Read and written under the settings lock fix, cache-ttl and compact-window take: no concurrent key is lost.
543
+ const { previousBaseUrl, setToolSearch } = withSettingsLock(paths.settings, () => {
544
+ const settings = readJson(paths.settings);
545
+ const env = (settings.env ??= {});
546
+ const previousBaseUrl = baseUrlToRestore(paths, port, env.ANTHROPIC_BASE_URL ?? null);
547
+ env.ANTHROPIC_BASE_URL = proxyUrl(port);
548
+ const setToolSearch = keepToolSearch(env);
549
+ writeJsonWithBackup(paths.settings, settings);
550
+ return { previousBaseUrl, setToolSearch };
551
+ });
541
552
  if (previousBaseUrl && previousBaseUrl !== proxyUrl(port)) {
542
553
  lines.push(`! settings.json already routed Claude Code to ${previousBaseUrl}; autopilot forwards to api.anthropic.com instead. \`autopilot off\` restores it.`);
543
554
  }
544
- env.ANTHROPIC_BASE_URL = proxyUrl(port);
545
- const setToolSearch = keepToolSearch(env);
546
- writeJsonWithBackup(paths.settings, settings);
547
555
  // Codex on an API key: its address is openai_base_url in config.toml.
548
556
  let codex = { routed: false };
549
557
  try {
@@ -569,13 +577,16 @@ export async function autopilotOn(port = DEFAULT_AUTOPILOT_PORT, paths = autopil
569
577
  export async function autopilotOff(paths = autopilotPaths(), exec = tryRun) {
570
578
  const lines = [];
571
579
  const cfg = readConfig(paths);
572
- const settings = readJson(paths.settings);
573
- const env = settings.env;
574
- // With the config damaged its port is unknown; the proxy URL in settings
575
- // must still go, or every new Claude Code session points at a proxy whose
576
- // service is being removed.
577
- const ours = env?.ANTHROPIC_BASE_URL ? isOurProxyUrl(env.ANTHROPIC_BASE_URL, cfg?.port, paths) : false;
578
- if (env && ours) {
580
+ // Read and written under the settings lock fix, cache-ttl and compact-window take.
581
+ const unrouted = withSettingsLock(paths.settings, () => {
582
+ const settings = readJson(paths.settings);
583
+ const env = settings.env;
584
+ // With the config damaged its port is unknown; the proxy URL in settings
585
+ // must still go, or every new Claude Code session points at a proxy whose
586
+ // service is being removed.
587
+ const ours = env?.ANTHROPIC_BASE_URL ? isOurProxyUrl(env.ANTHROPIC_BASE_URL, cfg?.port, paths) : false;
588
+ if (!env || !ours)
589
+ return false;
579
590
  const restore = cfg?.previousBaseUrl && !isOurProxyUrl(cfg.previousBaseUrl, cfg.port, paths) ? cfg.previousBaseUrl : undefined;
580
591
  if (restore)
581
592
  env.ANTHROPIC_BASE_URL = restore;
@@ -586,8 +597,10 @@ export async function autopilotOff(paths = autopilotPaths(), exec = tryRun) {
586
597
  if (Object.keys(env).length === 0)
587
598
  delete settings.env;
588
599
  writeJsonWithBackup(paths.settings, settings);
600
+ return true;
601
+ });
602
+ if (unrouted)
589
603
  lines.push("✓ Claude Code no longer routed through the proxy (new sessions)");
590
- }
591
604
  // Our address in Codex's config.toml goes too, whether or not we recorded it.
592
605
  try {
593
606
  if (unrouteCodex(homeOf(paths), isOurCodexUrl(cfg?.port, paths)))
@@ -682,7 +695,7 @@ export async function autopilotStatus(paths = autopilotPaths()) {
682
695
  * Called by the every-prompt hook: if autopilot is on and the proxy is down,
683
696
  * start it before the prompt's request goes out. Returns quickly either way.
684
697
  */
685
- export async function ensureProxyUp(paths = autopilotPaths(), exec = tryRun) {
698
+ export async function ensureProxyUp(paths = autopilotPaths(), exec = tryRun, healthMs = 300) {
686
699
  const cfg = readConfig(paths);
687
700
  if (!cfg)
688
701
  return;
@@ -696,7 +709,8 @@ export async function ensureProxyUp(paths = autopilotPaths(), exec = tryRun) {
696
709
  }
697
710
  catch { /* never fail a prompt over this */ }
698
711
  }
699
- const h = await health(cfg.port, 300);
712
+ // 300 ms: a prompt is waiting. (Tests that are not about a slow proxy pass more.)
713
+ const h = await health(cfg.port, healthMs);
700
714
  if (h.ok) {
701
715
  // A service keeps running the code it started with: after an update it
702
716
  // answers fine but is still the old version (seen: 0.25 serving for days
package/dist/budget.d.ts CHANGED
@@ -36,14 +36,21 @@ export interface Budget {
36
36
  export declare function budgetPath(): string;
37
37
  /** The period's spend ledger and what was said: ~/.claude/.context-doctor-budget-state.json. */
38
38
  export declare function budgetStatePath(): string;
39
- /** "50/day", "$200/week", "7.5/d", "100/wk": a budget, or an error to show. */
39
+ /**
40
+ * "50/day", "$200/week", "7.5/d", "100/wk", "50/days": a budget, or an
41
+ * error to show. Dollars are kept to the cent (50.555 was stored as given
42
+ * and shown as $50.55); `note` says so when the amount was rounded.
43
+ */
40
44
  export declare function parseBudget(arg: string): {
41
45
  usd: number;
42
46
  period: Period;
47
+ note?: string;
43
48
  } | {
44
49
  error: string;
45
50
  };
46
51
  export declare function readBudget(): Budget | undefined;
52
+ /** A whole file renamed into place, so two prompts at once never read half of one. */
53
+ export declare function writeWhole(path: string, value: unknown): void;
47
54
  export declare function writeBudget(b: Budget): void;
48
55
  /** Remove the budget and its ledger. True when there was one. */
49
56
  export declare function clearBudget(): boolean;
@@ -51,11 +58,56 @@ export declare function clearBudget(): boolean;
51
58
  export declare function periodStart(period: Period, now?: number): number;
52
59
  /** When the period holding `now` ends (the next one starts). */
53
60
  export declare function periodEnd(period: Period, now?: number): number;
61
+ /**
62
+ * One transcript as last read: size, time, inode; the period's requests in
63
+ * it as keys ("" for none) and dollars. A Claude Code transcript also keeps
64
+ * where reading stopped (`o`, after the last whole line) and its last
65
+ * replies (`r`: message id, index into k/d or -1, output so far, output
66
+ * price per 1M), so an append is read from there: a reply's later rows are
67
+ * met within its last few, and only settle its output. `a` fingerprints the
68
+ * bytes before `o` (the shared scan's anchorOf): a transcript rewritten in
69
+ * place, same inode and no smaller, is read again in full, not from `o`.
70
+ * `x` lists the requests on a model with no list price (index into k/d,
71
+ * model): in `d` at $0, and said so rather than silently left out.
72
+ */
73
+ export interface FileEntry {
74
+ t: Tool;
75
+ s: number;
76
+ m: number;
77
+ i: number;
78
+ k: string[];
79
+ d: number[];
80
+ o?: number;
81
+ a?: string;
82
+ r?: Array<[string, number, number, number]>;
83
+ x?: Array<[number, string]>;
84
+ }
85
+ /** A ledger entry this version can use: a damaged one threw on every prompt until its transcript changed. */
86
+ export declare function wellFormed(e: FileEntry | undefined): e is FileEntry;
87
+ /**
88
+ * One transcript's entry brought up to date: kept when the file is as last
89
+ * read, read from where the last read stopped when a Claude Code transcript
90
+ * only grew, read in full otherwise. `read`: the bytes read, -1 when the
91
+ * entry was kept as it was. Undefined when the file cannot be read now.
92
+ * `direct`: a Claude Code transcript met for the first time is read here,
93
+ * not through the shared scan, which keeps a cache entry of it on disk (the
94
+ * session price reads one session, and writes nothing while it has nothing
95
+ * to say).
96
+ */
97
+ export declare function refreshEntry(tool: Tool, file: string, prev: FileEntry | undefined, since: number, direct?: boolean): {
98
+ e: FileEntry;
99
+ read: number;
100
+ } | undefined;
54
101
  export interface PeriodSpend {
55
102
  start: number;
56
103
  end: number;
57
104
  usd: number;
58
105
  byTool: Partial<Record<Tool, number>>;
106
+ /** Requests on a model with no list price: counted here, not in `usd`. */
107
+ unpriced?: {
108
+ requests: number;
109
+ models: string[];
110
+ };
59
111
  }
60
112
  /**
61
113
  * What the period holding `now` has cost so far, across Claude Code, Codex
@@ -65,6 +117,7 @@ export interface PeriodSpend {
65
117
  */
66
118
  export declare function periodSpend(period: Period, now?: number, home?: string, warnAt?: (usd: number, warned: number) => number): PeriodSpend & {
67
119
  warn?: number;
120
+ unpricedNew?: boolean;
68
121
  };
69
122
  /** The thresholds the hook speaks at. */
70
123
  export declare const THRESHOLDS: readonly [50, 80, 100];