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
|
@@ -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
|
+
}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Where Codex keeps its home: `~/.codex` (config.toml, hooks.json, auth.json,
|
|
3
|
+
* AGENTS.md, skills/, sessions/, archived_sessions/), unless CODEX_HOME
|
|
4
|
+
* names another folder. Read from the Codex binary (ChatGPT.app's, 2026-09):
|
|
5
|
+
* a non-empty CODEX_HOME is used as given (it must exist; Codex refuses to
|
|
6
|
+
* start otherwise), else `~/.codex`. As with CLAUDE_CONFIG_DIR (claudedir.ts),
|
|
7
|
+
* a caller that passes its own `home` (tests, a throwaway home) gets that
|
|
8
|
+
* home's folder: the variable describes the real user's setup.
|
|
9
|
+
*/
|
|
10
|
+
/** `~/.codex`, or CODEX_HOME. */
|
|
11
|
+
export declare function codexDir(home?: string, env?: NodeJS.ProcessEnv): string;
|
package/dist/codexdir.js
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Where Codex keeps its home: `~/.codex` (config.toml, hooks.json, auth.json,
|
|
3
|
+
* AGENTS.md, skills/, sessions/, archived_sessions/), unless CODEX_HOME
|
|
4
|
+
* names another folder. Read from the Codex binary (ChatGPT.app's, 2026-09):
|
|
5
|
+
* a non-empty CODEX_HOME is used as given (it must exist; Codex refuses to
|
|
6
|
+
* start otherwise), else `~/.codex`. As with CLAUDE_CONFIG_DIR (claudedir.ts),
|
|
7
|
+
* a caller that passes its own `home` (tests, a throwaway home) gets that
|
|
8
|
+
* home's folder: the variable describes the real user's setup.
|
|
9
|
+
*/
|
|
10
|
+
import { homedir } from "node:os";
|
|
11
|
+
import { join, resolve } from "node:path";
|
|
12
|
+
/** `~/.codex`, or CODEX_HOME. */
|
|
13
|
+
export function codexDir(home, env = process.env) {
|
|
14
|
+
if (home === undefined || home === homedir()) {
|
|
15
|
+
const v = env.CODEX_HOME?.trim();
|
|
16
|
+
if (v)
|
|
17
|
+
return resolve(v);
|
|
18
|
+
}
|
|
19
|
+
return join(home ?? homedir(), ".codex");
|
|
20
|
+
}
|
package/dist/codexroute.d.ts
CHANGED
|
@@ -21,6 +21,7 @@
|
|
|
21
21
|
* config.toml is the user's file: only our one top-level line is ever
|
|
22
22
|
* added, replaced or removed, and a value someone else set is left alone.
|
|
23
23
|
*/
|
|
24
|
+
/** Codex's home for `home`: CODEX_HOME when `home` is this user's (codexdir.ts). */
|
|
24
25
|
export declare function codexHomeIn(home: string): string;
|
|
25
26
|
/** How Codex signs in, from auth.json: "apikey", "chatgpt", another mode, or undefined (none yet). */
|
|
26
27
|
export declare function codexAuthMode(codexHome: string): string | undefined;
|
package/dist/codexroute.js
CHANGED
|
@@ -23,11 +23,13 @@
|
|
|
23
23
|
*/
|
|
24
24
|
import { existsSync, readFileSync, writeFileSync, copyFileSync } from "node:fs";
|
|
25
25
|
import { join } from "node:path";
|
|
26
|
+
import { codexDir } from "./codexdir.js";
|
|
26
27
|
const KEY = "openai_base_url";
|
|
27
28
|
const ANY_HEADER = /^\s*\[/;
|
|
28
29
|
const keyLine = (key) => new RegExp(String.raw `^\s*(?:${key}|"${key}"|'${key}')\s*=\s*(?:"([^"]*)"|'([^']*)')\s*(?:#.*)?$`);
|
|
30
|
+
/** Codex's home for `home`: CODEX_HOME when `home` is this user's (codexdir.ts). */
|
|
29
31
|
export function codexHomeIn(home) {
|
|
30
|
-
return
|
|
32
|
+
return codexDir(home);
|
|
31
33
|
}
|
|
32
34
|
/** How Codex signs in, from auth.json: "apikey", "chatgpt", another mode, or undefined (none yet). */
|
|
33
35
|
export function codexAuthMode(codexHome) {
|
package/dist/compactwindow.js
CHANGED
|
@@ -25,7 +25,7 @@ import { listSessions, replyCounter, isClaudeSession } from "./session.js";
|
|
|
25
25
|
import { cacheWriteSplit, pricingFor, usageCost, writeMultiplier } from "./pricing.js";
|
|
26
26
|
import { realModel } from "./tokens.js";
|
|
27
27
|
import { backupOnce } from "./install.js";
|
|
28
|
-
import { ABSENT, readSettings, setJsonPath, writeAtomic } from "./settingsedit.js";
|
|
28
|
+
import { ABSENT, readSettings, setJsonPath, withSettingsLock, writeAtomic } from "./settingsedit.js";
|
|
29
29
|
import { compactWindowOverrides, effectiveCompactWindow, settingsSources } from "./effective.js";
|
|
30
30
|
import { withInvocation } from "./invocation.js";
|
|
31
31
|
import { idleCompactMinTokens, isIdleCompactNotice, REQUEST_ROWS } from "./coldresume.js";
|
|
@@ -254,14 +254,17 @@ export function setCompactWindow(window, home) {
|
|
|
254
254
|
throw new Error(`window must be a whole number of tokens between ${MIN_WINDOW} and ${MAX_WINDOW}`);
|
|
255
255
|
}
|
|
256
256
|
const p = settingsPath(home);
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
257
|
+
// Read and written under the lock fix and autopilot take: a concurrent writer's key is not lost.
|
|
258
|
+
return withSettingsLock(p, () => {
|
|
259
|
+
const cur = readSettings(p);
|
|
260
|
+
const previous = cur.data.autoCompactWindow;
|
|
261
|
+
if (window === undefined ? previous === undefined : previous === window)
|
|
262
|
+
return { changed: false, created: false, ...(previous !== undefined ? { previous } : {}) };
|
|
263
|
+
const next = setJsonPath(cur.text, ["autoCompactWindow"], window === undefined ? ABSENT : window);
|
|
264
|
+
backupOnce(p);
|
|
265
|
+
writeAtomic(p, next);
|
|
266
|
+
return { changed: true, created: cur.text === undefined, backup: cur.text !== undefined ? `${p}.context-doctor.backup` : undefined, previous };
|
|
267
|
+
});
|
|
265
268
|
}
|
|
266
269
|
/** "400k" / "400000" / "0.4m" -> 400000. Undefined when unparseable. */
|
|
267
270
|
export function parseWindow(raw) {
|
package/dist/cursor.js
CHANGED
|
@@ -16,6 +16,7 @@ import { existsSync, readdirSync, readFileSync, statSync } from "node:fs";
|
|
|
16
16
|
import { createRequire } from "node:module";
|
|
17
17
|
import { homedir, platform } from "node:os";
|
|
18
18
|
import { join } from "node:path";
|
|
19
|
+
import { pathToFileURL } from "node:url";
|
|
19
20
|
import { readSideEntry, writeSideEntry } from "./scan.js";
|
|
20
21
|
const require = createRequire(import.meta.url);
|
|
21
22
|
/** Cursor bubble type codes. */
|
|
@@ -125,12 +126,26 @@ export function queryRows(dbPath, sql) {
|
|
|
125
126
|
}
|
|
126
127
|
}
|
|
127
128
|
// Fallback: the sqlite3 CLI, if the user has it.
|
|
129
|
+
const cli = (target) => execFileSync("sqlite3", ["-readonly", "-json", target, sql], {
|
|
130
|
+
encoding: "utf8",
|
|
131
|
+
maxBuffer: 512 * 1024 * 1024,
|
|
132
|
+
stdio: ["ignore", "pipe", "ignore"], // a missing table is expected on some DBs
|
|
133
|
+
});
|
|
128
134
|
try {
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
135
|
+
let out;
|
|
136
|
+
try {
|
|
137
|
+
out = cli(dbPath);
|
|
138
|
+
}
|
|
139
|
+
catch (e) {
|
|
140
|
+
// macOS's own sqlite3 cannot open a WAL database read-only once its
|
|
141
|
+
// -wal and -shm files are gone, which is how Cursor leaves it when it
|
|
142
|
+
// quits ("unable to open database file"): every Cursor read failed
|
|
143
|
+
// there on Node < 22.13. With no -wal file nothing is writing it, so
|
|
144
|
+
// it is read as immutable.
|
|
145
|
+
if (e.code === "ENOENT" || existsSync(`${dbPath}-wal`))
|
|
146
|
+
throw e;
|
|
147
|
+
out = cli(`${pathToFileURL(dbPath).href}?immutable=1`);
|
|
148
|
+
}
|
|
134
149
|
return out.trim() ? JSON.parse(out) : [];
|
|
135
150
|
}
|
|
136
151
|
catch (cliErr) {
|
package/dist/doctor.d.ts
CHANGED
|
@@ -37,6 +37,15 @@ export declare function cacheTtlCheck(home?: string, env?: NodeJS.ProcessEnv): C
|
|
|
37
37
|
* rather than nothing or a false "ok".
|
|
38
38
|
*/
|
|
39
39
|
export declare function devinCheck(home?: string): Check;
|
|
40
|
+
/**
|
|
41
|
+
* How long the handshake may take: 15 s, or CONTEXT_DOCTOR_MCP_HANDSHAKE_MS.
|
|
42
|
+
* 5 s failed on a loaded machine (Node starting the server is most of it); a
|
|
43
|
+
* server that crashes is reported as soon as it exits, so only one that
|
|
44
|
+
* hangs alive waits this long.
|
|
45
|
+
*/
|
|
46
|
+
export declare function handshakeTimeoutMs(env?: NodeJS.ProcessEnv): number;
|
|
47
|
+
/** Spawn our own MCP server and run the initialize handshake over stdio. */
|
|
48
|
+
export declare function checkMcpHandshake(mcpPath?: string, timeoutMs?: number): Promise<Check>;
|
|
40
49
|
export declare function runDoctor(): Promise<void>;
|
|
41
50
|
/**
|
|
42
51
|
* The Cursor version here: the newest one that ran the hook (its input
|