context-doctor 0.41.0 → 0.43.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 +7 -4
- package/dist/ab.js +3 -1
- package/dist/autopilot.d.ts +1 -1
- package/dist/autopilot.js +38 -24
- package/dist/budget.d.ts +54 -1
- package/dist/budget.js +207 -53
- package/dist/cachettl.js +12 -9
- package/dist/claudedir.d.ts +8 -0
- package/dist/claudedir.js +19 -0
- package/dist/cli.js +90 -15
- package/dist/codexcompact.d.ts +116 -0
- package/dist/codexcompact.js +415 -0
- package/dist/codexdir.d.ts +11 -0
- package/dist/codexdir.js +20 -0
- package/dist/codexroute.d.ts +1 -0
- package/dist/codexroute.js +3 -1
- package/dist/compactwindow.js +12 -9
- package/dist/cursor.js +20 -5
- package/dist/doctor.d.ts +9 -0
- package/dist/doctor.js +42 -14
- package/dist/effective.d.ts +18 -0
- package/dist/effective.js +39 -4
- package/dist/extract.d.ts +12 -3
- package/dist/extract.js +39 -12
- package/dist/fileparams.d.ts +1 -1
- package/dist/fileparams.js +8 -8
- package/dist/fix.d.ts +33 -4
- package/dist/fix.js +221 -19
- package/dist/hook.js +35 -5
- package/dist/install.js +106 -47
- package/dist/ledger.d.ts +17 -1
- package/dist/ledger.js +31 -1
- package/dist/limits.d.ts +15 -1
- package/dist/limits.js +71 -28
- package/dist/mcp.js +58 -58
- package/dist/overhead.js +2 -1
- package/dist/pack.js +3 -2
- package/dist/proxy.d.ts +1 -1
- package/dist/proxy.js +1 -1
- package/dist/recall.js +3 -2
- package/dist/scan.d.ts +2 -0
- package/dist/scan.js +2 -1
- package/dist/session.js +2 -1
- package/dist/sessionprice.d.ts +71 -0
- package/dist/sessionprice.js +216 -0
- package/dist/settingsedit.d.ts +4 -0
- package/dist/settingsedit.js +61 -3
- package/dist/spend.d.ts +8 -1
- package/dist/spend.js +27 -10
- package/dist/subagentmodel.d.ts +19 -4
- package/dist/subagentmodel.js +116 -28
- package/dist/tooloutput.d.ts +118 -0
- package/dist/tooloutput.js +355 -0
- package/package.json +1 -1
package/dist/cli.js
CHANGED
|
@@ -30,6 +30,8 @@ import { estimateSavings, renderSavings, renderShare, savingsRows } from "./savi
|
|
|
30
30
|
import { prescan } from "./scan.js";
|
|
31
31
|
import { REQUEST_ROWS } from "./coldresume.js";
|
|
32
32
|
import { replaySubagentModels, shares, SUBAGENT_MODEL_ENV, SUBAGENT_MODEL_FORCE_ENV, SUBAGENT_ROWS } from "./subagentmodel.js";
|
|
33
|
+
import { BASH_OUTPUT_ENV, BASH_OUTPUT_KEY, replayToolOutput, TOOL_OUTPUT_ROWS } from "./tooloutput.js";
|
|
34
|
+
import { CODEX_COMPACT_ROWS, codexRollouts, currentCodexCompact, replayCodexCompact } from "./codexcompact.js";
|
|
33
35
|
import { currentCompactWindow, estimateCompactWindows, MAX_WINDOW, MIN_WINDOW, parseWindow, renderCompactWindows, setCompactWindow, settingsPath } from "./compactwindow.js";
|
|
34
36
|
import { tilde } from "./claudedir.js";
|
|
35
37
|
import { renderPreferences, copyToClipboard, CHAT_PREFERENCES } from "./preferences.js";
|
|
@@ -57,7 +59,7 @@ import { renderReads, repeatedReads } from "./reads.js";
|
|
|
57
59
|
import { costPerTask, renderTasks } from "./tasks.js";
|
|
58
60
|
import { planCache, renderCachePlan } from "./cacheplan.js";
|
|
59
61
|
import { cacheMisses, cacheMissesLine, cacheMissesSignificant, renderCacheMisses, MISS_ROWS } from "./cachemisses.js";
|
|
60
|
-
import { renderPayback, subagentPayback } from "./subagentpay.js";
|
|
62
|
+
import { renderPayback, subagentPayback, SUBAGENT_CANDIDATE } from "./subagentpay.js";
|
|
61
63
|
import { compactionQuality, renderCompactionQuality, QUALITY_ROWS } from "./compactquality.js";
|
|
62
64
|
import { isHandoffId, listHandoffs, readHandoff, renderHandoffList, stripControls } from "./handoff.js";
|
|
63
65
|
import { claudeLimitFit, limitSavingsLines, limitsReport, renderLimits } from "./limits.js";
|
|
@@ -67,12 +69,37 @@ import { applyPrune, canonical, installedSkills, planPrune, renderPrune, undoPru
|
|
|
67
69
|
import { lensOverSessions, renderLens, sessionLens, LENS_ROWS } from "./lens.js";
|
|
68
70
|
import { applyFix, fixOverrides, loadFixRecords, parseFixIds, planFixes, readFixRecords, renderFixPlan, renderFixShare, savedSince, undoFixes } from "./fix.js";
|
|
69
71
|
import { claudeMcpConfigs, MCP_ROWS } from "./mcpschema.js";
|
|
70
|
-
import { effectiveEnv, settingsSources } from "./effective.js";
|
|
72
|
+
import { effectiveEnv, settingsSources, shellSet, underClaudeCode } from "./effective.js";
|
|
71
73
|
import { SettingsError } from "./settingsedit.js";
|
|
72
74
|
import { currentTtl, estimateCacheTtl, renderCacheTtl, setCacheTtl, settingKey, subagentTranscripts, ttlUnsupported, CACHE_TTL_SINCE } from "./cachettl.js";
|
|
73
75
|
import { claudeDir } from "./claudedir.js";
|
|
74
76
|
import { renderSpend, renderSpendShare, spendReport } from "./spend.js";
|
|
75
77
|
import { clearBudget, parseBudget, periodSpend, promptHookInstalled, readBudget, renderBudgetStatus, writeBudget } from "./budget.js";
|
|
78
|
+
/**
|
|
79
|
+
* The commands that print JSON with --json. Any other command refuses the
|
|
80
|
+
* flag: it used to print its text report anyway and exit 0, so a script
|
|
81
|
+
* piping it into a JSON parser failed far from the cause.
|
|
82
|
+
*/
|
|
83
|
+
const JSON_COMMANDS = [
|
|
84
|
+
"analyze", "optimize", "session", "cursor", "savings", "fix", "spend", "budget", "limits", "subagents", "tasks",
|
|
85
|
+
"reads", "compactions", "cache-misses", "cache-ttl", "compact-window", "overhead", "accuracy", "recall", "handoff",
|
|
86
|
+
"pack", "cache-plan", "ci", "experiment", "ab",
|
|
87
|
+
];
|
|
88
|
+
/** An option's description, wrapped under the option column as the help text is (98 columns). */
|
|
89
|
+
function optionText(text) {
|
|
90
|
+
const lines = [];
|
|
91
|
+
let line = "";
|
|
92
|
+
for (const word of text.split(" ")) {
|
|
93
|
+
if (line && 26 + line.length + 1 + word.length > 98) {
|
|
94
|
+
lines.push(line);
|
|
95
|
+
line = word;
|
|
96
|
+
}
|
|
97
|
+
else
|
|
98
|
+
line = line ? `${line} ${word}` : word;
|
|
99
|
+
}
|
|
100
|
+
lines.push(line);
|
|
101
|
+
return lines.join(`\n${" ".repeat(26)}`);
|
|
102
|
+
}
|
|
76
103
|
const HELP = `context-doctor — profile and optimize LLM context windows
|
|
77
104
|
|
|
78
105
|
Start here:
|
|
@@ -251,7 +278,7 @@ Options:
|
|
|
251
278
|
Claude models (needs ANTHROPIC_API_KEY), tiktoken for GPT (if installed)
|
|
252
279
|
--redact Mask message previews and file paths in the report, so it can be
|
|
253
280
|
shared in a bug report without leaking conversation content
|
|
254
|
-
--json Machine-readable output
|
|
281
|
+
--json ${optionText(`(${JSON_COMMANDS.join(", ")}) Machine-readable output on stdout`)}
|
|
255
282
|
--fail-over-budget (analyze/session) Exit 1 when the .contextdoctorrc budget is
|
|
256
283
|
exceeded — lets CI gate a pull request on context size
|
|
257
284
|
--out <file> (optimize) Write result to file instead of stdout
|
|
@@ -263,7 +290,7 @@ Options:
|
|
|
263
290
|
--max-tool-tokens <n> (optimize) Token budget for trimmed tool results (default 300)
|
|
264
291
|
--limit <n> (accuracy, session --list, reads, tasks, subagents, spend) How many to
|
|
265
292
|
sample or list
|
|
266
|
-
--days <n> (savings, compact-window, cache-ttl, overhead, reads, tasks, subagents,
|
|
293
|
+
--days <n> (savings, fix, compact-window, cache-ttl, overhead, reads, tasks, subagents,
|
|
267
294
|
compactions, cache-misses, limits, spend)
|
|
268
295
|
Days of history to read (default 30; compactions 60)
|
|
269
296
|
--block (budget) Over the budget, the every-prompt hook holds the prompt and
|
|
@@ -323,6 +350,7 @@ Start here
|
|
|
323
350
|
context-doctor fix what to change, ranked by what it saves you; applied only on a yes
|
|
324
351
|
context-doctor install wire the MCP server, skill and hooks into the apps it finds
|
|
325
352
|
context-doctor savings what your recent sessions cost, and what each fix would save
|
|
353
|
+
context-doctor spend one bill across Claude Code, Codex, Gemini CLI and Cursor
|
|
326
354
|
context-doctor doctor check the installation
|
|
327
355
|
|
|
328
356
|
All commands: context-doctor --help
|
|
@@ -344,9 +372,10 @@ async function measureFixInputs(days) {
|
|
|
344
372
|
const setWindow = currentCompactWindow();
|
|
345
373
|
// Each transcript read once for every replay below; what an earlier run kept is not read again (scan.ts).
|
|
346
374
|
prescan([
|
|
347
|
-
{ paths: claudeTranscripts(days), extractors: [savingsRows(!autopilotOnNow), REQUEST_ROWS] },
|
|
348
|
-
{ paths: subagentTranscripts(Date.now() - days * 86_400_000), extractors: [REQUEST_ROWS, SUBAGENT_ROWS] },
|
|
375
|
+
{ paths: claudeTranscripts(days), extractors: [savingsRows(!autopilotOnNow), REQUEST_ROWS, TOOL_OUTPUT_ROWS] },
|
|
376
|
+
{ paths: subagentTranscripts(Date.now() - days * 86_400_000), extractors: [REQUEST_ROWS, SUBAGENT_ROWS, TOOL_OUTPUT_ROWS] },
|
|
349
377
|
...(setWindow === undefined ? [{ paths: claudeTranscripts(60), extractors: [QUALITY_ROWS] }] : []),
|
|
378
|
+
{ paths: codexRollouts(Date.now() - days * 86_400_000), extractors: [CODEX_COMPACT_ROWS] },
|
|
350
379
|
], replaying.tick);
|
|
351
380
|
const report = estimateSavings(days, {}, undefined, replaying.tick, !autopilotOnNow);
|
|
352
381
|
replaying.clear();
|
|
@@ -374,7 +403,29 @@ async function measureFixInputs(days) {
|
|
|
374
403
|
const subagentModel = replaySubagentModels({ since: Date.now() - days * 86_400_000, force: !!force && !/^(0|false)$/i.test(force.value.trim()) });
|
|
375
404
|
const userSm = sources.find((s) => s.name === "user")?.settings.env?.[SUBAGENT_MODEL_ENV];
|
|
376
405
|
const shellSm = process.env[SUBAGENT_MODEL_ENV];
|
|
377
|
-
|
|
406
|
+
// Inside a Claude Code session (the plugin's /context-doctor:fix) the
|
|
407
|
+
// process carries the settings files' env as the session started: a
|
|
408
|
+
// project's or managed value is that file's (named as an override, not as
|
|
409
|
+
// "a value you set"), and fix's own value just undone is no one's.
|
|
410
|
+
const subagentModelSet = userSm !== undefined && userSm !== null
|
|
411
|
+
? { value: String(userSm), where: `${tilde(join(claudeDir(), "settings.json"))} env` }
|
|
412
|
+
: shellSet(SUBAGENT_MODEL_ENV, sources, process.env, SUBAGENT_CANDIDATE)
|
|
413
|
+
? { value: shellSm, where: underClaudeCode() ? "this Claude Code session's environment (from the shell that started it, or a settings env removed since: a new session reads settings again)" : "the environment" }
|
|
414
|
+
: undefined;
|
|
415
|
+
// Long Bash output: every result replayed at lower caps; a cap the user set (or the read-back variable the setting would replace) is theirs.
|
|
416
|
+
const toolOutput = replayToolOutput({ since: Date.now() - days * 86_400_000, paths: [...claudeTranscripts(days), ...subagentTranscripts(Date.now() - days * 86_400_000)] });
|
|
417
|
+
const userCap = sources.find((s) => s.name === "user")?.settings[BASH_OUTPUT_KEY];
|
|
418
|
+
const readBack = sources.find((s) => s.name === "user")?.settings.env?.[BASH_OUTPUT_ENV];
|
|
419
|
+
const toolOutputSet = userCap !== undefined && userCap !== null
|
|
420
|
+
? { name: BASH_OUTPUT_KEY, value: userCap, where: tilde(join(claudeDir(), "settings.json")) }
|
|
421
|
+
: readBack !== undefined && readBack !== null && String(readBack).trim() !== ""
|
|
422
|
+
? { name: BASH_OUTPUT_ENV, value: String(readBack), where: `${tilde(join(claudeDir(), "settings.json"))} env` }
|
|
423
|
+
: shellSet(BASH_OUTPUT_ENV, sources, process.env)
|
|
424
|
+
? { name: BASH_OUTPUT_ENV, value: process.env[BASH_OUTPUT_ENV], where: underClaudeCode() ? "this Claude Code session's environment" : "the environment" }
|
|
425
|
+
: undefined;
|
|
426
|
+
// Codex's auto-compact limit: its rollouts replayed at earlier limits; a limit the user set is theirs.
|
|
427
|
+
const codexCompact = replayCodexCompact({ days });
|
|
428
|
+
const cxSet = currentCodexCompact();
|
|
378
429
|
const ts = effectiveEnv("ENABLE_TOOL_SEARCH", sources);
|
|
379
430
|
const toolSearchOff = ts && /^(false|0|no|off)$/i.test(ts.value.trim()) ? ts.value : undefined;
|
|
380
431
|
const servers = claudeMcpConfigs(cwd).filter((c) => !/context-doctor/i.test(c.name));
|
|
@@ -399,7 +450,7 @@ async function measureFixInputs(days) {
|
|
|
399
450
|
recordProblem = e.message;
|
|
400
451
|
}
|
|
401
452
|
const sessions = report.sessions.length;
|
|
402
|
-
const ids = ["compact-window", "cache-ttl", "cache-ttl-subagents", "tool-search", "subagent-model"];
|
|
453
|
+
const ids = ["compact-window", "cache-ttl", "cache-ttl-subagents", "tool-search", "subagent-model", "tool-output", "codex-compact"];
|
|
403
454
|
return {
|
|
404
455
|
prunePlan,
|
|
405
456
|
inputs: {
|
|
@@ -414,6 +465,10 @@ async function measureFixInputs(days) {
|
|
|
414
465
|
prune: prunePlan,
|
|
415
466
|
subagentModel,
|
|
416
467
|
subagentModelSet,
|
|
468
|
+
toolOutput,
|
|
469
|
+
toolOutputSet,
|
|
470
|
+
...(codexCompact.requests > 0 ? { codexCompact } : {}),
|
|
471
|
+
...(cxSet ? { codexCompactSet: { raw: cxSet.raw, where: cxSet.where } } : {}),
|
|
417
472
|
overrides: Object.fromEntries(ids.map((id) => [id, fixOverrides(id, { cwd })])),
|
|
418
473
|
recordProblem,
|
|
419
474
|
coldResume: { netUsd: Math.max(0, report.coldResumeNetUsd), returns: report.coldResumes, hooked: claudePluginEnabled() || /context-doctor|cli\.js"?\s+hook/.test(JSON.stringify(userSettings.hooks?.UserPromptSubmit ?? [])) },
|
|
@@ -473,7 +528,7 @@ const FLAGS = [
|
|
|
473
528
|
{ names: ["--statusline"], set: (a) => { a.statusLine = true; } },
|
|
474
529
|
{ names: ["--host"], value: "text", set: (a, v) => { a.host = v; } },
|
|
475
530
|
{ names: ["--token"], value: "text", set: (a, v) => { a.token = v; } },
|
|
476
|
-
{ names: ["--days"], value: "number", num: { min: 1 }, set: (a, v) => { a.days = v; } },
|
|
531
|
+
{ names: ["--days"], value: "number", num: { min: 1, integer: true }, set: (a, v) => { a.days = v; } },
|
|
477
532
|
{ names: ["--autopilot"], set: (a) => { a.autopilot = true; } },
|
|
478
533
|
{ names: ["--autopilot-state"], value: "text", set: (a, v) => { a.autopilotState = v; } },
|
|
479
534
|
{ names: ["--autopilot-pause-file"], value: "text", set: (a, v) => { a.autopilotPauseFile = v; } },
|
|
@@ -676,6 +731,9 @@ async function main() {
|
|
|
676
731
|
console.log((topic && commandHelp(HELP, topic)) || HELP);
|
|
677
732
|
return;
|
|
678
733
|
}
|
|
734
|
+
if (args.json && args.command && !JSON_COMMANDS.includes(args.command)) {
|
|
735
|
+
usageError(`${args.command} has no --json output. Commands with one: ${JSON_COMMANDS.join(", ")}.`);
|
|
736
|
+
}
|
|
679
737
|
// Run by hand in a terminal, these waited forever for JSON that only
|
|
680
738
|
// Claude Code sends.
|
|
681
739
|
if ((args.command === "hook" || args.command === "statusline") && process.stdin.isTTY) {
|
|
@@ -793,6 +851,10 @@ async function main() {
|
|
|
793
851
|
process.exit(1);
|
|
794
852
|
}
|
|
795
853
|
if (args.list) {
|
|
854
|
+
if (args.json) {
|
|
855
|
+
console.log(JSON.stringify(chats.map((c) => ({ id: c.composerId, title: c.title ?? null, messages: c.messageCount })), null, 2));
|
|
856
|
+
return;
|
|
857
|
+
}
|
|
796
858
|
for (const c of chats) {
|
|
797
859
|
console.log(`${String(c.messageCount).padStart(5)} msgs ${(c.title ?? "(untitled)").slice(0, 48).padEnd(50)} ${c.composerId}`);
|
|
798
860
|
}
|
|
@@ -826,6 +888,10 @@ async function main() {
|
|
|
826
888
|
if (args.command === "session") {
|
|
827
889
|
if (args.list) {
|
|
828
890
|
const sessions = listSessions(args.limit ?? 20);
|
|
891
|
+
if (args.json) {
|
|
892
|
+
console.log(JSON.stringify(sessions.map((s) => ({ path: s.path, modifiedAt: s.modifiedAt.toISOString(), sizeBytes: s.sizeBytes })), null, 2));
|
|
893
|
+
return;
|
|
894
|
+
}
|
|
829
895
|
if (sessions.length === 0) {
|
|
830
896
|
console.log("No sessions found under ~/.claude/projects or ~/.codex/sessions.");
|
|
831
897
|
return;
|
|
@@ -1050,6 +1116,10 @@ async function main() {
|
|
|
1050
1116
|
const replaying = progressLine("Replaying your sessions at each window");
|
|
1051
1117
|
const cw = estimateCompactWindows(windows.sort((a, b) => a - b), args.days ?? 30, undefined, reread, replaying.tick);
|
|
1052
1118
|
replaying.clear();
|
|
1119
|
+
if (args.json) {
|
|
1120
|
+
console.log(JSON.stringify({ ...cw, current: current ?? null }, null, 2));
|
|
1121
|
+
return;
|
|
1122
|
+
}
|
|
1053
1123
|
const limitFit = claudeLimitFit(limitsReport(cw.days, { claudeOnly: true }));
|
|
1054
1124
|
console.log(renderCompactWindows(cw, current, (estimates) => limitSavingsLines(limitFit, estimates.map((e) => [`${Math.round(e.window / 1000)}k window`, Math.max(0, e.savedUsd)]), cw.days)));
|
|
1055
1125
|
return;
|
|
@@ -1200,7 +1270,7 @@ async function main() {
|
|
|
1200
1270
|
chosen = ids;
|
|
1201
1271
|
}
|
|
1202
1272
|
if (!args.json)
|
|
1203
|
-
console.log(renderFixPlan(inputs.days, inputs.billedUsd, fixes, since, selfCommand, inputs.coldResume, inputs.recordProblem));
|
|
1273
|
+
console.log(renderFixPlan(inputs.days, inputs.billedUsd, fixes, since, selfCommand, inputs.coldResume, inputs.recordProblem, inputs.codexCompact?.billedUsd));
|
|
1204
1274
|
if (args.apply === undefined && !args.json && process.stdin.isTTY && process.stdout.isTTY && available.length && !inputs.recordProblem) {
|
|
1205
1275
|
const rl = (await import("node:readline/promises")).createInterface({ input: process.stdin, output: process.stdout });
|
|
1206
1276
|
console.log("");
|
|
@@ -1219,14 +1289,14 @@ async function main() {
|
|
|
1219
1289
|
continue;
|
|
1220
1290
|
}
|
|
1221
1291
|
const kind = id === "cache-ttl" ? "main" : id === "cache-ttl-subagents" ? "subagents" : undefined;
|
|
1222
|
-
const r = await applyFix(f, { autopilotOn: () => autopilotOn(args.port ?? DEFAULT_AUTOPILOT_PORT) }, { oneHourShare: kind ? inputs.ttl?.[kind].oneHourShare : undefined, prune: prunePlan, modelsBefore: inputs.subagentModel ? shares(inputs.subagentModel.
|
|
1292
|
+
const r = await applyFix(f, { autopilotOn: () => autopilotOn(args.port ?? DEFAULT_AUTOPILOT_PORT) }, { oneHourShare: kind ? inputs.ttl?.[kind].oneHourShare : undefined, prune: prunePlan, modelsBefore: inputs.subagentModel ? shares(inputs.subagentModel.before) : undefined });
|
|
1223
1293
|
results.push({ id, ...r });
|
|
1224
1294
|
}
|
|
1225
1295
|
// Naming fixes that are not there (or nothing at all, with "all") is not a silent success.
|
|
1226
1296
|
if (args.apply !== undefined && (chosen.length === 0 || results.some((r) => !r.ok)))
|
|
1227
1297
|
process.exitCode = 1;
|
|
1228
1298
|
if (args.json) {
|
|
1229
|
-
console.log(JSON.stringify({ days: inputs.days, billedUsd: inputs.billedUsd, fixes, since, ...(args.apply !== undefined ? { applied: results } : {}), ...(inputs.recordProblem ? { recordProblem: inputs.recordProblem } : {}) }, null, 2));
|
|
1299
|
+
console.log(JSON.stringify({ days: inputs.days, billedUsd: inputs.billedUsd, ...(inputs.codexCompact ? { codexBilledUsd: inputs.codexCompact.billedUsd } : {}), fixes, since, ...(args.apply !== undefined ? { applied: results } : {}), ...(inputs.recordProblem ? { recordProblem: inputs.recordProblem } : {}) }, null, 2));
|
|
1230
1300
|
if (args.apply !== undefined && chosen.length === 0)
|
|
1231
1301
|
console.error("--apply: no fix available to apply.");
|
|
1232
1302
|
return;
|
|
@@ -1239,7 +1309,7 @@ async function main() {
|
|
|
1239
1309
|
for (const r of results)
|
|
1240
1310
|
console.log(r.lines.join("\n"));
|
|
1241
1311
|
if (results.some((r) => r.ok))
|
|
1242
|
-
console.log(`\nNew Claude Code sessions pick these up. Undo: ${selfCommand("fix undo")}; ${selfCommand("fix")} later shows what each saved since.`);
|
|
1312
|
+
console.log(`\nNew ${results.every((r) => !r.ok || r.id === "codex-compact") ? "Codex" : results.some((r) => r.ok && r.id === "codex-compact") ? "Claude Code and Codex" : "Claude Code"} sessions pick these up. Undo: ${selfCommand("fix undo")}; ${selfCommand("fix")} later shows what each saved since.`);
|
|
1243
1313
|
return;
|
|
1244
1314
|
}
|
|
1245
1315
|
if (args.command === "cache-ttl") {
|
|
@@ -1348,7 +1418,9 @@ async function main() {
|
|
|
1348
1418
|
if (sub === "off") {
|
|
1349
1419
|
if (args.block)
|
|
1350
1420
|
usageError("--block goes with a budget: context-doctor budget 50/day --block.");
|
|
1351
|
-
|
|
1421
|
+
const was = clearBudget();
|
|
1422
|
+
// --json: the budget as it now stands, as `budget --json` prints it (none).
|
|
1423
|
+
console.log(args.json ? "null" : was ? "Budget off: the every-prompt hook no longer counts spend." : "No budget was set.");
|
|
1352
1424
|
return;
|
|
1353
1425
|
}
|
|
1354
1426
|
if (sub !== undefined) {
|
|
@@ -1356,6 +1428,9 @@ async function main() {
|
|
|
1356
1428
|
if ("error" in parsed)
|
|
1357
1429
|
usageError(`${parsed.error}${didYouMean(sub, ["off"])} ${usage}.`);
|
|
1358
1430
|
writeBudget({ ...parsed, block: Boolean(args.block), at: Date.now() });
|
|
1431
|
+
// Rounded to the cent: said, on stderr under --json so stdout stays JSON.
|
|
1432
|
+
if (parsed.note)
|
|
1433
|
+
(args.json ? console.error : console.log)(parsed.note);
|
|
1359
1434
|
}
|
|
1360
1435
|
else if (args.block) {
|
|
1361
1436
|
usageError("--block goes with a budget: context-doctor budget 50/day --block.");
|
|
@@ -1363,7 +1438,7 @@ async function main() {
|
|
|
1363
1438
|
const b = readBudget();
|
|
1364
1439
|
const s = b ? periodSpend(b.period) : undefined;
|
|
1365
1440
|
if (args.json)
|
|
1366
|
-
console.log(JSON.stringify(b && s ? { ...b, spent: s.usd, byTool: s.byTool, periodStart: s.start, periodEnd: s.end } : null, null, 2));
|
|
1441
|
+
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));
|
|
1367
1442
|
else
|
|
1368
1443
|
console.log(withInvocation(renderBudgetStatus(b, s, promptHookInstalled())));
|
|
1369
1444
|
return;
|
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Codex's auto-compact limit: what an earlier compaction would have saved on
|
|
3
|
+
* the user's Codex rollouts, and the `codex-compact` lever of `fix`.
|
|
4
|
+
*
|
|
5
|
+
* Verified 2026-11-04 against codex-cli 0.153.4 (the ChatGPT app's binary)
|
|
6
|
+
* and openai/codex main (config.schema.json, protocol/src/openai_models.rs,
|
|
7
|
+
* models-manager/src/model_info.rs) and the config reference at
|
|
8
|
+
* developers.openai.com/codex/config-reference:
|
|
9
|
+
* - `model_auto_compact_token_limit`, a top-level integer in
|
|
10
|
+
* ~/.codex/config.toml (CODEX_HOME), is the token count that triggers an
|
|
11
|
+
* automatic compaction. Unset, it is 90% of the model's context window
|
|
12
|
+
* (244,800 on a 272k window: gpt-5.5, gpt-6); set, the smaller of the two,
|
|
13
|
+
* so it can only bring compaction earlier. `..._scope` ("total", the
|
|
14
|
+
* default, or "body_after_prefix") says what it counts.
|
|
15
|
+
* - A rollout records each request as a `token_count` event (the last
|
|
16
|
+
* request's input, cached input and output, and `model_context_window`,
|
|
17
|
+
* 95% of the window), and a compaction as a `compacted` item (its
|
|
18
|
+
* replacement history) followed by a `context_compacted` event. On the
|
|
19
|
+
* author's one compaction the next request's input fell from 243,893 to
|
|
20
|
+
* 22,507 tokens. The compaction's own request is not recorded.
|
|
21
|
+
*
|
|
22
|
+
* The replay walks each rollout's requests twice: as billed, and compacting
|
|
23
|
+
* whenever the context reaches the candidate limit. Context a simulated
|
|
24
|
+
* compaction removed is priced at each later request as that request billed
|
|
25
|
+
* it (cached tokens at the cached rate, the rest at the input rate), until a
|
|
26
|
+
* real compaction; the request after a simulated one pays the input rate on
|
|
27
|
+
* its whole (now small) context, and each simulated compaction pays one
|
|
28
|
+
* request reading the context and a summary at the output rate (an estimate:
|
|
29
|
+
* Codex does not record it). What the summary dropped, and the model reading
|
|
30
|
+
* files again because of it, is not priced.
|
|
31
|
+
*/
|
|
32
|
+
import { type Extractor } from "./scan.js";
|
|
33
|
+
/** The config.toml key the lever writes. */
|
|
34
|
+
export declare const CODEX_COMPACT_KEY = "model_auto_compact_token_limit";
|
|
35
|
+
/** The limit `fix` offers, and the others the replay shows. */
|
|
36
|
+
export declare const CODEX_COMPACT_LIMIT = 150000;
|
|
37
|
+
export declare const CODEX_COMPACT_LIMITS: number[];
|
|
38
|
+
/**
|
|
39
|
+
* What the replay takes from a rollout: each model change, every request's
|
|
40
|
+
* usage (token_count: time, running total, the fork key, the window), and
|
|
41
|
+
* each compaction. No text.
|
|
42
|
+
*/
|
|
43
|
+
export declare const CODEX_COMPACT_ROWS: Extractor<null>;
|
|
44
|
+
export interface CodexCompactEstimate {
|
|
45
|
+
limit: number;
|
|
46
|
+
savedUsd: number;
|
|
47
|
+
/** Of the input billed over the same requests. */
|
|
48
|
+
savedShare: number;
|
|
49
|
+
/** Compactions there would be over the period at this limit. */
|
|
50
|
+
compactions: number;
|
|
51
|
+
}
|
|
52
|
+
export interface CodexCompactReport {
|
|
53
|
+
days: number;
|
|
54
|
+
rollouts: number;
|
|
55
|
+
requests: number;
|
|
56
|
+
/** Input billed (prompt only) over the period's requests, forks' copies once. */
|
|
57
|
+
billedUsd: number;
|
|
58
|
+
/** Requests on a model with no price (left out of the dollars). */
|
|
59
|
+
unpriced: number;
|
|
60
|
+
/** Compactions that happened over the period. */
|
|
61
|
+
actualCompactions: number;
|
|
62
|
+
/** Context right after a compaction: the median of the user's own, or 25k. */
|
|
63
|
+
afterCompact: number;
|
|
64
|
+
estimates: CodexCompactEstimate[];
|
|
65
|
+
}
|
|
66
|
+
/** Codex rollouts written since `since`: the live ones and the archived. */
|
|
67
|
+
export declare function codexRollouts(since: number, home?: string): string[];
|
|
68
|
+
/** Replay Codex's rollouts of the last `days` at each limit. */
|
|
69
|
+
export declare function replayCodexCompact(opts: {
|
|
70
|
+
days: number;
|
|
71
|
+
paths?: string[];
|
|
72
|
+
limits?: number[];
|
|
73
|
+
home?: string;
|
|
74
|
+
now?: number;
|
|
75
|
+
}): CodexCompactReport;
|
|
76
|
+
/**
|
|
77
|
+
* What a limit set at `since` saved: each compaction since that came before
|
|
78
|
+
* the old trigger (`previous`, or Codex's own), priced as the context it took
|
|
79
|
+
* off every later request until the session would have reached the old
|
|
80
|
+
* trigger, less the compaction's request and summary (an estimate, as in
|
|
81
|
+
* the replay).
|
|
82
|
+
*/
|
|
83
|
+
export declare function codexCompactSavedSince(since: number, previous: number | undefined, paths?: string[]): {
|
|
84
|
+
usd: number;
|
|
85
|
+
compactions: number;
|
|
86
|
+
};
|
|
87
|
+
/** The top-level value of `key` (before the first [table]): as written, and as a number when it is one. */
|
|
88
|
+
export declare function topLevelValue(toml: string, key?: string): {
|
|
89
|
+
raw: string;
|
|
90
|
+
value?: number;
|
|
91
|
+
} | undefined;
|
|
92
|
+
/**
|
|
93
|
+
* Set (or with undefined, remove) a top-level integer key, touching no other
|
|
94
|
+
* byte: a line replaced keeps its line end; a new line goes after the last
|
|
95
|
+
* top-level key (or at the top), with the file's own line ends. A missing
|
|
96
|
+
* file (undefined) becomes the one line.
|
|
97
|
+
*/
|
|
98
|
+
export declare function setTopLevelInt(toml: string | undefined, key: string, value: number | undefined): string;
|
|
99
|
+
/** `[profiles.<name>]` tables that set `key`, and the profile the file selects by default. */
|
|
100
|
+
export declare function profileValues(toml: string, key?: string): Array<{
|
|
101
|
+
profile: string;
|
|
102
|
+
raw: string;
|
|
103
|
+
selected: boolean;
|
|
104
|
+
}>;
|
|
105
|
+
/** ~/.codex/config.toml (CODEX_HOME honoured for this user). */
|
|
106
|
+
export declare function codexConfigPath(home?: string): string;
|
|
107
|
+
/** The limit the user set at the top of config.toml, as written. */
|
|
108
|
+
export declare function currentCodexCompact(home?: string): {
|
|
109
|
+
raw: string;
|
|
110
|
+
value?: number;
|
|
111
|
+
where: string;
|
|
112
|
+
} | undefined;
|
|
113
|
+
/** What would keep a top-level limit from applying: a profile's own, a project's config.toml. */
|
|
114
|
+
export declare function codexCompactOverrides(home?: string, cwd?: string): string[];
|
|
115
|
+
/** The lines under the lever in `fix`: each limit tried. */
|
|
116
|
+
export declare function renderCodexLimits(r: CodexCompactReport, offered: number): string[];
|