context-doctor 0.49.0 → 0.49.1

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
@@ -30,7 +30,7 @@ Pick where you work. Each takes about a minute and is fully reversible.
30
30
  | **claude.ai, ChatGPT, phone apps** | `npx context-doctor instructions --copy`, then paste into the app's personal preferences (it tells you where). ChatGPT can also reach the MCP server at a URL ([how](./docs/chat-apps.md#chatgpt)) |
31
31
  | **Your own app on an LLM API** | Run `npx context-doctor proxy --autopilot` and point `ANTHROPIC_BASE_URL`, `OPENAI_BASE_URL` (add `/v1`) or `GOOGLE_GEMINI_BASE_URL` at the proxy on `127.0.0.1:8787`, plain HTTP ([exact values](./docs/proxy.md)). No proxy possible? Wrap the SDK client: `withContextDoctor(new Anthropic())` ([library](./docs/library.md)) |
32
32
  | **Python / RAG pipelines** | `pip install "git+https://github.com/KushalP1/context-doctor#subdirectory=python"` (PyPI release coming), then `pack_documents(retrieved_docs, question, budget=4000)` trims LangChain or LlamaIndex results to the chunks that matter. [Python README](./python/README.md) |
33
- | **GitHub pull requests** | `uses: KushalP1/context-doctor@v0.49.0` comments how much a PR grows CLAUDE.md, AGENTS.md and rules, and can fail over a budget ([setup](./docs/ci.md)) |
33
+ | **GitHub pull requests** | `uses: KushalP1/context-doctor@v0.49.1` comments how much a PR grows CLAUDE.md, AGENTS.md and rules, and can fail over a budget ([setup](./docs/ci.md)) |
34
34
 
35
35
  ## What it does
36
36
 
@@ -136,7 +136,7 @@ Rules 1-4 end exactly at character 512, the part ChatGPT's guide says must stand
136
136
  |---|---|
137
137
  | `context-doctor install` / `uninstall` | Wire (or remove) everything it finds: the MCP server for Claude Desktop, Claude Code, Cursor, Codex, Gemini CLI, Google Antigravity and GitHub Copilot; the Agent Skill (Claude Code, Codex, Antigravity); the every-prompt hook (Claude Code, Codex, Gemini CLI's `BeforeAgent`, Cursor's `postToolUse`, `postToolUseFailure` and `sessionStart`); Claude Code's `PreCompact`, `SessionStart`, `PreToolUse` (the subagent price) and, on 2.1.251+, `PreModelSwitch` hooks; Copilot's `sessionStart` (the standing rules). `--statusline` adds the status bar line ([details](./docs/install.md)) |
138
138
  | `context-doctor fix [--apply ids\|all] [--share]` / `fix undo` | Every lever ranked by what it would have saved on your last 30 days (compact earlier, the cache lifetime, autopilot, MCP tool search, MCP servers set to load up front, 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)) |
139
- | `context-doctor spend [--days n] [--by repo\|branch] [--share] [--export]`, `spend merge <folder>` | One bill across every tool on this machine: Claude Code (main conversation and subagents), Codex, Gemini CLI, Cursor (an estimate: no cache split), Copilot CLI (with the AI credits it counted), OpenCode and Cline, by tool, project (or repository or branch), model and day; `--export` writes a file of totals (no prompt or path) and `spend merge` adds up a team's files, with a month-end forecast, with what drives it, and Claude Code's own figure (its `cost-state`) beside ours with what the gap is made of ([docs](./docs/spend.md)) |
139
+ | `context-doctor spend [--days n] [--by repo\|branch] [--share] [--export]`, `spend merge <folder>` | One bill across every tool on this machine: Claude Code (main conversation and subagents), Codex, Gemini CLI, Cursor (an estimate: no cache split), Copilot CLI (with the AI credits it counted), OpenCode and Cline, by tool, project (or repository or branch), model and day; `--export` writes a file of totals (no prompt or path) and `spend merge` adds up a team's files, with a month-end forecast, with what drives it, and Claude Code's own figure (its `cost-state`) beside ours with what the gap is made of: its side requests, prompt suggestions and requests that hung and were sent again, named; subagent output Claude Code 2.1.284-2.1.299 never settled in its rows, estimated from the content and counted ([docs](./docs/spend.md)) |
140
140
  | `context-doctor budget [<$>/day\|<$>/week [--block]\|off]` | A spend budget the every-prompt hook applies: a line at 50%, 80% and 100%, and with `--block` prompts over it are held until you raise it or turn it off ([docs](./docs/spend.md#a-budget-the-hook-applies-context-doctor-budget)) |
141
141
  | `context-doctor doctor` | Self-check the whole installation — one pasteable ✓/✗ diagnosis with fixes, including which surfaces autopilot can reach and any other program on its port |
142
142
  | `context-doctor savings [--days n] [--share [--copy]]` | What your recent Claude Code sessions cost, and what `/compact` at cold resumes, autopilot and an earlier auto-compact window would save, replayed through the shipped code against your actual billed usage. `--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 |
@@ -183,6 +183,7 @@ Rules 1-4 end exactly at character 512, the part ChatGPT's guide says must stand
183
183
 
184
184
  ## What's new
185
185
 
186
+ - **0.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)).
186
187
  - **0.49 Count what Claude Code counts, cold returns, limits you can paste, a Desktop usage pane, and teams**: `spend` and `doctor` show Claude Code's own cost (its `cost-state`) beside ours, 2% apart on the author's 30 days, and count the advisor's calls and replies a server-side fallback replaced. `cache-misses` replays every return after the cache expired three ways (as billed, compacted, kept warm) by time away (the author's: $894 in 183 returns), and the mod's `/context-doctor-keep-warm` keeps it warm on request only, capped in hours and dollars. `overhead` prices every session's and subagent's start ($455 a month here) and `fix` gains `mcp-defer`. `limits` gives dollars per 1% per weekly reset with the moves dated, `limits --report` a block for a bug report, and handles Ultra (no 5-hour window). `/context-doctor-usage` is a usage pane in the Desktop app. `spend` reads Copilot CLI, OpenCode and Cline, splits `--by repo|branch`, and `--export` / `spend merge` add up a team's totals with no prompt or path ([details](./ROADMAP.md#shipped-in-0490-count-what-claude-code-counts-cold-returns-limits-you-can-paste-a-desktop-usage-pane-and-teams)).
187
188
  - **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)).
188
189
  - **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)).
@@ -214,7 +215,7 @@ Every release, with the details: [docs/whats-new.md](./docs/whats-new.md).
214
215
  - [Library](./docs/library.md): `profileConversation`, `optimizeConversation`, `packContext`, `withContextDoctor`
215
216
  - [Budgets and CI](./docs/ci.md): the GitHub Action and `.contextdoctorrc`
216
217
  - [Privacy](./docs/privacy.md) and [the directory submission](./docs/directory-submission.md): what the plugin reads, writes and sends; the package for Anthropic's plugin directory
217
- - [Desktop app and VS Code](./docs/desktop.md): the plugin's mod: limit readings, Claude Code's own cost, `/context-doctor-fix`, `/context-doctor-usage` (the context ring, limit windows, tokens and dollars by model, running subagents) and `/context-doctor-keep-warm` (Desktop app, VS Code, terminal), and the cache band with Compact first (Desktop app and terminal only)
218
+ - [Desktop app and VS Code](./docs/desktop.md): the plugin's mod: limit readings, Claude Code's own cost, `/context-doctor-fix`, `/context-doctor-usage` (the context ring, limit windows, tokens and dollars by model, running subagents) and `/context-doctor-keep-warm` (Desktop app, VS Code, terminal), and an optional cache band with Compact first (`CONTEXT_DOCTOR_MOD_BAND=cold`; Desktop app and terminal only)
218
219
  - [Editor and status line](./docs/editor-and-statusline.md): the VS Code / Cursor extension and Claude Code's status bar
219
220
  - [Token counts](./docs/tokenizer.md): why counts are "~", how the Claude ratios were measured, exact counts
220
221
  - [Performance](./docs/performance.md): what context-doctor itself costs (its six MCP tool definitions: at most ~2,344 tokens)
package/dist/ccost.d.ts CHANGED
@@ -109,6 +109,21 @@ export interface SessionGap {
109
109
  /** Of ours: the compactions' own requests, which we estimate (no row records their usage). */
110
110
  compactionUsd: number;
111
111
  compactions: number;
112
+ /**
113
+ * The main-thread turns that ended where Claude Code may send a prompt
114
+ * suggestion (sidecost.ts), and what one after each would cost: not in
115
+ * ours, since whether it was sent is in no file (gapText takes the count
116
+ * from Claude Code's own input tokens).
117
+ */
118
+ turnEnds?: {
119
+ n: number;
120
+ usd: number;
121
+ };
122
+ /** Of ours: subagent replies whose rows never settled their output, estimated from their content (sidecost.ts). */
123
+ unsettledUsd?: number;
124
+ unsettled?: number;
125
+ /** Requests that hung and Claude Code sent again (stalledRetries): billed when the API had begun them, and in no row. */
126
+ stalled?: number;
112
127
  version?: string;
113
128
  unknown?: true;
114
129
  models: ModelGap[];
@@ -130,6 +145,26 @@ export interface GapParts {
130
145
  }
131
146
  /** The parts of the gap of one or more sessions (see GapParts). */
132
147
  export declare function gapParts(sessions: SessionGap[]): GapParts;
148
+ /** The turns of a main transcript's rows that ended where Claude Code may send a prompt suggestion, within [`from`, `to`], and their price (sidecost.ts). */
149
+ export declare function turnEnds(rows: unknown[], from: number, to: number): {
150
+ n: number;
151
+ usd: number;
152
+ };
153
+ /** A request no reply answers, sent again unchanged this long after or later: it hung. */
154
+ export declare const HUNG_MS = 60000;
155
+ /**
156
+ * Requests that hung: Claude Code sent one (an `api-request` row, 2.1.308+),
157
+ * no reply answers it, and Claude Code sent it again unchanged (a row whose
158
+ * `base` is it, with no new messages) a minute or more later, with no error
159
+ * between saying it never left the machine. On the author's machine they
160
+ * come in runs while the network is down or the machine sleeps (a subagent
161
+ * sent the same 380k-token prompt every ~16 minutes through a night), and
162
+ * the two stretches between Claude Code's cost-state records that hold most
163
+ * of them hold most of the gap: Claude Code bills a request the API had
164
+ * begun, and no row records its usage. Which ones the API had begun is in
165
+ * no file, so they are counted, not priced. Within [`from`, `to`].
166
+ */
167
+ export declare function stalledRetries(files: string[], from: number, to: number): number;
133
168
  /**
134
169
  * The comparison for the sessions among `tops` whose Claude Code record and
135
170
  * our requests both fall inside [`since`, `until`]: `items` are spend's
package/dist/ccost.js CHANGED
@@ -32,6 +32,8 @@ import { requestCost } from "./pricing.js";
32
32
  import { realModel } from "./tokens.js";
33
33
  import { rowsOf } from "./scan.js";
34
34
  import { USAGE_ROWS } from "./limits.js";
35
+ import { subagentFiles } from "./subagents.js";
36
+ import { SUGGESTION_PROMPT_TOKENS, suggestionCost } from "./sidecost.js";
35
37
  const num = (v) => (typeof v === "number" && Number.isFinite(v) && v > 0 ? v : 0);
36
38
  /** A `cost-state` row, kept as numbers; undefined when it is not one. */
37
39
  export function costStateRecord(e, version) {
@@ -143,6 +145,68 @@ function atOurPrices(model, m, at, writePerToken) {
143
145
  return 0;
144
146
  return c.totalUsd - c.modifiers.longUsd + (writePerToken === undefined ? 0 : rest * writePerToken);
145
147
  }
148
+ /** The turns of a main transcript's rows that ended where Claude Code may send a prompt suggestion, within [`from`, `to`], and their price (sidecost.ts). */
149
+ export function turnEnds(rows, from, to) {
150
+ let n = 0, usd = 0;
151
+ for (const r of rows) {
152
+ const ts = Date.parse(String(r?.timestamp ?? ""));
153
+ if (!(ts >= from && ts <= to))
154
+ continue;
155
+ const c = suggestionCost(r);
156
+ if (c) {
157
+ n++;
158
+ usd += c.cost.totalUsd;
159
+ }
160
+ }
161
+ return { n, usd };
162
+ }
163
+ /** A connection error that means the request never reached the API (not billed). */
164
+ const UNSENT = /^(ENOTFOUND|EAI_AGAIN|ECONNREFUSED|ENETUNREACH|EHOSTUNREACH)$/;
165
+ /** A request no reply answers, sent again unchanged this long after or later: it hung. */
166
+ export const HUNG_MS = 60_000;
167
+ /**
168
+ * Requests that hung: Claude Code sent one (an `api-request` row, 2.1.308+),
169
+ * no reply answers it, and Claude Code sent it again unchanged (a row whose
170
+ * `base` is it, with no new messages) a minute or more later, with no error
171
+ * between saying it never left the machine. On the author's machine they
172
+ * come in runs while the network is down or the machine sleeps (a subagent
173
+ * sent the same 380k-token prompt every ~16 minutes through a night), and
174
+ * the two stretches between Claude Code's cost-state records that hold most
175
+ * of them hold most of the gap: Claude Code bills a request the API had
176
+ * begun, and no row records its usage. Which ones the API had begun is in
177
+ * no file, so they are counted, not priced. Within [`from`, `to`].
178
+ */
179
+ export function stalledRetries(files, from, to) {
180
+ let n = 0;
181
+ for (const f of files) {
182
+ let rows;
183
+ try {
184
+ rows = rowsOf(f, USAGE_ROWS);
185
+ }
186
+ catch {
187
+ continue;
188
+ }
189
+ const answered = new Set();
190
+ for (const r of rows)
191
+ if (r?.type === "assistant" && typeof r.requestRef === "string")
192
+ answered.add(r.requestRef);
193
+ let pending;
194
+ for (const r of rows) {
195
+ if (r?.type === "system" && r.subtype === "api_error") {
196
+ if (pending && UNSENT.test(String(r.code ?? "")))
197
+ pending.unsent = true;
198
+ continue;
199
+ }
200
+ if (r?.type !== "api-request")
201
+ continue;
202
+ const at = Date.parse(String(r.timestamp ?? ""));
203
+ if (pending && r.base === pending.id && r.t === 0 && !pending.unsent && at - pending.at >= HUNG_MS && pending.at >= from && pending.at <= to)
204
+ n++;
205
+ pending = typeof r.id === "string" && !answered.has(r.id) && Number.isFinite(at) ? { id: r.id, at, unsent: false } : undefined;
206
+ }
207
+ }
208
+ return n;
209
+ }
146
210
  /**
147
211
  * The comparison for the sessions among `tops` whose Claude Code record and
148
212
  * our requests both fall inside [`since`, `until`]: `items` are spend's
@@ -173,7 +237,14 @@ export function compareSessions(tops, items, since = -Infinity, until = Infinity
173
237
  continue;
174
238
  const session = basename(top, ".jsonl");
175
239
  const mine = (bySession.get(session) ?? []).filter((it) => it.ts >= start - 1000 && it.ts <= rec.to);
176
- out.push(sessionGap(session, rec.cs, mine, start, rec.to, rec.declined));
240
+ const g = sessionGap(session, rec.cs, mine, start, rec.to, rec.declined);
241
+ const stalled = stalledRetries([top, ...subagentFiles(top).map((f) => f.file)], start - 1000, rec.to);
242
+ if (stalled)
243
+ g.stalled = stalled;
244
+ const ends = turnEnds(rowsOf(top, USAGE_ROWS), start - 1000, rec.to);
245
+ if (ends.n)
246
+ g.turnEnds = ends;
247
+ out.push(g);
177
248
  }
178
249
  return out.sort((a, b) => b.ccUsd - a.ccUsd);
179
250
  }
@@ -181,7 +252,7 @@ export function compareSessions(tops, items, since = -Infinity, until = Infinity
181
252
  export function sessionGap(session, cs, mine, from, to, declined = {}) {
182
253
  const models = new Map();
183
254
  const line = (model) => models.get(model) ?? models.set(model, { model, ccUsd: 0, cc: { input: 0, output: 0, read: 0, write: 0, searches: 0 }, ourUsd: 0, ours: { input: 0, output: 0, read: 0, write: 0, requests: 0 }, ccAtOurUsd: 0 }).get(model);
184
- let compactionUsd = 0, compactions = 0;
255
+ let compactionUsd = 0, compactions = 0, unsettledUsd = 0, unsettled = 0;
185
256
  const writeUsd = new Map();
186
257
  for (const it of mine) {
187
258
  const g = line(it.model ?? "unknown");
@@ -196,6 +267,10 @@ export function sessionGap(session, cs, mine, from, to, declined = {}) {
196
267
  compactionUsd += it.usd;
197
268
  compactions++;
198
269
  }
270
+ if (it.unsettled && it.output > 0) {
271
+ unsettledUsd += (it.outputUsd * it.unsettled) / it.output;
272
+ unsettled++;
273
+ }
199
274
  }
200
275
  for (const [model, m] of Object.entries(cs.models)) {
201
276
  const g = line(realModel(model) ?? model);
@@ -214,6 +289,7 @@ export function sessionGap(session, cs, mine, from, to, declined = {}) {
214
289
  }
215
290
  return {
216
291
  session, ...(mine[0]?.project ? { project: mine[0].project } : {}), from, to, ccUsd: cs.usd, ourUsd: mine.reduce((n, it) => n + it.usd, 0), compactionUsd, compactions,
292
+ ...(unsettled ? { unsettledUsd, unsettled } : {}),
217
293
  ...(cs.version ? { version: cs.version } : {}), ...(cs.unknown ? { unknown: true } : {}),
218
294
  models: [...models.values()].sort((a, b) => b.ccUsd - a.ccUsd),
219
295
  };
@@ -248,10 +324,30 @@ export function gapText(sessions) {
248
324
  if (Math.abs(p.sideUsd) >= 0.005)
249
325
  parts.push([p.sideUsd, `Claude Code counts ${more(p.sideUsd)} on ${list(p.sideModels)}, its own side requests${p.sideSearches ? ` (${p.sideSearches} web search${p.sideSearches === 1 ? "" : "es"} among them)` : ""}: no transcript row records them`]);
250
326
  // Ours holds the compactions' own requests as estimates (no row records their usage): what its tokens say of them.
251
- const compText = nComp ? `${nComp} compaction${nComp === 1 ? "'s" : "s'"} own request${nComp === 1 ? "" : "s"}, which we estimate at ${usd(comp)}` : "";
327
+ // Claude Code's prompt suggestions: as many as its input beyond ours on the session's models has room for (each adds its
328
+ // ~506-token instruction), priced as the turn ends they may follow are on average (sidecost.ts). An estimate of a part of the gap.
329
+ let nSug = 0, sug = 0;
330
+ for (const s of sessions) {
331
+ const ends = s.turnEnds;
332
+ if (!ends?.n)
333
+ continue;
334
+ const room = Math.round(s.models.filter((m) => m.ours.requests > 0).reduce((t, m) => t + Math.max(0, m.cc.input - m.ours.input), 0) / SUGGESTION_PROMPT_TOKENS);
335
+ const k = Math.min(ends.n, room);
336
+ nSug += k;
337
+ sug += (ends.usd * k) / ends.n;
338
+ }
339
+ const nUns = sessions.reduce((n, s) => n + (s.unsettled ?? 0), 0), uns = sessions.reduce((n, s) => n + (s.unsettledUsd ?? 0), 0);
340
+ const stalled = sessions.reduce((n, s) => n + (s.stalled ?? 0), 0);
341
+ const ests = [
342
+ nComp ? `${nComp} compaction${nComp === 1 ? "'s" : "s'"} own request${nComp === 1 ? "" : "s"} (${usd(comp)})` : "",
343
+ nUns ? `the output of ${nUns.toLocaleString("en-US")} subagent repl${nUns === 1 ? "y" : "ies"} whose rows never settled it (${usd(uns)})` : "",
344
+ ].filter(Boolean);
345
+ const compText = ests.length ? `${ests.length > 1 ? `${ests.slice(0, -1).join(", ")} and ${ests[ests.length - 1]}` : ests[0]}, which we estimate` : "";
346
+ const sugText = nSug ? `; about ${nSug.toLocaleString("en-US")} of them Claude Code's prompt suggestions (the line it suggests after a turn, reading the conversation from the cache; counted by the ${SUGGESTION_PROMPT_TOKENS} input tokens each adds), about ${usd(sug)}` : "";
347
+ const hung = stalled ? `; ${stalled.toLocaleString("en-US")} request${stalled === 1 ? "" : "s"} hung and ${stalled === 1 ? "was" : "were"} sent again (no reply, retried a minute or more later, most while the network was down): Claude Code bills those the API had begun, and no file says which` : "";
252
348
  if (Math.abs(p.tokensUsd) >= 0.005) {
253
349
  parts.push([p.tokensUsd, p.tokensUsd > 0
254
- ? `Claude Code counts ${more(p.tokensUsd)} in tokens on the same models, at our prices: requests no row records the usage of${compText ? `, beyond our ${compText}` : ""}`
350
+ ? `Claude Code counts ${more(p.tokensUsd)} in tokens on the same models, at our prices: requests no row records the usage of${compText ? `, beyond our ${compText}` : ""}${sugText}${hung}`
255
351
  : `Claude Code counts ${more(p.tokensUsd)} in tokens on the same models, at our prices: ${compText ? `our ${compText}, are above what it counted` : "requests we count that it does not"}`]);
256
352
  }
257
353
  if (Math.abs(p.priceUsd) >= 0.005)
package/dist/install.js CHANGED
@@ -1194,7 +1194,7 @@ function routeClaudeCode(route, attempt) {
1194
1194
  ? `✓ Claude Code: the context-doctor plugin enabled (${tilde(settingsPath)}: extraKnownMarketplaces, enabledPlugins), in place of install's own MCP server, skill and hooks`
1195
1195
  : "✓ Claude Code: the context-doctor plugin already enabled, unchanged");
1196
1196
  console.log(` ${describeInstalls(route.readiness.installs)} ${route.readiness.installs.length === 1 ? "runs" : "run"} its mod: limit readings and Claude Code's own session cost after each turn,`);
1197
- console.log(" the Compact first button on a cold return, /context-doctor-fix; and the MCP server, skills and hooks install used to add itself.");
1197
+ console.log(" /context-doctor-fix, /context-doctor-usage (a Compact first band with CONTEXT_DOCTOR_MOD_BAND=cold); and the MCP server, skills and hooks install used to add itself.");
1198
1198
  if (pluginStage().stage !== "installed") {
1199
1199
  console.log(" Claude Code downloads it in the background at its next start and loads it from the session after (or at once: /reload-plugins).");
1200
1200
  }
package/dist/limits.d.ts CHANGED
@@ -132,7 +132,15 @@ export declare function codexLimitData(since: number, root?: string): {
132
132
  * kept only where some bill beyond its top-level usage (extraIterations).
133
133
  * Also Claude Code's own running cost: each `cost-state` row as
134
134
  * costStateRecord keeps it, with the Claude Code version of the replies
135
- * before it (ccost.ts compares it with ours).
135
+ * before it (ccost.ts compares it with ours). A reply row keeps its
136
+ * `stop_reason` and `entrypoint` (a prompt suggestion follows a main-thread
137
+ * turn's end, sidecost.ts) and, where it has no `stop_reason`, its content
138
+ * as output tokens (`oc`: what a reply whose rows never settled cost,
139
+ * sidecost.ts). Each `api-request` row (what Claude Code sent, 2.1.308+) as
140
+ * its id, the request it repeats or extends and the time, a reply's
141
+ * `requestRef` to it, and an `api_error` row's code: a request no reply
142
+ * answers and Claude Code sent again a minute or more later is one that hung
143
+ * (ccost.ts names them).
136
144
  */
137
145
  export declare const USAGE_ROWS: Extractor<{
138
146
  ids: Record<string, 1>;
@@ -160,6 +168,8 @@ export interface ClaudeRequest extends UsagePoint {
160
168
  changedOn?: string;
161
169
  /** A compaction's own request, which no row records usage for: estimated (compactcost.ts). */
162
170
  compaction?: boolean;
171
+ /** Output tokens estimated from the reply's content, inside `output` and `usd`: its rows never settled it (sidecost.ts). */
172
+ unsettled?: number;
163
173
  /**
164
174
  * The iterations its top-level usage leaves out (extraIterations: an
165
175
  * advisor's call, an attempt a fallback replaced), each priced at its own
package/dist/limits.js CHANGED
@@ -43,6 +43,7 @@ import { addModifiers, extraIterations, isUnbilledModel, NO_MODIFIERS, openAIUsa
43
43
  import { realModel } from "./tokens.js";
44
44
  import { isCompactionRow, newTrack, slimSummary, trackCompaction } from "./compactcost.js";
45
45
  import { PROXY_VERSION } from "./proxy.js";
46
+ import { contentOutputTokens, unsettledVersion } from "./sidecost.js";
46
47
  const MIN = 60_000;
47
48
  const HOUR = 60 * MIN;
48
49
  const DAY = 24 * HOUR;
@@ -372,16 +373,26 @@ export function codexLimitData(since, root = codexSessionsRoot()) {
372
373
  * kept only where some bill beyond its top-level usage (extraIterations).
373
374
  * Also Claude Code's own running cost: each `cost-state` row as
374
375
  * costStateRecord keeps it, with the Claude Code version of the replies
375
- * before it (ccost.ts compares it with ours).
376
+ * before it (ccost.ts compares it with ours). A reply row keeps its
377
+ * `stop_reason` and `entrypoint` (a prompt suggestion follows a main-thread
378
+ * turn's end, sidecost.ts) and, where it has no `stop_reason`, its content
379
+ * as output tokens (`oc`: what a reply whose rows never settled cost,
380
+ * sidecost.ts). Each `api-request` row (what Claude Code sent, 2.1.308+) as
381
+ * its id, the request it repeats or extends and the time, a reply's
382
+ * `requestRef` to it, and an `api_error` row's code: a request no reply
383
+ * answers and Claude Code sent again a minute or more later is one that hung
384
+ * (ccost.ts names them).
376
385
  */
377
386
  export const USAGE_ROWS = {
378
- id: "usage.5",
387
+ id: "usage.6",
379
388
  init: () => ({ ids: {} }),
380
389
  line(line, row, out, st) {
381
390
  const compaction = isCompactionRow(line);
382
391
  const cost = !compaction && line.startsWith('{"type":"cost-state"');
383
392
  const refusal = !compaction && !cost && line.includes('"model_refusal_fallback"');
384
- if (!compaction && !cost && !refusal && !line.includes('"usage"'))
393
+ const sent = !compaction && !cost && line.startsWith('{"type":"api-request",');
394
+ const failed = !compaction && !cost && !sent && line.includes('"subtype":"api_error"');
395
+ if (!compaction && !cost && !refusal && !sent && !failed && !line.includes('"usage"'))
385
396
  return;
386
397
  let e;
387
398
  try {
@@ -390,6 +401,16 @@ export const USAGE_ROWS = {
390
401
  catch {
391
402
  return;
392
403
  }
404
+ if (sent) {
405
+ if (e?.type === "api-request" && typeof e.id === "string")
406
+ out.push({ type: "api-request", id: e.id, ...(typeof e.base === "string" ? { base: e.base } : {}), t: Array.isArray(e.tail) ? e.tail.length : 0, timestamp: e.timestamp });
407
+ return;
408
+ }
409
+ if (failed) {
410
+ if (e?.type === "system" && e.subtype === "api_error")
411
+ out.push({ type: "system", subtype: "api_error", timestamp: e.timestamp, code: String(e.error?.connection?.code ?? e.error?.status ?? "").slice(0, 40) });
412
+ return;
413
+ }
393
414
  if (cost || refusal) {
394
415
  const r = cost ? costStateRecord(e, st.v) : refusalRecord(e);
395
416
  if (r)
@@ -415,14 +436,23 @@ export const USAGE_ROWS = {
415
436
  if (st.ids[m.id]) {
416
437
  // Its billed iterations too: a streamed reply may settle those on a later row as well.
417
438
  const its = slimUsage(m.usage, { iterations: true });
418
- out.push({ type: "assistant", message: { id: m.id, usage: { ...pick(m.usage, ["output_tokens"]), ...(its?.iterations ? { iterations: its.iterations } : {}) } } });
439
+ out.push({ type: "assistant", message: { id: m.id, usage: { ...pick(m.usage, ["output_tokens"]), ...(its?.iterations ? { iterations: its.iterations } : {}) }, ...settling(m, e.version) } });
419
440
  return;
420
441
  }
421
442
  st.ids[m.id] = 1;
422
443
  }
423
- out.push(pick({ ...e, isSidechain: e.isSidechain === true || undefined, message: pick({ ...m, usage: slimUsage(m.usage, { iterations: true }) }, ["id", "model", "usage"]) }, ["type", "uuid", "timestamp", "isSidechain", "message"]));
444
+ out.push(pick({ ...e, isSidechain: e.isSidechain === true || undefined, message: { ...pick({ ...m, usage: slimUsage(m.usage, { iterations: true }) }, ["id", "model", "usage"]), ...settling(m, e.version) } }, ["type", "uuid", "timestamp", "isSidechain", "entrypoint", "requestRef", "message"]));
424
445
  },
425
446
  };
447
+ /** A reply row's `stop_reason`, or (none, from a Claude Code that left replies unsettled: unsettledVersion) its content as output tokens. */
448
+ function settling(m, version) {
449
+ if (typeof m.stop_reason === "string" && m.stop_reason)
450
+ return { stop_reason: m.stop_reason.slice(0, 40) };
451
+ if (!unsettledVersion(version))
452
+ return {};
453
+ const oc = contentOutputTokens(m.content);
454
+ return oc > 0 ? { oc } : {};
455
+ }
426
456
  /** A compaction's estimated request as a request point (no message id: its key is the boundary's uuid). */
427
457
  export function compactionPoint(c) {
428
458
  const u = c.usage;
@@ -476,6 +506,8 @@ export function claudeFileUsage(file, since, until = Infinity, runRows) {
476
506
  const sighting = replyCounter(runRows);
477
507
  const settle = outputSettler();
478
508
  const byId = new Map();
509
+ // Per reply: whether a row of it settled (has a stop_reason), and what its rows' content took to write (sidecost.ts).
510
+ const settled = new Map();
479
511
  const track = newTrack();
480
512
  rowsOf(file, USAGE_ROWS).forEach((e) => {
481
513
  const done = trackCompaction(track, e);
@@ -484,6 +516,12 @@ export function claudeFileUsage(file, since, until = Infinity, runRows) {
484
516
  const m = e?.message;
485
517
  if (e?.type !== "assistant" || !m?.usage)
486
518
  return;
519
+ if (typeof m.id === "string") {
520
+ const s = settled.get(m.id) ?? settled.set(m.id, { stop: false, oc: 0 }).get(m.id);
521
+ if (m.stop_reason)
522
+ s.stop = true;
523
+ s.oc += typeof m.oc === "number" ? m.oc : 0;
524
+ }
487
525
  const seen = sighting(e);
488
526
  if (seen === "repeat") {
489
527
  const known = typeof m.id === "string" ? byId.get(m.id) : undefined;
@@ -547,6 +585,23 @@ export function claudeFileUsage(file, since, until = Infinity, runRows) {
547
585
  if (typeof m.id === "string")
548
586
  byId.set(m.id, { point, u });
549
587
  });
588
+ // A reply none of whose rows settled (Claude Code 2.1.284-2.1.299's subagents): its output from its content, where that is more.
589
+ for (const [id, s] of settled) {
590
+ const known = byId.get(id);
591
+ if (s.stop || !known || s.oc <= known.point.output)
592
+ continue;
593
+ const p = known.point, more = s.oc - p.output;
594
+ p.output += more;
595
+ p.unsettled = more;
596
+ if (p.rates) {
597
+ p.usd += (more * p.rates.outputPerM) / 1e6;
598
+ if (p.modifiers.fastUsd || p.modifiers.geoUsd || p.modifiers.longUsd) {
599
+ p.modifiers = { ...requestCost(p.model, { ...known.u, output_tokens: p.output }, p.ts).modifiers };
600
+ for (const x of p.extra ?? [])
601
+ addModifiers(p.modifiers, x.modifiers);
602
+ }
603
+ }
604
+ }
550
605
  return out;
551
606
  }
552
607
  /**