context-doctor 0.50.0 → 0.52.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +36 -38
- package/dist/apptools.d.ts +89 -0
- package/dist/apptools.js +203 -0
- package/dist/appwindow.d.ts +6 -0
- package/dist/appwindow.js +15 -1
- package/dist/budget.d.ts +20 -2
- package/dist/budget.js +43 -3
- package/dist/cachemisses.d.ts +70 -0
- package/dist/cachemisses.js +126 -0
- package/dist/cli.js +39 -10
- package/dist/credits.d.ts +64 -2
- package/dist/credits.js +88 -3
- package/dist/doctor.d.ts +18 -6
- package/dist/doctor.js +82 -14
- package/dist/fileparams.js +15 -3
- package/dist/fix.d.ts +11 -2
- package/dist/fix.js +53 -18
- package/dist/limits.d.ts +44 -3
- package/dist/limits.js +210 -22
- package/dist/mcp.js +68 -68
- package/dist/mod/api.d.ts +1 -1
- package/dist/mod/logic.d.ts +46 -1
- package/dist/mod/logic.js +76 -4
- package/dist/mod/register.d.ts +13 -3
- package/dist/mod/register.js +39 -9
- package/dist/modelids.d.ts +15 -0
- package/dist/modelids.js +33 -0
- package/dist/modmeasure.d.ts +7 -0
- package/dist/modmeasure.js +9 -0
- package/dist/overhead.js +8 -2
- package/dist/progresssummaries.d.ts +85 -2
- package/dist/progresssummaries.js +169 -23
- package/dist/proxy.d.ts +1 -1
- package/dist/proxy.js +1 -1
- package/dist/sample.d.ts +8 -0
- package/dist/sample.js +86 -0
- package/dist/savings.d.ts +8 -1
- package/dist/savings.js +32 -7
- package/dist/spend.d.ts +4 -2
- package/dist/spend.js +33 -4
- package/dist/starts.d.ts +7 -0
- package/dist/starts.js +7 -3
- package/dist/usagepane.js +1 -1
- package/package.json +1 -1
package/dist/budget.js
CHANGED
|
@@ -34,6 +34,7 @@ import { subagentFiles } from "./subagents.js";
|
|
|
34
34
|
import { codexFileSpend, codexFiles, geminiFileSpend, geminiFiles, TOOL_NAME } from "./spend.js";
|
|
35
35
|
import { billedCost, isUnbilledModel, priceChangedText, priceTableKey, requestCost } from "./pricing.js";
|
|
36
36
|
import { orgRates, orgRatesLine } from "./orgrates.js";
|
|
37
|
+
import { creditsAheadLine, creditsSince } from "./credits.js";
|
|
37
38
|
import { anchorOf, rowsOf } from "./scan.js";
|
|
38
39
|
import { realModel } from "./tokens.js";
|
|
39
40
|
import { isCompactionRow, isTrack, newTrack, trackCompaction } from "./compactcost.js";
|
|
@@ -683,6 +684,33 @@ function resets(p) {
|
|
|
683
684
|
function raised(b, spent) {
|
|
684
685
|
return Math.ceil(Math.max(b.usd * 1.5, spent * 1.2) / 5) * 5;
|
|
685
686
|
}
|
|
687
|
+
/**
|
|
688
|
+
* Claude Code's part of the period that ran past the plan's limit, paid from
|
|
689
|
+
* usage credits (credits.ts): already in the period's dollars, said apart.
|
|
690
|
+
* Reads the limits ledger, and the transcripts only when the ledger says a
|
|
691
|
+
* limit ran out or credits were in use. Undefined when nothing was; never
|
|
692
|
+
* throws (a damaged ledger must not cost the budget its line).
|
|
693
|
+
*/
|
|
694
|
+
export function periodCredits(start, now = Date.now(), home) {
|
|
695
|
+
try {
|
|
696
|
+
return creditsSince(start, { now, ...(home ? { home } : {}) });
|
|
697
|
+
}
|
|
698
|
+
catch {
|
|
699
|
+
return undefined;
|
|
700
|
+
}
|
|
701
|
+
}
|
|
702
|
+
/**
|
|
703
|
+
* "$4.20 of this was paid from usage credits, past your plan's limit (37
|
|
704
|
+
* requests, at API list prices, an estimate)." Inferred ones say so.
|
|
705
|
+
*/
|
|
706
|
+
export function creditsLine(c) {
|
|
707
|
+
if (!c || !c.requests)
|
|
708
|
+
return undefined;
|
|
709
|
+
const n = `${c.requests.toLocaleString("en-US")} request${c.requests === 1 ? "" : "s"}`;
|
|
710
|
+
const how = c.inferred && !c.fromHeaders ? "was most likely paid" : "was paid";
|
|
711
|
+
const why = !c.inferred ? "" : !c.fromHeaders ? "; inferred: they went through after a limit read 100%" : `; ${c.inferred.toLocaleString("en-US")} of them inferred from a limit at 100%`;
|
|
712
|
+
return `${money(c.usd)} of this ${how} from usage credits, past your plan's limit (${n}, at API list prices, an estimate${why}).`;
|
|
713
|
+
}
|
|
686
714
|
/**
|
|
687
715
|
* The hook's check: undefined with no budget set (one failed read: the hot
|
|
688
716
|
* path stays a stat), otherwise the spend so far and what to say or do.
|
|
@@ -704,9 +732,12 @@ export function budgetVerdict(now = Date.now(), home = homedir()) {
|
|
|
704
732
|
const unpriced = spend.unpricedNew && spend.unpriced ? unpricedText(spend.unpriced) : undefined;
|
|
705
733
|
if (!spend.warn)
|
|
706
734
|
return unpriced ? { spend, budget: b, message: `context-doctor: ${unpriced}` } : { spend, budget: b };
|
|
707
|
-
const
|
|
735
|
+
const base = spend.warn >= 100
|
|
708
736
|
? `${head}${byToolText(spend.byTool)}: over your ${amount(b.usd)}/${per(b.period)} budget (${pct}%). Raise it with context-doctor budget ${raised(b, spend.usd)}/${per(b.period)}, or add --block to hold prompts over it.`
|
|
709
737
|
: `${head}${byToolText(spend.byTool)}: ${pct}% of your ${amount(b.usd)}/${per(b.period)} budget.`;
|
|
738
|
+
// Once per threshold, so the ledger (and the transcripts only past a limit) is read only then.
|
|
739
|
+
const credits = creditsLine(periodCredits(spend.start, now, home));
|
|
740
|
+
const message = credits ? `${base} ${credits}` : base;
|
|
710
741
|
return { spend, budget: b, message: unpriced ? `${message} ${unpriced}` : message };
|
|
711
742
|
}
|
|
712
743
|
/** The status line's part: "$12/$50 today", or undefined with no budget set. */
|
|
@@ -718,14 +749,23 @@ export function budgetStatus(now = Date.now(), home = homedir()) {
|
|
|
718
749
|
const short = (n) => (n >= 10 ? `$${Math.round(n).toLocaleString("en-US")}` : `$${n.toFixed(2)}`);
|
|
719
750
|
return `${short(s.usd)}/${amount(b.usd)} ${span(b.period)}${s.usd >= b.usd ? " ⚠" : ""}`;
|
|
720
751
|
}
|
|
721
|
-
/**
|
|
722
|
-
|
|
752
|
+
/**
|
|
753
|
+
* `budget` with no argument, and after setting one: the budget and where the
|
|
754
|
+
* period stands. `ahead`: the weekly limit running out before its reset with
|
|
755
|
+
* extra usage on (credits.ts creditsAheadNow), said in one line.
|
|
756
|
+
*/
|
|
757
|
+
export function renderBudgetStatus(b, s, hookInstalled, credits, ahead, now = Date.now()) {
|
|
723
758
|
if (!b || !s)
|
|
724
759
|
return "No spend budget set. Set one: context-doctor budget 50/day (or 200/week; --block to hold prompts over it).";
|
|
725
760
|
const lines = [
|
|
726
761
|
`Budget: ${amount(b.usd)} a ${per(b.period)}, across Claude Code, Codex and Gemini CLI${b.block ? "; prompts over it are held" : ""}.`,
|
|
727
762
|
`${span(b.period) === "today" ? "Today" : "This week"}: ${money(s.usd)} so far, ${Math.round((s.usd / b.usd) * 100)}%${byToolText(s.byTool)}. ${resets(b.period)}`,
|
|
728
763
|
];
|
|
764
|
+
const paid = creditsLine(credits);
|
|
765
|
+
if (paid)
|
|
766
|
+
lines.push(paid);
|
|
767
|
+
if (ahead)
|
|
768
|
+
lines.push(creditsAheadLine(ahead, now));
|
|
729
769
|
const org = orgRatesLine();
|
|
730
770
|
if (org)
|
|
731
771
|
lines.push(org);
|
package/dist/cachemisses.d.ts
CHANGED
|
@@ -127,6 +127,8 @@ export interface CacheMissReport {
|
|
|
127
127
|
};
|
|
128
128
|
/** Returns after the cache expired, replayed as billed, compacted and kept warm (coldreturns.ts). */
|
|
129
129
|
coldReturns: ColdReturnReport;
|
|
130
|
+
/** Requests the cache never saw (#111948); only when there are any. */
|
|
131
|
+
uncached?: UncachedReport;
|
|
130
132
|
}
|
|
131
133
|
/** One Claude Code version's requests (the `version` every transcript line carries). */
|
|
132
134
|
export interface VersionStats {
|
|
@@ -196,6 +198,74 @@ export declare function missesInTranscript(path: string, since?: number, add?: (
|
|
|
196
198
|
}, miss?: CacheMiss) => void, onRequest?: (writeUsd: number, info: RequestInfo) => void,
|
|
197
199
|
/** Shared by every transcript of one report: a fork's copied rows (same uuids) have no first request of their own. */
|
|
198
200
|
runRows?: Set<string>, onLate?: (late: LateRewrite) => void): void;
|
|
201
|
+
/**
|
|
202
|
+
* Requests the prompt cache never saw (anthropics/claude-code#111948): on
|
|
203
|
+
* Claude Code 2.1.329 a cache breakpoint can land on a `role:"system"`
|
|
204
|
+
* message inside `messages[]`, which writes nothing, so every turn bills the
|
|
205
|
+
* whole prompt as new input (~$80 a long session reported). They write and
|
|
206
|
+
* read (almost) nothing, so the misses above, re-writes, never count them.
|
|
207
|
+
*
|
|
208
|
+
* One counts when all of these hold:
|
|
209
|
+
* - a Claude model, and a transcript that used the cache elsewhere (a
|
|
210
|
+
* session that never wrote or read it had caching off, or a provider
|
|
211
|
+
* that does not cache: uncached by choice, not by fault);
|
|
212
|
+
* - it wrote nothing to the cache, sent over 20k tokens as new input, and
|
|
213
|
+
* that input was over half the prompt (a tiny context, or a cache read
|
|
214
|
+
* with a few new turns after it, is normal);
|
|
215
|
+
* - not a session's first request, nor the first after a compaction, a
|
|
216
|
+
* model switch or an hour's pause: a working cache would have had to
|
|
217
|
+
* write those anyway.
|
|
218
|
+
* Priced as what a working cache would have read instead: the input, up to
|
|
219
|
+
* the previous request's prompt, at the input rate minus the cache-read
|
|
220
|
+
* rate. What it would have written (the new turns) is left out, so the
|
|
221
|
+
* figure is a floor.
|
|
222
|
+
*/
|
|
223
|
+
export interface UncachedRequest {
|
|
224
|
+
path: string;
|
|
225
|
+
at: string;
|
|
226
|
+
/** The Claude Code version on the transcript line, when recorded. */
|
|
227
|
+
version?: string;
|
|
228
|
+
model: string;
|
|
229
|
+
/** Billed as new input. */
|
|
230
|
+
inputTokens: number;
|
|
231
|
+
/** The whole prompt: input, cache read and cache write. */
|
|
232
|
+
promptTokens: number;
|
|
233
|
+
/** Above what a working cache would have charged; undefined when the model has no known price. */
|
|
234
|
+
extraUsd?: number;
|
|
235
|
+
}
|
|
236
|
+
export interface UncachedReport {
|
|
237
|
+
days: number;
|
|
238
|
+
requests: number;
|
|
239
|
+
sessions: number;
|
|
240
|
+
inputTokens: number;
|
|
241
|
+
extraUsd: number;
|
|
242
|
+
/** On models with no known price (not in extraUsd). */
|
|
243
|
+
unpriced: number;
|
|
244
|
+
/** Per Claude Code version, costliest first ("unknown" when the line carried none). */
|
|
245
|
+
byVersion: Array<{
|
|
246
|
+
version: string;
|
|
247
|
+
requests: number;
|
|
248
|
+
sessions: number;
|
|
249
|
+
inputTokens: number;
|
|
250
|
+
extraUsd: number;
|
|
251
|
+
models: string[];
|
|
252
|
+
from: string;
|
|
253
|
+
to: string;
|
|
254
|
+
}>;
|
|
255
|
+
largest: UncachedRequest[];
|
|
256
|
+
}
|
|
257
|
+
/** Requests in one transcript the cache never saw; `since` drops earlier ones. `seen`: uuids of rows already read (a fork's copied rows count once). */
|
|
258
|
+
export declare function uncachedInTranscript(path: string, since?: number, seen?: Set<string>): UncachedRequest[];
|
|
259
|
+
/** The requests the cache never saw in the last `days`, by Claude Code version. */
|
|
260
|
+
export declare function uncachedRequests(days?: number, paths?: string[], now?: number): UncachedReport;
|
|
261
|
+
/** The section in `cache-misses`, or nothing when there are none. */
|
|
262
|
+
export declare function renderUncached(u: UncachedReport | undefined): string[];
|
|
263
|
+
/** `doctor`'s line when the last `days` hold any; undefined otherwise. */
|
|
264
|
+
export declare function uncachedCheck(days?: number, paths?: string[]): {
|
|
265
|
+
label: string;
|
|
266
|
+
status: "warn";
|
|
267
|
+
detail: string;
|
|
268
|
+
} | undefined;
|
|
199
269
|
export declare function cacheMisses(days?: number, paths?: string[], onProgress?: (done: number, total: number) => void, missLog?: string): CacheMissReport;
|
|
200
270
|
/** The late re-writes section, or nothing when there are none. */
|
|
201
271
|
export declare function renderLate(l: CacheMissReport["late"]): string[];
|
package/dist/cachemisses.js
CHANGED
|
@@ -262,6 +262,124 @@ runRows, onLate = () => { }) {
|
|
|
262
262
|
blocks = 0;
|
|
263
263
|
}
|
|
264
264
|
}
|
|
265
|
+
const CLAUDE_MODEL = /claude|opus|sonnet|haiku|fable|mythos/i;
|
|
266
|
+
/** Requests in one transcript the cache never saw; `since` drops earlier ones. `seen`: uuids of rows already read (a fork's copied rows count once). */
|
|
267
|
+
export function uncachedInTranscript(path, since = 0, seen) {
|
|
268
|
+
const found = [];
|
|
269
|
+
let cached = false;
|
|
270
|
+
let prev;
|
|
271
|
+
let compacted = false;
|
|
272
|
+
for (const r of rowsOf(path, MISS_ROWS)) {
|
|
273
|
+
if (r.k === "c") {
|
|
274
|
+
compacted = true;
|
|
275
|
+
continue;
|
|
276
|
+
}
|
|
277
|
+
if (r.k !== "r")
|
|
278
|
+
continue;
|
|
279
|
+
const { model, at, u } = r;
|
|
280
|
+
const write = num(u.cache_creation_input_tokens);
|
|
281
|
+
const read = num(u.cache_read_input_tokens);
|
|
282
|
+
const input = num(u.input_tokens);
|
|
283
|
+
const total = write + read + input;
|
|
284
|
+
if (write > 0 || read > 0)
|
|
285
|
+
cached = true;
|
|
286
|
+
const copied = r.uuid !== undefined && seen !== undefined && seen.has(r.uuid);
|
|
287
|
+
if (r.uuid !== undefined)
|
|
288
|
+
seen?.add(r.uuid);
|
|
289
|
+
if (at >= since && !copied && write === 0 && input > MIN_CONTEXT && input > total / 2 && CLAUDE_MODEL.test(model) &&
|
|
290
|
+
prev && !compacted && prev.model === model && at - prev.at < HOUR) {
|
|
291
|
+
const rates = requestCost(model, u, at)?.rates;
|
|
292
|
+
found.push({
|
|
293
|
+
path,
|
|
294
|
+
at: new Date(at).toISOString(),
|
|
295
|
+
...(r.version ? { version: r.version } : {}),
|
|
296
|
+
model,
|
|
297
|
+
inputTokens: input,
|
|
298
|
+
promptTokens: total,
|
|
299
|
+
extraUsd: rates ? (Math.min(input, prev.total) * Math.max(0, rates.inputPerM - rates.cacheReadPerM)) / 1e6 : undefined,
|
|
300
|
+
});
|
|
301
|
+
}
|
|
302
|
+
prev = { at, total, model };
|
|
303
|
+
compacted = false;
|
|
304
|
+
}
|
|
305
|
+
return cached ? found : [];
|
|
306
|
+
}
|
|
307
|
+
/** The requests the cache never saw in the last `days`, by Claude Code version. */
|
|
308
|
+
export function uncachedRequests(days = 30, paths, now = Date.now()) {
|
|
309
|
+
const since = now - days * 86_400_000;
|
|
310
|
+
const targets = paths ?? listSessions(10_000).filter((s) => isClaudeSession(s) && s.modifiedAt.getTime() >= since).map((s) => s.path);
|
|
311
|
+
const seen = new Set();
|
|
312
|
+
const all = [];
|
|
313
|
+
for (const p of targets) {
|
|
314
|
+
try {
|
|
315
|
+
all.push(...uncachedInTranscript(p, since, seen));
|
|
316
|
+
}
|
|
317
|
+
catch {
|
|
318
|
+
/* one unreadable transcript must not sink the report */
|
|
319
|
+
}
|
|
320
|
+
}
|
|
321
|
+
const versions = new Map();
|
|
322
|
+
for (const q of all) {
|
|
323
|
+
const v = q.version ?? "unknown";
|
|
324
|
+
versions.set(v, [...(versions.get(v) ?? []), q]);
|
|
325
|
+
}
|
|
326
|
+
const usd = (qs) => qs.reduce((n, q) => n + (q.extraUsd ?? 0), 0);
|
|
327
|
+
return {
|
|
328
|
+
days,
|
|
329
|
+
requests: all.length,
|
|
330
|
+
sessions: new Set(all.map((q) => q.path)).size,
|
|
331
|
+
inputTokens: all.reduce((n, q) => n + q.inputTokens, 0),
|
|
332
|
+
extraUsd: usd(all),
|
|
333
|
+
unpriced: all.filter((q) => q.extraUsd === undefined).length,
|
|
334
|
+
byVersion: [...versions.entries()]
|
|
335
|
+
.map(([version, qs]) => ({
|
|
336
|
+
version,
|
|
337
|
+
requests: qs.length,
|
|
338
|
+
sessions: new Set(qs.map((q) => q.path)).size,
|
|
339
|
+
inputTokens: qs.reduce((n, q) => n + q.inputTokens, 0),
|
|
340
|
+
extraUsd: usd(qs),
|
|
341
|
+
models: [...new Set(qs.map((q) => q.model))],
|
|
342
|
+
from: qs.reduce((a, q) => (q.at < a ? q.at : a), qs[0].at),
|
|
343
|
+
to: qs.reduce((a, q) => (q.at > a ? q.at : a), qs[0].at),
|
|
344
|
+
}))
|
|
345
|
+
.sort((a, b) => b.extraUsd - a.extraUsd || b.requests - a.requests),
|
|
346
|
+
largest: [...all].sort((a, b) => (b.extraUsd ?? 0) - (a.extraUsd ?? 0) || b.inputTokens - a.inputTokens).slice(0, 10),
|
|
347
|
+
};
|
|
348
|
+
}
|
|
349
|
+
/** "Claude Code 2.1.329" or "Claude Code 2.1.329 and 2.1.330": the versions that sent them, most costly first. */
|
|
350
|
+
function versionsText(u) {
|
|
351
|
+
const named = u.byVersion.filter((v) => v.version !== "unknown").map((v) => v.version);
|
|
352
|
+
const list = named.length > 3 ? `${named.slice(0, 3).join(", ")} and ${named.length - 3} more` : named.join(", ").replace(/, ([^,]+)$/, " and $1");
|
|
353
|
+
return named.length ? `Claude Code ${list}` : "Claude Code";
|
|
354
|
+
}
|
|
355
|
+
/** The section in `cache-misses`, or nothing when there are none. */
|
|
356
|
+
export function renderUncached(u) {
|
|
357
|
+
if (!u || u.requests === 0)
|
|
358
|
+
return [];
|
|
359
|
+
const out = [
|
|
360
|
+
...wrap(`Requests the cache never saw: ${versionsText(u)} sent ${u.requests} request${u.requests === 1 ? "" : "s"} that wrote nothing to the ` +
|
|
361
|
+
`prompt cache and billed ~${formatTokens(u.inputTokens)} tokens as new input. With the cache working they would have ` +
|
|
362
|
+
`cost ${money(u.extraUsd)} less${u.unpriced ? ` (${u.unpriced} on unpriced models not included)` : ""}. Claude Code 2.1.329 does this when hooks add text at session ` +
|
|
363
|
+
"start (anthropics/claude-code#111948): update Claude Code when a fixed version is out.", 82),
|
|
364
|
+
` ${"version".padEnd(10)} ${"requests".padStart(8)} ${"sessions".padStart(8)} ${"new input".padStart(10)} ${"cost".padStart(9)}`,
|
|
365
|
+
];
|
|
366
|
+
for (const v of u.byVersion.slice(0, 8)) {
|
|
367
|
+
out.push(` ${v.version.padEnd(10)} ${String(v.requests).padStart(8)} ${String(v.sessions).padStart(8)} ${`~${formatTokens(v.inputTokens)}`.padStart(10)} ${money(v.extraUsd).padStart(9)}`);
|
|
368
|
+
}
|
|
369
|
+
out.push(" Not counted: contexts under 20k, a session's first request, the first after a", " compaction, a model switch or an hour's pause, and sessions that never cached.");
|
|
370
|
+
return out;
|
|
371
|
+
}
|
|
372
|
+
/** `doctor`'s line when the last `days` hold any; undefined otherwise. */
|
|
373
|
+
export function uncachedCheck(days = 30, paths) {
|
|
374
|
+
const u = uncachedRequests(days, paths);
|
|
375
|
+
if (u.requests === 0)
|
|
376
|
+
return undefined;
|
|
377
|
+
return {
|
|
378
|
+
label: "Prompt cache",
|
|
379
|
+
status: "warn",
|
|
380
|
+
detail: `${versionsText(u)} sent ${u.requests} request${u.requests === 1 ? "" : "s"} in the last ${days} days that the prompt cache never saw: ${money(u.extraUsd)} more than cached (anthropics/claude-code#111948). Update Claude Code when a fixed version is out; context-doctor cache-misses has the detail`,
|
|
381
|
+
};
|
|
382
|
+
}
|
|
265
383
|
/** Two rates differ beyond chance (two-proportion z-test, 99%). */
|
|
266
384
|
function differs(a, b) {
|
|
267
385
|
const p = (a.misses + b.misses) / (a.eligible + b.eligible);
|
|
@@ -397,6 +515,7 @@ export function cacheMisses(days = 30, paths, onProgress, missLog = missLogPath(
|
|
|
397
515
|
}
|
|
398
516
|
}
|
|
399
517
|
onProgress?.(targets.length, targets.length);
|
|
518
|
+
const uncached = uncachedRequests(days, targets);
|
|
400
519
|
const finish = (s) => ({ ...s, rate: s.eligible ? s.misses / s.eligible : 0 });
|
|
401
520
|
const byModel = [...models.entries()].map(([model, s]) => ({ model, ...finish(s) })).sort((a, b) => b.rate - a.rate);
|
|
402
521
|
const bySize = SIZE_BUCKETS.filter(([b]) => sizes.has(b)).map(([bucket]) => ({ bucket, ...finish(sizes.get(bucket)) }));
|
|
@@ -419,6 +538,7 @@ export function cacheMisses(days = 30, paths, onProgress, missLog = missLogPath(
|
|
|
419
538
|
diagnosed: diagnosedMisses(since, missLog),
|
|
420
539
|
late: lateReport(late),
|
|
421
540
|
coldReturns: coldReturns(days, targets),
|
|
541
|
+
...(uncached.requests ? { uncached } : {}),
|
|
422
542
|
};
|
|
423
543
|
}
|
|
424
544
|
/**
|
|
@@ -662,6 +782,9 @@ export function renderCacheMisses(r, limitLines) {
|
|
|
662
782
|
const out = ["CACHE MISSES WITHIN THE CACHE LIFETIME", "═".repeat(60)];
|
|
663
783
|
if (r.eligible === 0) {
|
|
664
784
|
out.push(`No Claude Code requests in the last ${r.days} days that could have read a warm cache (consecutive, within the cache lifetime, over 20k tokens).`);
|
|
785
|
+
const never = renderUncached(r.uncached);
|
|
786
|
+
if (never.length)
|
|
787
|
+
out.push("", ...never);
|
|
665
788
|
const late = renderLate(r.late);
|
|
666
789
|
if (late.length)
|
|
667
790
|
out.push("", ...late);
|
|
@@ -691,6 +814,9 @@ export function renderCacheMisses(r, limitLines) {
|
|
|
691
814
|
out.push(" \"Nothing visible\": no model switch, compaction, context edit, API error or", " long tool run before it. The system prompt, tools or memory changing, or the", " provider evicting the cache early, would look like this from the client.");
|
|
692
815
|
}
|
|
693
816
|
}
|
|
817
|
+
const never = renderUncached(r.uncached);
|
|
818
|
+
if (never.length)
|
|
819
|
+
out.push("", ...never);
|
|
694
820
|
const late = renderLate(r.late);
|
|
695
821
|
if (late.length)
|
|
696
822
|
out.push("", ...late);
|
package/dist/cli.js
CHANGED
|
@@ -27,7 +27,8 @@ import { latestModelComparison } from "./abstore.js";
|
|
|
27
27
|
import { buildImpactReport } from "./impact.js";
|
|
28
28
|
import { measureTokenizer, renderTokenizer } from "./tokenizer-measure.js";
|
|
29
29
|
import { autopilotOff, autopilotOn, autopilotPauseResult, autopilotPaths, autopilotStatus, DEFAULT_AUTOPILOT_PORT } from "./autopilot.js";
|
|
30
|
-
import { estimateSavings, renderSavings, renderShare, savingsRows } from "./savings.js";
|
|
30
|
+
import { estimateSavings, renderSampleSavings, renderSavings, renderShare, savingsRows } from "./savings.js";
|
|
31
|
+
import { writeSampleHistory } from "./sample.js";
|
|
31
32
|
import { prescan } from "./scan.js";
|
|
32
33
|
import { REQUEST_ROWS } from "./coldresume.js";
|
|
33
34
|
import { coldReturns } from "./coldreturns.js";
|
|
@@ -46,6 +47,7 @@ import { renderDiff } from "./diff.js";
|
|
|
46
47
|
import { renderExperiment, runExperiment } from "./experiment.js";
|
|
47
48
|
import { runStatusLine } from "./statusline.js";
|
|
48
49
|
import { runMod } from "./modmeasure.js";
|
|
50
|
+
import { recentToolLines } from "./apptools.js";
|
|
49
51
|
import { renderSubagents, subagentFiles, subagentReport } from "./subagents.js";
|
|
50
52
|
import { findPreset, PRESETS, RC_FILENAME } from "./config.js";
|
|
51
53
|
import { runWatch } from "./watch.js";
|
|
@@ -70,7 +72,7 @@ import { renderPayback, subagentPayback, SUBAGENT_CANDIDATE } from "./subagentpa
|
|
|
70
72
|
import { compactionQuality, renderCompactionQuality, QUALITY_ROWS } from "./compactquality.js";
|
|
71
73
|
import { isHandoffId, listHandoffs, readHandoff, renderHandoffList, stripControls } from "./handoff.js";
|
|
72
74
|
import { claudeLimitFit, limitSavingsLines, limitsReport, renderLimits, renderLimitsReport } from "./limits.js";
|
|
73
|
-
import { creditsLines, creditsReport } from "./credits.js";
|
|
75
|
+
import { creditsAheadLine, creditsAheadNow, creditsLines, creditsReport } from "./credits.js";
|
|
74
76
|
import { currentTranscript, findSession, recall, renderRecall } from "./recall.js";
|
|
75
77
|
import { measureSubagentCosts, renderCostMedians, saveSubagentCosts } from "./fanout.js";
|
|
76
78
|
import { applyPrune, canonical, installedSkills, planPrune, renderPrune, undoPrune } from "./prune.js";
|
|
@@ -87,7 +89,7 @@ import { claudeCodeSession, collectSpend, renderSpend, renderSpendShare, session
|
|
|
87
89
|
import { buildExport, defaultDeveloper, exportFileName, mergeExports, readExports, renderExportDone, renderMerge } from "./spendteam.js";
|
|
88
90
|
import { renderSessionComparison } from "./ccost.js";
|
|
89
91
|
import { withOrgRatesHeld } from "./orgrates.js";
|
|
90
|
-
import { clearBudget, parseBudget, periodSpend, promptHookInstalled, readBudget, renderBudgetStatus, writeBudget } from "./budget.js";
|
|
92
|
+
import { clearBudget, parseBudget, periodCredits, periodSpend, promptHookInstalled, readBudget, renderBudgetStatus, writeBudget } from "./budget.js";
|
|
91
93
|
/**
|
|
92
94
|
* The commands that print JSON with --json. Any other command refuses the
|
|
93
95
|
* flag: it used to print its text report anyway and exit 0, so a script
|
|
@@ -124,7 +126,7 @@ Start here:
|
|
|
124
126
|
Cursor's postToolUse), Claude Code's PreCompact
|
|
125
127
|
hook, which tells each compaction what to keep,
|
|
126
128
|
and Copilot's sessionStart (the standing rules)
|
|
127
|
-
context-doctor savings [--days n] [--share [--copy]]
|
|
129
|
+
context-doctor savings [--days n] [--share [--copy]] [--sample]
|
|
128
130
|
What your recent Claude Code sessions cost, and what
|
|
129
131
|
/compact at cold resumes, autopilot and an earlier
|
|
130
132
|
auto-compact window would save, replayed and priced
|
|
@@ -483,7 +485,7 @@ async function measureFixInputs(days) {
|
|
|
483
485
|
// The subagents' progress summaries: estimated from their transcripts; a value of the variable the user set is theirs.
|
|
484
486
|
const psState = progressSummariesState({ cwd });
|
|
485
487
|
const psSince = Date.now() - days * 86_400_000;
|
|
486
|
-
const progressSummaries = estimateProgressSummaries(subagentTranscripts(psSince), { since: psSince, forkGateOff: psState.forkGateOff, offSince: psState.offSince });
|
|
488
|
+
const progressSummaries = estimateProgressSummaries(subagentTranscripts(psSince), { since: psSince, forkGateOff: psState.forkGateOff, offSince: psState.offSince, route: psState.route });
|
|
487
489
|
// Codex's auto-compact limit: its rollouts replayed at earlier limits; a limit the user set is theirs.
|
|
488
490
|
const codexCompact = replayCodexCompact({ days });
|
|
489
491
|
const cxSet = currentCodexCompact();
|
|
@@ -516,6 +518,7 @@ async function measureFixInputs(days) {
|
|
|
516
518
|
: !underClaudeCode() && shellSet(DEFER_APP_TOOLS_ENV, sources, process.env)
|
|
517
519
|
? { value: process.env[DEFER_APP_TOOLS_ENV], where: "the environment" }
|
|
518
520
|
: undefined;
|
|
521
|
+
const appToolsSeen = recentToolLines(days);
|
|
519
522
|
let recordProblem;
|
|
520
523
|
try {
|
|
521
524
|
loadFixRecords();
|
|
@@ -544,6 +547,8 @@ async function measureFixInputs(days) {
|
|
|
544
547
|
...(deferrable.length ? { mcpDefer: { servers: deferrable, days } } : {}),
|
|
545
548
|
...(appTools.length ? { desktopTools: { servers: appTools.map((s) => ({ name: s.name, tools: s.tools, tokens: s.tokens, starts: s.starts, calledStarts: s.calledStarts, usd: s.usd, unusedUsd: s.unusedUsd, calledUsd: s.calledUsd })), days } } : {}),
|
|
546
549
|
...(desktopToolsSet ? { desktopToolsSet } : {}),
|
|
550
|
+
// What context-doctor's mod saw Claude Code hand over (apptools.ts): proof the lever reaches the app, or why not.
|
|
551
|
+
...(appToolsSeen.length ? { appToolsSeen } : {}),
|
|
547
552
|
subagentModel,
|
|
548
553
|
subagentModelSet,
|
|
549
554
|
// The newest ab --via claude-code comparison of Sonnet 5.5 with another model: the subagent-model line quotes it.
|
|
@@ -614,6 +619,7 @@ const FLAGS = [
|
|
|
614
619
|
{ names: ["--dry-run"], set: (a) => { a.dryRun = true; } },
|
|
615
620
|
{ names: ["--copy"], set: (a) => { a.copy = true; } },
|
|
616
621
|
{ names: ["--share"], set: (a) => { a.share = true; } },
|
|
622
|
+
{ names: ["--sample"], set: (a) => { a.sample = true; } },
|
|
617
623
|
{ names: ["--report"], set: (a) => { a.report = true; } },
|
|
618
624
|
{ names: ["--by"], value: "text", set: (a, v) => { a.by = v; } },
|
|
619
625
|
{ names: ["--export"], set: (a) => { a.exportSpend = true; } },
|
|
@@ -1182,6 +1188,8 @@ async function main() {
|
|
|
1182
1188
|
if (args.command === "savings" || (!args.command && process.stdout.isTTY && hasClaudeSessions())) {
|
|
1183
1189
|
// `savings`, and a bare `context-doctor --json` or `--share` in a terminal
|
|
1184
1190
|
// with Claude Code history (what a bare run printed before the one-question screen).
|
|
1191
|
+
if (args.sample && (args.json || args.share))
|
|
1192
|
+
usageError("--sample is a demonstration for the terminal; it does not go with --json or --share.");
|
|
1185
1193
|
const replaying = progressLine("Replaying your Claude Code sessions through autopilot");
|
|
1186
1194
|
// Each transcript read once for every report below; what an earlier run kept is not read again (scan.ts).
|
|
1187
1195
|
prescan([
|
|
@@ -1190,6 +1198,19 @@ async function main() {
|
|
|
1190
1198
|
], replaying.tick);
|
|
1191
1199
|
const report = estimateSavings(args.days ?? 30, {}, undefined, replaying.tick);
|
|
1192
1200
|
replaying.clear();
|
|
1201
|
+
// --sample: the real report on a generated history, said to be a sample.
|
|
1202
|
+
// Never substituted for the real one: with no history the empty report
|
|
1203
|
+
// says so and offers this flag (renderSavings' empty branch).
|
|
1204
|
+
if (args.sample) {
|
|
1205
|
+
const demo = writeSampleHistory();
|
|
1206
|
+
try {
|
|
1207
|
+
console.log(renderSampleSavings(estimateSavings(30, {}, demo.paths)));
|
|
1208
|
+
}
|
|
1209
|
+
finally {
|
|
1210
|
+
demo.cleanup();
|
|
1211
|
+
}
|
|
1212
|
+
return;
|
|
1213
|
+
}
|
|
1193
1214
|
const setWindow = currentCompactWindow();
|
|
1194
1215
|
const measuring = progressLine("Measuring your compactions");
|
|
1195
1216
|
const reread = compactionQuality(60, undefined, measuring.tick).extraRereadTokensPerCompaction;
|
|
@@ -1456,7 +1477,7 @@ async function main() {
|
|
|
1456
1477
|
usageError("--apply and --share do not go together: --share only prints totals.");
|
|
1457
1478
|
const { inputs, prunePlan } = await measureFixInputs(args.days ?? 30);
|
|
1458
1479
|
const fixes = planFixes(inputs);
|
|
1459
|
-
const since = savedSince(readFixRecords());
|
|
1480
|
+
const since = savedSince(readFixRecords(), { progressRoute: progressSummariesState({ cwd: process.cwd() }).route });
|
|
1460
1481
|
if (args.share) {
|
|
1461
1482
|
const text = renderFixShare(inputs.days, inputs.billedUsd, fixes, inputs.codexCompact?.billedUsd);
|
|
1462
1483
|
console.log(text);
|
|
@@ -1586,7 +1607,11 @@ async function main() {
|
|
|
1586
1607
|
}
|
|
1587
1608
|
// Requests paid from usage credits past a limit: read only when the ledger says a limit ran out.
|
|
1588
1609
|
const credits = creditsReport(report.days, { now: report.now });
|
|
1589
|
-
|
|
1610
|
+
// Running out before the weekly reset with extra usage on: what the hours past it would cost (the transcripts read only then).
|
|
1611
|
+
const ahead = creditsAheadNow({ now: report.now, status: report.windows.find((w) => w.app === "claude" && w.window === "seven_day") });
|
|
1612
|
+
console.log(args.json
|
|
1613
|
+
? JSON.stringify({ ...report, ...(credits ? { credits } : {}), ...(ahead ? { creditsAhead: ahead } : {}) }, null, 2)
|
|
1614
|
+
: renderLimits(report, credits ? creditsLines(credits, report.now) : [], ahead ? creditsAheadLine(ahead, report.now) : undefined));
|
|
1590
1615
|
return;
|
|
1591
1616
|
}
|
|
1592
1617
|
if (args.command === "spend") {
|
|
@@ -1649,7 +1674,7 @@ async function main() {
|
|
|
1649
1674
|
const reading = progressLine("Reading your usage across tools");
|
|
1650
1675
|
// The progress summaries' estimate: none after the variable turned them off (fix's record), none at all when set with no record.
|
|
1651
1676
|
const ps = progressSummariesState({ cwd: process.cwd() });
|
|
1652
|
-
const report = spendReport(args.days ?? 30, { onProgress: reading.tick, ...(by ? { by } : {}), progress: { forkGateOff: ps.forkGateOff, offSince: ps.offSince, ...(ps.set && disablesSummaries(ps.set.value) ? { set: ps.set.where } : {}) } });
|
|
1677
|
+
const report = spendReport(args.days ?? 30, { onProgress: reading.tick, ...(by ? { by } : {}), progress: { forkGateOff: ps.forkGateOff, offSince: ps.offSince, route: ps.route, ...(ps.set && disablesSummaries(ps.set.value) ? { set: ps.set.where } : {}) } });
|
|
1653
1678
|
reading.clear();
|
|
1654
1679
|
if (args.json)
|
|
1655
1680
|
console.log(JSON.stringify(report, null, 2));
|
|
@@ -1690,10 +1715,14 @@ async function main() {
|
|
|
1690
1715
|
}
|
|
1691
1716
|
const b = readBudget();
|
|
1692
1717
|
const s = b ? periodSpend(b.period) : undefined;
|
|
1718
|
+
// Claude Code's part past the plan's limit, on usage credits: in `spent` already, said apart.
|
|
1719
|
+
const c = s ? periodCredits(s.start) : undefined;
|
|
1720
|
+
// With a budget set: running out before the weekly reset with extra usage on, and what that would cost.
|
|
1721
|
+
const ahead = s ? creditsAheadNow() : undefined;
|
|
1693
1722
|
if (args.json)
|
|
1694
|
-
console.log(JSON.stringify(b && s ? { ...b, spent: s.usd, byTool: s.byTool, periodStart: s.start, periodEnd: s.end, unpriced: s.unpriced ?? null } : null, null, 2));
|
|
1723
|
+
console.log(JSON.stringify(b && s ? { ...b, spent: s.usd, byTool: s.byTool, periodStart: s.start, periodEnd: s.end, unpriced: s.unpriced ?? null, credits: c ? { usd: c.usd, requests: c.requests, fromHeaders: c.fromHeaders, inferred: c.inferred } : null, creditsAhead: ahead ?? null } : null, null, 2));
|
|
1695
1724
|
else
|
|
1696
|
-
console.log(withInvocation(renderBudgetStatus(b, s, promptHookInstalled())));
|
|
1725
|
+
console.log(withInvocation(renderBudgetStatus(b, s, promptHookInstalled(), c, ahead)));
|
|
1697
1726
|
return;
|
|
1698
1727
|
}
|
|
1699
1728
|
if (args.command === "compactions") {
|
package/dist/credits.d.ts
CHANGED
|
@@ -21,10 +21,11 @@
|
|
|
21
21
|
* Dollars are each request at API list prices, as `spend` prices it.
|
|
22
22
|
* Whether usage credits are billed at exactly those prices is not verified
|
|
23
23
|
* here, so every figure is said to be an estimate. Read only by commands
|
|
24
|
-
* the user runs (`limits`, `spend`, `doctor`)
|
|
24
|
+
* the user runs (`limits`, `spend`, `doctor`, `budget`), and by the
|
|
25
|
+
* budget's hook at a threshold it already speaks at: nothing is drawn or sent.
|
|
25
26
|
*/
|
|
26
27
|
import { type ExtraUsage } from "./claudedir.js";
|
|
27
|
-
import { type LimitReading, type OverageReading } from "./limits.js";
|
|
28
|
+
import { type LimitReading, type OverageReading, type UsagePoint, type WindowStatus } from "./limits.js";
|
|
28
29
|
/** A window that read 100%: from that reading until it reset. */
|
|
29
30
|
export interface SpentSpan {
|
|
30
31
|
window: "five_hour" | "seven_day";
|
|
@@ -107,6 +108,67 @@ export declare function nothingPast(inp: CreditsInputs): boolean;
|
|
|
107
108
|
export declare function creditsReport(days?: number, opts?: CreditsOptions): (CreditsSummary & {
|
|
108
109
|
extraUsage?: ExtraUsage;
|
|
109
110
|
}) | undefined;
|
|
111
|
+
/** The same from `since` to now (`budget`'s day or week). Undefined when nothing was past the limit. */
|
|
112
|
+
export declare function creditsSince(since: number, opts?: CreditsOptions): (CreditsSummary & {
|
|
113
|
+
extraUsage?: ExtraUsage;
|
|
114
|
+
}) | undefined;
|
|
115
|
+
/**
|
|
116
|
+
* The weekly limit at the recent pace runs out before it resets, and extra
|
|
117
|
+
* usage is on: Claude Code would keep working on usage credits from then
|
|
118
|
+
* until the reset. About how much, at the last 24 hours' dollars an hour on
|
|
119
|
+
* this machine (list prices, an estimate).
|
|
120
|
+
*/
|
|
121
|
+
export interface CreditsAhead {
|
|
122
|
+
/** When the weekly limit runs out at the recent pace, and when it resets, ms. */
|
|
123
|
+
runsOutAt: number;
|
|
124
|
+
resetsAt: number;
|
|
125
|
+
/** Hours from the run-out (or now, if later) to the reset. */
|
|
126
|
+
hours: number;
|
|
127
|
+
/** Claude Code's list-price dollars an hour over the last 24 hours, on this machine, subagents included. */
|
|
128
|
+
usdPerHour: number;
|
|
129
|
+
/** hours times usdPerHour. */
|
|
130
|
+
usd: number;
|
|
131
|
+
/** The model most of those dollars went to, and its share, when it is most of them. */
|
|
132
|
+
model?: string;
|
|
133
|
+
modelShare?: number;
|
|
134
|
+
/** The window's average pace (% an hour), and whether the limit lasts to the reset at it. */
|
|
135
|
+
averagePerHour?: number;
|
|
136
|
+
averageLasts?: boolean;
|
|
137
|
+
}
|
|
138
|
+
/** Extra usage on, and nothing in `~/.claude.json` saying credits are not paying now. */
|
|
139
|
+
export declare function extraUsageOn(x: ExtraUsage | undefined): boolean;
|
|
140
|
+
/**
|
|
141
|
+
* The weekly window's run-out and what the hours past it would cost. Pure:
|
|
142
|
+
* `usage` is the last 24 hours' requests. Undefined unless extra usage is on
|
|
143
|
+
* and the weekly window, read recently, runs out before its reset at the
|
|
144
|
+
* recent pace, with dollars to price the hours at.
|
|
145
|
+
*/
|
|
146
|
+
export declare function creditsAhead(status: WindowStatus | undefined, extra: ExtraUsage | undefined, usage: Array<Pick<UsagePoint, "ts" | "usd" | "model">>, now: number): CreditsAhead | undefined;
|
|
147
|
+
export interface CreditsAheadOptions {
|
|
148
|
+
now?: number;
|
|
149
|
+
logPath?: string;
|
|
150
|
+
/** Claude Code transcripts to read (tests); default every one touched in the last day. */
|
|
151
|
+
claudePaths?: string[];
|
|
152
|
+
/** `~/.claude.json`'s word (tests); default read from the home below. */
|
|
153
|
+
extraUsage?: ExtraUsage | null;
|
|
154
|
+
home?: string;
|
|
155
|
+
/** The weekly window's status when the caller has it (`limits`); default read from the ledger. */
|
|
156
|
+
status?: WindowStatus;
|
|
157
|
+
}
|
|
158
|
+
/**
|
|
159
|
+
* creditsAhead from this machine: `~/.claude.json` first, then the ledger's
|
|
160
|
+
* weekly window, and the transcripts of the last day only when both say it
|
|
161
|
+
* applies. Never throws: a command's own figures must not be lost to it.
|
|
162
|
+
*/
|
|
163
|
+
export declare function creditsAheadNow(opts?: CreditsAheadOptions): CreditsAhead | undefined;
|
|
164
|
+
/**
|
|
165
|
+
* One line: "Extra usage is on: at this pace your weekly limit runs out on
|
|
166
|
+
* Thu, Nov 26 at 18:19, 46 hours before it resets, and Claude Code would
|
|
167
|
+
* keep working on usage credits until then: about $1,234 at API list prices
|
|
168
|
+
* (an estimate), at your last 24 hours' $26.80 an hour, mostly Fable 5.2.
|
|
169
|
+
* At this week's average pace (0.55% an hour) it lasts until the reset."
|
|
170
|
+
*/
|
|
171
|
+
export declare function creditsAheadLine(a: CreditsAhead, now: number): string;
|
|
110
172
|
/** "at 14:05" within the day, else "on Tue, Nov 17 at 14:05": local time. */
|
|
111
173
|
export declare function whenText(ms: number, now: number): string;
|
|
112
174
|
/** The dollars, in the words every report uses: list prices, an estimate. */
|