context-doctor 0.50.0 → 0.51.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 +10 -9
- 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 +20 -8
- package/dist/credits.d.ts +64 -2
- package/dist/credits.js +88 -3
- package/dist/doctor.d.ts +18 -6
- package/dist/doctor.js +56 -11
- 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/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/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
|
@@ -46,6 +46,7 @@ import { renderDiff } from "./diff.js";
|
|
|
46
46
|
import { renderExperiment, runExperiment } from "./experiment.js";
|
|
47
47
|
import { runStatusLine } from "./statusline.js";
|
|
48
48
|
import { runMod } from "./modmeasure.js";
|
|
49
|
+
import { recentToolLines } from "./apptools.js";
|
|
49
50
|
import { renderSubagents, subagentFiles, subagentReport } from "./subagents.js";
|
|
50
51
|
import { findPreset, PRESETS, RC_FILENAME } from "./config.js";
|
|
51
52
|
import { runWatch } from "./watch.js";
|
|
@@ -70,7 +71,7 @@ import { renderPayback, subagentPayback, SUBAGENT_CANDIDATE } from "./subagentpa
|
|
|
70
71
|
import { compactionQuality, renderCompactionQuality, QUALITY_ROWS } from "./compactquality.js";
|
|
71
72
|
import { isHandoffId, listHandoffs, readHandoff, renderHandoffList, stripControls } from "./handoff.js";
|
|
72
73
|
import { claudeLimitFit, limitSavingsLines, limitsReport, renderLimits, renderLimitsReport } from "./limits.js";
|
|
73
|
-
import { creditsLines, creditsReport } from "./credits.js";
|
|
74
|
+
import { creditsAheadLine, creditsAheadNow, creditsLines, creditsReport } from "./credits.js";
|
|
74
75
|
import { currentTranscript, findSession, recall, renderRecall } from "./recall.js";
|
|
75
76
|
import { measureSubagentCosts, renderCostMedians, saveSubagentCosts } from "./fanout.js";
|
|
76
77
|
import { applyPrune, canonical, installedSkills, planPrune, renderPrune, undoPrune } from "./prune.js";
|
|
@@ -87,7 +88,7 @@ import { claudeCodeSession, collectSpend, renderSpend, renderSpendShare, session
|
|
|
87
88
|
import { buildExport, defaultDeveloper, exportFileName, mergeExports, readExports, renderExportDone, renderMerge } from "./spendteam.js";
|
|
88
89
|
import { renderSessionComparison } from "./ccost.js";
|
|
89
90
|
import { withOrgRatesHeld } from "./orgrates.js";
|
|
90
|
-
import { clearBudget, parseBudget, periodSpend, promptHookInstalled, readBudget, renderBudgetStatus, writeBudget } from "./budget.js";
|
|
91
|
+
import { clearBudget, parseBudget, periodCredits, periodSpend, promptHookInstalled, readBudget, renderBudgetStatus, writeBudget } from "./budget.js";
|
|
91
92
|
/**
|
|
92
93
|
* The commands that print JSON with --json. Any other command refuses the
|
|
93
94
|
* flag: it used to print its text report anyway and exit 0, so a script
|
|
@@ -483,7 +484,7 @@ async function measureFixInputs(days) {
|
|
|
483
484
|
// The subagents' progress summaries: estimated from their transcripts; a value of the variable the user set is theirs.
|
|
484
485
|
const psState = progressSummariesState({ cwd });
|
|
485
486
|
const psSince = Date.now() - days * 86_400_000;
|
|
486
|
-
const progressSummaries = estimateProgressSummaries(subagentTranscripts(psSince), { since: psSince, forkGateOff: psState.forkGateOff, offSince: psState.offSince });
|
|
487
|
+
const progressSummaries = estimateProgressSummaries(subagentTranscripts(psSince), { since: psSince, forkGateOff: psState.forkGateOff, offSince: psState.offSince, route: psState.route });
|
|
487
488
|
// Codex's auto-compact limit: its rollouts replayed at earlier limits; a limit the user set is theirs.
|
|
488
489
|
const codexCompact = replayCodexCompact({ days });
|
|
489
490
|
const cxSet = currentCodexCompact();
|
|
@@ -516,6 +517,7 @@ async function measureFixInputs(days) {
|
|
|
516
517
|
: !underClaudeCode() && shellSet(DEFER_APP_TOOLS_ENV, sources, process.env)
|
|
517
518
|
? { value: process.env[DEFER_APP_TOOLS_ENV], where: "the environment" }
|
|
518
519
|
: undefined;
|
|
520
|
+
const appToolsSeen = recentToolLines(days);
|
|
519
521
|
let recordProblem;
|
|
520
522
|
try {
|
|
521
523
|
loadFixRecords();
|
|
@@ -544,6 +546,8 @@ async function measureFixInputs(days) {
|
|
|
544
546
|
...(deferrable.length ? { mcpDefer: { servers: deferrable, days } } : {}),
|
|
545
547
|
...(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
548
|
...(desktopToolsSet ? { desktopToolsSet } : {}),
|
|
549
|
+
// What context-doctor's mod saw Claude Code hand over (apptools.ts): proof the lever reaches the app, or why not.
|
|
550
|
+
...(appToolsSeen.length ? { appToolsSeen } : {}),
|
|
547
551
|
subagentModel,
|
|
548
552
|
subagentModelSet,
|
|
549
553
|
// The newest ab --via claude-code comparison of Sonnet 5.5 with another model: the subagent-model line quotes it.
|
|
@@ -1456,7 +1460,7 @@ async function main() {
|
|
|
1456
1460
|
usageError("--apply and --share do not go together: --share only prints totals.");
|
|
1457
1461
|
const { inputs, prunePlan } = await measureFixInputs(args.days ?? 30);
|
|
1458
1462
|
const fixes = planFixes(inputs);
|
|
1459
|
-
const since = savedSince(readFixRecords());
|
|
1463
|
+
const since = savedSince(readFixRecords(), { progressRoute: progressSummariesState({ cwd: process.cwd() }).route });
|
|
1460
1464
|
if (args.share) {
|
|
1461
1465
|
const text = renderFixShare(inputs.days, inputs.billedUsd, fixes, inputs.codexCompact?.billedUsd);
|
|
1462
1466
|
console.log(text);
|
|
@@ -1586,7 +1590,11 @@ async function main() {
|
|
|
1586
1590
|
}
|
|
1587
1591
|
// Requests paid from usage credits past a limit: read only when the ledger says a limit ran out.
|
|
1588
1592
|
const credits = creditsReport(report.days, { now: report.now });
|
|
1589
|
-
|
|
1593
|
+
// Running out before the weekly reset with extra usage on: what the hours past it would cost (the transcripts read only then).
|
|
1594
|
+
const ahead = creditsAheadNow({ now: report.now, status: report.windows.find((w) => w.app === "claude" && w.window === "seven_day") });
|
|
1595
|
+
console.log(args.json
|
|
1596
|
+
? JSON.stringify({ ...report, ...(credits ? { credits } : {}), ...(ahead ? { creditsAhead: ahead } : {}) }, null, 2)
|
|
1597
|
+
: renderLimits(report, credits ? creditsLines(credits, report.now) : [], ahead ? creditsAheadLine(ahead, report.now) : undefined));
|
|
1590
1598
|
return;
|
|
1591
1599
|
}
|
|
1592
1600
|
if (args.command === "spend") {
|
|
@@ -1649,7 +1657,7 @@ async function main() {
|
|
|
1649
1657
|
const reading = progressLine("Reading your usage across tools");
|
|
1650
1658
|
// The progress summaries' estimate: none after the variable turned them off (fix's record), none at all when set with no record.
|
|
1651
1659
|
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 } : {}) } });
|
|
1660
|
+
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
1661
|
reading.clear();
|
|
1654
1662
|
if (args.json)
|
|
1655
1663
|
console.log(JSON.stringify(report, null, 2));
|
|
@@ -1690,10 +1698,14 @@ async function main() {
|
|
|
1690
1698
|
}
|
|
1691
1699
|
const b = readBudget();
|
|
1692
1700
|
const s = b ? periodSpend(b.period) : undefined;
|
|
1701
|
+
// Claude Code's part past the plan's limit, on usage credits: in `spent` already, said apart.
|
|
1702
|
+
const c = s ? periodCredits(s.start) : undefined;
|
|
1703
|
+
// With a budget set: running out before the weekly reset with extra usage on, and what that would cost.
|
|
1704
|
+
const ahead = s ? creditsAheadNow() : undefined;
|
|
1693
1705
|
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));
|
|
1706
|
+
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
1707
|
else
|
|
1696
|
-
console.log(withInvocation(renderBudgetStatus(b, s, promptHookInstalled())));
|
|
1708
|
+
console.log(withInvocation(renderBudgetStatus(b, s, promptHookInstalled(), c, ahead)));
|
|
1697
1709
|
return;
|
|
1698
1710
|
}
|
|
1699
1711
|
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. */
|
package/dist/credits.js
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 { readExtraUsage } from "./claudedir.js";
|
|
27
|
-
import { claudeUsage, cleanReadings, CLAUDE_WINDOWS, limitsLogPath, readClaudeReadings, readOverageReadings } from "./limits.js";
|
|
28
|
+
import { claudeUsage, cleanReadings, CLAUDE_WINDOWS, limitsLogPath, modelLabel, readClaudeReadings, readOverageReadings, windowStatus } from "./limits.js";
|
|
28
29
|
const MIN = 60_000;
|
|
29
30
|
const HOUR = 60 * MIN;
|
|
30
31
|
const DAY = 24 * HOUR;
|
|
@@ -185,7 +186,11 @@ export function nothingPast(inp) {
|
|
|
185
186
|
*/
|
|
186
187
|
export function creditsReport(days = 30, opts = {}) {
|
|
187
188
|
const now = opts.now ?? Date.now();
|
|
188
|
-
|
|
189
|
+
return creditsSince(now - days * DAY, { ...opts, now });
|
|
190
|
+
}
|
|
191
|
+
/** The same from `since` to now (`budget`'s day or week). Undefined when nothing was past the limit. */
|
|
192
|
+
export function creditsSince(since, opts = {}) {
|
|
193
|
+
const now = opts.now ?? Date.now();
|
|
189
194
|
const inp = creditsInputs(since, { ...opts, now });
|
|
190
195
|
if (nothingPast(inp))
|
|
191
196
|
return undefined;
|
|
@@ -194,6 +199,86 @@ export function creditsReport(days = 30, opts = {}) {
|
|
|
194
199
|
const s = creditsOf(usage, inp);
|
|
195
200
|
return s.requests ? { ...s, ...(inp.extraUsage ? { extraUsage: inp.extraUsage } : {}) } : undefined;
|
|
196
201
|
}
|
|
202
|
+
/** The look-back the dollars an hour are read over: the same day `limits`' recent pace is. */
|
|
203
|
+
const AHEAD_LOOKBACK_MS = DAY;
|
|
204
|
+
/** Extra usage on, and nothing in `~/.claude.json` saying credits are not paying now. */
|
|
205
|
+
export function extraUsageOn(x) {
|
|
206
|
+
if (x?.enabled !== true)
|
|
207
|
+
return false;
|
|
208
|
+
return !(typeof x.disabledReason === "string" && x.disabledReason !== "fetch_error" && x.disabledReason !== "unknown");
|
|
209
|
+
}
|
|
210
|
+
/**
|
|
211
|
+
* The weekly window's run-out and what the hours past it would cost. Pure:
|
|
212
|
+
* `usage` is the last 24 hours' requests. Undefined unless extra usage is on
|
|
213
|
+
* and the weekly window, read recently, runs out before its reset at the
|
|
214
|
+
* recent pace, with dollars to price the hours at.
|
|
215
|
+
*/
|
|
216
|
+
export function creditsAhead(status, extra, usage, now) {
|
|
217
|
+
if (!status || status.app !== "claude" || status.window !== "seven_day" || status.resetSince || status.stale)
|
|
218
|
+
return undefined;
|
|
219
|
+
if (status.runsOutAt === undefined || !status.beforeReset || status.resetsAt === undefined || !extraUsageOn(extra))
|
|
220
|
+
return undefined;
|
|
221
|
+
const from = now - AHEAD_LOOKBACK_MS;
|
|
222
|
+
const recent = usage.filter((p) => p.ts > from && p.ts <= now);
|
|
223
|
+
const total = recent.reduce((a, p) => a + p.usd, 0);
|
|
224
|
+
if (!(total > 0))
|
|
225
|
+
return undefined;
|
|
226
|
+
const usdPerHour = total / (AHEAD_LOOKBACK_MS / HOUR);
|
|
227
|
+
const hours = Math.max(0, status.resetsAt - Math.max(status.runsOutAt, now)) / HOUR;
|
|
228
|
+
if (!(hours > 0))
|
|
229
|
+
return undefined;
|
|
230
|
+
const byModel = new Map();
|
|
231
|
+
for (const p of recent)
|
|
232
|
+
if (p.model)
|
|
233
|
+
byModel.set(p.model, (byModel.get(p.model) ?? 0) + p.usd);
|
|
234
|
+
const [top] = [...byModel].sort((a, b) => b[1] - a[1]);
|
|
235
|
+
const out = { runsOutAt: status.runsOutAt, resetsAt: status.resetsAt, hours, usdPerHour, usd: hours * usdPerHour };
|
|
236
|
+
if (top && top[1] / total >= 0.5) {
|
|
237
|
+
out.model = top[0];
|
|
238
|
+
out.modelShare = top[1] / total;
|
|
239
|
+
}
|
|
240
|
+
if (status.averagePerHour !== undefined && status.averagePerHour > 0) {
|
|
241
|
+
out.averagePerHour = status.averagePerHour;
|
|
242
|
+
out.averageLasts = status.at + ((100 - status.pct) / status.averagePerHour) * HOUR >= status.resetsAt;
|
|
243
|
+
}
|
|
244
|
+
return out;
|
|
245
|
+
}
|
|
246
|
+
/**
|
|
247
|
+
* creditsAhead from this machine: `~/.claude.json` first, then the ledger's
|
|
248
|
+
* weekly window, and the transcripts of the last day only when both say it
|
|
249
|
+
* applies. Never throws: a command's own figures must not be lost to it.
|
|
250
|
+
*/
|
|
251
|
+
export function creditsAheadNow(opts = {}) {
|
|
252
|
+
try {
|
|
253
|
+
const now = opts.now ?? Date.now();
|
|
254
|
+
const extra = opts.extraUsage === null ? undefined : opts.extraUsage ?? readExtraUsage(opts.home);
|
|
255
|
+
if (!extraUsageOn(extra))
|
|
256
|
+
return undefined;
|
|
257
|
+
const status = opts.status ?? windowStatus(cleanReadings(readClaudeReadings(now - 8 * DAY, opts.logPath ?? limitsLogPath()).filter((r) => r.window === "seven_day")), now);
|
|
258
|
+
if (!status?.beforeReset || status.runsOutAt === undefined || status.stale)
|
|
259
|
+
return undefined;
|
|
260
|
+
return creditsAhead(status, extra, claudeUsage(now - AHEAD_LOOKBACK_MS, now, opts.claudePaths), now);
|
|
261
|
+
}
|
|
262
|
+
catch {
|
|
263
|
+
return undefined;
|
|
264
|
+
}
|
|
265
|
+
}
|
|
266
|
+
/**
|
|
267
|
+
* One line: "Extra usage is on: at this pace your weekly limit runs out on
|
|
268
|
+
* Thu, Nov 26 at 18:19, 46 hours before it resets, and Claude Code would
|
|
269
|
+
* keep working on usage credits until then: about $1,234 at API list prices
|
|
270
|
+
* (an estimate), at your last 24 hours' $26.80 an hour, mostly Fable 5.2.
|
|
271
|
+
* At this week's average pace (0.55% an hour) it lasts until the reset."
|
|
272
|
+
*/
|
|
273
|
+
export function creditsAheadLine(a, now) {
|
|
274
|
+
const hours = a.hours >= 10 ? Math.round(a.hours) : Math.round(a.hours * 10) / 10;
|
|
275
|
+
const mostly = a.model ? `, mostly ${modelLabel(a.model)}` : "";
|
|
276
|
+
const avg = a.averagePerHour === undefined ? ""
|
|
277
|
+
: a.averageLasts ? ` At this week's average pace (${pace(a.averagePerHour)}% an hour) it lasts until the reset.`
|
|
278
|
+
: ` At this week's average pace (${pace(a.averagePerHour)}% an hour) it runs out before the reset too.`;
|
|
279
|
+
return `Extra usage is on: at this pace your weekly limit runs out ${whenText(a.runsOutAt, now)}, ${hours} hour${hours === 1 ? "" : "s"} before it resets, and Claude Code would keep working on usage credits until then: about ${dollars(a.usd)} ${AT_LIST_PRICES}, at your last 24 hours' ${dollars(a.usdPerHour)} an hour${mostly}.${avg}`;
|
|
280
|
+
}
|
|
281
|
+
const pace = (v) => (v >= 10 ? Math.round(v).toString() : v >= 1 ? v.toFixed(1) : v.toFixed(2));
|
|
197
282
|
// ---------------------------------------------------------------------------
|
|
198
283
|
// Words
|
|
199
284
|
// ---------------------------------------------------------------------------
|
package/dist/doctor.d.ts
CHANGED
|
@@ -40,6 +40,24 @@ export declare function cacheTtlCheck(home?: string, env?: NodeJS.ProcessEnv): C
|
|
|
40
40
|
*/
|
|
41
41
|
export declare function claudeCodeCostCheck(days?: number, now?: number): Check | undefined;
|
|
42
42
|
export declare function unpricedModelsCheck(days?: number, now?: number, home?: string): Check | undefined;
|
|
43
|
+
/**
|
|
44
|
+
* The Desktop app's answer to its own auto-compact offer (appwindow.ts),
|
|
45
|
+
* only when one is on file: what it offered and what you chose. A fact, not
|
|
46
|
+
* a fault.
|
|
47
|
+
*/
|
|
48
|
+
export declare function appWindowCheck(home?: string): Check | undefined;
|
|
49
|
+
/**
|
|
50
|
+
* Extra usage (usage credits past a plan's limit), as Claude Code cached it
|
|
51
|
+
* in `~/.claude.json`: on or off, and when on but held back, why. A fact,
|
|
52
|
+
* not a fault: "ok" either way. Undefined when the file says nothing.
|
|
53
|
+
*/
|
|
54
|
+
export declare function extraUsageCheck(home?: string): Check | undefined;
|
|
55
|
+
/**
|
|
56
|
+
* The MCP servers the newest Desktop session handed context-doctor's mod
|
|
57
|
+
* (apptools.ts), their type and placement, and what desktop-tools-defer
|
|
58
|
+
* would do with them. A fact, not a fault: only when one is on file.
|
|
59
|
+
*/
|
|
60
|
+
export declare function appToolsCheck(path?: string, now?: number): Check | undefined;
|
|
43
61
|
/**
|
|
44
62
|
* Devin (Cognition): the Devin CLI, and Devin Desktop (formerly Windsurf).
|
|
45
63
|
* Checked against docs.devin.ai (2026-10-20): the CLI runs hooks from
|
|
@@ -51,12 +69,6 @@ export declare function unpricedModelsCheck(days?: number, now?: number, home?:
|
|
|
51
69
|
* does not (Desktop) and has no transcript to measure either way: say that,
|
|
52
70
|
* rather than nothing or a false "ok".
|
|
53
71
|
*/
|
|
54
|
-
/**
|
|
55
|
-
* Extra usage (usage credits past a plan's limit), as Claude Code cached it
|
|
56
|
-
* in `~/.claude.json`: on or off, and when on but held back, why. A fact,
|
|
57
|
-
* not a fault: "ok" either way. Undefined when the file says nothing.
|
|
58
|
-
*/
|
|
59
|
-
export declare function extraUsageCheck(home?: string): Check | undefined;
|
|
60
72
|
export declare function devinCheck(home?: string): Check;
|
|
61
73
|
/**
|
|
62
74
|
* How long the handshake may take: 15 s, or CONTEXT_DOCTOR_MCP_HANDSHAKE_MS.
|