context-doctor 0.42.0 → 0.44.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 +6 -3
- package/dist/budget.d.ts +52 -0
- package/dist/budget.js +209 -59
- package/dist/cachettl.d.ts +5 -1
- package/dist/cachettl.js +10 -25
- package/dist/cli.js +33 -15
- package/dist/codexcompact.d.ts +137 -0
- package/dist/codexcompact.js +581 -0
- package/dist/compactwindow.js +2 -2
- package/dist/cursor.d.ts +10 -0
- package/dist/cursor.js +20 -0
- package/dist/doctor.d.ts +9 -0
- package/dist/doctor.js +55 -0
- package/dist/fanout.js +4 -2
- package/dist/fix.d.ts +38 -4
- package/dist/fix.js +249 -21
- package/dist/hook.js +65 -16
- package/dist/install.js +56 -19
- package/dist/ledger.d.ts +2 -1
- package/dist/ledger.js +1 -0
- package/dist/limits.d.ts +6 -2
- package/dist/limits.js +19 -16
- package/dist/mcp.js +63 -63
- package/dist/mcpclient.js +19 -19
- package/dist/mcpschema.js +5 -9
- package/dist/overhead.d.ts +7 -2
- package/dist/overhead.js +11 -3
- package/dist/pack.js +23 -3
- package/dist/pricing.d.ts +25 -5
- package/dist/pricing.js +157 -48
- package/dist/proxy.d.ts +15 -1
- package/dist/proxy.js +33 -5
- package/dist/prune.d.ts +8 -0
- package/dist/prune.js +20 -9
- package/dist/savings.js +2 -1
- package/dist/sessionprice.d.ts +77 -0
- package/dist/sessionprice.js +267 -0
- package/dist/settingsedit.js +3 -2
- package/dist/spend.d.ts +25 -3
- package/dist/spend.js +67 -19
- package/dist/subagentmodel.js +11 -1
- package/dist/subagentpay.d.ts +17 -0
- package/dist/subagentpay.js +41 -2
- package/dist/subagents.d.ts +24 -0
- package/dist/subagents.js +82 -17
- package/dist/tooloutput.d.ts +120 -0
- package/dist/tooloutput.js +357 -0
- package/package.json +1 -1
|
@@ -0,0 +1,581 @@
|
|
|
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, statSync } from "node:fs";
|
|
33
|
+
import { homedir } from "node:os";
|
|
34
|
+
import { basename, dirname, join, resolve } 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; with the `body_after_prefix` scope, when what the
|
|
153
|
+
* turn holds beyond the first request of its window (the session's start or
|
|
154
|
+
* the last compaction) reaches it (codex-rs session/context_window.rs).
|
|
155
|
+
*/
|
|
156
|
+
function replay(steps, limit, since, until, after, scope = "total") {
|
|
157
|
+
let billed = 0, sim = 0, extra = 0, actual = 0;
|
|
158
|
+
let removed = 0, fresh = false, prevCounted = false;
|
|
159
|
+
// The input of the window's first request: what body_after_prefix does not count.
|
|
160
|
+
let prefill;
|
|
161
|
+
for (const s of steps) {
|
|
162
|
+
if (s.k === "c") {
|
|
163
|
+
// A compaction after a fork's copy of its parent's requests is the parent's, counted there.
|
|
164
|
+
if (prevCounted)
|
|
165
|
+
actual++;
|
|
166
|
+
removed = 0;
|
|
167
|
+
fresh = false;
|
|
168
|
+
prefill = undefined;
|
|
169
|
+
continue;
|
|
170
|
+
}
|
|
171
|
+
const counted = s.at >= since && s.at < until && !s.copy;
|
|
172
|
+
prevCounted = counted;
|
|
173
|
+
let ctx = s.prompt - removed;
|
|
174
|
+
// The real context fell below what was removed (a rewind with no compaction recorded): back in step.
|
|
175
|
+
if (removed > 0 && ctx < after) {
|
|
176
|
+
removed = 0;
|
|
177
|
+
ctx = s.prompt;
|
|
178
|
+
fresh = false;
|
|
179
|
+
}
|
|
180
|
+
let cost = s.billedUsd;
|
|
181
|
+
if (fresh)
|
|
182
|
+
cost = (ctx * s.inPerM) / 1e6;
|
|
183
|
+
else if (removed > 0) {
|
|
184
|
+
const fromCache = Math.min(removed, s.cached);
|
|
185
|
+
cost = Math.max(0, s.billedUsd - (fromCache * s.readPerM + (removed - fromCache) * s.inPerM) / 1e6);
|
|
186
|
+
}
|
|
187
|
+
fresh = false;
|
|
188
|
+
prefill ??= ctx;
|
|
189
|
+
if (counted) {
|
|
190
|
+
billed += s.billedUsd;
|
|
191
|
+
sim += cost;
|
|
192
|
+
}
|
|
193
|
+
const reached = scope === "body_after_prefix"
|
|
194
|
+
? ctx + s.out - prefill >= limit && ctx + s.out < s.trigger
|
|
195
|
+
: ctx + s.out >= Math.min(limit, s.trigger) && limit < s.trigger;
|
|
196
|
+
if (reached) {
|
|
197
|
+
// Compacted after this turn: one request reading the context, a summary written; the next starts from `after`.
|
|
198
|
+
if (counted) {
|
|
199
|
+
sim += (ctx * s.readPerM + SUMMARY_OUTPUT * s.outPerM) / 1e6;
|
|
200
|
+
extra++;
|
|
201
|
+
}
|
|
202
|
+
removed = s.prompt + s.out - after;
|
|
203
|
+
fresh = true;
|
|
204
|
+
prefill = undefined;
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
return { billed, sim, extra, actual };
|
|
208
|
+
}
|
|
209
|
+
export const CODEX_COMPACT_SCOPE_KEY = "model_auto_compact_token_limit_scope";
|
|
210
|
+
/** Codex rollouts written since `since`: the live ones and the archived. */
|
|
211
|
+
export function codexRollouts(since, home = homedir()) {
|
|
212
|
+
const roots = [codexSessionsRoot(home), join(codexDir(home), "archived_sessions")];
|
|
213
|
+
// Oldest first by name (rollout-YYYY-MM-DDThh-mm-ss-…): a parent before the forks that copy it.
|
|
214
|
+
return roots.filter((r) => existsSync(r)).flatMap((r) => rolloutFiles(r, since)).sort((a, b) => basename(a).localeCompare(basename(b)));
|
|
215
|
+
}
|
|
216
|
+
/** Replay Codex's rollouts of the last `days` at each limit. */
|
|
217
|
+
export function replayCodexCompact(opts) {
|
|
218
|
+
const now = opts.now ?? Date.now();
|
|
219
|
+
const scope = opts.scope ?? codexCompactScope(opts.home);
|
|
220
|
+
const since = now - opts.days * 86_400_000;
|
|
221
|
+
const paths = opts.paths ?? codexRollouts(since, opts.home);
|
|
222
|
+
const seen = new Set();
|
|
223
|
+
const all = [];
|
|
224
|
+
for (const p of paths) {
|
|
225
|
+
try {
|
|
226
|
+
all.push(readSteps(p, seen));
|
|
227
|
+
}
|
|
228
|
+
catch { /* unreadable: skipped */ }
|
|
229
|
+
}
|
|
230
|
+
// The context right after each of the user's own compactions.
|
|
231
|
+
const afters = [];
|
|
232
|
+
let requests = 0, unpriced = 0;
|
|
233
|
+
for (const steps of all) {
|
|
234
|
+
steps.forEach((s, i) => {
|
|
235
|
+
if (s.k === "c") {
|
|
236
|
+
const n = steps[i + 1];
|
|
237
|
+
if (n?.k === "r" && !n.copy)
|
|
238
|
+
afters.push(n.prompt);
|
|
239
|
+
return;
|
|
240
|
+
}
|
|
241
|
+
if (s.at >= since && !s.copy) {
|
|
242
|
+
requests++;
|
|
243
|
+
if (!s.billedUsd && !s.inPerM)
|
|
244
|
+
unpriced++;
|
|
245
|
+
}
|
|
246
|
+
});
|
|
247
|
+
}
|
|
248
|
+
afters.sort((a, b) => a - b);
|
|
249
|
+
const after = afters.length ? afters[Math.floor(afters.length / 2)] : AFTER_COMPACT;
|
|
250
|
+
let billedUsd = 0, actual = 0;
|
|
251
|
+
const estimates = (opts.limits ?? CODEX_COMPACT_LIMITS).map((limit, i) => {
|
|
252
|
+
let billed = 0, sim = 0, extra = 0;
|
|
253
|
+
for (const steps of all) {
|
|
254
|
+
const r = replay(steps, limit, since, Infinity, after, scope);
|
|
255
|
+
billed += r.billed;
|
|
256
|
+
sim += r.sim;
|
|
257
|
+
extra += r.extra;
|
|
258
|
+
if (i === 0)
|
|
259
|
+
actual += r.actual;
|
|
260
|
+
}
|
|
261
|
+
if (i === 0)
|
|
262
|
+
billedUsd = billed;
|
|
263
|
+
return { limit, savedUsd: billed - sim, savedShare: billed > 0 ? (billed - sim) / billed : 0, compactions: extra };
|
|
264
|
+
});
|
|
265
|
+
return { days: opts.days, scope, rollouts: paths.length, requests, billedUsd, unpriced, actualCompactions: actual, afterCompact: after, estimates };
|
|
266
|
+
}
|
|
267
|
+
/**
|
|
268
|
+
* What a limit set at `since` saved: each compaction since that came before
|
|
269
|
+
* the old trigger (`previous`, or Codex's own), priced as the context it took
|
|
270
|
+
* off every later request until the session would have reached the old
|
|
271
|
+
* trigger, less the compaction's request and summary (an estimate, as in
|
|
272
|
+
* the replay).
|
|
273
|
+
*/
|
|
274
|
+
export function codexCompactSavedSince(since, previous, paths) {
|
|
275
|
+
const seen = new Set();
|
|
276
|
+
let usd = 0, compactions = 0;
|
|
277
|
+
for (const p of paths ?? codexRollouts(since)) {
|
|
278
|
+
let steps;
|
|
279
|
+
try {
|
|
280
|
+
steps = readSteps(p, seen);
|
|
281
|
+
}
|
|
282
|
+
catch {
|
|
283
|
+
continue;
|
|
284
|
+
}
|
|
285
|
+
let last;
|
|
286
|
+
let episode;
|
|
287
|
+
let pending = false;
|
|
288
|
+
for (const s of steps) {
|
|
289
|
+
if (s.k === "c") {
|
|
290
|
+
episode = undefined;
|
|
291
|
+
pending = !!last && last.at >= since && !last.copy;
|
|
292
|
+
continue;
|
|
293
|
+
}
|
|
294
|
+
if (pending && last) {
|
|
295
|
+
pending = false;
|
|
296
|
+
const pre = last.prompt + last.out;
|
|
297
|
+
const trigger = Math.min(previous ?? Infinity, last.trigger);
|
|
298
|
+
if (pre < 0.9 * trigger) {
|
|
299
|
+
episode = { pre, post: s.prompt, trigger };
|
|
300
|
+
compactions++;
|
|
301
|
+
usd -= (pre * last.readPerM + SUMMARY_OUTPUT * last.outPerM) / 1e6;
|
|
302
|
+
}
|
|
303
|
+
}
|
|
304
|
+
else if (episode?.post !== undefined && !s.copy) {
|
|
305
|
+
const would = episode.pre + Math.max(0, s.prompt - episode.post);
|
|
306
|
+
if (would >= episode.trigger)
|
|
307
|
+
episode = undefined;
|
|
308
|
+
else
|
|
309
|
+
usd += ((would - s.prompt) * s.readPerM) / 1e6;
|
|
310
|
+
}
|
|
311
|
+
last = s;
|
|
312
|
+
}
|
|
313
|
+
}
|
|
314
|
+
return { usd, compactions };
|
|
315
|
+
}
|
|
316
|
+
// -- config.toml, key by key ---------------------------------------------------------
|
|
317
|
+
const HEADER = /^\s*\[/;
|
|
318
|
+
const keyLine = (key) => new RegExp(String.raw `^\s*(?:${key}|"${key}"|'${key}')\s*=\s*([^#\r]*?)\s*(?:#[^\r]*)?\r?$`);
|
|
319
|
+
/** A TOML integer as written (`150000`, `150_000`, `+150000`), or undefined. */
|
|
320
|
+
const tomlInt = (raw) => (/^[+-]?\d[\d_]*$/.test(raw.trim()) ? Number(raw.trim().replace(/_/g, "")) : undefined);
|
|
321
|
+
const BOM = "";
|
|
322
|
+
/**
|
|
323
|
+
* For each line, whether it starts a statement (a key, a [table], a comment
|
|
324
|
+
* or a blank) rather than continuing a value that spans lines: a multi-line
|
|
325
|
+
* string ("""…""", '''…''') or an array or inline table left open. A
|
|
326
|
+
* `[x]` or `key = 1` inside one of those is the value's text, not a table or
|
|
327
|
+
* a key, and a line put there would land inside the user's value.
|
|
328
|
+
*/
|
|
329
|
+
function statementStarts(lines) {
|
|
330
|
+
const out = [];
|
|
331
|
+
let depth = 0;
|
|
332
|
+
let ml;
|
|
333
|
+
for (const line of lines) {
|
|
334
|
+
out.push(depth === 0 && ml === undefined);
|
|
335
|
+
let i = 0;
|
|
336
|
+
while (i < line.length) {
|
|
337
|
+
const c = line[i];
|
|
338
|
+
if (ml !== undefined) {
|
|
339
|
+
if (ml === '"""' && c === "\\") {
|
|
340
|
+
i += 2;
|
|
341
|
+
continue;
|
|
342
|
+
}
|
|
343
|
+
if (line.startsWith(ml, i)) {
|
|
344
|
+
// Up to two quotes more belong to the string: `""""` ends it with one.
|
|
345
|
+
let j = i + 3;
|
|
346
|
+
while (j < line.length && j < i + 5 && line[j] === ml[0])
|
|
347
|
+
j++;
|
|
348
|
+
ml = undefined;
|
|
349
|
+
i = j;
|
|
350
|
+
}
|
|
351
|
+
else
|
|
352
|
+
i++;
|
|
353
|
+
continue;
|
|
354
|
+
}
|
|
355
|
+
if (c === "#")
|
|
356
|
+
break;
|
|
357
|
+
if (c === '"' || c === "'") {
|
|
358
|
+
if (line.startsWith(c.repeat(3), i)) {
|
|
359
|
+
ml = c.repeat(3);
|
|
360
|
+
i += 3;
|
|
361
|
+
continue;
|
|
362
|
+
}
|
|
363
|
+
let j = i + 1;
|
|
364
|
+
while (j < line.length && line[j] !== c)
|
|
365
|
+
j += c === '"' && line[j] === "\\" ? 2 : 1;
|
|
366
|
+
i = j + 1;
|
|
367
|
+
continue;
|
|
368
|
+
}
|
|
369
|
+
if (c === "[" || c === "{")
|
|
370
|
+
depth++;
|
|
371
|
+
else if ((c === "]" || c === "}") && depth > 0)
|
|
372
|
+
depth--;
|
|
373
|
+
i++;
|
|
374
|
+
}
|
|
375
|
+
}
|
|
376
|
+
return out;
|
|
377
|
+
}
|
|
378
|
+
/** The lines, which of them start a statement, and the first [table] (lines.length when none). */
|
|
379
|
+
function tomlLayout(toml) {
|
|
380
|
+
const lines = toml.split("\n");
|
|
381
|
+
const starts = statementStarts(lines);
|
|
382
|
+
const header = lines.findIndex((l, i) => starts[i] && HEADER.test(l));
|
|
383
|
+
return { lines, starts, header: header === -1 ? lines.length : header };
|
|
384
|
+
}
|
|
385
|
+
/** The top-level value of `key` (before the first [table]): as written, and as a number when it is one. */
|
|
386
|
+
export function topLevelValue(toml, key = CODEX_COMPACT_KEY) {
|
|
387
|
+
const re = keyLine(key);
|
|
388
|
+
const { lines, starts, header } = tomlLayout(toml.startsWith(BOM) ? toml.slice(1) : toml);
|
|
389
|
+
for (let i = 0; i < header; i++) {
|
|
390
|
+
const m = starts[i] ? re.exec(lines[i]) : null;
|
|
391
|
+
if (m)
|
|
392
|
+
return { raw: m[1], value: tomlInt(m[1]) };
|
|
393
|
+
}
|
|
394
|
+
return undefined;
|
|
395
|
+
}
|
|
396
|
+
/**
|
|
397
|
+
* Set (or with undefined, remove) a top-level integer key, touching no other
|
|
398
|
+
* byte: a line replaced keeps its line end; a new line goes after the last
|
|
399
|
+
* top-level statement (or at the top, after a byte order mark), with the
|
|
400
|
+
* file's own line ends, never inside a multi-line string or array. A
|
|
401
|
+
* missing file (undefined) becomes the one line.
|
|
402
|
+
*/
|
|
403
|
+
export function setTopLevelInt(toml, key, value) {
|
|
404
|
+
if (toml === undefined || toml === "")
|
|
405
|
+
return value === undefined ? "" : `${key} = ${value}\n`;
|
|
406
|
+
const bom = toml.startsWith(BOM) ? BOM : "";
|
|
407
|
+
const { lines, starts, header: end } = tomlLayout(toml.slice(bom.length));
|
|
408
|
+
const cr = toml.includes("\r\n") ? "\r" : "";
|
|
409
|
+
const re = keyLine(key);
|
|
410
|
+
const at = lines.slice(0, end).findIndex((l, i) => starts[i] && re.test(l));
|
|
411
|
+
if (at >= 0) {
|
|
412
|
+
if (value === undefined)
|
|
413
|
+
lines.splice(at, 1);
|
|
414
|
+
else
|
|
415
|
+
lines[at] = `${key} = ${value}${lines[at].endsWith("\r") ? "\r" : ""}`;
|
|
416
|
+
return bom + lines.join("\n");
|
|
417
|
+
}
|
|
418
|
+
if (value === undefined)
|
|
419
|
+
return toml;
|
|
420
|
+
// After the last top-level statement (all of its lines), so a comment above a [table] stays with it.
|
|
421
|
+
let pos = 0;
|
|
422
|
+
for (let i = 0; i < end; i++) {
|
|
423
|
+
if (!starts[i] || !/^\s*[^\s#[]/.test(lines[i]))
|
|
424
|
+
continue;
|
|
425
|
+
pos = i + 1;
|
|
426
|
+
while (pos < end && !starts[pos])
|
|
427
|
+
pos++;
|
|
428
|
+
}
|
|
429
|
+
lines.splice(pos, 0, `${key} = ${value}${cr}`);
|
|
430
|
+
return bom + lines.join("\n");
|
|
431
|
+
}
|
|
432
|
+
/** A profile name as a TOML key part: bare, "quoted" or 'quoted'. */
|
|
433
|
+
const PROFILE = String.raw `(?:"([^"]+)"|'([^']+)'|([\w-]+))`;
|
|
434
|
+
/**
|
|
435
|
+
* Profiles that set `key`, and the profile the file selects by default:
|
|
436
|
+
* `[profiles.<name>]` tables, a `[profiles]` table's `<name>.key`, and a
|
|
437
|
+
* top-level `profiles.<name>.key`.
|
|
438
|
+
*/
|
|
439
|
+
export function profileValues(toml, key = CODEX_COMPACT_KEY) {
|
|
440
|
+
const re = keyLine(key);
|
|
441
|
+
const { lines, starts, header } = tomlLayout(toml.startsWith(BOM) ? toml.slice(1) : toml);
|
|
442
|
+
const name = (m) => m?.slice(1, 4).find((x) => x !== undefined);
|
|
443
|
+
let selected;
|
|
444
|
+
for (let i = 0; i < header && selected === undefined; i++)
|
|
445
|
+
if (starts[i])
|
|
446
|
+
selected = /^\s*profile\s*=\s*["']([^"']+)["']/.exec(lines[i])?.[1];
|
|
447
|
+
const dotted = (prefix) => new RegExp(String.raw `^\s*${prefix}${PROFILE}\s*\.\s*(?:${key}|"${key}"|'${key}')\s*=\s*([^#\r]*?)\s*(?:#[^\r]*)?\r?$`);
|
|
448
|
+
const top = dotted(String.raw `profiles\s*\.\s*`);
|
|
449
|
+
const inProfiles = dotted("");
|
|
450
|
+
const out = [];
|
|
451
|
+
// undefined: the top level; "": the [profiles] table; a name: [profiles.<name>]; null: any other table.
|
|
452
|
+
let table;
|
|
453
|
+
lines.forEach((line, i) => {
|
|
454
|
+
if (!starts[i])
|
|
455
|
+
return;
|
|
456
|
+
if (HEADER.test(line)) {
|
|
457
|
+
table = /^\s*\[\s*profiles\s*\]/.test(line) ? "" : name(new RegExp(String.raw `^\s*\[\s*profiles\s*\.\s*${PROFILE}\s*\]`).exec(line)) ?? null;
|
|
458
|
+
return;
|
|
459
|
+
}
|
|
460
|
+
let profile, raw;
|
|
461
|
+
if (table) {
|
|
462
|
+
const m = re.exec(line);
|
|
463
|
+
if (m) {
|
|
464
|
+
profile = table;
|
|
465
|
+
raw = m[1];
|
|
466
|
+
}
|
|
467
|
+
}
|
|
468
|
+
else if (table === "" || table === undefined) {
|
|
469
|
+
const m = (table === "" ? inProfiles : top).exec(line);
|
|
470
|
+
if (m) {
|
|
471
|
+
profile = name(m);
|
|
472
|
+
raw = m[4];
|
|
473
|
+
}
|
|
474
|
+
}
|
|
475
|
+
if (profile !== undefined && raw !== undefined)
|
|
476
|
+
out.push({ profile, raw, selected: profile === selected });
|
|
477
|
+
});
|
|
478
|
+
return out;
|
|
479
|
+
}
|
|
480
|
+
/** ~/.codex/config.toml (CODEX_HOME honoured for this user). */
|
|
481
|
+
export function codexConfigPath(home) {
|
|
482
|
+
return join(codexDir(home), "config.toml");
|
|
483
|
+
}
|
|
484
|
+
/** The limit the user set at the top of config.toml, as written. */
|
|
485
|
+
export function currentCodexCompact(home) {
|
|
486
|
+
const p = codexConfigPath(home);
|
|
487
|
+
let text;
|
|
488
|
+
try {
|
|
489
|
+
text = readFileSync(p, "utf8");
|
|
490
|
+
}
|
|
491
|
+
catch {
|
|
492
|
+
return undefined;
|
|
493
|
+
}
|
|
494
|
+
const v = topLevelValue(text);
|
|
495
|
+
return v ? { ...v, where: tilde(p) } : undefined;
|
|
496
|
+
}
|
|
497
|
+
/** model_auto_compact_token_limit_scope at the top of config.toml: "body_after_prefix", else Codex's default, "total". */
|
|
498
|
+
export function codexCompactScope(home) {
|
|
499
|
+
let text;
|
|
500
|
+
try {
|
|
501
|
+
text = readFileSync(codexConfigPath(home), "utf8");
|
|
502
|
+
}
|
|
503
|
+
catch {
|
|
504
|
+
return "total";
|
|
505
|
+
}
|
|
506
|
+
const raw = topLevelValue(text, CODEX_COMPACT_SCOPE_KEY)?.raw.trim().replace(/^["']|["']$/g, "");
|
|
507
|
+
return raw === "body_after_prefix" ? "body_after_prefix" : "total";
|
|
508
|
+
}
|
|
509
|
+
/** What would keep a top-level limit from applying: a profile's own, a project's config.toml. */
|
|
510
|
+
export function codexCompactOverrides(home, cwd = process.cwd()) {
|
|
511
|
+
const out = [];
|
|
512
|
+
const p = codexConfigPath(home);
|
|
513
|
+
let user;
|
|
514
|
+
try {
|
|
515
|
+
user = readFileSync(p, "utf8");
|
|
516
|
+
}
|
|
517
|
+
catch { /* none */ }
|
|
518
|
+
if (user !== undefined) {
|
|
519
|
+
for (const v of profileValues(user))
|
|
520
|
+
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}`})`);
|
|
521
|
+
}
|
|
522
|
+
// Closest folder first: the one whose value Codex applies last.
|
|
523
|
+
for (const dir of [...projectConfigFolders(cwd, rootMarkers(user))].reverse()) {
|
|
524
|
+
const project = join(dir, ".codex", "config.toml");
|
|
525
|
+
if (resolve(project) === resolve(p))
|
|
526
|
+
continue;
|
|
527
|
+
try {
|
|
528
|
+
const v = topLevelValue(readFileSync(project, "utf8"));
|
|
529
|
+
if (v)
|
|
530
|
+
out.push(`${CODEX_COMPACT_KEY} = ${v.raw} in ${tilde(project)} (this project's, when Codex trusts it)`);
|
|
531
|
+
}
|
|
532
|
+
catch { /* none */ }
|
|
533
|
+
}
|
|
534
|
+
return out;
|
|
535
|
+
}
|
|
536
|
+
/** `project_root_markers` at the top of the user's config.toml (strings of a one-line array), else Codex's default, [".git"]. */
|
|
537
|
+
function rootMarkers(toml) {
|
|
538
|
+
const raw = toml === undefined ? undefined : topLevelValue(toml, "project_root_markers")?.raw.trim();
|
|
539
|
+
if (!raw || !raw.startsWith("[") || !raw.endsWith("]"))
|
|
540
|
+
return [".git"];
|
|
541
|
+
return [...raw.matchAll(/"([^"]*)"|'([^']*)'/g)].map((m) => m[1] ?? m[2]);
|
|
542
|
+
}
|
|
543
|
+
/**
|
|
544
|
+
* The folders whose `.codex/config.toml` Codex layers over the user's, root
|
|
545
|
+
* first (codex-rs config/src/loader/mod.rs, discover_project_layers): from
|
|
546
|
+
* the project root (the closest folder holding a root marker; a `.git`
|
|
547
|
+
* folder counts only with a HEAD in it) down to `cwd`; with no root, `cwd`
|
|
548
|
+
* alone.
|
|
549
|
+
*/
|
|
550
|
+
export function projectConfigFolders(cwd, markers = [".git"]) {
|
|
551
|
+
const dirs = [];
|
|
552
|
+
let dir = resolve(cwd);
|
|
553
|
+
for (;;) {
|
|
554
|
+
dirs.push(dir);
|
|
555
|
+
const isRoot = markers.some((m) => {
|
|
556
|
+
const at = join(dir, m);
|
|
557
|
+
try {
|
|
558
|
+
return m === ".git" && statSync(at).isDirectory() ? existsSync(join(at, "HEAD")) : existsSync(at);
|
|
559
|
+
}
|
|
560
|
+
catch {
|
|
561
|
+
return false;
|
|
562
|
+
}
|
|
563
|
+
});
|
|
564
|
+
if (isRoot)
|
|
565
|
+
return dirs.reverse();
|
|
566
|
+
const up = dirname(dir);
|
|
567
|
+
if (up === dir)
|
|
568
|
+
return [resolve(cwd)];
|
|
569
|
+
dir = up;
|
|
570
|
+
}
|
|
571
|
+
}
|
|
572
|
+
const usd = (n) => (Math.abs(n) >= 100 ? `$${Math.round(n).toLocaleString("en-US")}` : `$${n.toFixed(2)}`);
|
|
573
|
+
const k = (n) => `${Math.round(n / 1000)}k`;
|
|
574
|
+
/** The lines under the lever in `fix`: each limit tried. */
|
|
575
|
+
export function renderCodexLimits(r, offered) {
|
|
576
|
+
const weeks = r.days / 7;
|
|
577
|
+
const out = [`${"limit".padEnd(10)}${"saved".padStart(10)} compactions a week (now ${(r.actualCompactions / weeks).toFixed(1)})`];
|
|
578
|
+
for (const e of r.estimates)
|
|
579
|
+
out.push(`${k(e.limit).padEnd(10)}${usd(e.savedUsd).padStart(10)} ${(e.compactions / weeks).toFixed(1)}${e.limit === offered ? " ←" : ""}`);
|
|
580
|
+
return out;
|
|
581
|
+
}
|
package/dist/compactwindow.js
CHANGED
|
@@ -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). */
|
|
@@ -282,7 +282,7 @@ export function renderCompactWindows(r, current, limitLines) {
|
|
|
282
282
|
// Counted and said exactly as `savings` says it, so the two screens agree.
|
|
283
283
|
lines.push(`Last ${r.days} days, ${sessionsLabel(r.sessions, r.transcripts ?? r.sessions)}, at list prices`);
|
|
284
284
|
lines.push("─".repeat(66));
|
|
285
|
-
lines.push(`Now: ${current ? `${k(current)} (set in
|
|
285
|
+
lines.push(`Now: ${current ? `${k(current)} (set in ${tilde(settingsPath())})` : "not set: Claude Code compacts near the model's full window"}`);
|
|
286
286
|
if (r.sessions === 0) {
|
|
287
287
|
lines.push("No sessions with 10+ requests in the window to replay.");
|
|
288
288
|
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
|