context-doctor 0.42.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 +4 -2
- package/dist/budget.d.ts +42 -0
- package/dist/budget.js +58 -26
- package/dist/cli.js +27 -6
- package/dist/codexcompact.d.ts +116 -0
- package/dist/codexcompact.js +415 -0
- package/dist/doctor.js +10 -0
- package/dist/fix.d.ts +30 -3
- package/dist/fix.js +193 -11
- package/dist/hook.js +23 -4
- package/dist/ledger.d.ts +2 -1
- package/dist/ledger.js +1 -0
- package/dist/mcp.js +1 -1
- package/dist/proxy.d.ts +1 -1
- package/dist/proxy.js +1 -1
- package/dist/sessionprice.d.ts +71 -0
- package/dist/sessionprice.js +216 -0
- package/dist/tooloutput.d.ts +118 -0
- package/dist/tooloutput.js +355 -0
- package/package.json +1 -1
|
@@ -0,0 +1,415 @@
|
|
|
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 { existsSync, readFileSync } from "node:fs";
|
|
33
|
+
import { homedir } from "node:os";
|
|
34
|
+
import { basename, join } from "node:path";
|
|
35
|
+
import { codexDir } from "./codexdir.js";
|
|
36
|
+
import { codexEventKey, codexSessionsRoot, rolloutFiles } from "./limits.js";
|
|
37
|
+
import { openAIUsage, pricingFor, usageCost } from "./pricing.js";
|
|
38
|
+
import { pick, rowsOf } from "./scan.js";
|
|
39
|
+
import { tilde } from "./claudedir.js";
|
|
40
|
+
/** The config.toml key the lever writes. */
|
|
41
|
+
export const CODEX_COMPACT_KEY = "model_auto_compact_token_limit";
|
|
42
|
+
/** The limit `fix` offers, and the others the replay shows. */
|
|
43
|
+
export const CODEX_COMPACT_LIMIT = 150_000;
|
|
44
|
+
export const CODEX_COMPACT_LIMITS = [100_000, 150_000, 200_000];
|
|
45
|
+
/** Codex's own trigger, unset: 90% of the context window. */
|
|
46
|
+
const DEFAULT_SHARE = 0.9;
|
|
47
|
+
/** The window a rollout records is 95% of the model's. */
|
|
48
|
+
const RECORDED_SHARE = 0.95;
|
|
49
|
+
/** A 272k window, when a rollout records none (gpt-5.5, gpt-6). */
|
|
50
|
+
const DEFAULT_WINDOW = 272_000;
|
|
51
|
+
/** Context right after a compaction when the user's own rollouts show none: system prompt, tools, summary, recent messages. */
|
|
52
|
+
const AFTER_COMPACT = 25_000;
|
|
53
|
+
/** Output a compaction's summary costs (an estimate: Codex does not record the compaction's request). */
|
|
54
|
+
const SUMMARY_OUTPUT = 5_000;
|
|
55
|
+
/**
|
|
56
|
+
* What the replay takes from a rollout: each model change, every request's
|
|
57
|
+
* usage (token_count: time, running total, the fork key, the window), and
|
|
58
|
+
* each compaction. No text.
|
|
59
|
+
*/
|
|
60
|
+
export const CODEX_COMPACT_ROWS = {
|
|
61
|
+
id: "codex-compact.1",
|
|
62
|
+
init: () => null,
|
|
63
|
+
line(line, row, out) {
|
|
64
|
+
if (!line.includes('"token_count"') && !line.includes('"turn_context"') && !line.includes('"compacted"') && !line.includes('"context_compacted"'))
|
|
65
|
+
return;
|
|
66
|
+
let e;
|
|
67
|
+
try {
|
|
68
|
+
e = row();
|
|
69
|
+
}
|
|
70
|
+
catch {
|
|
71
|
+
return;
|
|
72
|
+
}
|
|
73
|
+
if (!e || typeof e !== "object")
|
|
74
|
+
return;
|
|
75
|
+
if (e.type === "compacted") {
|
|
76
|
+
out.push({ k: "c" });
|
|
77
|
+
return;
|
|
78
|
+
}
|
|
79
|
+
const p = e.payload;
|
|
80
|
+
if (!p || typeof p !== "object")
|
|
81
|
+
return;
|
|
82
|
+
if (e.type === "turn_context") {
|
|
83
|
+
if (typeof p.model === "string")
|
|
84
|
+
out.push({ k: "model", model: p.model });
|
|
85
|
+
return;
|
|
86
|
+
}
|
|
87
|
+
if (e.type !== "event_msg")
|
|
88
|
+
return;
|
|
89
|
+
if (p.type === "context_compacted") {
|
|
90
|
+
out.push({ k: "c" });
|
|
91
|
+
return;
|
|
92
|
+
}
|
|
93
|
+
if (p.type !== "token_count")
|
|
94
|
+
return;
|
|
95
|
+
const last = p.info?.last_token_usage;
|
|
96
|
+
if (!last || typeof last !== "object")
|
|
97
|
+
return;
|
|
98
|
+
const total = p.info?.total_token_usage?.total_tokens;
|
|
99
|
+
const win = p.info?.model_context_window;
|
|
100
|
+
out.push({ k: "t", ts: String(e.timestamp ?? ""), total: typeof total === "number" ? total : 0, key: codexEventKey(p.info?.total_token_usage, last), ...(typeof win === "number" && win > 0 ? { win } : {}), u: pick(last, ["input_tokens", "cached_input_tokens", "cache_write_input_tokens", "output_tokens", "input_tokens_details", "prompt_tokens", "prompt_tokens_details", "completion_tokens"]) });
|
|
101
|
+
},
|
|
102
|
+
};
|
|
103
|
+
const num = (v) => (typeof v === "number" && Number.isFinite(v) && v > 0 ? v : 0);
|
|
104
|
+
/** One rollout's requests and compactions; a request a forked rollout copied from its parent (`seen`) is marked, not dropped. */
|
|
105
|
+
function readSteps(file, seen) {
|
|
106
|
+
const steps = [];
|
|
107
|
+
let model;
|
|
108
|
+
let total = -1;
|
|
109
|
+
for (const r of rowsOf(file, CODEX_COMPACT_ROWS)) {
|
|
110
|
+
if (r?.k === "model") {
|
|
111
|
+
model = r.model;
|
|
112
|
+
continue;
|
|
113
|
+
}
|
|
114
|
+
if (r?.k === "c") {
|
|
115
|
+
// A compaction is written twice (the item and its event): one boundary.
|
|
116
|
+
if (steps[steps.length - 1]?.k !== "c")
|
|
117
|
+
steps.push({ k: "c" });
|
|
118
|
+
continue;
|
|
119
|
+
}
|
|
120
|
+
if (r?.k !== "t")
|
|
121
|
+
continue;
|
|
122
|
+
// A token_count event repeats the last request when only the limits were refreshed.
|
|
123
|
+
const runTotal = num(r.total);
|
|
124
|
+
if (num(r.u?.input_tokens) === 0 || (runTotal !== 0 && runTotal === total))
|
|
125
|
+
continue;
|
|
126
|
+
total = runTotal;
|
|
127
|
+
const at = Date.parse(r.ts);
|
|
128
|
+
if (!Number.isFinite(at))
|
|
129
|
+
continue;
|
|
130
|
+
const u = openAIUsage(r.u);
|
|
131
|
+
const price = pricingFor(model);
|
|
132
|
+
const copy = !!r.key && seen.has(r.key);
|
|
133
|
+
if (r.key)
|
|
134
|
+
seen.add(r.key);
|
|
135
|
+
const window = num(r.win) ? num(r.win) / RECORDED_SHARE : DEFAULT_WINDOW;
|
|
136
|
+
steps.push({
|
|
137
|
+
k: "r", at, copy,
|
|
138
|
+
prompt: num(u.input_tokens) + num(u.cache_read_input_tokens) + num(u.cache_creation_input_tokens),
|
|
139
|
+
cached: num(u.cache_read_input_tokens),
|
|
140
|
+
out: num(u.output_tokens),
|
|
141
|
+
inPerM: price?.inputPerM ?? 0, readPerM: price?.cacheReadPerM ?? 0, outPerM: price?.outputPerM ?? 0,
|
|
142
|
+
billedUsd: price ? usageCost(u, price).promptUsd : 0,
|
|
143
|
+
trigger: DEFAULT_SHARE * window,
|
|
144
|
+
});
|
|
145
|
+
}
|
|
146
|
+
return steps;
|
|
147
|
+
}
|
|
148
|
+
/**
|
|
149
|
+
* One rollout at `limit`: as billed and with compaction at the limit, in USD
|
|
150
|
+
* over the requests in [since, until) that are not a fork's copy. Codex
|
|
151
|
+
* compacts when a turn's input and output reach the limit, which is never
|
|
152
|
+
* above its own trigger.
|
|
153
|
+
*/
|
|
154
|
+
function replay(steps, limit, since, until, after) {
|
|
155
|
+
let billed = 0, sim = 0, extra = 0, actual = 0;
|
|
156
|
+
let removed = 0, fresh = false, prevAt;
|
|
157
|
+
for (const s of steps) {
|
|
158
|
+
if (s.k === "c") {
|
|
159
|
+
if (prevAt !== undefined && prevAt >= since && prevAt < until)
|
|
160
|
+
actual++;
|
|
161
|
+
removed = 0;
|
|
162
|
+
fresh = false;
|
|
163
|
+
continue;
|
|
164
|
+
}
|
|
165
|
+
const counted = s.at >= since && s.at < until && !s.copy;
|
|
166
|
+
prevAt = s.at;
|
|
167
|
+
let ctx = s.prompt - removed;
|
|
168
|
+
// The real context fell below what was removed (a rewind with no compaction recorded): back in step.
|
|
169
|
+
if (removed > 0 && ctx < after) {
|
|
170
|
+
removed = 0;
|
|
171
|
+
ctx = s.prompt;
|
|
172
|
+
fresh = false;
|
|
173
|
+
}
|
|
174
|
+
let cost = s.billedUsd;
|
|
175
|
+
if (fresh)
|
|
176
|
+
cost = (ctx * s.inPerM) / 1e6;
|
|
177
|
+
else if (removed > 0) {
|
|
178
|
+
const fromCache = Math.min(removed, s.cached);
|
|
179
|
+
cost = Math.max(0, s.billedUsd - (fromCache * s.readPerM + (removed - fromCache) * s.inPerM) / 1e6);
|
|
180
|
+
}
|
|
181
|
+
fresh = false;
|
|
182
|
+
if (counted) {
|
|
183
|
+
billed += s.billedUsd;
|
|
184
|
+
sim += cost;
|
|
185
|
+
}
|
|
186
|
+
if (ctx + s.out >= Math.min(limit, s.trigger) && limit < s.trigger) {
|
|
187
|
+
// Compacted after this turn: one request reading the context, a summary written; the next starts from `after`.
|
|
188
|
+
if (counted) {
|
|
189
|
+
sim += (ctx * s.readPerM + SUMMARY_OUTPUT * s.outPerM) / 1e6;
|
|
190
|
+
extra++;
|
|
191
|
+
}
|
|
192
|
+
removed = s.prompt + s.out - after;
|
|
193
|
+
fresh = true;
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
return { billed, sim, extra, actual };
|
|
197
|
+
}
|
|
198
|
+
/** Codex rollouts written since `since`: the live ones and the archived. */
|
|
199
|
+
export function codexRollouts(since, home = homedir()) {
|
|
200
|
+
const roots = [codexSessionsRoot(home), join(codexDir(home), "archived_sessions")];
|
|
201
|
+
// Oldest first by name (rollout-YYYY-MM-DDThh-mm-ss-…): a parent before the forks that copy it.
|
|
202
|
+
return roots.filter((r) => existsSync(r)).flatMap((r) => rolloutFiles(r, since)).sort((a, b) => basename(a).localeCompare(basename(b)));
|
|
203
|
+
}
|
|
204
|
+
/** Replay Codex's rollouts of the last `days` at each limit. */
|
|
205
|
+
export function replayCodexCompact(opts) {
|
|
206
|
+
const now = opts.now ?? Date.now();
|
|
207
|
+
const since = now - opts.days * 86_400_000;
|
|
208
|
+
const paths = opts.paths ?? codexRollouts(since, opts.home);
|
|
209
|
+
const seen = new Set();
|
|
210
|
+
const all = [];
|
|
211
|
+
for (const p of paths) {
|
|
212
|
+
try {
|
|
213
|
+
all.push(readSteps(p, seen));
|
|
214
|
+
}
|
|
215
|
+
catch { /* unreadable: skipped */ }
|
|
216
|
+
}
|
|
217
|
+
// The context right after each of the user's own compactions.
|
|
218
|
+
const afters = [];
|
|
219
|
+
let requests = 0, unpriced = 0;
|
|
220
|
+
for (const steps of all) {
|
|
221
|
+
steps.forEach((s, i) => {
|
|
222
|
+
if (s.k === "c") {
|
|
223
|
+
const n = steps[i + 1];
|
|
224
|
+
if (n?.k === "r")
|
|
225
|
+
afters.push(n.prompt);
|
|
226
|
+
return;
|
|
227
|
+
}
|
|
228
|
+
if (s.at >= since && !s.copy) {
|
|
229
|
+
requests++;
|
|
230
|
+
if (!s.billedUsd && !s.inPerM)
|
|
231
|
+
unpriced++;
|
|
232
|
+
}
|
|
233
|
+
});
|
|
234
|
+
}
|
|
235
|
+
afters.sort((a, b) => a - b);
|
|
236
|
+
const after = afters.length ? afters[Math.floor(afters.length / 2)] : AFTER_COMPACT;
|
|
237
|
+
let billedUsd = 0, actual = 0;
|
|
238
|
+
const estimates = (opts.limits ?? CODEX_COMPACT_LIMITS).map((limit, i) => {
|
|
239
|
+
let billed = 0, sim = 0, extra = 0;
|
|
240
|
+
for (const steps of all) {
|
|
241
|
+
const r = replay(steps, limit, since, Infinity, after);
|
|
242
|
+
billed += r.billed;
|
|
243
|
+
sim += r.sim;
|
|
244
|
+
extra += r.extra;
|
|
245
|
+
if (i === 0)
|
|
246
|
+
actual += r.actual;
|
|
247
|
+
}
|
|
248
|
+
if (i === 0)
|
|
249
|
+
billedUsd = billed;
|
|
250
|
+
return { limit, savedUsd: billed - sim, savedShare: billed > 0 ? (billed - sim) / billed : 0, compactions: extra };
|
|
251
|
+
});
|
|
252
|
+
return { days: opts.days, rollouts: paths.length, requests, billedUsd, unpriced, actualCompactions: actual, afterCompact: after, estimates };
|
|
253
|
+
}
|
|
254
|
+
/**
|
|
255
|
+
* What a limit set at `since` saved: each compaction since that came before
|
|
256
|
+
* the old trigger (`previous`, or Codex's own), priced as the context it took
|
|
257
|
+
* off every later request until the session would have reached the old
|
|
258
|
+
* trigger, less the compaction's request and summary (an estimate, as in
|
|
259
|
+
* the replay).
|
|
260
|
+
*/
|
|
261
|
+
export function codexCompactSavedSince(since, previous, paths) {
|
|
262
|
+
const seen = new Set();
|
|
263
|
+
let usd = 0, compactions = 0;
|
|
264
|
+
for (const p of paths ?? codexRollouts(since)) {
|
|
265
|
+
let steps;
|
|
266
|
+
try {
|
|
267
|
+
steps = readSteps(p, seen);
|
|
268
|
+
}
|
|
269
|
+
catch {
|
|
270
|
+
continue;
|
|
271
|
+
}
|
|
272
|
+
let last;
|
|
273
|
+
let episode;
|
|
274
|
+
let pending = false;
|
|
275
|
+
for (const s of steps) {
|
|
276
|
+
if (s.k === "c") {
|
|
277
|
+
episode = undefined;
|
|
278
|
+
pending = !!last && last.at >= since && !last.copy;
|
|
279
|
+
continue;
|
|
280
|
+
}
|
|
281
|
+
if (pending && last) {
|
|
282
|
+
pending = false;
|
|
283
|
+
const pre = last.prompt + last.out;
|
|
284
|
+
const trigger = Math.min(previous ?? Infinity, last.trigger);
|
|
285
|
+
if (pre < 0.9 * trigger) {
|
|
286
|
+
episode = { pre, post: s.prompt, trigger };
|
|
287
|
+
compactions++;
|
|
288
|
+
usd -= (pre * last.readPerM + SUMMARY_OUTPUT * last.outPerM) / 1e6;
|
|
289
|
+
}
|
|
290
|
+
}
|
|
291
|
+
else if (episode?.post !== undefined && !s.copy) {
|
|
292
|
+
const would = episode.pre + Math.max(0, s.prompt - episode.post);
|
|
293
|
+
if (would >= episode.trigger)
|
|
294
|
+
episode = undefined;
|
|
295
|
+
else
|
|
296
|
+
usd += ((would - s.prompt) * s.readPerM) / 1e6;
|
|
297
|
+
}
|
|
298
|
+
last = s;
|
|
299
|
+
}
|
|
300
|
+
}
|
|
301
|
+
return { usd, compactions };
|
|
302
|
+
}
|
|
303
|
+
// -- config.toml, key by key ---------------------------------------------------------
|
|
304
|
+
const HEADER = /^\s*\[/;
|
|
305
|
+
const keyLine = (key) => new RegExp(String.raw `^\s*(?:${key}|"${key}"|'${key}')\s*=\s*([^#\r]*?)\s*(?:#[^\r]*)?\r?$`);
|
|
306
|
+
/** A TOML integer as written (`150000`, `150_000`, `+150000`), or undefined. */
|
|
307
|
+
const tomlInt = (raw) => (/^[+-]?\d[\d_]*$/.test(raw.trim()) ? Number(raw.trim().replace(/_/g, "")) : undefined);
|
|
308
|
+
/** The top-level value of `key` (before the first [table]): as written, and as a number when it is one. */
|
|
309
|
+
export function topLevelValue(toml, key = CODEX_COMPACT_KEY) {
|
|
310
|
+
const re = keyLine(key);
|
|
311
|
+
for (const line of toml.split("\n")) {
|
|
312
|
+
if (HEADER.test(line))
|
|
313
|
+
return undefined;
|
|
314
|
+
const m = re.exec(line);
|
|
315
|
+
if (m)
|
|
316
|
+
return { raw: m[1], value: tomlInt(m[1]) };
|
|
317
|
+
}
|
|
318
|
+
return undefined;
|
|
319
|
+
}
|
|
320
|
+
/**
|
|
321
|
+
* Set (or with undefined, remove) a top-level integer key, touching no other
|
|
322
|
+
* byte: a line replaced keeps its line end; a new line goes after the last
|
|
323
|
+
* top-level key (or at the top), with the file's own line ends. A missing
|
|
324
|
+
* file (undefined) becomes the one line.
|
|
325
|
+
*/
|
|
326
|
+
export function setTopLevelInt(toml, key, value) {
|
|
327
|
+
if (toml === undefined || toml === "")
|
|
328
|
+
return value === undefined ? "" : `${key} = ${value}\n`;
|
|
329
|
+
const lines = toml.split("\n");
|
|
330
|
+
const cr = toml.includes("\r\n") ? "\r" : "";
|
|
331
|
+
const re = keyLine(key);
|
|
332
|
+
const header = lines.findIndex((l) => HEADER.test(l));
|
|
333
|
+
const end = header === -1 ? lines.length : header;
|
|
334
|
+
const at = lines.slice(0, end).findIndex((l) => re.test(l));
|
|
335
|
+
if (at >= 0) {
|
|
336
|
+
if (value === undefined)
|
|
337
|
+
lines.splice(at, 1);
|
|
338
|
+
else
|
|
339
|
+
lines[at] = `${key} = ${value}${lines[at].endsWith("\r") ? "\r" : ""}`;
|
|
340
|
+
return lines.join("\n");
|
|
341
|
+
}
|
|
342
|
+
if (value === undefined)
|
|
343
|
+
return toml;
|
|
344
|
+
// After the last top-level key = value line, so a comment above a [table] stays with it.
|
|
345
|
+
let pos = 0;
|
|
346
|
+
for (let i = 0; i < end; i++)
|
|
347
|
+
if (/^\s*[\w"'.-]+\s*=/.test(lines[i]))
|
|
348
|
+
pos = i + 1;
|
|
349
|
+
lines.splice(pos, 0, `${key} = ${value}${cr}`);
|
|
350
|
+
return lines.join("\n");
|
|
351
|
+
}
|
|
352
|
+
/** `[profiles.<name>]` tables that set `key`, and the profile the file selects by default. */
|
|
353
|
+
export function profileValues(toml, key = CODEX_COMPACT_KEY) {
|
|
354
|
+
const re = keyLine(key);
|
|
355
|
+
const selected = /^\s*profile\s*=\s*["']([^"']+)["']/m.exec(toml.split(/\n\s*\[/)[0])?.[1];
|
|
356
|
+
const out = [];
|
|
357
|
+
let table;
|
|
358
|
+
for (const line of toml.split("\n")) {
|
|
359
|
+
if (HEADER.test(line)) {
|
|
360
|
+
table = /^\s*\[\s*profiles\.(?:"([^"]+)"|'([^']+)'|([\w-]+))\s*\]/.exec(line)?.slice(1).find((x) => x !== undefined);
|
|
361
|
+
continue;
|
|
362
|
+
}
|
|
363
|
+
const m = table !== undefined ? re.exec(line) : null;
|
|
364
|
+
if (m && table !== undefined)
|
|
365
|
+
out.push({ profile: table, raw: m[1], selected: table === selected });
|
|
366
|
+
}
|
|
367
|
+
return out;
|
|
368
|
+
}
|
|
369
|
+
/** ~/.codex/config.toml (CODEX_HOME honoured for this user). */
|
|
370
|
+
export function codexConfigPath(home) {
|
|
371
|
+
return join(codexDir(home), "config.toml");
|
|
372
|
+
}
|
|
373
|
+
/** The limit the user set at the top of config.toml, as written. */
|
|
374
|
+
export function currentCodexCompact(home) {
|
|
375
|
+
const p = codexConfigPath(home);
|
|
376
|
+
let text;
|
|
377
|
+
try {
|
|
378
|
+
text = readFileSync(p, "utf8");
|
|
379
|
+
}
|
|
380
|
+
catch {
|
|
381
|
+
return undefined;
|
|
382
|
+
}
|
|
383
|
+
const v = topLevelValue(text);
|
|
384
|
+
return v ? { ...v, where: tilde(p) } : undefined;
|
|
385
|
+
}
|
|
386
|
+
/** What would keep a top-level limit from applying: a profile's own, a project's config.toml. */
|
|
387
|
+
export function codexCompactOverrides(home, cwd = process.cwd()) {
|
|
388
|
+
const out = [];
|
|
389
|
+
const p = codexConfigPath(home);
|
|
390
|
+
try {
|
|
391
|
+
for (const v of profileValues(readFileSync(p, "utf8")))
|
|
392
|
+
out.push(`${CODEX_COMPACT_KEY} = ${v.raw} in [profiles.${v.profile}] of ${tilde(p)} (${v.selected ? "the profile it selects" : `when Codex runs with --profile ${v.profile}`})`);
|
|
393
|
+
}
|
|
394
|
+
catch { /* none */ }
|
|
395
|
+
const project = join(cwd, ".codex", "config.toml");
|
|
396
|
+
if (project !== p) {
|
|
397
|
+
try {
|
|
398
|
+
const v = topLevelValue(readFileSync(project, "utf8"));
|
|
399
|
+
if (v)
|
|
400
|
+
out.push(`${CODEX_COMPACT_KEY} = ${v.raw} in ${tilde(project)} (this project's)`);
|
|
401
|
+
}
|
|
402
|
+
catch { /* none */ }
|
|
403
|
+
}
|
|
404
|
+
return out;
|
|
405
|
+
}
|
|
406
|
+
const usd = (n) => (Math.abs(n) >= 100 ? `$${Math.round(n).toLocaleString("en-US")}` : `$${n.toFixed(2)}`);
|
|
407
|
+
const k = (n) => `${Math.round(n / 1000)}k`;
|
|
408
|
+
/** The lines under the lever in `fix`: each limit tried. */
|
|
409
|
+
export function renderCodexLimits(r, offered) {
|
|
410
|
+
const weeks = r.days / 7;
|
|
411
|
+
const out = [`${"limit".padEnd(10)}${"saved".padStart(10)} compactions a week (now ${(r.actualCompactions / weeks).toFixed(1)})`];
|
|
412
|
+
for (const e of r.estimates)
|
|
413
|
+
out.push(`${k(e.limit).padEnd(10)}${usd(e.savedUsd).padStart(10)} ${(e.compactions / weeks).toFixed(1)}${e.limit === offered ? " ←" : ""}`);
|
|
414
|
+
return out;
|
|
415
|
+
}
|
package/dist/doctor.js
CHANGED
|
@@ -28,6 +28,7 @@ import { describeCosts, subagentCostsPath } from "./fanout.js";
|
|
|
28
28
|
import { claudeCodePresent, claudeDir, claudeJsonPath } from "./claudedir.js";
|
|
29
29
|
import { codexDir } from "./codexdir.js";
|
|
30
30
|
import { periodSpend, readBudget } from "./budget.js";
|
|
31
|
+
import { sessionPriceThresholds } from "./sessionprice.js";
|
|
31
32
|
function claudeDesktopConfigPath() {
|
|
32
33
|
switch (platform()) {
|
|
33
34
|
case "darwin": return join(homedir(), "Library", "Application Support", "Claude", "claude_desktop_config.json");
|
|
@@ -765,6 +766,15 @@ export async function runDoctor() {
|
|
|
765
766
|
: { label: "Spend budget", status: "warn", detail: `${usd} a ${b.period}${spent}, but no every-prompt hook is registered to apply it: run context-doctor install` });
|
|
766
767
|
}
|
|
767
768
|
}
|
|
769
|
+
// The session price: where the every-prompt hook speaks, and how to change or stop it.
|
|
770
|
+
{
|
|
771
|
+
const at = sessionPriceThresholds();
|
|
772
|
+
const hooked = checks.some((c) => ["Every-prompt hook", "Codex hook", "Gemini CLI hook"].includes(c.label) && c.status === "ok");
|
|
773
|
+
if (!at.length)
|
|
774
|
+
checks.push({ label: "Session price", status: "skip", detail: "off (CONTEXT_DOCTOR_NO_SESSION_PRICE=1)" });
|
|
775
|
+
else if (hooked)
|
|
776
|
+
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
|
+
}
|
|
768
778
|
checks.push(await checkMcpHandshake());
|
|
769
779
|
// Autopilot: optional, so "off" is a skip, not a failure. When it is on, a
|
|
770
780
|
// dead proxy or a settings file pointing elsewhere is a real problem.
|
package/dist/fix.d.ts
CHANGED
|
@@ -24,7 +24,10 @@
|
|
|
24
24
|
* priced);
|
|
25
25
|
* - autopilot: what the proxy recorded saving since (its own ledger);
|
|
26
26
|
* - the subagents' model: the requests it moved, priced at the model they
|
|
27
|
-
* ran on before against as billed (the same token counts: an estimate)
|
|
27
|
+
* ran on before against as billed (the same token counts: an estimate);
|
|
28
|
+
* - long Bash output: the results moved to a file that the cap before left
|
|
29
|
+
* inline, priced at the requests that re-read them no more (an estimate:
|
|
30
|
+
* a file the model opens again is not counted).
|
|
28
31
|
*
|
|
29
32
|
* The subagents' model is the one lever with a quality cost `fix` cannot
|
|
30
33
|
* measure: it is offered with that said, applied only when named (never by
|
|
@@ -34,7 +37,9 @@ import { type CacheTtlReport, type CurrentTtl } from "./cachettl.js";
|
|
|
34
37
|
import { type ProjectPlan } from "./prune.js";
|
|
35
38
|
import { readLedger } from "./ledger.js";
|
|
36
39
|
import { type SubagentModelReplay } from "./subagentmodel.js";
|
|
37
|
-
|
|
40
|
+
import { type ToolOutputReplay } from "./tooloutput.js";
|
|
41
|
+
import { type CodexCompactReport } from "./codexcompact.js";
|
|
42
|
+
export type FixId = "compact-window" | "cache-ttl" | "cache-ttl-subagents" | "autopilot" | "tool-search" | "prune" | "subagent-model" | "tool-output" | "codex-compact";
|
|
38
43
|
export interface Fix {
|
|
39
44
|
id: FixId;
|
|
40
45
|
title: string;
|
|
@@ -104,6 +109,21 @@ export interface FixInputs {
|
|
|
104
109
|
returns: number;
|
|
105
110
|
hooked: boolean;
|
|
106
111
|
};
|
|
112
|
+
/** Every Bash and MCP result replayed at lower caps (tooloutput.ts). */
|
|
113
|
+
toolOutput?: ToolOutputReplay;
|
|
114
|
+
/** bashOutputMaxChars in the user's settings.json, or BASH_MAX_OUTPUT_LENGTH as the user set it (the setting would replace it): never overwritten. */
|
|
115
|
+
toolOutputSet?: {
|
|
116
|
+
name: string;
|
|
117
|
+
value: string | number;
|
|
118
|
+
where: string;
|
|
119
|
+
};
|
|
120
|
+
/** Codex's rollouts replayed at earlier auto-compact limits (codexcompact.ts). */
|
|
121
|
+
codexCompact?: CodexCompactReport;
|
|
122
|
+
/** model_auto_compact_token_limit at the top of the user's config.toml, as written: never overwritten. */
|
|
123
|
+
codexCompactSet?: {
|
|
124
|
+
raw: string;
|
|
125
|
+
where: string;
|
|
126
|
+
};
|
|
107
127
|
}
|
|
108
128
|
export declare function planFixes(i: FixInputs): Fix[];
|
|
109
129
|
export interface FixRecord {
|
|
@@ -129,6 +149,12 @@ export interface FixRecord {
|
|
|
129
149
|
/** For subagent-model: the models the moved types' subagents ran on before the change, each one's share of their tokens (Sonnet-or-cheaper ones included): the baseline "since" compares against. */
|
|
130
150
|
modelsBefore?: Record<string, number>;
|
|
131
151
|
}
|
|
152
|
+
/**
|
|
153
|
+
* ~/.claude/.context-doctor-fixes.json, as always. On a machine with no
|
|
154
|
+
* ~/.claude (Codex only), the state folder the ledger falls back to: `fix`
|
|
155
|
+
* must not make a ~/.claude there. Once records are in that folder they stay
|
|
156
|
+
* there, so a Claude Code installed later does not strand them.
|
|
157
|
+
*/
|
|
132
158
|
export declare function fixRecordPath(home?: string): string;
|
|
133
159
|
/**
|
|
134
160
|
* The records, strictly: an absent file is none; a file that is not ours to
|
|
@@ -187,9 +213,10 @@ export declare function compactWindowSavingsSince(since: number, previousWindow:
|
|
|
187
213
|
export declare function savedSince(records: FixRecord[], opts?: {
|
|
188
214
|
paths?: string[];
|
|
189
215
|
subagentPaths?: string[];
|
|
216
|
+
codexPaths?: string[];
|
|
190
217
|
ledger?: ReturnType<typeof readLedger>;
|
|
191
218
|
}): SinceResult[];
|
|
192
|
-
export declare function renderFixPlan(days: number, billedUsd: number, fixes: Fix[], since: SinceResult[], command?: (s: string) => string, coldResume?: FixInputs["coldResume"], recordProblem?: string): string;
|
|
219
|
+
export declare function renderFixPlan(days: number, billedUsd: number, fixes: Fix[], since: SinceResult[], command?: (s: string) => string, coldResume?: FixInputs["coldResume"], recordProblem?: string, codexBilledUsd?: number): string;
|
|
193
220
|
export declare function renderFixShare(days: number, billedUsd: number, fixes: Fix[]): string;
|
|
194
221
|
export declare function parseFixIds(raw: string, fixes: Fix[]): {
|
|
195
222
|
ids: FixId[];
|