context-doctor 0.43.0 → 0.45.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 +4 -2
- package/dist/budget.d.ts +23 -3
- package/dist/budget.js +184 -50
- package/dist/cache.js +5 -4
- package/dist/cachemisses.js +1 -1
- package/dist/cachettl.d.ts +5 -1
- package/dist/cachettl.js +16 -29
- package/dist/ci.js +18 -2
- package/dist/cli.js +16 -12
- package/dist/codexcompact.d.ts +24 -3
- package/dist/codexcompact.js +221 -48
- package/dist/coldresume.js +16 -8
- package/dist/compactwindow.js +14 -9
- package/dist/cursor.d.ts +10 -0
- package/dist/cursor.js +20 -0
- package/dist/doctor.d.ts +9 -0
- package/dist/doctor.js +52 -0
- package/dist/extract.d.ts +2 -2
- package/dist/extract.js +14 -3
- package/dist/fanout.js +4 -2
- package/dist/fix.d.ts +8 -1
- package/dist/fix.js +59 -13
- package/dist/hook.js +45 -15
- package/dist/httpguard.d.ts +9 -1
- package/dist/httpguard.js +5 -4
- package/dist/install.js +56 -19
- package/dist/lens.js +7 -7
- package/dist/limits.d.ts +17 -4
- package/dist/limits.js +41 -29
- package/dist/mcp.js +63 -63
- package/dist/mcpclient.js +19 -19
- package/dist/mcpschema.js +10 -12
- package/dist/overhead.d.ts +7 -2
- package/dist/overhead.js +11 -3
- package/dist/pack.js +87 -23
- package/dist/pricing.d.ts +125 -6
- package/dist/pricing.js +304 -59
- package/dist/proxy.d.ts +26 -1
- package/dist/proxy.js +45 -5
- package/dist/prune.d.ts +8 -0
- package/dist/prune.js +73 -10
- package/dist/savings.js +17 -9
- package/dist/scan.d.ts +7 -1
- package/dist/scan.js +19 -1
- package/dist/sessionprice.d.ts +9 -2
- package/dist/sessionprice.js +95 -36
- package/dist/settingsedit.js +3 -2
- package/dist/spend.d.ts +75 -10
- package/dist/spend.js +279 -37
- package/dist/statusline.d.ts +10 -2
- package/dist/statusline.js +17 -8
- package/dist/subagentmodel.d.ts +2 -2
- package/dist/subagentmodel.js +42 -25
- package/dist/subagentpay.d.ts +17 -0
- package/dist/subagentpay.js +41 -2
- package/dist/subagents.d.ts +24 -0
- package/dist/subagents.js +93 -27
- package/dist/tasks.js +9 -6
- package/dist/tooloutput.d.ts +2 -0
- package/dist/tooloutput.js +16 -5
- package/package.json +1 -1
package/dist/coldresume.js
CHANGED
|
@@ -30,7 +30,7 @@ import { homedir } from "node:os";
|
|
|
30
30
|
import { join } from "node:path";
|
|
31
31
|
import { forEachLine, replyCounter, textOf } from "./session.js";
|
|
32
32
|
import { pick, rowsOf, slimUsage } from "./scan.js";
|
|
33
|
-
import { cacheWriteSplit,
|
|
33
|
+
import { cacheWriteSplit, formatUsd, rateCard, ratesAt, writeMultiplier } from "./pricing.js";
|
|
34
34
|
import { contextWindowFor, formatTokens, isCodeLike, realModel } from "./tokens.js";
|
|
35
35
|
import { claudeDir } from "./claudedir.js";
|
|
36
36
|
/**
|
|
@@ -68,7 +68,7 @@ export function isIdleCompactNotice(e) {
|
|
|
68
68
|
* reader meets it as a repeat of that reply and skips it.
|
|
69
69
|
*/
|
|
70
70
|
export const REQUEST_ROWS = {
|
|
71
|
-
id: "requests.
|
|
71
|
+
id: "requests.2",
|
|
72
72
|
init: () => ({ ids: {}, user: false }),
|
|
73
73
|
line(raw, row, out, st) {
|
|
74
74
|
let e;
|
|
@@ -260,7 +260,9 @@ export function detectColdResume(path, now = Date.now(), idleMs, minTokens = COL
|
|
|
260
260
|
if (idle < gate || tokens < minTokens)
|
|
261
261
|
return undefined;
|
|
262
262
|
const model = realModel(e.message?.model);
|
|
263
|
-
|
|
263
|
+
// As the resuming request bills: fast mode and US-only as the last one recorded, its prompt's tier.
|
|
264
|
+
const card = rateCard(model, u, now);
|
|
265
|
+
const p = card && ratesAt(card, tokens);
|
|
264
266
|
// The rebuild is written at the TTL this session writes at: Claude
|
|
265
267
|
// Code's main thread has mostly written the 1-hour cache (2x input,
|
|
266
268
|
// 97% of the author's main-thread writes), which a flat 1.25x
|
|
@@ -394,7 +396,7 @@ export function coldResumeEvents(path, idleMs, minTokens = COLD_MIN_TOKENS, runR
|
|
|
394
396
|
writes5m += w.fiveMinute;
|
|
395
397
|
writes1h += w.oneHour;
|
|
396
398
|
ttl = writtenTtlMs(u) ?? ttl;
|
|
397
|
-
reqs.push({ at, total,
|
|
399
|
+
reqs.push({ at, total, card: rateCard(model, u, at), copy: seen === "copy", ttl });
|
|
398
400
|
});
|
|
399
401
|
const mix = writeMultiplier(writes5m, writes1h);
|
|
400
402
|
const real = reqs.filter((r) => r !== "compact");
|
|
@@ -409,8 +411,9 @@ export function coldResumeEvents(path, idleMs, minTokens = COLD_MIN_TOKENS, runR
|
|
|
409
411
|
const gate = (r) => idleMs ?? r.ttl + COLD_MARGIN_MS;
|
|
410
412
|
if (b.at - a.at <= gate(a) || b.total < minTokens)
|
|
411
413
|
continue;
|
|
412
|
-
if (b.copy || !b.
|
|
414
|
+
if (b.copy || !b.card)
|
|
413
415
|
continue;
|
|
416
|
+
const price = ratesAt(b.card, b.total);
|
|
414
417
|
const removed = Math.max(0, b.total - AFTER_COMPACT_TOKENS);
|
|
415
418
|
let saved = 0, n = 0, prev = b;
|
|
416
419
|
for (const c of reqs.slice(i + 1)) {
|
|
@@ -418,14 +421,19 @@ export function coldResumeEvents(path, idleMs, minTokens = COLD_MIN_TOKENS, runR
|
|
|
418
421
|
break;
|
|
419
422
|
if (c.at - prev.at > gate(prev) && c.total >= minTokens)
|
|
420
423
|
break;
|
|
421
|
-
const
|
|
422
|
-
|
|
424
|
+
const card = c.card ?? b.card;
|
|
425
|
+
const cold = c.at - prev.at > prev.ttl;
|
|
426
|
+
const per = (p) => (cold ? mix * p.inputPerM : p.cacheReadPerM);
|
|
427
|
+
// A long-prompt tier: the smaller prompt may bill all of it at the lower rates.
|
|
428
|
+
const after = Math.max(0, c.total - removed);
|
|
429
|
+
const hi = ratesAt(card, c.total), lo = ratesAt(card, after);
|
|
430
|
+
saved += hi === lo ? removed * per(hi) : c.total * per(hi) - after * per(lo);
|
|
423
431
|
prev = c;
|
|
424
432
|
n++;
|
|
425
433
|
}
|
|
426
434
|
// The compaction re-reads the context just rebuilt and writes a summary;
|
|
427
435
|
// the next request writes the fresh context.
|
|
428
|
-
const cost = b.total *
|
|
436
|
+
const cost = b.total * price.cacheReadPerM + SUMMARY_OUTPUT_TOKENS * price.outputPerM + mix * AFTER_COMPACT_TOKENS * ratesAt(b.card, AFTER_COMPACT_TOKENS).inputPerM;
|
|
429
437
|
events.push({ at: b.at, tokens: b.total, messagesAfter: n, netUsd: (saved - cost) / 1e6 });
|
|
430
438
|
}
|
|
431
439
|
return events;
|
package/dist/compactwindow.js
CHANGED
|
@@ -22,7 +22,7 @@
|
|
|
22
22
|
*/
|
|
23
23
|
import { join } from "node:path";
|
|
24
24
|
import { listSessions, replyCounter, isClaudeSession } from "./session.js";
|
|
25
|
-
import { cacheWriteSplit,
|
|
25
|
+
import { cacheWriteSplit, rateCard, ratesAt, requestCost, writeMultiplier } from "./pricing.js";
|
|
26
26
|
import { realModel } from "./tokens.js";
|
|
27
27
|
import { backupOnce } from "./install.js";
|
|
28
28
|
import { ABSENT, readSettings, setJsonPath, withSettingsLock, writeAtomic } from "./settingsedit.js";
|
|
@@ -30,7 +30,7 @@ import { compactWindowOverrides, effectiveCompactWindow, settingsSources } from
|
|
|
30
30
|
import { withInvocation } from "./invocation.js";
|
|
31
31
|
import { idleCompactMinTokens, isIdleCompactNotice, REQUEST_ROWS } from "./coldresume.js";
|
|
32
32
|
import { rowsOf } from "./scan.js";
|
|
33
|
-
import { claudeDir } from "./claudedir.js";
|
|
33
|
+
import { claudeDir, tilde } from "./claudedir.js";
|
|
34
34
|
/** Claude Code compacts at about this share of the window (970k of 1M, measured). */
|
|
35
35
|
const TRIGGER_SHARE = 0.97;
|
|
36
36
|
/** Context right after a compaction: system prompt, tools and the summary (median 75,447, measured). */
|
|
@@ -40,6 +40,7 @@ const SUMMARY_OUTPUT = 20_000;
|
|
|
40
40
|
const TTL_MS = 3_600_000;
|
|
41
41
|
export const MIN_WINDOW = 100_000;
|
|
42
42
|
export const MAX_WINDOW = 1_000_000;
|
|
43
|
+
const UNPRICED = { inputPerM: 0, outputPerM: 0, cacheReadPerM: 0 };
|
|
43
44
|
/**
|
|
44
45
|
* `writeMult`: what this session pays to write a token to the cache,
|
|
45
46
|
* relative to input, from the 5-minute and 1-hour writes its usage records.
|
|
@@ -81,13 +82,13 @@ function readRequests(path, runRows) {
|
|
|
81
82
|
return;
|
|
82
83
|
// Each request at its own model's price; "<synthetic>" rows carry no usage.
|
|
83
84
|
model = realModel(e.message.model) ?? model;
|
|
84
|
-
const
|
|
85
|
-
if (
|
|
85
|
+
const card = rateCard(model, u, at);
|
|
86
|
+
if (card)
|
|
86
87
|
priced = true;
|
|
87
88
|
const w = cacheWriteSplit(u);
|
|
88
89
|
writes5m += w.fiveMinute;
|
|
89
90
|
writes1h += w.oneHour;
|
|
90
|
-
reqs.push({ at, prompt,
|
|
91
|
+
reqs.push({ at, prompt, ...(card ? { card } : {}), copy: seen === "copy", billedUsd: requestCost(model, u, at)?.promptUsd ?? 0 });
|
|
91
92
|
});
|
|
92
93
|
return { reqs, writeMult: writeMultiplier(writes5m, writes1h), priced };
|
|
93
94
|
}
|
|
@@ -133,12 +134,15 @@ function replay(reqs, window, since, reread = 0, writeMult = 1.25, idleMin = idl
|
|
|
133
134
|
// still shape both arms; only the rest are billed.
|
|
134
135
|
const counted = r.at >= since && !r.copy;
|
|
135
136
|
const cold = prevAt === undefined || r.at - prevAt > TTL_MS;
|
|
136
|
-
|
|
137
|
+
// Each prompt, real or simulated, at its own tier's rates.
|
|
138
|
+
const rates = (ctx) => (r.card ? ratesAt(r.card, ctx) : UNPRICED);
|
|
137
139
|
const cost = (ctx, prev) => {
|
|
140
|
+
const p = rates(ctx);
|
|
141
|
+
const write = writeMult * p.inputPerM;
|
|
138
142
|
if (cold)
|
|
139
143
|
return write * ctx;
|
|
140
144
|
const fresh = prev === undefined || ctx < prev ? ctx : ctx - prev;
|
|
141
|
-
return
|
|
145
|
+
return p.cacheReadPerM * (ctx - fresh) + write * fresh;
|
|
142
146
|
};
|
|
143
147
|
if (counted)
|
|
144
148
|
base += cost(r.prompt, prevActual);
|
|
@@ -151,8 +155,9 @@ function replay(reqs, window, since, reread = 0, writeMult = 1.25, idleMin = idl
|
|
|
151
155
|
}
|
|
152
156
|
let simPrev = prevSim;
|
|
153
157
|
if (ctx >= TRIGGER_SHARE * window) {
|
|
158
|
+
const p = rates(ctx);
|
|
154
159
|
if (counted) {
|
|
155
|
-
sim +=
|
|
160
|
+
sim += p.cacheReadPerM * ctx + p.outputPerM * SUMMARY_OUTPUT + writeMult * p.inputPerM * reread;
|
|
156
161
|
extra++;
|
|
157
162
|
}
|
|
158
163
|
removed = r.prompt - AFTER_COMPACT - reread;
|
|
@@ -282,7 +287,7 @@ export function renderCompactWindows(r, current, limitLines) {
|
|
|
282
287
|
// Counted and said exactly as `savings` says it, so the two screens agree.
|
|
283
288
|
lines.push(`Last ${r.days} days, ${sessionsLabel(r.sessions, r.transcripts ?? r.sessions)}, at list prices`);
|
|
284
289
|
lines.push("─".repeat(66));
|
|
285
|
-
lines.push(`Now: ${current ? `${k(current)} (set in
|
|
290
|
+
lines.push(`Now: ${current ? `${k(current)} (set in ${tilde(settingsPath())})` : "not set: Claude Code compacts near the model's full window"}`);
|
|
286
291
|
if (r.sessions === 0) {
|
|
287
292
|
lines.push("No sessions with 10+ requests in the window to replay.");
|
|
288
293
|
return withInvocation(lines.join("\n"));
|
package/dist/cursor.d.ts
CHANGED
|
@@ -67,6 +67,16 @@ export interface CursorReply {
|
|
|
67
67
|
/** The workspace folder the chat belongs to, when Cursor recorded one. */
|
|
68
68
|
folder?: string;
|
|
69
69
|
}
|
|
70
|
+
/**
|
|
71
|
+
* The Claude id a Cursor model name stands for, so it gets that version's
|
|
72
|
+
* list price rather than its family's: Cursor puts the version first and
|
|
73
|
+
* adds its own modes ("claude-4.6-opus-high-thinking" is claude-opus-4-6,
|
|
74
|
+
* "claude-3.7-sonnet" claude-3-7-sonnet). Thinking and effort levels bill as
|
|
75
|
+
* output at the same rates. Undefined for anything else, and for a "fast"
|
|
76
|
+
* variant, which Anthropic bills at a premium of its own (left to the
|
|
77
|
+
* family's price, an estimate).
|
|
78
|
+
*/
|
|
79
|
+
export declare function cursorClaudeId(name: string | undefined): string | undefined;
|
|
70
80
|
/**
|
|
71
81
|
* Every Cursor reply with token counts since `since`. Only chats updated
|
|
72
82
|
* since then are read, each by its key range (on the author's 3 GB history
|
package/dist/cursor.js
CHANGED
|
@@ -294,6 +294,26 @@ function cursorFolders() {
|
|
|
294
294
|
}
|
|
295
295
|
return out;
|
|
296
296
|
}
|
|
297
|
+
/**
|
|
298
|
+
* The Claude id a Cursor model name stands for, so it gets that version's
|
|
299
|
+
* list price rather than its family's: Cursor puts the version first and
|
|
300
|
+
* adds its own modes ("claude-4.6-opus-high-thinking" is claude-opus-4-6,
|
|
301
|
+
* "claude-3.7-sonnet" claude-3-7-sonnet). Thinking and effort levels bill as
|
|
302
|
+
* output at the same rates. Undefined for anything else, and for a "fast"
|
|
303
|
+
* variant, which Anthropic bills at a premium of its own (left to the
|
|
304
|
+
* family's price, an estimate).
|
|
305
|
+
*/
|
|
306
|
+
export function cursorClaudeId(name) {
|
|
307
|
+
const m = /^claude-(\d+)(?:\.(\d{1,2}))?-(opus|sonnet|haiku|fable|mythos)((?:-[a-z0-9]+)*)$/i.exec(name ?? "");
|
|
308
|
+
if (!m || /-fast\b/i.test(m[4]))
|
|
309
|
+
return undefined;
|
|
310
|
+
const [, major, minor, family] = m;
|
|
311
|
+
const fam = family.toLowerCase();
|
|
312
|
+
// Claude 3's ids put the version first too (claude-3-5-sonnet); from Claude 4 on, the family does.
|
|
313
|
+
return Number(major) < 4
|
|
314
|
+
? `claude-${major}${minor ? `-${minor}` : ""}-${fam}`
|
|
315
|
+
: `claude-${fam}-${major}${minor ? `-${minor}` : ""}`;
|
|
316
|
+
}
|
|
297
317
|
/** A time Cursor wrote: epoch ms (as a number or digits) or an ISO string. */
|
|
298
318
|
function cursorTime(v) {
|
|
299
319
|
const n = typeof v === "number" ? v : typeof v === "string" ? (/^\d+$/.test(v) ? Number(v) : Date.parse(v)) : Number.NaN;
|
package/dist/doctor.d.ts
CHANGED
|
@@ -25,6 +25,15 @@ export declare function skillCheck(label: string, files: string[], okDetail?: st
|
|
|
25
25
|
* read it (it ignores the key; nothing else in the file is affected).
|
|
26
26
|
*/
|
|
27
27
|
export declare function cacheTtlCheck(home?: string, env?: NodeJS.ProcessEnv): Check | undefined;
|
|
28
|
+
/**
|
|
29
|
+
* Models Claude Code (subagents included) and Codex ran in the last `days`
|
|
30
|
+
* that the price table has no row for: priced by a family fallback (an
|
|
31
|
+
* estimate) or not at all, in spend, savings, fix and the budget alike.
|
|
32
|
+
* Read through spend's own readers, so the transcript cache they keep makes
|
|
33
|
+
* a second doctor cheap. Undefined when nothing ran in the period; ids that
|
|
34
|
+
* are never billed (`<synthetic>`) are not named.
|
|
35
|
+
*/
|
|
36
|
+
export declare function unpricedModelsCheck(days?: number, now?: number, home?: string): Check | undefined;
|
|
28
37
|
/**
|
|
29
38
|
* Devin (Cognition): the Devin CLI, and Devin Desktop (formerly Windsurf).
|
|
30
39
|
* Checked against docs.devin.ai (2026-10-20): the CLI runs hooks from
|
package/dist/doctor.js
CHANGED
|
@@ -29,6 +29,8 @@ import { claudeCodePresent, claudeDir, claudeJsonPath } from "./claudedir.js";
|
|
|
29
29
|
import { codexDir } from "./codexdir.js";
|
|
30
30
|
import { periodSpend, readBudget } from "./budget.js";
|
|
31
31
|
import { sessionPriceThresholds } from "./sessionprice.js";
|
|
32
|
+
import { claudeSpend, codexSpend } from "./spend.js";
|
|
33
|
+
import { hasKnownPrice, isUnbilledModel, priceChangedText } from "./pricing.js";
|
|
32
34
|
function claudeDesktopConfigPath() {
|
|
33
35
|
switch (platform()) {
|
|
34
36
|
case "darwin": return join(homedir(), "Library", "Application Support", "Claude", "claude_desktop_config.json");
|
|
@@ -283,6 +285,50 @@ export function cacheTtlCheck(home = homedir(), env = process.env) {
|
|
|
283
285
|
return { label, status: "warn", detail: `${set}; ${describeInstalls(old)} predates the setting (${CACHE_TTL_SINCE}) and ignores it` };
|
|
284
286
|
return { label, status: "ok", detail: `${set} (context-doctor cache-ttl; off removes it)` };
|
|
285
287
|
}
|
|
288
|
+
/**
|
|
289
|
+
* Models Claude Code (subagents included) and Codex ran in the last `days`
|
|
290
|
+
* that the price table has no row for: priced by a family fallback (an
|
|
291
|
+
* estimate) or not at all, in spend, savings, fix and the budget alike.
|
|
292
|
+
* Read through spend's own readers, so the transcript cache they keep makes
|
|
293
|
+
* a second doctor cheap. Undefined when nothing ran in the period; ids that
|
|
294
|
+
* are never billed (`<synthetic>`) are not named.
|
|
295
|
+
*/
|
|
296
|
+
export function unpricedModelsCheck(days = 30, now = Date.now(), home = homedir()) {
|
|
297
|
+
const label = "Model prices";
|
|
298
|
+
const since = now - days * 86_400_000;
|
|
299
|
+
const seen = new Map();
|
|
300
|
+
// A price in the table that changed on a day before some requests (pricing.ts's end dates).
|
|
301
|
+
const changed = new Map();
|
|
302
|
+
const add = (items) => {
|
|
303
|
+
for (const i of items)
|
|
304
|
+
if (i.model) {
|
|
305
|
+
seen.set(i.model, (seen.get(i.model) ?? 0) + 1);
|
|
306
|
+
if (i.changedOn)
|
|
307
|
+
changed.set(i.model, [i.model, i.changedOn]);
|
|
308
|
+
}
|
|
309
|
+
};
|
|
310
|
+
try {
|
|
311
|
+
add(claudeSpend(since, now));
|
|
312
|
+
}
|
|
313
|
+
catch { /* unreadable: the rest still counts */ }
|
|
314
|
+
try {
|
|
315
|
+
add(codexSpend(since, now, home));
|
|
316
|
+
}
|
|
317
|
+
catch { /* unreadable: the rest still counts */ }
|
|
318
|
+
if (seen.size === 0)
|
|
319
|
+
return undefined;
|
|
320
|
+
const unknown = [...seen].filter(([m]) => !hasKnownPrice(m) && !isUnbilledModel(m)).sort((a, b) => b[1] - a[1]);
|
|
321
|
+
if (!unknown.length && changed.size)
|
|
322
|
+
return { label, status: "warn", detail: `${priceChangedText([...changed.values()])}: those requests are estimated. npm install -g context-doctor@latest` };
|
|
323
|
+
if (!unknown.length)
|
|
324
|
+
return { label, status: "ok", detail: `every model used in the last ${days} days has a list price on file` };
|
|
325
|
+
const named = unknown.slice(0, 5).map(([m, n]) => `${m} (${n.toLocaleString("en-US")} request${n === 1 ? "" : "s"})`).join(", ") + (unknown.length > 5 ? ` and ${unknown.length - 5} more` : "");
|
|
326
|
+
return {
|
|
327
|
+
label,
|
|
328
|
+
status: "warn",
|
|
329
|
+
detail: `no list price on file for ${named} in the last ${days} days: their dollars (spend, savings, fix, budget) are estimated from the model family or missing. A newer context-doctor may know them: npm install -g context-doctor@latest`,
|
|
330
|
+
};
|
|
331
|
+
}
|
|
286
332
|
/**
|
|
287
333
|
* Devin (Cognition): the Devin CLI, and Devin Desktop (formerly Windsurf).
|
|
288
334
|
* Checked against docs.devin.ai (2026-10-20): the CLI runs hooks from
|
|
@@ -775,6 +821,12 @@ export async function runDoctor() {
|
|
|
775
821
|
else if (hooked)
|
|
776
822
|
checks.push({ label: "Session price", status: "ok", detail: `said once when a session passes ${at.map((t) => `$${t.toLocaleString("en-US")}`).join(", ").replace(/, ([^,]+)$/, " and $1")} (CONTEXT_DOCTOR_SESSION_PRICE to change; CONTEXT_DOCTOR_NO_SESSION_PRICE=1 for off)` });
|
|
777
823
|
}
|
|
824
|
+
// Models in the last 30 days with no list price of their own: their dollars everywhere are a guess or missing.
|
|
825
|
+
{
|
|
826
|
+
const c = unpricedModelsCheck();
|
|
827
|
+
if (c)
|
|
828
|
+
checks.push(c);
|
|
829
|
+
}
|
|
778
830
|
checks.push(await checkMcpHandshake());
|
|
779
831
|
// Autopilot: optional, so "off" is a skip, not a failure. When it is on, a
|
|
780
832
|
// dead proxy or a settings file pointing elsewhere is a real problem.
|
package/dist/extract.d.ts
CHANGED
|
@@ -22,7 +22,7 @@ export declare const EXTRACTABLE: Set<string>;
|
|
|
22
22
|
/** Never load or write a document's subsidiary resources (stylesheets, images, frames). */
|
|
23
23
|
export declare const TEXTUTIL_ARGS: string[];
|
|
24
24
|
/** The document's text, or the reason it could not be read. */
|
|
25
|
-
export declare function extractText(
|
|
25
|
+
export declare function extractText(name: string): {
|
|
26
26
|
text: string;
|
|
27
27
|
} | {
|
|
28
28
|
error: string;
|
|
@@ -42,7 +42,7 @@ export declare const monotonicNow: () => number;
|
|
|
42
42
|
* `end` on the same clock: a deadline on the wall clock, converted per
|
|
43
43
|
* document, let a clock jump between two documents cut the later ones short.
|
|
44
44
|
*/
|
|
45
|
-
export declare function extractTextAsync(
|
|
45
|
+
export declare function extractTextAsync(name: string, end?: number): Promise<{
|
|
46
46
|
text: string;
|
|
47
47
|
} | {
|
|
48
48
|
error: string;
|
package/dist/extract.js
CHANGED
|
@@ -21,7 +21,7 @@
|
|
|
21
21
|
import { execFile, spawnSync } from "node:child_process";
|
|
22
22
|
import { existsSync, mkdtempSync, readFileSync, rmSync } from "node:fs";
|
|
23
23
|
import { tmpdir } from "node:os";
|
|
24
|
-
import { dirname, extname, join } from "node:path";
|
|
24
|
+
import { dirname, extname, join, resolve } from "node:path";
|
|
25
25
|
export const EXTRACTABLE = new Set([".pdf", ".docx", ".doc", ".rtf", ".odt", ".pptx"]);
|
|
26
26
|
const RUN = { encoding: "utf8", timeout: 30_000, maxBuffer: 64 * 1024 * 1024 };
|
|
27
27
|
function run(cmd, args) {
|
|
@@ -72,8 +72,18 @@ function xmlToText(xml) {
|
|
|
72
72
|
.replace(/\n{3,}/g, "\n\n")
|
|
73
73
|
.trim();
|
|
74
74
|
}
|
|
75
|
+
/**
|
|
76
|
+
* The document's path as a converter's argument: absolute, so a file named
|
|
77
|
+
* like an option is never read as one. `pack .` met
|
|
78
|
+
* `-eObjC.import("stdlib");$.system("…");var x={};x.pdf` as that very
|
|
79
|
+
* string, and osascript ran it as a second script statement.
|
|
80
|
+
*/
|
|
81
|
+
function argPath(path) {
|
|
82
|
+
return resolve(path);
|
|
83
|
+
}
|
|
75
84
|
/** The document's text, or the reason it could not be read. */
|
|
76
|
-
export function extractText(
|
|
85
|
+
export function extractText(name) {
|
|
86
|
+
const path = argPath(name);
|
|
77
87
|
const ext = extname(path).toLowerCase();
|
|
78
88
|
const mac = process.platform === "darwin";
|
|
79
89
|
let text;
|
|
@@ -173,7 +183,8 @@ function runAsync(cmd, args, end) {
|
|
|
173
183
|
* `end` on the same clock: a deadline on the wall clock, converted per
|
|
174
184
|
* document, let a clock jump between two documents cut the later ones short.
|
|
175
185
|
*/
|
|
176
|
-
export async function extractTextAsync(
|
|
186
|
+
export async function extractTextAsync(name, end = monotonicNow() + EXTRACT_BUDGET_MS) {
|
|
187
|
+
const path = argPath(name);
|
|
177
188
|
const ext = extname(path).toLowerCase();
|
|
178
189
|
const mac = process.platform === "darwin";
|
|
179
190
|
let text;
|
package/dist/fanout.js
CHANGED
|
@@ -159,6 +159,8 @@ function aliasModel(alias, costs) {
|
|
|
159
159
|
const seen = Object.entries(costs.byModel).filter(([m]) => a.family.test(m)).sort((x, y) => y[1].n - x[1].n)[0]?.[0];
|
|
160
160
|
return seen ?? a.fallback;
|
|
161
161
|
}
|
|
162
|
+
/** "an Explore", "a general-purpose": the article for a subagent type (it read "a Explore subagent"). */
|
|
163
|
+
const an = (type) => (/^[aeiou]/i.test(type) ? `an ${type}` : `a ${type}`);
|
|
162
164
|
const short = (model) => {
|
|
163
165
|
const m = /claude-(opus|sonnet|haiku|fable|mythos)-(\d+)(?:-(\d{1,2}))?(?!\d)/i.exec(model ?? "");
|
|
164
166
|
return m ? `${m[1][0].toUpperCase()}${m[1].slice(1)} ${m[2]}${m[3] ? `.${m[3]}` : ""}` : model ?? "its model";
|
|
@@ -279,10 +281,10 @@ export function fanoutMessage(est, alias, log, own) {
|
|
|
279
281
|
const sonnet = cheaper ? ` On Sonnet: ~${formatUsd(cheaper.median)}${cheaper.measured ? "" : " at its price"}.` : "";
|
|
280
282
|
out.systemMessage = showBurst
|
|
281
283
|
? `context-doctor: ${burst} subagents in 2 minutes, ~${formatUsd(est.median * burst)} together at your median of ~${formatUsd(est.median)} for ${own.type} on ${short(est.model)} (${runs}).${sonnet}`
|
|
282
|
-
: `context-doctor:
|
|
284
|
+
: `context-doctor: ${an(own.type)} subagent on ${short(est.model)} costs ~${formatUsd(est.median)} at your median (p90 ${formatUsd(est.p90)}, ${runs}, list price).${sonnet}`;
|
|
283
285
|
}
|
|
284
286
|
if (cheaper && upTo.find((l) => l.c)?.id === own.id) {
|
|
285
|
-
out.additionalContext = `context-doctor: on this machine
|
|
287
|
+
out.additionalContext = `context-doctor: on this machine ${an(own.type)} subagent costs ~${formatUsd(est.median)} at the median on ${short(est.model)}, ~${formatUsd(cheaper.median)} on Sonnet. For search, reading or summarising, pass model: "sonnet" to the Agent tool.`;
|
|
286
288
|
}
|
|
287
289
|
return out;
|
|
288
290
|
}
|
package/dist/fix.d.ts
CHANGED
|
@@ -34,6 +34,7 @@
|
|
|
34
34
|
* `--apply all`), and never over a value the user set.
|
|
35
35
|
*/
|
|
36
36
|
import { type CacheTtlReport, type CurrentTtl } from "./cachettl.js";
|
|
37
|
+
import { type ClaudeCodeInstall } from "./modelswitch.js";
|
|
37
38
|
import { type ProjectPlan } from "./prune.js";
|
|
38
39
|
import { readLedger } from "./ledger.js";
|
|
39
40
|
import { type SubagentModelReplay } from "./subagentmodel.js";
|
|
@@ -61,6 +62,8 @@ export interface Fix {
|
|
|
61
62
|
value?: number | string;
|
|
62
63
|
/** What would keep it from taking effect (environment, project or managed settings, per-model values). */
|
|
63
64
|
overriddenBy?: string[];
|
|
65
|
+
/** Installed Claude Code versions older than the setting: they ignore it (named, not blocked). */
|
|
66
|
+
tooOld?: string;
|
|
64
67
|
/** More lines under it in the plan (the subagents' model: per agent type). */
|
|
65
68
|
detail?: string[];
|
|
66
69
|
}
|
|
@@ -119,6 +122,8 @@ export interface FixInputs {
|
|
|
119
122
|
};
|
|
120
123
|
/** Codex's rollouts replayed at earlier auto-compact limits (codexcompact.ts). */
|
|
121
124
|
codexCompact?: CodexCompactReport;
|
|
125
|
+
/** The Claude Code installs found here (CLI and desktop app), to name the ones a setting is too new for. */
|
|
126
|
+
claudeCodeInstalls?: ClaudeCodeInstall[];
|
|
122
127
|
/** model_auto_compact_token_limit at the top of the user's config.toml, as written: never overwritten. */
|
|
123
128
|
codexCompactSet?: {
|
|
124
129
|
raw: string;
|
|
@@ -216,8 +221,10 @@ export declare function savedSince(records: FixRecord[], opts?: {
|
|
|
216
221
|
codexPaths?: string[];
|
|
217
222
|
ledger?: ReturnType<typeof readLedger>;
|
|
218
223
|
}): SinceResult[];
|
|
224
|
+
/** The overlap lines for the priced fixes in a plan, "a and b: why;" each. */
|
|
225
|
+
export declare function overlaps(fixes: Fix[]): string[];
|
|
219
226
|
export declare function renderFixPlan(days: number, billedUsd: number, fixes: Fix[], since: SinceResult[], command?: (s: string) => string, coldResume?: FixInputs["coldResume"], recordProblem?: string, codexBilledUsd?: number): string;
|
|
220
|
-
export declare function renderFixShare(days: number, billedUsd: number, fixes: Fix[]): string;
|
|
227
|
+
export declare function renderFixShare(days: number, billedUsd: number, fixes: Fix[], codexBilledUsd?: number): string;
|
|
221
228
|
export declare function parseFixIds(raw: string, fixes: Fix[]): {
|
|
222
229
|
ids: FixId[];
|
|
223
230
|
unknown: string[];
|
package/dist/fix.js
CHANGED
|
@@ -39,7 +39,8 @@ import { dirname, join } from "node:path";
|
|
|
39
39
|
import { forEachLine, listSessions, isClaudeSession } from "./session.js";
|
|
40
40
|
import { pricingFor } from "./pricing.js";
|
|
41
41
|
import { contextWindowFor, realModel } from "./tokens.js";
|
|
42
|
-
import { adviseTtl, estimateCacheTtl } from "./cachettl.js";
|
|
42
|
+
import { adviseTtl, CACHE_TTL_SINCE, estimateCacheTtl } from "./cachettl.js";
|
|
43
|
+
import { compareVersions, describeInstalls } from "./modelswitch.js";
|
|
43
44
|
import { ABSENT, getPath, parseSettingsText, readSettings, removeFile, sameJson, setJsonPath, SettingsError, settingsLockPath, withLock, withSettingsLock, writeAtomic } from "./settingsedit.js";
|
|
44
45
|
import { compactWindowOverrides, processEnvWhere, settingsSources, shellSet, ttlOverrides } from "./effective.js";
|
|
45
46
|
import { tilde } from "./claudedir.js";
|
|
@@ -47,8 +48,17 @@ import { applyPrune, undoPrune } from "./prune.js";
|
|
|
47
48
|
import { fallbackStateDir, readLedger } from "./ledger.js";
|
|
48
49
|
import { claudeDir } from "./claudedir.js";
|
|
49
50
|
import { movedFromNames, renderSubagentTypes, subagentModelSavedSince, SUBAGENT_CANDIDATE, SUBAGENT_CANDIDATE_NAME, SUBAGENT_MODEL_ENV } from "./subagentmodel.js";
|
|
50
|
-
import { BASH_OUTPUT_DEFAULT, BASH_OUTPUT_KEY, breakEven, renderToolOutputCaps, toolOutputSavedSince } from "./tooloutput.js";
|
|
51
|
+
import { BASH_OUTPUT_DEFAULT, BASH_OUTPUT_KEY, BASH_OUTPUT_SINCE, breakEven, renderToolOutputCaps, toolOutputSavedSince } from "./tooloutput.js";
|
|
51
52
|
import { CODEX_COMPACT_KEY, CODEX_COMPACT_LIMIT, codexCompactOverrides, codexCompactSavedSince, codexConfigPath, renderCodexLimits, setTopLevelInt, topLevelValue } from "./codexcompact.js";
|
|
53
|
+
/**
|
|
54
|
+
* The Claude Code version that first reads each setting a fix writes, from
|
|
55
|
+
* its changelog (2.1.243 added promptCacheTtl and subagentPromptCacheTtl,
|
|
56
|
+
* 2.1.261 bashOutputMaxChars). CLAUDE_CODE_SUBAGENT_MODEL and
|
|
57
|
+
* ENABLE_TOOL_SEARCH are read by 2.1.62 already (the oldest binary checked;
|
|
58
|
+
* the subagent variable ahead of agent definitions there). autoCompactWindow
|
|
59
|
+
* is not in 2.1.62 and the changelog does not say when it came: not named.
|
|
60
|
+
*/
|
|
61
|
+
const SINCE = { "cache-ttl": CACHE_TTL_SINCE, "cache-ttl-subagents": CACHE_TTL_SINCE, "tool-output": BASH_OUTPUT_SINCE };
|
|
52
62
|
/** Below this a priced fix is not worth a setting. */
|
|
53
63
|
const MIN_USD = 1;
|
|
54
64
|
const money = (n) => (n >= 100 ? `$${Math.round(n).toLocaleString("en-US")}` : `$${n.toFixed(2)}`);
|
|
@@ -143,7 +153,7 @@ export function planFixes(i) {
|
|
|
143
153
|
title: `Switch off ${names.length} unused MCP server${names.length === 1 ? "" : "s"} or skill${names.length === 1 ? "" : "s"} in this project`,
|
|
144
154
|
basis: `none used in ${i.prune.sessions} sessions of this project in ${i.days} days: ${names.slice(0, 5).join(", ")}${names.length > 5 ? ", …" : ""}`,
|
|
145
155
|
quality: "none while they stay unused; undo brings them back",
|
|
146
|
-
change:
|
|
156
|
+
change: join(i.prune.cwd, ".claude", "settings.local.json"),
|
|
147
157
|
state: "available",
|
|
148
158
|
});
|
|
149
159
|
}
|
|
@@ -212,7 +222,7 @@ export function planFixes(i) {
|
|
|
212
222
|
savedUsd: cxOffer.savedUsd,
|
|
213
223
|
savedShare: cxOffer.savedShare,
|
|
214
224
|
shareOf: "of Codex input",
|
|
215
|
-
basis: `your ${cx.requests.toLocaleString("en-US")} Codex requests replayed at a ${k(CODEX_COMPACT_LIMIT)} limit: ${(cxOffer.compactions / weeks).toFixed(1)} compactions a week instead of ${(cx.actualCompactions / weeks).toFixed(1)}, each paying a request and a ${k(5_000)}-token summary (an estimate: Codex does not record its compactions' own usage)`,
|
|
225
|
+
basis: `your ${cx.requests.toLocaleString("en-US")} Codex requests replayed at a ${k(CODEX_COMPACT_LIMIT)} limit: ${(cxOffer.compactions / weeks).toFixed(1)} compactions a week instead of ${(cx.actualCompactions / weeks).toFixed(1)}, each paying a request and a ${k(5_000)}-token summary (an estimate: Codex does not record its compactions' own usage)${cx.scope === "body_after_prefix" ? "; the limit counted as your model_auto_compact_token_limit_scope = \"body_after_prefix\" counts it: what a session added after the first request since its start or last compaction" : ""}`,
|
|
216
226
|
quality: "each compaction replaces the history with a summary: detail for money",
|
|
217
227
|
change: `${tilde(codexConfigPath())}: ${CODEX_COMPACT_KEY} = ${CODEX_COMPACT_LIMIT}`,
|
|
218
228
|
state: "available",
|
|
@@ -224,6 +234,10 @@ export function planFixes(i) {
|
|
|
224
234
|
const o = i.overrides?.[f.id];
|
|
225
235
|
if (o?.length && f.state === "available")
|
|
226
236
|
f.overriddenBy = o;
|
|
237
|
+
const since = SINCE[f.id];
|
|
238
|
+
const old = since && f.state === "available" ? (i.claudeCodeInstalls ?? []).filter((c) => compareVersions(c.version, since) < 0) : [];
|
|
239
|
+
if (old.length)
|
|
240
|
+
f.tooOld = `${describeInstalls(old)} ${old.length === 1 ? "predates" : "predate"} this setting (Claude Code ${since}+) and ${old.length === 1 ? "ignores" : "ignore"} it: update ${old.length === 1 ? "it" : "them"} for it to take effect there`;
|
|
227
241
|
}
|
|
228
242
|
const rank = (f) => (f.state === "available" ? 0 : f.state === "applied" ? 2 : 3) + (f.savedUsd === undefined ? 1 : 0);
|
|
229
243
|
return fixes.sort((a, b) => rank(a) - rank(b) || (b.savedUsd ?? 0) - (a.savedUsd ?? 0));
|
|
@@ -335,7 +349,8 @@ function applySetting(fix, home, at, extra) {
|
|
|
335
349
|
const key = KEY_PATH[fix.id];
|
|
336
350
|
const file = join(claudeDir(home), "settings.json");
|
|
337
351
|
mkdirSync(dirname(file), { recursive: true });
|
|
338
|
-
|
|
352
|
+
// The records' lock, and settings.json's own: the same file unless the records live in the state folder (a machine that had only Codex at first).
|
|
353
|
+
return withLock(lockPath(home), () => withSettingsLock(file, () => {
|
|
339
354
|
const records = loadFixRecords(home);
|
|
340
355
|
const cur = readSettings(file);
|
|
341
356
|
const now = getPath(cur.data, key);
|
|
@@ -369,7 +384,7 @@ function applySetting(fix, home, at, extra) {
|
|
|
369
384
|
};
|
|
370
385
|
writeFixRecords([...records.filter((r) => r.id !== fix.id), rec], home);
|
|
371
386
|
return [`✓ ${fix.change}`];
|
|
372
|
-
});
|
|
387
|
+
}));
|
|
373
388
|
}
|
|
374
389
|
/**
|
|
375
390
|
* Set Codex's limit at the top of config.toml, under the records' lock and
|
|
@@ -508,6 +523,9 @@ export async function applyFix(fix, deps = {}, context = {}) {
|
|
|
508
523
|
function undoSetting(r, home) {
|
|
509
524
|
const key = r.key ?? KEY_PATH[r.id];
|
|
510
525
|
const file = r.file ?? join(claudeDir(home), "settings.json");
|
|
526
|
+
return withSettingsLock(file, () => undoSettingLocked(r, key, file));
|
|
527
|
+
}
|
|
528
|
+
function undoSettingLocked(r, key, file) {
|
|
511
529
|
const name = key.join(".");
|
|
512
530
|
const cur = readSettings(file);
|
|
513
531
|
const text = cur.text ?? null;
|
|
@@ -740,6 +758,26 @@ const LABEL = {
|
|
|
740
758
|
"tool-output": "Long Bash output",
|
|
741
759
|
"codex-compact": "Codex auto-compact limit",
|
|
742
760
|
};
|
|
761
|
+
/**
|
|
762
|
+
* Priced levers that save part of the same dollars, and why: each is
|
|
763
|
+
* replayed alone on the history as billed, so applying both saves less than
|
|
764
|
+
* the two figures added. Codex's limit shares nothing with Claude Code's.
|
|
765
|
+
*/
|
|
766
|
+
const OVERLAPS = [
|
|
767
|
+
["compact-window", "cache-ttl", "compacting earlier and the main conversation's cache lifetime both change what is written to the cache"],
|
|
768
|
+
["compact-window", "tool-output", "an earlier compaction drops long Bash output sooner, so there is less left to move to a file"],
|
|
769
|
+
["compact-window", "autopilot", "compacting earlier and autopilot both take old tool output out of the context"],
|
|
770
|
+
["tool-output", "autopilot", "output moved to a file is no longer there for autopilot to clear"],
|
|
771
|
+
["tool-output", "cache-ttl", "the main conversation's cache lifetime changes how often long output is written to the cache again"],
|
|
772
|
+
["tool-output", "cache-ttl-subagents", "the subagents' cache lifetime changes how often their long output is written to the cache again"],
|
|
773
|
+
["tool-output", "subagent-model", "long output in subagents is priced at the subagents' model, which subagent-model changes"],
|
|
774
|
+
["subagent-model", "cache-ttl-subagents", "the subagents' cache is priced at their model's rates, which subagent-model changes"],
|
|
775
|
+
];
|
|
776
|
+
/** The overlap lines for the priced fixes in a plan, "a and b: why;" each. */
|
|
777
|
+
export function overlaps(fixes) {
|
|
778
|
+
const priced = new Set(fixes.filter((f) => f.savedUsd !== undefined).map((f) => f.id));
|
|
779
|
+
return OVERLAPS.filter(([a, b]) => priced.has(a) && priced.has(b)).map(([a, b, why]) => `${a} and ${b}: ${why}.`);
|
|
780
|
+
}
|
|
743
781
|
export function renderFixPlan(days, billedUsd, fixes, since, command = (s) => `context-doctor ${s}`, coldResume, recordProblem, codexBilledUsd = 0) {
|
|
744
782
|
const out = [];
|
|
745
783
|
if (recordProblem)
|
|
@@ -768,10 +806,14 @@ export function renderFixPlan(days, billedUsd, fixes, since, command = (s) => `c
|
|
|
768
806
|
out.push(` ${d}`);
|
|
769
807
|
if (f.overriddenBy?.length)
|
|
770
808
|
out.push(` ⚠ would not take effect: ${f.overriddenBy.join("; ")}`);
|
|
809
|
+
if (f.tooOld)
|
|
810
|
+
out.push(` ⚠ ${f.tooOld}`);
|
|
771
811
|
});
|
|
772
|
-
|
|
773
|
-
|
|
774
|
-
out.push("
|
|
812
|
+
const pairs = overlaps(avail);
|
|
813
|
+
if (pairs.length) {
|
|
814
|
+
out.push(" Each figure is measured alone. Do not add them up: the levers overlap, so together they save less:");
|
|
815
|
+
for (const p of pairs)
|
|
816
|
+
out.push(` ${p}`);
|
|
775
817
|
}
|
|
776
818
|
const applied = fixes.filter((f) => f.state === "applied");
|
|
777
819
|
if (applied.length) {
|
|
@@ -810,14 +852,18 @@ export function renderFixPlan(days, billedUsd, fixes, since, command = (s) => `c
|
|
|
810
852
|
function noHistory(days, command) {
|
|
811
853
|
return [`No Claude Code sessions in the last ${days} days to measure yet, so no fix can be priced.`, `Use Claude Code for a while, then run this again: ${command("fix")}.`];
|
|
812
854
|
}
|
|
813
|
-
export function renderFixShare(days, billedUsd, fixes) {
|
|
855
|
+
export function renderFixShare(days, billedUsd, fixes, codexBilledUsd = 0) {
|
|
814
856
|
const avail = fixes.filter((f) => f.state === "available" && f.savedUsd !== undefined);
|
|
815
|
-
|
|
857
|
+
// As the plan's first line: Codex's input beside Claude Code's, or alone on a machine with only Codex.
|
|
858
|
+
const of = codexBilledUsd > 0 && billedUsd > 0
|
|
859
|
+
? `Claude Code and Codex (${money(billedUsd)} and ${money(codexBilledUsd)} of input at list price)`
|
|
860
|
+
: codexBilledUsd > 0 ? `Codex (${money(codexBilledUsd)} of input at list price)` : `Claude Code (${money(billedUsd)} of input at list price)`;
|
|
861
|
+
const lines = [`context-doctor fix on my last ${days} days of ${of}:`];
|
|
816
862
|
for (const f of avail)
|
|
817
863
|
lines.push(`- ${LABEL[f.id]}: ${money(f.savedUsd)}${share(f)}`);
|
|
818
864
|
if (avail.length === 0)
|
|
819
|
-
lines.push(billedUsd > 0 ? "- nothing left to fix" : "- no Claude Code sessions to measure yet");
|
|
820
|
-
if (avail.length
|
|
865
|
+
lines.push(billedUsd + codexBilledUsd > 0 ? "- nothing left to fix" : "- no Claude Code sessions to measure yet");
|
|
866
|
+
if (overlaps(avail).length)
|
|
821
867
|
lines.push("Each measured alone; they overlap, so do not add them up.");
|
|
822
868
|
lines.push("Measured on my own sessions, locally: npx context-doctor fix");
|
|
823
869
|
return lines.join("\n");
|