context-doctor 0.44.0 → 0.46.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 +5 -2
- package/dist/budget.d.ts +14 -1
- package/dist/budget.js +50 -28
- package/dist/cache.js +5 -4
- package/dist/cachemisses.js +6 -4
- package/dist/cacheplan.js +2 -2
- package/dist/cachettl.js +8 -5
- package/dist/ci.js +18 -2
- package/dist/cli.js +27 -6
- package/dist/codexcompact.js +14 -7
- package/dist/coldresume.d.ts +6 -0
- package/dist/coldresume.js +20 -11
- package/dist/compactwindow.js +14 -8
- package/dist/doctor.js +26 -2
- package/dist/extract.d.ts +2 -2
- package/dist/extract.js +14 -3
- package/dist/fanout.js +1 -1
- package/dist/fix.js +14 -10
- package/dist/hook.js +6 -2
- package/dist/httpguard.d.ts +9 -1
- package/dist/httpguard.js +5 -4
- package/dist/lens.js +7 -7
- package/dist/limits.d.ts +14 -5
- package/dist/limits.js +26 -17
- package/dist/mcp.js +62 -62
- package/dist/mcpschema.js +5 -3
- package/dist/mod/api.d.ts +129 -0
- package/dist/mod/api.js +12 -0
- package/dist/mod/logic.d.ts +146 -0
- package/dist/mod/logic.js +222 -0
- package/dist/mod/register.d.ts +58 -0
- package/dist/mod/register.js +237 -0
- package/dist/modelids.d.ts +23 -0
- package/dist/modelids.js +49 -0
- package/dist/modmeasure.d.ts +121 -0
- package/dist/modmeasure.js +298 -0
- package/dist/orgrates.d.ts +75 -0
- package/dist/orgrates.js +165 -0
- package/dist/overhead.js +11 -8
- package/dist/pack.js +95 -22
- package/dist/pricing.d.ts +123 -6
- package/dist/pricing.js +236 -62
- package/dist/proxy.d.ts +12 -1
- package/dist/proxy.js +13 -1
- package/dist/prune.js +55 -3
- package/dist/savings.js +19 -10
- package/dist/scan.d.ts +7 -1
- package/dist/scan.js +19 -1
- package/dist/sessionprice.d.ts +25 -2
- package/dist/sessionprice.js +60 -20
- package/dist/spend.d.ts +62 -10
- package/dist/spend.js +255 -29
- package/dist/statusline.d.ts +10 -2
- package/dist/statusline.js +18 -9
- package/dist/subagentmodel.d.ts +2 -2
- package/dist/subagentmodel.js +31 -24
- package/dist/subagentpay.d.ts +7 -1
- package/dist/subagentpay.js +51 -25
- package/dist/subagents.js +15 -10
- package/dist/tasks.js +9 -6
- package/dist/tooloutput.js +14 -5
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -28,12 +28,12 @@ Pick where you work. Each takes about a minute and is fully reversible.
|
|
|
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.
|
|
31
|
+
| **GitHub pull requests** | `uses: KushalP1/context-doctor@v0.46.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
|
|
|
35
35
|
**Measure, in dollars, on your own history** ([profiling](./docs/profiling.md))
|
|
36
|
-
- `spend`: one bill across Claude Code (subagents and workflow agents included), Codex, Gemini CLI and Cursor, by tool, project, model and day, at list
|
|
36
|
+
- `spend`: one bill across Claude Code (subagents and workflow agents included), Codex, Gemini CLI and Cursor, by tool, project, model and day, as billed at list rates ([spend and budget](./docs/spend.md)).
|
|
37
37
|
- `savings`: what your recent Claude Code sessions cost and what each fix below would have saved, replayed request by request against what you were billed.
|
|
38
38
|
- `overhead`: what every request re-reads before your message (system prompt, tools, MCP servers, CLAUDE.md, rules, memory), each file priced per month.
|
|
39
39
|
- `tasks`, `reads`, `subagents`, `compactions`: cost per commit; files read into session after session; whether each subagent was cheaper than the same steps in the parent; whether sessions work worse after compacting.
|
|
@@ -181,6 +181,8 @@ Rules 1-4 end exactly at character 512, the part ChatGPT's guide says must stand
|
|
|
181
181
|
|
|
182
182
|
## What's new
|
|
183
183
|
|
|
184
|
+
- **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, a cache-expiry band with **Compact first**, and `/context-doctor-fix` with Apply and Undo buttons to the Desktop app and VS Code ([Desktop](./docs/desktop.md), [details](./ROADMAP.md#shipped-in-0460-fable-52-the-desktop-app-and-an-audit-of-045)).
|
|
185
|
+
- **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)).
|
|
184
186
|
- **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)).
|
|
185
187
|
- **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).
|
|
186
188
|
- **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)).
|
|
@@ -206,6 +208,7 @@ Every release, with the details: [docs/whats-new.md](./docs/whats-new.md).
|
|
|
206
208
|
- [Detectors and fixes](./docs/detectors.md): what the profiler finds and what each optimizer strategy changes
|
|
207
209
|
- [Library](./docs/library.md): `profileConversation`, `optimizeConversation`, `packContext`, `withContextDoctor`
|
|
208
210
|
- [Budgets and CI](./docs/ci.md): the GitHub Action and `.contextdoctorrc`
|
|
211
|
+
- [Desktop app and VS Code](./docs/desktop.md): the plugin's mod: limit readings, Claude Code's own cost, the cache band with Compact first, and `/context-doctor-fix`
|
|
209
212
|
- [Editor and status line](./docs/editor-and-statusline.md): the VS Code / Cursor extension and Claude Code's status bar
|
|
210
213
|
- [Token counts](./docs/tokenizer.md): why counts are "~", how the Claude ratios were measured, exact counts
|
|
211
214
|
- [Performance](./docs/performance.md): what context-doctor itself costs (its six MCP tool definitions: at most ~2,344 tokens)
|
package/dist/budget.d.ts
CHANGED
|
@@ -69,7 +69,12 @@ export declare function periodEnd(period: Period, now?: number): number;
|
|
|
69
69
|
* place, same inode and no smaller, is read again in full, not from `o`.
|
|
70
70
|
* `x` lists the requests on a model with no list price (index into k/d,
|
|
71
71
|
* model): in `d` at $0, and said so rather than silently left out. `y`
|
|
72
|
-
* lists those priced only by their model's family (an estimate), the same
|
|
72
|
+
* lists those priced only by their model's family (an estimate), the same
|
|
73
|
+
* way; `z` those priced past the day their model's price changed (index,
|
|
74
|
+
* model, the day). `d` is requestCost's: each request's tier, fast mode,
|
|
75
|
+
* US-only and web searches, and the output price in `r` is its own. `p`
|
|
76
|
+
* fingerprints the organization's rates `d` was priced at (orgrates.ts;
|
|
77
|
+
* absent at list prices): an entry priced under other rates is read again.
|
|
73
78
|
*/
|
|
74
79
|
export interface FileEntry {
|
|
75
80
|
t: Tool;
|
|
@@ -83,6 +88,8 @@ export interface FileEntry {
|
|
|
83
88
|
r?: Array<[string, number, number, number]>;
|
|
84
89
|
x?: Array<[number, string]>;
|
|
85
90
|
y?: Array<[number, string]>;
|
|
91
|
+
z?: Array<[number, string, string]>;
|
|
92
|
+
p?: string;
|
|
86
93
|
}
|
|
87
94
|
/** A ledger entry this version can use: a damaged one threw on every prompt until its transcript changed. */
|
|
88
95
|
export declare function wellFormed(e: FileEntry | undefined): e is FileEntry;
|
|
@@ -118,6 +125,12 @@ export interface PeriodSpend {
|
|
|
118
125
|
usd: number;
|
|
119
126
|
models: string[];
|
|
120
127
|
};
|
|
128
|
+
/** Requests priced past the day their model's price changed (model, day): in `usd`, an estimate. */
|
|
129
|
+
changed?: {
|
|
130
|
+
requests: number;
|
|
131
|
+
usd: number;
|
|
132
|
+
models: Array<[string, string]>;
|
|
133
|
+
};
|
|
121
134
|
}
|
|
122
135
|
/**
|
|
123
136
|
* What the period holding `now` has cost so far, across Claude Code, Codex
|
package/dist/budget.js
CHANGED
|
@@ -32,7 +32,8 @@ import { claudeCodePresent, claudeDir } from "./claudedir.js";
|
|
|
32
32
|
import { claudeFileUsage, codexSessionsRoot, rolloutFiles, SUBAGENT_LOOKBACK_MS, USAGE_ROWS } from "./limits.js";
|
|
33
33
|
import { subagentFiles } from "./subagents.js";
|
|
34
34
|
import { codexFileSpend, codexFiles, geminiFileSpend, geminiFiles, TOOL_NAME } from "./spend.js";
|
|
35
|
-
import {
|
|
35
|
+
import { isUnbilledModel, priceChangedText, requestCost } from "./pricing.js";
|
|
36
|
+
import { orgRates, orgRatesLine } from "./orgrates.js";
|
|
36
37
|
import { anchorOf, rowsOf } from "./scan.js";
|
|
37
38
|
import { realModel } from "./tokens.js";
|
|
38
39
|
/** Beside the hook state and the ledger: ~/.claude/.context-doctor-budget.json. */
|
|
@@ -303,26 +304,29 @@ function lineStart(fd, size) {
|
|
|
303
304
|
* shared scan, so only what it has not cached), as the ledger keeps them.
|
|
304
305
|
*/
|
|
305
306
|
function readFile(tool, file, since, size) {
|
|
306
|
-
const k = [], d = [], x = [], y = [];
|
|
307
|
+
const k = [], d = [], x = [], y = [], z = [];
|
|
308
|
+
const flag = (i, q) => {
|
|
309
|
+
if (!q.priced)
|
|
310
|
+
x.push([i, q.model ?? "unknown"]);
|
|
311
|
+
else if (q.changedOn)
|
|
312
|
+
z.push([i, q.model ?? "unknown", q.changedOn]);
|
|
313
|
+
else if (q.estimated)
|
|
314
|
+
y.push([i, q.model ?? "unknown"]);
|
|
315
|
+
};
|
|
316
|
+
const flags = () => ({ ...(x.length ? { x } : {}), ...(y.length ? { y } : {}), ...(z.length ? { z } : {}) });
|
|
307
317
|
if (tool !== "claude") {
|
|
308
318
|
// A Codex request's key (a forked rollout repeats its parent's) kept short: 12 hex digits of its hash.
|
|
309
319
|
for (const r of tool === "codex" ? codexFileSpend(file, since) : geminiFileSpend(file, since)) {
|
|
310
|
-
|
|
311
|
-
x.push([k.length, r.model ?? "unknown"]);
|
|
312
|
-
else if (r.estimated)
|
|
313
|
-
y.push([k.length, r.model ?? "unknown"]);
|
|
320
|
+
flag(k.length, r);
|
|
314
321
|
k.push(r.key ? createHash("sha1").update(r.key).digest("hex").slice(0, 12) : "");
|
|
315
322
|
d.push(r.usd);
|
|
316
323
|
}
|
|
317
|
-
return { k, d, ...(
|
|
324
|
+
return { k, d, ...flags() };
|
|
318
325
|
}
|
|
319
326
|
const reqs = claudeFileUsage(file, since);
|
|
320
327
|
const at = new Map();
|
|
321
328
|
reqs.forEach((q, i) => {
|
|
322
|
-
|
|
323
|
-
x.push([i, q.model ?? "unknown"]);
|
|
324
|
-
else if (!hasKnownPrice(q.model))
|
|
325
|
-
y.push([i, q.model ?? "unknown"]);
|
|
329
|
+
flag(i, { ...q, priced: q.rates !== undefined });
|
|
326
330
|
k.push(keyOf(q.uuid));
|
|
327
331
|
d.push(q.usd);
|
|
328
332
|
if (q.id)
|
|
@@ -344,7 +348,7 @@ function readFile(tool, file, since, size) {
|
|
|
344
348
|
continue;
|
|
345
349
|
}
|
|
346
350
|
const i = at.get(m.id) ?? -1;
|
|
347
|
-
last.set(m.id, [m.id, i, out,
|
|
351
|
+
last.set(m.id, [m.id, i, out, (i >= 0 ? reqs[i].rates : requestCost(realModel(m.model), m.usage, Date.parse(String(row.timestamp ?? "")))?.rates)?.outputPerM ?? 0]);
|
|
348
352
|
if (last.size > RECENT_REPLIES)
|
|
349
353
|
last.delete(last.keys().next().value);
|
|
350
354
|
}
|
|
@@ -352,7 +356,7 @@ function readFile(tool, file, since, size) {
|
|
|
352
356
|
const fd = openSync(file, "r");
|
|
353
357
|
try {
|
|
354
358
|
const o = lineStart(fd, size);
|
|
355
|
-
return { k, d, o, a: anchorOf(fd, o), r: r.slice(-RECENT_REPLIES), ...(
|
|
359
|
+
return { k, d, o, a: anchorOf(fd, o), r: r.slice(-RECENT_REPLIES), ...flags() };
|
|
356
360
|
}
|
|
357
361
|
finally {
|
|
358
362
|
closeSync(fd);
|
|
@@ -441,22 +445,26 @@ function countLines(e, recent, text, since, own) {
|
|
|
441
445
|
}
|
|
442
446
|
const ts = Date.parse(String(row.timestamp ?? ""));
|
|
443
447
|
const tokens = [u.input_tokens, u.cache_read_input_tokens, u.cache_creation_input_tokens].reduce((t, v) => t + (Number(v) > 0 ? Number(v) : 0), 0);
|
|
444
|
-
const
|
|
448
|
+
const model = realModel(m.model);
|
|
449
|
+
const c = requestCost(model, u, ts);
|
|
445
450
|
let index = -1;
|
|
446
451
|
// A reply on <synthetic> was made by Claude Code itself, never billed: not a request at all.
|
|
447
452
|
// A row of another session (`own`): a copy of its history, its spend, not this session's.
|
|
448
453
|
const copied = own !== undefined && typeof row.sessionId === "string" && row.sessionId !== own;
|
|
449
|
-
|
|
454
|
+
// A row with no time of its own fits no period, but it is in the session's price (since 0), at today's rates (requestCost).
|
|
455
|
+
if ((Number.isFinite(ts) ? ts >= since : since <= 0) && tokens > 0 && !isUnbilledModel(m.model) && !copied) {
|
|
450
456
|
index = e.k.length;
|
|
451
|
-
if (!
|
|
452
|
-
(e.x ??= []).push([index,
|
|
453
|
-
else if (
|
|
454
|
-
(e.
|
|
457
|
+
if (!c)
|
|
458
|
+
(e.x ??= []).push([index, model ?? "unknown"]);
|
|
459
|
+
else if (c.changedOn)
|
|
460
|
+
(e.z ??= []).push([index, model ?? "unknown", c.changedOn]);
|
|
461
|
+
else if (c.estimated)
|
|
462
|
+
(e.y ??= []).push([index, model ?? "unknown"]);
|
|
455
463
|
e.k.push(keyOf(typeof row.uuid === "string" ? row.uuid : undefined));
|
|
456
|
-
e.d.push(
|
|
464
|
+
e.d.push(c ? c.totalUsd : 0);
|
|
457
465
|
}
|
|
458
466
|
if (typeof m.id === "string")
|
|
459
|
-
recent.push([m.id, index, out,
|
|
467
|
+
recent.push([m.id, index, out, c?.rates.outputPerM ?? 0]);
|
|
460
468
|
}
|
|
461
469
|
}
|
|
462
470
|
}
|
|
@@ -464,7 +472,8 @@ function countLines(e, recent, text, since, own) {
|
|
|
464
472
|
export function wellFormed(e) {
|
|
465
473
|
return Boolean(e) && typeof e === "object" && Array.isArray(e.k) && Array.isArray(e.d) && e.k.length === e.d.length &&
|
|
466
474
|
e.k.every((x) => typeof x === "string") && e.d.every((x) => typeof x === "number" && Number.isFinite(x)) &&
|
|
467
|
-
(e.a === undefined || typeof e.a === "string") && (e.x === undefined || (Array.isArray(e.x) && e.x.every((y) => Array.isArray(y) && typeof y[0] === "number"))) && (e.y === undefined || (Array.isArray(e.y) && e.y.every((y) => Array.isArray(y) && typeof y[0] === "number"))) && (e.r === undefined || (Array.isArray(e.r) && e.r.every((x) => Array.isArray(x) && x.length === 4)))
|
|
475
|
+
(e.a === undefined || typeof e.a === "string") && (e.x === undefined || (Array.isArray(e.x) && e.x.every((y) => Array.isArray(y) && typeof y[0] === "number"))) && (e.y === undefined || (Array.isArray(e.y) && e.y.every((y) => Array.isArray(y) && typeof y[0] === "number"))) && (e.r === undefined || (Array.isArray(e.r) && e.r.every((x) => Array.isArray(x) && x.length === 4))) &&
|
|
476
|
+
(e.z === undefined || (Array.isArray(e.z) && e.z.every((z) => Array.isArray(z) && typeof z[0] === "number" && typeof z[2] === "string")));
|
|
468
477
|
}
|
|
469
478
|
/**
|
|
470
479
|
* One transcript's entry brought up to date: kept when the file is as last
|
|
@@ -486,8 +495,9 @@ export function refreshEntry(tool, file, prev, since, direct = false, own) {
|
|
|
486
495
|
catch {
|
|
487
496
|
return undefined;
|
|
488
497
|
}
|
|
489
|
-
// An entry not in the shape this version writes (edited, or another version's) is read again.
|
|
490
|
-
const
|
|
498
|
+
// An entry not in the shape this version writes (edited, or another version's), or priced at other rates, is read again.
|
|
499
|
+
const org = orgRates()?.key;
|
|
500
|
+
const e = wellFormed(prev) && prev.p === org ? prev : undefined;
|
|
491
501
|
if (e && e.t === tool && e.s === s.size && e.m === s.mtimeMs && e.i === s.ino)
|
|
492
502
|
return { e, read: -1 };
|
|
493
503
|
try {
|
|
@@ -507,11 +517,11 @@ export function refreshEntry(tool, file, prev, since, direct = false, own) {
|
|
|
507
517
|
finally {
|
|
508
518
|
closeSync(fd);
|
|
509
519
|
}
|
|
510
|
-
const blank = { t: tool, s: 0, m: 0, i: s.ino, k: [], d: [], o: 0, a, r: [] };
|
|
520
|
+
const blank = { t: tool, s: 0, m: 0, i: s.ino, k: [], d: [], o: 0, a, r: [], ...(org ? { p: org } : {}) };
|
|
511
521
|
if (readAppended(blank, file, since, own))
|
|
512
522
|
return { e: { ...blank, s: s.size, m: s.mtimeMs }, read: s.size };
|
|
513
523
|
}
|
|
514
|
-
return { e: { t: tool, s: s.size, m: s.mtimeMs, i: s.ino, ...readFile(tool, file, since, s.size) }, read: s.size };
|
|
524
|
+
return { e: { t: tool, s: s.size, m: s.mtimeMs, i: s.ino, ...readFile(tool, file, since, s.size), ...(org ? { p: org } : {}) }, read: s.size };
|
|
515
525
|
}
|
|
516
526
|
catch {
|
|
517
527
|
return undefined;
|
|
@@ -553,9 +563,10 @@ export function periodSpend(period, now = Date.now(), home = homedir(), warnAt)
|
|
|
553
563
|
let unpriced = 0;
|
|
554
564
|
const models = new Set();
|
|
555
565
|
const estimated = { requests: 0, usd: 0, models: new Set() };
|
|
566
|
+
const changedPrice = { requests: 0, usd: 0, models: new Map() };
|
|
556
567
|
for (const file of Object.keys(kept).sort()) {
|
|
557
568
|
const e = kept[file];
|
|
558
|
-
const x = new Map(e.x ?? []), y = new Map(e.y ?? []);
|
|
569
|
+
const x = new Map(e.x ?? []), y = new Map(e.y ?? []), z = new Map((e.z ?? []).map(([i, m, on]) => [i, [m, on]]));
|
|
559
570
|
e.k.forEach((key, i) => {
|
|
560
571
|
if (key) {
|
|
561
572
|
if (seen.has(key))
|
|
@@ -573,6 +584,12 @@ export function periodSpend(period, now = Date.now(), home = homedir(), warnAt)
|
|
|
573
584
|
estimated.usd += e.d[i];
|
|
574
585
|
estimated.models.add(y.get(i));
|
|
575
586
|
}
|
|
587
|
+
else if (z.has(i)) {
|
|
588
|
+
const [m, on] = z.get(i);
|
|
589
|
+
changedPrice.requests++;
|
|
590
|
+
changedPrice.usd += e.d[i];
|
|
591
|
+
changedPrice.models.set(`${m}\u0000${on}`, [m, on]);
|
|
592
|
+
}
|
|
576
593
|
});
|
|
577
594
|
}
|
|
578
595
|
const level = warnAt ? warnAt(usd, st.warned) : 0;
|
|
@@ -594,7 +611,7 @@ export function periodSpend(period, now = Date.now(), home = homedir(), warnAt)
|
|
|
594
611
|
}
|
|
595
612
|
if (changed)
|
|
596
613
|
saveState({ ...st, files: kept, usd, byTool });
|
|
597
|
-
return { start, end: periodEnd(period, now), usd, byTool, ...(unpriced ? { unpriced: { requests: unpriced, models: [...models] } } : {}), ...(estimated.requests ? { estimated: { requests: estimated.requests, usd: estimated.usd, models: [...estimated.models] } } : {}), ...(warn ? { warn } : {}), ...(unpricedNew ? { unpricedNew } : {}) };
|
|
614
|
+
return { start, end: periodEnd(period, now), usd, byTool, ...(unpriced ? { unpriced: { requests: unpriced, models: [...models] } } : {}), ...(estimated.requests ? { estimated: { requests: estimated.requests, usd: estimated.usd, models: [...estimated.models] } } : {}), ...(changedPrice.requests ? { changed: { requests: changedPrice.requests, usd: changedPrice.usd, models: [...changedPrice.models.values()] } } : {}), ...(warn ? { warn } : {}), ...(unpricedNew ? { unpricedNew } : {}) };
|
|
598
615
|
}
|
|
599
616
|
// ---------------------------------------------------------------------------
|
|
600
617
|
// What the hook, the status line and `budget` say
|
|
@@ -672,12 +689,17 @@ export function renderBudgetStatus(b, s, hookInstalled) {
|
|
|
672
689
|
`Budget: ${amount(b.usd)} a ${per(b.period)}, across Claude Code, Codex and Gemini CLI${b.block ? "; prompts over it are held" : ""}.`,
|
|
673
690
|
`${span(b.period) === "today" ? "Today" : "This week"}: ${money(s.usd)} so far, ${Math.round((s.usd / b.usd) * 100)}%${byToolText(s.byTool)}. ${resets(b.period)}`,
|
|
674
691
|
];
|
|
692
|
+
const org = orgRatesLine();
|
|
693
|
+
if (org)
|
|
694
|
+
lines.push(org);
|
|
675
695
|
if (s.unpriced)
|
|
676
696
|
lines.push(`Not counted: ${unpricedText(s.unpriced)}`);
|
|
677
697
|
if (s.estimated) {
|
|
678
698
|
const one = s.estimated.models.length === 1;
|
|
679
699
|
lines.push(`An estimate: ${money(s.estimated.usd)} of it is on ${s.estimated.models.slice(0, 2).join(", ")}${s.estimated.models.length > 2 ? " and others" : ""}, with no list price of ${one ? "its" : "their"} own, priced as ${one ? "its" : "their"} model's family.`);
|
|
680
700
|
}
|
|
701
|
+
if (s.changed)
|
|
702
|
+
lines.push(`An estimate: ${money(s.changed.usd)} of it is priced past the day its model's price changed (${priceChangedText(s.changed.models)}).`);
|
|
681
703
|
lines.push(hookInstalled
|
|
682
704
|
? `The every-prompt hook says so at ${THRESHOLDS.join("%, ").replace(/, (\d+)$/, " and $1")}%${b.block ? ", and holds prompts over it" : ""}. Cursor is not counted (context-doctor spend shows it).`
|
|
683
705
|
: "No every-prompt hook is installed, so nothing will say so: run context-doctor install.");
|
package/dist/cache.js
CHANGED
|
@@ -10,7 +10,7 @@
|
|
|
10
10
|
* caching at all.
|
|
11
11
|
*/
|
|
12
12
|
import { readFileSync } from "node:fs";
|
|
13
|
-
import { cacheWriteSplit,
|
|
13
|
+
import { cacheWriteSplit, requestCost } from "./pricing.js";
|
|
14
14
|
import { replyCounter } from "./session.js";
|
|
15
15
|
import { realModel } from "./tokens.js";
|
|
16
16
|
export function analyzeCacheUsage(transcriptPath) {
|
|
@@ -65,9 +65,10 @@ export function analyzeCacheUsage(transcriptPath) {
|
|
|
65
65
|
cacheWrite1hTokens += cacheWriteSplit(usage).oneHour;
|
|
66
66
|
uncachedTokens += fresh;
|
|
67
67
|
// Each request at its own model's price: a session can switch models.
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
68
|
+
// As billed (requestCost): its tier, fast mode, US-only.
|
|
69
|
+
const cost = requestCost(model, usage, Date.parse(String(entry.timestamp ?? "")) || undefined);
|
|
70
|
+
const pricing = cost?.rates;
|
|
71
|
+
if (cost && pricing) {
|
|
71
72
|
priced++;
|
|
72
73
|
paidUsd += cost.promptUsd;
|
|
73
74
|
writeUsd += cost.writeUsd;
|
package/dist/cachemisses.js
CHANGED
|
@@ -37,7 +37,7 @@
|
|
|
37
37
|
import { listSessions, isClaudeSession } from "./session.js";
|
|
38
38
|
import { rowsOf, slimUsage } from "./scan.js";
|
|
39
39
|
import { formatTokens, isCodeLike, realModel, tokensForLength } from "./tokens.js";
|
|
40
|
-
import { CACHE_WRITE_1H, CACHE_WRITE_5M,
|
|
40
|
+
import { CACHE_WRITE_1H, CACHE_WRITE_5M, requestCost } from "./pricing.js";
|
|
41
41
|
import { compareVersions } from "./modelswitch.js";
|
|
42
42
|
import { diagnosedMisses, missLogPath } from "./missledger.js";
|
|
43
43
|
/** Dollars as a person reads them: "$1,925", "$12.26", "$0". */
|
|
@@ -66,7 +66,7 @@ const SIZE_BUCKETS = [["<100k", 100_000], ["100-300k", 300_000], ["300-600k", 60
|
|
|
66
66
|
const bucketOf = (tokens) => SIZE_BUCKETS.find(([, max]) => tokens < max)[0];
|
|
67
67
|
const num = (x) => (typeof x === "number" && Number.isFinite(x) && x > 0 ? x : 0);
|
|
68
68
|
export const MISS_ROWS = {
|
|
69
|
-
id: "misses.
|
|
69
|
+
id: "misses.2",
|
|
70
70
|
init: () => ({ user: false }),
|
|
71
71
|
line(line, row, out, st) {
|
|
72
72
|
const block = () => {
|
|
@@ -209,10 +209,12 @@ runRows, onLate = () => { }) {
|
|
|
209
209
|
if (prev && at - prev.at >= prev.ttl)
|
|
210
210
|
colds++;
|
|
211
211
|
if (at >= since) {
|
|
212
|
-
|
|
212
|
+
// As billed (requestCost): fast mode, US-only, the prompt's tier, its day's price, each TTL at its own rate.
|
|
213
|
+
const cost = requestCost(model, u, at);
|
|
214
|
+
const price = cost?.rates;
|
|
213
215
|
const w1h = Math.min(write, num(u.cache_creation?.ephemeral_1h_input_tokens));
|
|
214
216
|
const w5m = u.cache_creation ? Math.min(write - w1h, num(u.cache_creation?.ephemeral_5m_input_tokens)) : write - w1h;
|
|
215
|
-
onRequest(
|
|
217
|
+
onRequest(cost?.writeUsd ?? 0, { at, version, write, oneHour: w1h, fiveMinute: w5m, first, model, entrypoint: r.ep });
|
|
216
218
|
if (prev && !compacted && at - prev.at < Math.min(ttl, prev.ttl) && prev.total > MIN_CONTEXT) {
|
|
217
219
|
const isMiss = write > MISS_SHARE * prev.total;
|
|
218
220
|
let miss;
|
package/dist/cacheplan.js
CHANGED
|
@@ -42,8 +42,8 @@ const MAX_BREAKPOINTS = 4;
|
|
|
42
42
|
* on some models and called cacheable prompts too small on others.
|
|
43
43
|
*/
|
|
44
44
|
const CACHE_MINIMUMS = {
|
|
45
|
-
"opus 5.5": 512, "opus 5.0": 512, "fable 5.0": 512, "fable 5.1": 512,
|
|
46
|
-
"mythos 5.0": 512, "mythos 5.1": 512, "sonnet 5.5": 512, "haiku 5.5": 512,
|
|
45
|
+
"opus 5.5": 512, "opus 5.0": 512, "fable 5.0": 512, "fable 5.1": 512, "fable 5.2": 512,
|
|
46
|
+
"mythos 5.0": 512, "mythos 5.1": 512, "mythos 5.2": 512, "sonnet 5.5": 512, "haiku 5.5": 512,
|
|
47
47
|
"opus 4.8": 1024, "sonnet 5.0": 1024, "sonnet 4.6": 1024, "sonnet 4.5": 1024,
|
|
48
48
|
"opus 4.1": 1024, "opus 4.0": 1024, "sonnet 4.0": 1024,
|
|
49
49
|
"opus 4.7": 2048, "haiku 3.5": 2048, "mythos preview": 2048,
|
package/dist/cachettl.js
CHANGED
|
@@ -38,7 +38,8 @@ import { join } from "node:path";
|
|
|
38
38
|
import { listSessions, replyCounter, isClaudeSession } from "./session.js";
|
|
39
39
|
import { REQUEST_ROWS } from "./coldresume.js";
|
|
40
40
|
import { rowsOf } from "./scan.js";
|
|
41
|
-
import { CACHE_WRITE_1H, CACHE_WRITE_5M, cacheWriteSplit,
|
|
41
|
+
import { CACHE_WRITE_1H, CACHE_WRITE_5M, cacheWriteSplit, requestCost } from "./pricing.js";
|
|
42
|
+
import { priceBasis } from "./orgrates.js";
|
|
42
43
|
import { realModel } from "./tokens.js";
|
|
43
44
|
import { backupOnce } from "./install.js";
|
|
44
45
|
import { ABSENT, readSettings, setJsonPath, withSettingsLock, writeAtomic } from "./settingsedit.js";
|
|
@@ -105,14 +106,16 @@ export function replayTtlTranscript(path, acc, since, until = Infinity, sidechai
|
|
|
105
106
|
// wrote nothing keeps the lifetime of the last one that did.
|
|
106
107
|
if (W > 0)
|
|
107
108
|
lastTtl = split.oneHour > split.fiveMinute ? HOUR : FIVE_MIN;
|
|
108
|
-
|
|
109
|
+
// The rates it billed at (its tier, fast mode, US-only): a lifetime changes reads and writes, not the prompt's length.
|
|
110
|
+
const c = requestCost(model, u, at);
|
|
111
|
+
const p = c?.rates;
|
|
109
112
|
if (at >= since && at < until && seen === "new") {
|
|
110
113
|
counted++;
|
|
111
114
|
acc.requests++;
|
|
112
|
-
if (!p)
|
|
115
|
+
if (!c || !p)
|
|
113
116
|
acc.unpriced++;
|
|
114
117
|
else {
|
|
115
|
-
acc.billedUsd +=
|
|
118
|
+
acc.billedUsd += c.promptUsd;
|
|
116
119
|
acc.writes += W;
|
|
117
120
|
acc.writes1h += split.oneHour;
|
|
118
121
|
const inp = p.inputPerM / 1e6;
|
|
@@ -309,7 +312,7 @@ function block(label, r, set, kind) {
|
|
|
309
312
|
export function renderCacheTtl(r, current, installs = [], command = (s) => `context-doctor ${s}`) {
|
|
310
313
|
const out = [];
|
|
311
314
|
out.push("Prompt cache lifetime: 5 minutes or 1 hour (Claude Code's own setting)");
|
|
312
|
-
out.push(`Last ${r.days} days,
|
|
315
|
+
out.push(`Last ${r.days} days, ${priceBasis()}; the same content is sent either way`);
|
|
313
316
|
out.push("─".repeat(66));
|
|
314
317
|
out.push(...block("Main conversation", r.main, current.main, "main"));
|
|
315
318
|
out.push("");
|
package/dist/ci.js
CHANGED
|
@@ -128,6 +128,22 @@ export function ciReport(opts = {}) {
|
|
|
128
128
|
}
|
|
129
129
|
return { base: opts.base, files, baseTotal, headTotal, breaches };
|
|
130
130
|
}
|
|
131
|
+
/**
|
|
132
|
+
* A path as inline code that stays code: a pull request names its files, and
|
|
133
|
+
* a name may hold a backtick, a pipe or a line break (all allowed in a
|
|
134
|
+
* repository), which closed the code span in the bot's comment and made the
|
|
135
|
+
* rest of the name markdown of the PR author's choosing (a link, an
|
|
136
|
+
* @mention, a heading). Line breaks are written as \n; in a table cell a
|
|
137
|
+
* pipe is escaped.
|
|
138
|
+
*/
|
|
139
|
+
function codePath(p, inTable = false) {
|
|
140
|
+
let s = p.replace(/[\r\n\t\u2028\u2029]/g, (c) => ({ "\r": "\\r", "\n": "\\n", "\t": "\\t" })[c] ?? `\\u${c.charCodeAt(0).toString(16)}`);
|
|
141
|
+
if (inTable)
|
|
142
|
+
s = s.replace(/\|/g, "\\|");
|
|
143
|
+
const fence = "`".repeat(Math.max(0, ...[...s.matchAll(/`+/g)].map((m) => m[0].length)) + 1);
|
|
144
|
+
const pad = s.startsWith("`") || s.endsWith("`") ? " " : "";
|
|
145
|
+
return `${fence}${pad}${s}${pad}${fence}`;
|
|
146
|
+
}
|
|
131
147
|
const signed = (n) => (n > 0 ? `+${formatTokens(n)}` : n < 0 ? `−${formatTokens(-n)}` : "0");
|
|
132
148
|
/** Markdown for a PR comment or a job summary. */
|
|
133
149
|
export function renderCiMarkdown(r, opts = {}) {
|
|
@@ -152,7 +168,7 @@ export function renderCiMarkdown(r, opts = {}) {
|
|
|
152
168
|
if (changed.length) {
|
|
153
169
|
out.push(r.base ? "| File | Agent | Base | This PR | Change |" : "| File | Agent | Tokens |", r.base ? "|---|---|---:|---:|---:|" : "|---|---|---:|");
|
|
154
170
|
for (const f of changed) {
|
|
155
|
-
const name =
|
|
171
|
+
const name = `${codePath(f.path, true)}${f.imported ? " (imported)" : ""}`;
|
|
156
172
|
out.push(r.base ? `| ${name} | ${f.agent} | ${f.base ? "~" + formatTokens(f.base) : "—"} | ${f.head ? "~" + formatTokens(f.head) : "—"} | ${signed(f.head - f.base)} |` : `| ${name} | ${f.agent} | ~${formatTokens(f.head)} |`);
|
|
157
173
|
}
|
|
158
174
|
}
|
|
@@ -163,7 +179,7 @@ export function renderCiMarkdown(r, opts = {}) {
|
|
|
163
179
|
out.push("", ...r.breaches.map((b) => `**Over budget:** ${b}.`));
|
|
164
180
|
const big = r.files.filter((f) => f.head >= 2000);
|
|
165
181
|
if (big.length)
|
|
166
|
-
out.push("", `Large files: ${big.map((f) =>
|
|
182
|
+
out.push("", `Large files: ${big.map((f) => codePath(f.path)).join(", ")}. \`npx context-doctor overhead split <file>\` moves reference sections out, word for word.`);
|
|
167
183
|
return out.join("\n");
|
|
168
184
|
}
|
|
169
185
|
/** Plain-text rendering for a terminal. */
|
package/dist/cli.js
CHANGED
|
@@ -41,6 +41,7 @@ import { measureAccuracy, renderAccuracy } from "./accuracy.js";
|
|
|
41
41
|
import { renderDiff } from "./diff.js";
|
|
42
42
|
import { renderExperiment, runExperiment } from "./experiment.js";
|
|
43
43
|
import { runStatusLine } from "./statusline.js";
|
|
44
|
+
import { runMod } from "./modmeasure.js";
|
|
44
45
|
import { renderSubagents, subagentFiles, subagentReport } from "./subagents.js";
|
|
45
46
|
import { findPreset, PRESETS, RC_FILENAME } from "./config.js";
|
|
46
47
|
import { runWatch } from "./watch.js";
|
|
@@ -156,8 +157,8 @@ Measure:
|
|
|
156
157
|
One bill across every tool here: Claude Code (with
|
|
157
158
|
its subagents), Codex, Gemini CLI and Cursor (an
|
|
158
159
|
estimate: no cache split), by project, model and
|
|
159
|
-
day, and what drives it, at list
|
|
160
|
-
totals only, to paste
|
|
160
|
+
day, and what drives it, as billed at list rates.
|
|
161
|
+
--share: totals only, to paste
|
|
161
162
|
context-doctor cache-misses [--days n] Requests that re-wrote the prompt cache while it was
|
|
162
163
|
still warm: priced, by model and context size, with
|
|
163
164
|
the cause where the transcript shows one
|
|
@@ -261,6 +262,9 @@ Internal (Claude Code and MCP clients run these for you):
|
|
|
261
262
|
context-doctor statusline Claude Code status bar line: live context size, cache
|
|
262
263
|
share, cost (wired by \`install --statusline\`; reads
|
|
263
264
|
the status JSON on stdin)
|
|
265
|
+
context-doctor mod measure|event Run by the plugin's mod after each turn (Desktop, VS Code,
|
|
266
|
+
terminal): limit readings, Claude Code's cost beside
|
|
267
|
+
ours, the band's figures (JSON on stdin and stdout)
|
|
264
268
|
context-doctor mcp [--http] The MCP server (same as context-doctor-mcp), for clients
|
|
265
269
|
that launch \`npx -y context-doctor mcp\`
|
|
266
270
|
|
|
@@ -302,7 +306,9 @@ Options:
|
|
|
302
306
|
--chunk-tokens <n> (pack) Largest chunk, in tokens (default 400)
|
|
303
307
|
--ids <a#2,b#5> (pack) Return these chunks by id
|
|
304
308
|
--include-secrets (pack) Also pack .env, .npmrc, private keys and other credential files,
|
|
305
|
-
|
|
309
|
+
paths under ~/.ssh, ~/.aws and similar, and the agents' MCP and
|
|
310
|
+
settings files in your home folder, whose servers' env holds API keys
|
|
311
|
+
(skipped by default; a project's own .mcp.json is read)
|
|
306
312
|
--min-tokens <n> (overhead split) Smallest section to move, in tokens (default 400)
|
|
307
313
|
--requests-per-day <n> (ci --markdown) Price the change at this many requests a day
|
|
308
314
|
--check <cmd> (experiment) Command whose exit code is the pass/fail for each arm
|
|
@@ -319,6 +325,9 @@ Options:
|
|
|
319
325
|
--token <secret> (proxy) Require /t/<secret>/ in every request path; needed before
|
|
320
326
|
putting the proxy on a public URL (Cursor BYO-key, tunnels).
|
|
321
327
|
Also read from CONTEXT_DOCTOR_PROXY_TOKEN
|
|
328
|
+
--allowed-hosts <names> (proxy) Host names it answers to besides localhost, an IP address and
|
|
329
|
+
--host (a container's service name); a web page that rebinds its own
|
|
330
|
+
name to this address is refused. Not checked with --token
|
|
322
331
|
--config <file> (proxy) Per-route overrides: {"routes":[{"modelPrefix":"gpt","strategies":[...],
|
|
323
332
|
"keepRecent":n,"maxToolResultTokens":n}]} — first prefix match wins
|
|
324
333
|
--upstream-anthropic <url> (proxy) Override Anthropic upstream (testing)
|
|
@@ -490,7 +499,7 @@ const COMMANDS = [
|
|
|
490
499
|
"analyze", "optimize", "proxy", "install", "uninstall", "savings", "compact-window", "autopilot", "mcp",
|
|
491
500
|
"instructions", "session", "cursor", "statusline", "hook", "report", "doctor", "dashboard", "init",
|
|
492
501
|
"experiment", "diff", "accuracy", "overhead", "ci", "cache-plan", "compactions", "cache-misses", "cache-ttl", "fix", "limits", "subagents", "tasks",
|
|
493
|
-
"spend", "budget", "reads", "pack", "watch", "ab", "handoff", "recall", "help", "version",
|
|
502
|
+
"spend", "budget", "reads", "pack", "watch", "ab", "handoff", "recall", "mod", "help", "version",
|
|
494
503
|
];
|
|
495
504
|
/** --strategy takes one of the optimizer's ids; a typo used to run nothing and report success. */
|
|
496
505
|
function strategyArg(v) {
|
|
@@ -561,8 +570,8 @@ const FLAGS = [
|
|
|
561
570
|
// Read by the MCP server itself: `mcp --http [--port n] [--host h]`.
|
|
562
571
|
{ names: ["--http"], set: () => { } },
|
|
563
572
|
{ names: ["--store-handoffs"], set: () => { } },
|
|
564
|
-
{ names: ["--allowed-hosts"], value: "text", set: () => { } },
|
|
565
|
-
{ names: ["--allowed-origins"], value: "text", set: () => { } },
|
|
573
|
+
{ names: ["--allowed-hosts"], value: "text", set: (a, v) => { a.allowedHosts = v; } },
|
|
574
|
+
{ names: ["--allowed-origins"], value: "text", set: (a, v) => { a.allowedOrigins = v; } },
|
|
566
575
|
];
|
|
567
576
|
const FLAG_BY_NAME = new Map(FLAGS.flatMap((f) => f.names.map((n) => [n, f])));
|
|
568
577
|
const FLAG_NAMES = [...FLAG_BY_NAME.keys(), "--help", "--version"];
|
|
@@ -791,6 +800,16 @@ async function main() {
|
|
|
791
800
|
void runStatusLine();
|
|
792
801
|
return;
|
|
793
802
|
}
|
|
803
|
+
if (args.command === "mod") {
|
|
804
|
+
if (args.file !== "measure" && args.file !== "event")
|
|
805
|
+
usageError(`Usage: context-doctor mod measure|event (the plugin's mod runs these, with JSON on stdin); got "${args.file ?? ""}".`);
|
|
806
|
+
if (process.stdin.isTTY) {
|
|
807
|
+
console.log("context-doctor mod is run by the plugin's mod in Claude Code with JSON on stdin; there is nothing for it to do in a terminal.");
|
|
808
|
+
return;
|
|
809
|
+
}
|
|
810
|
+
await runMod(args.file);
|
|
811
|
+
return;
|
|
812
|
+
}
|
|
794
813
|
if (args.command === "ab") {
|
|
795
814
|
process.exitCode = await abCommand({
|
|
796
815
|
levers: args.levers, tasks: args.abTasks, model: args.model, repeat: args.repeat, maxTurns: args.maxTurns,
|
|
@@ -1226,6 +1245,8 @@ async function main() {
|
|
|
1226
1245
|
port: args.port,
|
|
1227
1246
|
host: args.host,
|
|
1228
1247
|
token: args.token ?? process.env.CONTEXT_DOCTOR_PROXY_TOKEN,
|
|
1248
|
+
allowedHosts: args.allowedHosts,
|
|
1249
|
+
allowedOrigins: args.allowedOrigins,
|
|
1229
1250
|
autopilot: args.autopilot,
|
|
1230
1251
|
autopilotStatePath: args.autopilotState,
|
|
1231
1252
|
autopilotPauseFile: args.autopilotPauseFile,
|
package/dist/codexcompact.js
CHANGED
|
@@ -34,7 +34,7 @@ import { homedir } from "node:os";
|
|
|
34
34
|
import { basename, dirname, join, resolve } from "node:path";
|
|
35
35
|
import { codexDir } from "./codexdir.js";
|
|
36
36
|
import { codexEventKey, codexSessionsRoot, rolloutFiles } from "./limits.js";
|
|
37
|
-
import { openAIUsage,
|
|
37
|
+
import { openAIUsage, rateCard, ratesAt, requestCost } from "./pricing.js";
|
|
38
38
|
import { pick, rowsOf } from "./scan.js";
|
|
39
39
|
import { tilde } from "./claudedir.js";
|
|
40
40
|
/** The config.toml key the lever writes. */
|
|
@@ -128,19 +128,21 @@ function readSteps(file, seen) {
|
|
|
128
128
|
if (!Number.isFinite(at))
|
|
129
129
|
continue;
|
|
130
130
|
const u = openAIUsage(r.u);
|
|
131
|
-
const
|
|
131
|
+
const prompt = num(u.input_tokens) + num(u.cache_read_input_tokens) + num(u.cache_creation_input_tokens);
|
|
132
|
+
const card = rateCard(model, u, at);
|
|
133
|
+
const price = card && ratesAt(card, prompt);
|
|
132
134
|
const copy = !!r.key && seen.has(r.key);
|
|
133
135
|
if (r.key)
|
|
134
136
|
seen.add(r.key);
|
|
135
137
|
const window = num(r.win) ? num(r.win) / RECORDED_SHARE : DEFAULT_WINDOW;
|
|
136
138
|
steps.push({
|
|
137
|
-
k: "r", at, copy,
|
|
138
|
-
prompt: num(u.input_tokens) + num(u.cache_read_input_tokens) + num(u.cache_creation_input_tokens),
|
|
139
|
+
k: "r", at, copy, prompt,
|
|
139
140
|
cached: num(u.cache_read_input_tokens),
|
|
140
141
|
out: num(u.output_tokens),
|
|
141
142
|
inPerM: price?.inputPerM ?? 0, readPerM: price?.cacheReadPerM ?? 0, outPerM: price?.outputPerM ?? 0,
|
|
142
|
-
billedUsd:
|
|
143
|
+
billedUsd: requestCost(model, u, at)?.promptUsd ?? 0,
|
|
143
144
|
trigger: DEFAULT_SHARE * window,
|
|
145
|
+
...(card ? { card } : {}),
|
|
144
146
|
});
|
|
145
147
|
}
|
|
146
148
|
return steps;
|
|
@@ -178,11 +180,15 @@ function replay(steps, limit, since, until, after, scope = "total") {
|
|
|
178
180
|
fresh = false;
|
|
179
181
|
}
|
|
180
182
|
let cost = s.billedUsd;
|
|
183
|
+
// A smaller prompt can fall under a long-context tier (OpenAI's 272k): all of it then bills at the lower rates.
|
|
184
|
+
const low = s.card && ctx < s.prompt ? ratesAt(s.card, ctx) : undefined;
|
|
181
185
|
if (fresh)
|
|
182
|
-
cost = (ctx * s.inPerM) / 1e6;
|
|
186
|
+
cost = (ctx * (low ? low.inputPerM : s.inPerM)) / 1e6;
|
|
183
187
|
else if (removed > 0) {
|
|
184
188
|
const fromCache = Math.min(removed, s.cached);
|
|
185
189
|
cost = Math.max(0, s.billedUsd - (fromCache * s.readPerM + (removed - fromCache) * s.inPerM) / 1e6);
|
|
190
|
+
if (low && low.inputPerM < s.inPerM)
|
|
191
|
+
cost *= low.inputPerM / s.inPerM;
|
|
186
192
|
}
|
|
187
193
|
fresh = false;
|
|
188
194
|
prefill ??= ctx;
|
|
@@ -195,8 +201,9 @@ function replay(steps, limit, since, until, after, scope = "total") {
|
|
|
195
201
|
: ctx + s.out >= Math.min(limit, s.trigger) && limit < s.trigger;
|
|
196
202
|
if (reached) {
|
|
197
203
|
// Compacted after this turn: one request reading the context, a summary written; the next starts from `after`.
|
|
204
|
+
const at = low ?? { cacheReadPerM: s.readPerM, outputPerM: s.outPerM };
|
|
198
205
|
if (counted) {
|
|
199
|
-
sim += (ctx *
|
|
206
|
+
sim += (ctx * at.cacheReadPerM + SUMMARY_OUTPUT * at.outputPerM) / 1e6;
|
|
200
207
|
extra++;
|
|
201
208
|
}
|
|
202
209
|
removed = s.prompt + s.out - after;
|
package/dist/coldresume.d.ts
CHANGED
|
@@ -77,8 +77,12 @@ export declare function idleCompactMinTokens(env?: NodeJS.ProcessEnv): number;
|
|
|
77
77
|
export declare function autoCompactsAt(model: string | undefined, home?: string, env?: NodeJS.ProcessEnv): number | undefined;
|
|
78
78
|
/** Just past Claude Code's one-hour cache, as Claude Code's own idle clearing uses. */
|
|
79
79
|
export declare const COLD_IDLE_MS: number;
|
|
80
|
+
/** Margin past a cache's lifetime before a return counts as cold. */
|
|
81
|
+
export declare const COLD_MARGIN_MS: number;
|
|
80
82
|
/** Below this, a rebuilt cache is cheap and compaction is not worth the interruption. */
|
|
81
83
|
export declare const COLD_MIN_TOKENS = 150000;
|
|
84
|
+
/** What a compacted session restarts from: system prompt and tools plus the summary. */
|
|
85
|
+
export declare const AFTER_COMPACT_TOKENS = 45000;
|
|
82
86
|
export interface ColdResume {
|
|
83
87
|
idleMs: number;
|
|
84
88
|
/** Context size at the last request, from the API's own usage. */
|
|
@@ -92,6 +96,8 @@ export interface ColdResume {
|
|
|
92
96
|
perMessageUsd?: number;
|
|
93
97
|
/** `resumeUsd` is Claude Code's own estimate (SessionStart), which honours a managed modelPricing. */
|
|
94
98
|
claudeCodePriced?: boolean;
|
|
99
|
+
/** How long the cache the last reply left behind lives, as the gate counted it. */
|
|
100
|
+
ttlMs?: number;
|
|
95
101
|
}
|
|
96
102
|
/**
|
|
97
103
|
* What Claude Code's SessionStart hook says on a resume (2.1.29x):
|