context-doctor 0.43.0 → 0.45.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +4 -2
- package/dist/budget.d.ts +23 -3
- package/dist/budget.js +184 -50
- package/dist/cache.js +5 -4
- package/dist/cachemisses.js +1 -1
- package/dist/cachettl.d.ts +5 -1
- package/dist/cachettl.js +16 -29
- package/dist/ci.js +18 -2
- package/dist/cli.js +16 -12
- package/dist/codexcompact.d.ts +24 -3
- package/dist/codexcompact.js +221 -48
- package/dist/coldresume.js +16 -8
- package/dist/compactwindow.js +14 -9
- package/dist/cursor.d.ts +10 -0
- package/dist/cursor.js +20 -0
- package/dist/doctor.d.ts +9 -0
- package/dist/doctor.js +52 -0
- package/dist/extract.d.ts +2 -2
- package/dist/extract.js +14 -3
- package/dist/fanout.js +4 -2
- package/dist/fix.d.ts +8 -1
- package/dist/fix.js +59 -13
- package/dist/hook.js +45 -15
- package/dist/httpguard.d.ts +9 -1
- package/dist/httpguard.js +5 -4
- package/dist/install.js +56 -19
- package/dist/lens.js +7 -7
- package/dist/limits.d.ts +17 -4
- package/dist/limits.js +41 -29
- package/dist/mcp.js +63 -63
- package/dist/mcpclient.js +19 -19
- package/dist/mcpschema.js +10 -12
- package/dist/overhead.d.ts +7 -2
- package/dist/overhead.js +11 -3
- package/dist/pack.js +87 -23
- package/dist/pricing.d.ts +125 -6
- package/dist/pricing.js +304 -59
- package/dist/proxy.d.ts +26 -1
- package/dist/proxy.js +45 -5
- package/dist/prune.d.ts +8 -0
- package/dist/prune.js +73 -10
- package/dist/savings.js +17 -9
- package/dist/scan.d.ts +7 -1
- package/dist/scan.js +19 -1
- package/dist/sessionprice.d.ts +9 -2
- package/dist/sessionprice.js +95 -36
- package/dist/settingsedit.js +3 -2
- package/dist/spend.d.ts +75 -10
- package/dist/spend.js +279 -37
- package/dist/statusline.d.ts +10 -2
- package/dist/statusline.js +17 -8
- package/dist/subagentmodel.d.ts +2 -2
- package/dist/subagentmodel.js +42 -25
- package/dist/subagentpay.d.ts +17 -0
- package/dist/subagentpay.js +41 -2
- package/dist/subagents.d.ts +24 -0
- package/dist/subagents.js +93 -27
- package/dist/tasks.js +9 -6
- package/dist/tooloutput.d.ts +2 -0
- package/dist/tooloutput.js +16 -5
- package/package.json +1 -1
package/dist/ci.js
CHANGED
|
@@ -128,6 +128,22 @@ export function ciReport(opts = {}) {
|
|
|
128
128
|
}
|
|
129
129
|
return { base: opts.base, files, baseTotal, headTotal, breaches };
|
|
130
130
|
}
|
|
131
|
+
/**
|
|
132
|
+
* A path as inline code that stays code: a pull request names its files, and
|
|
133
|
+
* a name may hold a backtick, a pipe or a line break (all allowed in a
|
|
134
|
+
* repository), which closed the code span in the bot's comment and made the
|
|
135
|
+
* rest of the name markdown of the PR author's choosing (a link, an
|
|
136
|
+
* @mention, a heading). Line breaks are written as \n; in a table cell a
|
|
137
|
+
* pipe is escaped.
|
|
138
|
+
*/
|
|
139
|
+
function codePath(p, inTable = false) {
|
|
140
|
+
let s = p.replace(/[\r\n\t\u2028\u2029]/g, (c) => ({ "\r": "\\r", "\n": "\\n", "\t": "\\t" })[c] ?? `\\u${c.charCodeAt(0).toString(16)}`);
|
|
141
|
+
if (inTable)
|
|
142
|
+
s = s.replace(/\|/g, "\\|");
|
|
143
|
+
const fence = "`".repeat(Math.max(0, ...[...s.matchAll(/`+/g)].map((m) => m[0].length)) + 1);
|
|
144
|
+
const pad = s.startsWith("`") || s.endsWith("`") ? " " : "";
|
|
145
|
+
return `${fence}${pad}${s}${pad}${fence}`;
|
|
146
|
+
}
|
|
131
147
|
const signed = (n) => (n > 0 ? `+${formatTokens(n)}` : n < 0 ? `−${formatTokens(-n)}` : "0");
|
|
132
148
|
/** Markdown for a PR comment or a job summary. */
|
|
133
149
|
export function renderCiMarkdown(r, opts = {}) {
|
|
@@ -152,7 +168,7 @@ export function renderCiMarkdown(r, opts = {}) {
|
|
|
152
168
|
if (changed.length) {
|
|
153
169
|
out.push(r.base ? "| File | Agent | Base | This PR | Change |" : "| File | Agent | Tokens |", r.base ? "|---|---|---:|---:|---:|" : "|---|---|---:|");
|
|
154
170
|
for (const f of changed) {
|
|
155
|
-
const name =
|
|
171
|
+
const name = `${codePath(f.path, true)}${f.imported ? " (imported)" : ""}`;
|
|
156
172
|
out.push(r.base ? `| ${name} | ${f.agent} | ${f.base ? "~" + formatTokens(f.base) : "—"} | ${f.head ? "~" + formatTokens(f.head) : "—"} | ${signed(f.head - f.base)} |` : `| ${name} | ${f.agent} | ~${formatTokens(f.head)} |`);
|
|
157
173
|
}
|
|
158
174
|
}
|
|
@@ -163,7 +179,7 @@ export function renderCiMarkdown(r, opts = {}) {
|
|
|
163
179
|
out.push("", ...r.breaches.map((b) => `**Over budget:** ${b}.`));
|
|
164
180
|
const big = r.files.filter((f) => f.head >= 2000);
|
|
165
181
|
if (big.length)
|
|
166
|
-
out.push("", `Large files: ${big.map((f) =>
|
|
182
|
+
out.push("", `Large files: ${big.map((f) => codePath(f.path)).join(", ")}. \`npx context-doctor overhead split <file>\` moves reference sections out, word for word.`);
|
|
167
183
|
return out.join("\n");
|
|
168
184
|
}
|
|
169
185
|
/** Plain-text rendering for a terminal. */
|
package/dist/cli.js
CHANGED
|
@@ -7,7 +7,7 @@
|
|
|
7
7
|
*
|
|
8
8
|
* `-` reads from stdin, so you can pipe: `cat chat.json | context-doctor analyze -`
|
|
9
9
|
*/
|
|
10
|
-
import { existsSync,
|
|
10
|
+
import { existsSync, readFileSync, writeFileSync } from "node:fs";
|
|
11
11
|
import { homedir } from "node:os";
|
|
12
12
|
import { join } from "node:path";
|
|
13
13
|
import process from "node:process";
|
|
@@ -41,7 +41,7 @@ import { measureAccuracy, renderAccuracy } from "./accuracy.js";
|
|
|
41
41
|
import { renderDiff } from "./diff.js";
|
|
42
42
|
import { renderExperiment, runExperiment } from "./experiment.js";
|
|
43
43
|
import { runStatusLine } from "./statusline.js";
|
|
44
|
-
import { renderSubagents,
|
|
44
|
+
import { renderSubagents, subagentFiles, subagentReport } from "./subagents.js";
|
|
45
45
|
import { findPreset, PRESETS, RC_FILENAME } from "./config.js";
|
|
46
46
|
import { runWatch } from "./watch.js";
|
|
47
47
|
import { exactTokenCount } from "./exact.js";
|
|
@@ -302,7 +302,9 @@ Options:
|
|
|
302
302
|
--chunk-tokens <n> (pack) Largest chunk, in tokens (default 400)
|
|
303
303
|
--ids <a#2,b#5> (pack) Return these chunks by id
|
|
304
304
|
--include-secrets (pack) Also pack .env, .npmrc, private keys and other credential files,
|
|
305
|
-
|
|
305
|
+
paths under ~/.ssh, ~/.aws and similar, and the agents' MCP and
|
|
306
|
+
settings files in your home folder, whose servers' env holds API keys
|
|
307
|
+
(skipped by default; a project's own .mcp.json is read)
|
|
306
308
|
--min-tokens <n> (overhead split) Smallest section to move, in tokens (default 400)
|
|
307
309
|
--requests-per-day <n> (ci --markdown) Price the change at this many requests a day
|
|
308
310
|
--check <cmd> (experiment) Command whose exit code is the pass/fail for each arm
|
|
@@ -319,6 +321,9 @@ Options:
|
|
|
319
321
|
--token <secret> (proxy) Require /t/<secret>/ in every request path; needed before
|
|
320
322
|
putting the proxy on a public URL (Cursor BYO-key, tunnels).
|
|
321
323
|
Also read from CONTEXT_DOCTOR_PROXY_TOKEN
|
|
324
|
+
--allowed-hosts <names> (proxy) Host names it answers to besides localhost, an IP address and
|
|
325
|
+
--host (a container's service name); a web page that rebinds its own
|
|
326
|
+
name to this address is refused. Not checked with --token
|
|
322
327
|
--config <file> (proxy) Per-route overrides: {"routes":[{"modelPrefix":"gpt","strategies":[...],
|
|
323
328
|
"keepRecent":n,"maxToolResultTokens":n}]} — first prefix match wins
|
|
324
329
|
--upstream-anthropic <url> (proxy) Override Anthropic upstream (testing)
|
|
@@ -471,6 +476,8 @@ async function measureFixInputs(days) {
|
|
|
471
476
|
...(cxSet ? { codexCompactSet: { raw: cxSet.raw, where: cxSet.where } } : {}),
|
|
472
477
|
overrides: Object.fromEntries(ids.map((id) => [id, fixOverrides(id, { cwd })])),
|
|
473
478
|
recordProblem,
|
|
479
|
+
// The installs a setting is too new for are named on its fix.
|
|
480
|
+
claudeCodeInstalls: claudeCodeInstallsFromEnv(),
|
|
474
481
|
coldResume: { netUsd: Math.max(0, report.coldResumeNetUsd), returns: report.coldResumes, hooked: claudePluginEnabled() || /context-doctor|cli\.js"?\s+hook/.test(JSON.stringify(userSettings.hooks?.UserPromptSubmit ?? [])) },
|
|
475
482
|
},
|
|
476
483
|
};
|
|
@@ -559,8 +566,8 @@ const FLAGS = [
|
|
|
559
566
|
// Read by the MCP server itself: `mcp --http [--port n] [--host h]`.
|
|
560
567
|
{ names: ["--http"], set: () => { } },
|
|
561
568
|
{ names: ["--store-handoffs"], set: () => { } },
|
|
562
|
-
{ names: ["--allowed-hosts"], value: "text", set: () => { } },
|
|
563
|
-
{ names: ["--allowed-origins"], value: "text", set: () => { } },
|
|
569
|
+
{ names: ["--allowed-hosts"], value: "text", set: (a, v) => { a.allowedHosts = v; } },
|
|
570
|
+
{ names: ["--allowed-origins"], value: "text", set: (a, v) => { a.allowedOrigins = v; } },
|
|
564
571
|
];
|
|
565
572
|
const FLAG_BY_NAME = new Map(FLAGS.flatMap((f) => f.names.map((n) => [n, f])));
|
|
566
573
|
const FLAG_NAMES = [...FLAG_BY_NAME.keys(), "--help", "--version"];
|
|
@@ -1224,6 +1231,8 @@ async function main() {
|
|
|
1224
1231
|
port: args.port,
|
|
1225
1232
|
host: args.host,
|
|
1226
1233
|
token: args.token ?? process.env.CONTEXT_DOCTOR_PROXY_TOKEN,
|
|
1234
|
+
allowedHosts: args.allowedHosts,
|
|
1235
|
+
allowedOrigins: args.allowedOrigins,
|
|
1227
1236
|
autopilot: args.autopilot,
|
|
1228
1237
|
autopilotStatePath: args.autopilotState,
|
|
1229
1238
|
autopilotPauseFile: args.autopilotPauseFile,
|
|
@@ -1255,7 +1264,7 @@ async function main() {
|
|
|
1255
1264
|
const fixes = planFixes(inputs);
|
|
1256
1265
|
const since = savedSince(readFixRecords());
|
|
1257
1266
|
if (args.share) {
|
|
1258
|
-
const text = renderFixShare(inputs.days, inputs.billedUsd, fixes);
|
|
1267
|
+
const text = renderFixShare(inputs.days, inputs.billedUsd, fixes, inputs.codexCompact?.billedUsd);
|
|
1259
1268
|
console.log(text);
|
|
1260
1269
|
if (args.copy)
|
|
1261
1270
|
console.log(copyToClipboard(text) ? "\n(copied to the clipboard)" : "\n(no clipboard tool found; copy the lines above)");
|
|
@@ -1578,12 +1587,7 @@ async function main() {
|
|
|
1578
1587
|
const mains = claudeTranscripts(args.days ?? 30);
|
|
1579
1588
|
prescan([
|
|
1580
1589
|
{ paths: mains, extractors: [REQUEST_ROWS, MCP_ROWS] },
|
|
1581
|
-
{ paths: mains.flatMap((p) =>
|
|
1582
|
-
return readdirSync(subagentDir(p)).filter((f) => f.endsWith(".jsonl")).map((f) => join(subagentDir(p), f));
|
|
1583
|
-
}
|
|
1584
|
-
catch {
|
|
1585
|
-
return [];
|
|
1586
|
-
} }), extractors: [MCP_ROWS] },
|
|
1590
|
+
{ paths: mains.flatMap((p) => subagentFiles(p).map((f) => f.file)), extractors: [MCP_ROWS] },
|
|
1587
1591
|
], sessions.tick);
|
|
1588
1592
|
const report = overheadReport({
|
|
1589
1593
|
days: args.days,
|
package/dist/codexcompact.d.ts
CHANGED
|
@@ -49,8 +49,13 @@ export interface CodexCompactEstimate {
|
|
|
49
49
|
/** Compactions there would be over the period at this limit. */
|
|
50
50
|
compactions: number;
|
|
51
51
|
}
|
|
52
|
+
/** What the limit counts: the whole context (Codex's default) or what a window added after its first request. */
|
|
53
|
+
export type CodexCompactScope = "total" | "body_after_prefix";
|
|
54
|
+
export declare const CODEX_COMPACT_SCOPE_KEY = "model_auto_compact_token_limit_scope";
|
|
52
55
|
export interface CodexCompactReport {
|
|
53
56
|
days: number;
|
|
57
|
+
/** model_auto_compact_token_limit_scope as config.toml sets it at the top (the replay counts the limit that way). */
|
|
58
|
+
scope: CodexCompactScope;
|
|
54
59
|
rollouts: number;
|
|
55
60
|
requests: number;
|
|
56
61
|
/** Input billed (prompt only) over the period's requests, forks' copies once. */
|
|
@@ -72,6 +77,7 @@ export declare function replayCodexCompact(opts: {
|
|
|
72
77
|
limits?: number[];
|
|
73
78
|
home?: string;
|
|
74
79
|
now?: number;
|
|
80
|
+
scope?: CodexCompactScope;
|
|
75
81
|
}): CodexCompactReport;
|
|
76
82
|
/**
|
|
77
83
|
* What a limit set at `since` saved: each compaction since that came before
|
|
@@ -92,11 +98,16 @@ export declare function topLevelValue(toml: string, key?: string): {
|
|
|
92
98
|
/**
|
|
93
99
|
* Set (or with undefined, remove) a top-level integer key, touching no other
|
|
94
100
|
* byte: a line replaced keeps its line end; a new line goes after the last
|
|
95
|
-
* top-level
|
|
96
|
-
* file
|
|
101
|
+
* top-level statement (or at the top, after a byte order mark), with the
|
|
102
|
+
* file's own line ends, never inside a multi-line string or array. A
|
|
103
|
+
* missing file (undefined) becomes the one line.
|
|
97
104
|
*/
|
|
98
105
|
export declare function setTopLevelInt(toml: string | undefined, key: string, value: number | undefined): string;
|
|
99
|
-
/**
|
|
106
|
+
/**
|
|
107
|
+
* Profiles that set `key`, and the profile the file selects by default:
|
|
108
|
+
* `[profiles.<name>]` tables, a `[profiles]` table's `<name>.key`, and a
|
|
109
|
+
* top-level `profiles.<name>.key`.
|
|
110
|
+
*/
|
|
100
111
|
export declare function profileValues(toml: string, key?: string): Array<{
|
|
101
112
|
profile: string;
|
|
102
113
|
raw: string;
|
|
@@ -110,7 +121,17 @@ export declare function currentCodexCompact(home?: string): {
|
|
|
110
121
|
value?: number;
|
|
111
122
|
where: string;
|
|
112
123
|
} | undefined;
|
|
124
|
+
/** model_auto_compact_token_limit_scope at the top of config.toml: "body_after_prefix", else Codex's default, "total". */
|
|
125
|
+
export declare function codexCompactScope(home?: string): CodexCompactScope;
|
|
113
126
|
/** What would keep a top-level limit from applying: a profile's own, a project's config.toml. */
|
|
114
127
|
export declare function codexCompactOverrides(home?: string, cwd?: string): string[];
|
|
128
|
+
/**
|
|
129
|
+
* The folders whose `.codex/config.toml` Codex layers over the user's, root
|
|
130
|
+
* first (codex-rs config/src/loader/mod.rs, discover_project_layers): from
|
|
131
|
+
* the project root (the closest folder holding a root marker; a `.git`
|
|
132
|
+
* folder counts only with a HEAD in it) down to `cwd`; with no root, `cwd`
|
|
133
|
+
* alone.
|
|
134
|
+
*/
|
|
135
|
+
export declare function projectConfigFolders(cwd: string, markers?: string[]): string[];
|
|
115
136
|
/** The lines under the lever in `fix`: each limit tried. */
|
|
116
137
|
export declare function renderCodexLimits(r: CodexCompactReport, offered: number): string[];
|
package/dist/codexcompact.js
CHANGED
|
@@ -29,12 +29,12 @@
|
|
|
29
29
|
* Codex does not record it). What the summary dropped, and the model reading
|
|
30
30
|
* files again because of it, is not priced.
|
|
31
31
|
*/
|
|
32
|
-
import { existsSync, readFileSync } from "node:fs";
|
|
32
|
+
import { existsSync, readFileSync, statSync } from "node:fs";
|
|
33
33
|
import { homedir } from "node:os";
|
|
34
|
-
import { basename, join } from "node:path";
|
|
34
|
+
import { basename, dirname, join, resolve } from "node:path";
|
|
35
35
|
import { codexDir } from "./codexdir.js";
|
|
36
36
|
import { codexEventKey, codexSessionsRoot, rolloutFiles } from "./limits.js";
|
|
37
|
-
import { openAIUsage,
|
|
37
|
+
import { openAIUsage, rateCard, ratesAt, requestCost } from "./pricing.js";
|
|
38
38
|
import { pick, rowsOf } from "./scan.js";
|
|
39
39
|
import { tilde } from "./claudedir.js";
|
|
40
40
|
/** The config.toml key the lever writes. */
|
|
@@ -128,19 +128,21 @@ function readSteps(file, seen) {
|
|
|
128
128
|
if (!Number.isFinite(at))
|
|
129
129
|
continue;
|
|
130
130
|
const u = openAIUsage(r.u);
|
|
131
|
-
const
|
|
131
|
+
const prompt = num(u.input_tokens) + num(u.cache_read_input_tokens) + num(u.cache_creation_input_tokens);
|
|
132
|
+
const card = rateCard(model, u, at);
|
|
133
|
+
const price = card && ratesAt(card, prompt);
|
|
132
134
|
const copy = !!r.key && seen.has(r.key);
|
|
133
135
|
if (r.key)
|
|
134
136
|
seen.add(r.key);
|
|
135
137
|
const window = num(r.win) ? num(r.win) / RECORDED_SHARE : DEFAULT_WINDOW;
|
|
136
138
|
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
|
+
k: "r", at, copy, prompt,
|
|
139
140
|
cached: num(u.cache_read_input_tokens),
|
|
140
141
|
out: num(u.output_tokens),
|
|
141
142
|
inPerM: price?.inputPerM ?? 0, readPerM: price?.cacheReadPerM ?? 0, outPerM: price?.outputPerM ?? 0,
|
|
142
|
-
billedUsd:
|
|
143
|
+
billedUsd: requestCost(model, u, at)?.promptUsd ?? 0,
|
|
143
144
|
trigger: DEFAULT_SHARE * window,
|
|
145
|
+
...(card ? { card } : {}),
|
|
144
146
|
});
|
|
145
147
|
}
|
|
146
148
|
return steps;
|
|
@@ -149,21 +151,27 @@ function readSteps(file, seen) {
|
|
|
149
151
|
* One rollout at `limit`: as billed and with compaction at the limit, in USD
|
|
150
152
|
* over the requests in [since, until) that are not a fork's copy. Codex
|
|
151
153
|
* compacts when a turn's input and output reach the limit, which is never
|
|
152
|
-
* above its own trigger
|
|
154
|
+
* above its own trigger; with the `body_after_prefix` scope, when what the
|
|
155
|
+
* turn holds beyond the first request of its window (the session's start or
|
|
156
|
+
* the last compaction) reaches it (codex-rs session/context_window.rs).
|
|
153
157
|
*/
|
|
154
|
-
function replay(steps, limit, since, until, after) {
|
|
158
|
+
function replay(steps, limit, since, until, after, scope = "total") {
|
|
155
159
|
let billed = 0, sim = 0, extra = 0, actual = 0;
|
|
156
|
-
let removed = 0, fresh = false,
|
|
160
|
+
let removed = 0, fresh = false, prevCounted = false;
|
|
161
|
+
// The input of the window's first request: what body_after_prefix does not count.
|
|
162
|
+
let prefill;
|
|
157
163
|
for (const s of steps) {
|
|
158
164
|
if (s.k === "c") {
|
|
159
|
-
|
|
165
|
+
// A compaction after a fork's copy of its parent's requests is the parent's, counted there.
|
|
166
|
+
if (prevCounted)
|
|
160
167
|
actual++;
|
|
161
168
|
removed = 0;
|
|
162
169
|
fresh = false;
|
|
170
|
+
prefill = undefined;
|
|
163
171
|
continue;
|
|
164
172
|
}
|
|
165
173
|
const counted = s.at >= since && s.at < until && !s.copy;
|
|
166
|
-
|
|
174
|
+
prevCounted = counted;
|
|
167
175
|
let ctx = s.prompt - removed;
|
|
168
176
|
// The real context fell below what was removed (a rewind with no compaction recorded): back in step.
|
|
169
177
|
if (removed > 0 && ctx < after) {
|
|
@@ -172,29 +180,40 @@ function replay(steps, limit, since, until, after) {
|
|
|
172
180
|
fresh = false;
|
|
173
181
|
}
|
|
174
182
|
let cost = s.billedUsd;
|
|
183
|
+
// A smaller prompt can fall under a long-context tier (OpenAI's 272k): all of it then bills at the lower rates.
|
|
184
|
+
const low = s.card && ctx < s.prompt ? ratesAt(s.card, ctx) : undefined;
|
|
175
185
|
if (fresh)
|
|
176
|
-
cost = (ctx * s.inPerM) / 1e6;
|
|
186
|
+
cost = (ctx * (low ? low.inputPerM : s.inPerM)) / 1e6;
|
|
177
187
|
else if (removed > 0) {
|
|
178
188
|
const fromCache = Math.min(removed, s.cached);
|
|
179
189
|
cost = Math.max(0, s.billedUsd - (fromCache * s.readPerM + (removed - fromCache) * s.inPerM) / 1e6);
|
|
190
|
+
if (low && low.inputPerM < s.inPerM)
|
|
191
|
+
cost *= low.inputPerM / s.inPerM;
|
|
180
192
|
}
|
|
181
193
|
fresh = false;
|
|
194
|
+
prefill ??= ctx;
|
|
182
195
|
if (counted) {
|
|
183
196
|
billed += s.billedUsd;
|
|
184
197
|
sim += cost;
|
|
185
198
|
}
|
|
186
|
-
|
|
199
|
+
const reached = scope === "body_after_prefix"
|
|
200
|
+
? ctx + s.out - prefill >= limit && ctx + s.out < s.trigger
|
|
201
|
+
: ctx + s.out >= Math.min(limit, s.trigger) && limit < s.trigger;
|
|
202
|
+
if (reached) {
|
|
187
203
|
// Compacted after this turn: one request reading the context, a summary written; the next starts from `after`.
|
|
204
|
+
const at = low ?? { cacheReadPerM: s.readPerM, outputPerM: s.outPerM };
|
|
188
205
|
if (counted) {
|
|
189
|
-
sim += (ctx *
|
|
206
|
+
sim += (ctx * at.cacheReadPerM + SUMMARY_OUTPUT * at.outputPerM) / 1e6;
|
|
190
207
|
extra++;
|
|
191
208
|
}
|
|
192
209
|
removed = s.prompt + s.out - after;
|
|
193
210
|
fresh = true;
|
|
211
|
+
prefill = undefined;
|
|
194
212
|
}
|
|
195
213
|
}
|
|
196
214
|
return { billed, sim, extra, actual };
|
|
197
215
|
}
|
|
216
|
+
export const CODEX_COMPACT_SCOPE_KEY = "model_auto_compact_token_limit_scope";
|
|
198
217
|
/** Codex rollouts written since `since`: the live ones and the archived. */
|
|
199
218
|
export function codexRollouts(since, home = homedir()) {
|
|
200
219
|
const roots = [codexSessionsRoot(home), join(codexDir(home), "archived_sessions")];
|
|
@@ -204,6 +223,7 @@ export function codexRollouts(since, home = homedir()) {
|
|
|
204
223
|
/** Replay Codex's rollouts of the last `days` at each limit. */
|
|
205
224
|
export function replayCodexCompact(opts) {
|
|
206
225
|
const now = opts.now ?? Date.now();
|
|
226
|
+
const scope = opts.scope ?? codexCompactScope(opts.home);
|
|
207
227
|
const since = now - opts.days * 86_400_000;
|
|
208
228
|
const paths = opts.paths ?? codexRollouts(since, opts.home);
|
|
209
229
|
const seen = new Set();
|
|
@@ -221,7 +241,7 @@ export function replayCodexCompact(opts) {
|
|
|
221
241
|
steps.forEach((s, i) => {
|
|
222
242
|
if (s.k === "c") {
|
|
223
243
|
const n = steps[i + 1];
|
|
224
|
-
if (n?.k === "r")
|
|
244
|
+
if (n?.k === "r" && !n.copy)
|
|
225
245
|
afters.push(n.prompt);
|
|
226
246
|
return;
|
|
227
247
|
}
|
|
@@ -238,7 +258,7 @@ export function replayCodexCompact(opts) {
|
|
|
238
258
|
const estimates = (opts.limits ?? CODEX_COMPACT_LIMITS).map((limit, i) => {
|
|
239
259
|
let billed = 0, sim = 0, extra = 0;
|
|
240
260
|
for (const steps of all) {
|
|
241
|
-
const r = replay(steps, limit, since, Infinity, after);
|
|
261
|
+
const r = replay(steps, limit, since, Infinity, after, scope);
|
|
242
262
|
billed += r.billed;
|
|
243
263
|
sim += r.sim;
|
|
244
264
|
extra += r.extra;
|
|
@@ -249,7 +269,7 @@ export function replayCodexCompact(opts) {
|
|
|
249
269
|
billedUsd = billed;
|
|
250
270
|
return { limit, savedUsd: billed - sim, savedShare: billed > 0 ? (billed - sim) / billed : 0, compactions: extra };
|
|
251
271
|
});
|
|
252
|
-
return { days: opts.days, rollouts: paths.length, requests, billedUsd, unpriced, actualCompactions: actual, afterCompact: after, estimates };
|
|
272
|
+
return { days: opts.days, scope, rollouts: paths.length, requests, billedUsd, unpriced, actualCompactions: actual, afterCompact: after, estimates };
|
|
253
273
|
}
|
|
254
274
|
/**
|
|
255
275
|
* What a limit set at `since` saved: each compaction since that came before
|
|
@@ -305,13 +325,76 @@ const HEADER = /^\s*\[/;
|
|
|
305
325
|
const keyLine = (key) => new RegExp(String.raw `^\s*(?:${key}|"${key}"|'${key}')\s*=\s*([^#\r]*?)\s*(?:#[^\r]*)?\r?$`);
|
|
306
326
|
/** A TOML integer as written (`150000`, `150_000`, `+150000`), or undefined. */
|
|
307
327
|
const tomlInt = (raw) => (/^[+-]?\d[\d_]*$/.test(raw.trim()) ? Number(raw.trim().replace(/_/g, "")) : undefined);
|
|
328
|
+
const BOM = "";
|
|
329
|
+
/**
|
|
330
|
+
* For each line, whether it starts a statement (a key, a [table], a comment
|
|
331
|
+
* or a blank) rather than continuing a value that spans lines: a multi-line
|
|
332
|
+
* string ("""…""", '''…''') or an array or inline table left open. A
|
|
333
|
+
* `[x]` or `key = 1` inside one of those is the value's text, not a table or
|
|
334
|
+
* a key, and a line put there would land inside the user's value.
|
|
335
|
+
*/
|
|
336
|
+
function statementStarts(lines) {
|
|
337
|
+
const out = [];
|
|
338
|
+
let depth = 0;
|
|
339
|
+
let ml;
|
|
340
|
+
for (const line of lines) {
|
|
341
|
+
out.push(depth === 0 && ml === undefined);
|
|
342
|
+
let i = 0;
|
|
343
|
+
while (i < line.length) {
|
|
344
|
+
const c = line[i];
|
|
345
|
+
if (ml !== undefined) {
|
|
346
|
+
if (ml === '"""' && c === "\\") {
|
|
347
|
+
i += 2;
|
|
348
|
+
continue;
|
|
349
|
+
}
|
|
350
|
+
if (line.startsWith(ml, i)) {
|
|
351
|
+
// Up to two quotes more belong to the string: `""""` ends it with one.
|
|
352
|
+
let j = i + 3;
|
|
353
|
+
while (j < line.length && j < i + 5 && line[j] === ml[0])
|
|
354
|
+
j++;
|
|
355
|
+
ml = undefined;
|
|
356
|
+
i = j;
|
|
357
|
+
}
|
|
358
|
+
else
|
|
359
|
+
i++;
|
|
360
|
+
continue;
|
|
361
|
+
}
|
|
362
|
+
if (c === "#")
|
|
363
|
+
break;
|
|
364
|
+
if (c === '"' || c === "'") {
|
|
365
|
+
if (line.startsWith(c.repeat(3), i)) {
|
|
366
|
+
ml = c.repeat(3);
|
|
367
|
+
i += 3;
|
|
368
|
+
continue;
|
|
369
|
+
}
|
|
370
|
+
let j = i + 1;
|
|
371
|
+
while (j < line.length && line[j] !== c)
|
|
372
|
+
j += c === '"' && line[j] === "\\" ? 2 : 1;
|
|
373
|
+
i = j + 1;
|
|
374
|
+
continue;
|
|
375
|
+
}
|
|
376
|
+
if (c === "[" || c === "{")
|
|
377
|
+
depth++;
|
|
378
|
+
else if ((c === "]" || c === "}") && depth > 0)
|
|
379
|
+
depth--;
|
|
380
|
+
i++;
|
|
381
|
+
}
|
|
382
|
+
}
|
|
383
|
+
return out;
|
|
384
|
+
}
|
|
385
|
+
/** The lines, which of them start a statement, and the first [table] (lines.length when none). */
|
|
386
|
+
function tomlLayout(toml) {
|
|
387
|
+
const lines = toml.split("\n");
|
|
388
|
+
const starts = statementStarts(lines);
|
|
389
|
+
const header = lines.findIndex((l, i) => starts[i] && HEADER.test(l));
|
|
390
|
+
return { lines, starts, header: header === -1 ? lines.length : header };
|
|
391
|
+
}
|
|
308
392
|
/** The top-level value of `key` (before the first [table]): as written, and as a number when it is one. */
|
|
309
393
|
export function topLevelValue(toml, key = CODEX_COMPACT_KEY) {
|
|
310
394
|
const re = keyLine(key);
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
const m = re.exec(line);
|
|
395
|
+
const { lines, starts, header } = tomlLayout(toml.startsWith(BOM) ? toml.slice(1) : toml);
|
|
396
|
+
for (let i = 0; i < header; i++) {
|
|
397
|
+
const m = starts[i] ? re.exec(lines[i]) : null;
|
|
315
398
|
if (m)
|
|
316
399
|
return { raw: m[1], value: tomlInt(m[1]) };
|
|
317
400
|
}
|
|
@@ -320,50 +403,85 @@ export function topLevelValue(toml, key = CODEX_COMPACT_KEY) {
|
|
|
320
403
|
/**
|
|
321
404
|
* Set (or with undefined, remove) a top-level integer key, touching no other
|
|
322
405
|
* byte: a line replaced keeps its line end; a new line goes after the last
|
|
323
|
-
* top-level
|
|
324
|
-
* file
|
|
406
|
+
* top-level statement (or at the top, after a byte order mark), with the
|
|
407
|
+
* file's own line ends, never inside a multi-line string or array. A
|
|
408
|
+
* missing file (undefined) becomes the one line.
|
|
325
409
|
*/
|
|
326
410
|
export function setTopLevelInt(toml, key, value) {
|
|
327
411
|
if (toml === undefined || toml === "")
|
|
328
412
|
return value === undefined ? "" : `${key} = ${value}\n`;
|
|
329
|
-
const
|
|
413
|
+
const bom = toml.startsWith(BOM) ? BOM : "";
|
|
414
|
+
const { lines, starts, header: end } = tomlLayout(toml.slice(bom.length));
|
|
330
415
|
const cr = toml.includes("\r\n") ? "\r" : "";
|
|
331
416
|
const re = keyLine(key);
|
|
332
|
-
const
|
|
333
|
-
const end = header === -1 ? lines.length : header;
|
|
334
|
-
const at = lines.slice(0, end).findIndex((l) => re.test(l));
|
|
417
|
+
const at = lines.slice(0, end).findIndex((l, i) => starts[i] && re.test(l));
|
|
335
418
|
if (at >= 0) {
|
|
336
419
|
if (value === undefined)
|
|
337
420
|
lines.splice(at, 1);
|
|
338
421
|
else
|
|
339
422
|
lines[at] = `${key} = ${value}${lines[at].endsWith("\r") ? "\r" : ""}`;
|
|
340
|
-
return lines.join("\n");
|
|
423
|
+
return bom + lines.join("\n");
|
|
341
424
|
}
|
|
342
425
|
if (value === undefined)
|
|
343
426
|
return toml;
|
|
344
|
-
// After the last top-level
|
|
427
|
+
// After the last top-level statement (all of its lines), so a comment above a [table] stays with it.
|
|
345
428
|
let pos = 0;
|
|
346
|
-
for (let i = 0; i < end; i++)
|
|
347
|
-
if (
|
|
348
|
-
|
|
429
|
+
for (let i = 0; i < end; i++) {
|
|
430
|
+
if (!starts[i] || !/^\s*[^\s#[]/.test(lines[i]))
|
|
431
|
+
continue;
|
|
432
|
+
pos = i + 1;
|
|
433
|
+
while (pos < end && !starts[pos])
|
|
434
|
+
pos++;
|
|
435
|
+
}
|
|
349
436
|
lines.splice(pos, 0, `${key} = ${value}${cr}`);
|
|
350
|
-
return lines.join("\n");
|
|
437
|
+
return bom + lines.join("\n");
|
|
351
438
|
}
|
|
352
|
-
/**
|
|
439
|
+
/** A profile name as a TOML key part: bare, "quoted" or 'quoted'. */
|
|
440
|
+
const PROFILE = String.raw `(?:"([^"]+)"|'([^']+)'|([\w-]+))`;
|
|
441
|
+
/**
|
|
442
|
+
* Profiles that set `key`, and the profile the file selects by default:
|
|
443
|
+
* `[profiles.<name>]` tables, a `[profiles]` table's `<name>.key`, and a
|
|
444
|
+
* top-level `profiles.<name>.key`.
|
|
445
|
+
*/
|
|
353
446
|
export function profileValues(toml, key = CODEX_COMPACT_KEY) {
|
|
354
447
|
const re = keyLine(key);
|
|
355
|
-
const
|
|
448
|
+
const { lines, starts, header } = tomlLayout(toml.startsWith(BOM) ? toml.slice(1) : toml);
|
|
449
|
+
const name = (m) => m?.slice(1, 4).find((x) => x !== undefined);
|
|
450
|
+
let selected;
|
|
451
|
+
for (let i = 0; i < header && selected === undefined; i++)
|
|
452
|
+
if (starts[i])
|
|
453
|
+
selected = /^\s*profile\s*=\s*["']([^"']+)["']/.exec(lines[i])?.[1];
|
|
454
|
+
const dotted = (prefix) => new RegExp(String.raw `^\s*${prefix}${PROFILE}\s*\.\s*(?:${key}|"${key}"|'${key}')\s*=\s*([^#\r]*?)\s*(?:#[^\r]*)?\r?$`);
|
|
455
|
+
const top = dotted(String.raw `profiles\s*\.\s*`);
|
|
456
|
+
const inProfiles = dotted("");
|
|
356
457
|
const out = [];
|
|
458
|
+
// undefined: the top level; "": the [profiles] table; a name: [profiles.<name>]; null: any other table.
|
|
357
459
|
let table;
|
|
358
|
-
|
|
460
|
+
lines.forEach((line, i) => {
|
|
461
|
+
if (!starts[i])
|
|
462
|
+
return;
|
|
359
463
|
if (HEADER.test(line)) {
|
|
360
|
-
table = /^\s*\[\s*profiles
|
|
361
|
-
|
|
464
|
+
table = /^\s*\[\s*profiles\s*\]/.test(line) ? "" : name(new RegExp(String.raw `^\s*\[\s*profiles\s*\.\s*${PROFILE}\s*\]`).exec(line)) ?? null;
|
|
465
|
+
return;
|
|
362
466
|
}
|
|
363
|
-
|
|
364
|
-
if (
|
|
365
|
-
|
|
366
|
-
|
|
467
|
+
let profile, raw;
|
|
468
|
+
if (table) {
|
|
469
|
+
const m = re.exec(line);
|
|
470
|
+
if (m) {
|
|
471
|
+
profile = table;
|
|
472
|
+
raw = m[1];
|
|
473
|
+
}
|
|
474
|
+
}
|
|
475
|
+
else if (table === "" || table === undefined) {
|
|
476
|
+
const m = (table === "" ? inProfiles : top).exec(line);
|
|
477
|
+
if (m) {
|
|
478
|
+
profile = name(m);
|
|
479
|
+
raw = m[4];
|
|
480
|
+
}
|
|
481
|
+
}
|
|
482
|
+
if (profile !== undefined && raw !== undefined)
|
|
483
|
+
out.push({ profile, raw, selected: profile === selected });
|
|
484
|
+
});
|
|
367
485
|
return out;
|
|
368
486
|
}
|
|
369
487
|
/** ~/.codex/config.toml (CODEX_HOME honoured for this user). */
|
|
@@ -383,26 +501,81 @@ export function currentCodexCompact(home) {
|
|
|
383
501
|
const v = topLevelValue(text);
|
|
384
502
|
return v ? { ...v, where: tilde(p) } : undefined;
|
|
385
503
|
}
|
|
504
|
+
/** model_auto_compact_token_limit_scope at the top of config.toml: "body_after_prefix", else Codex's default, "total". */
|
|
505
|
+
export function codexCompactScope(home) {
|
|
506
|
+
let text;
|
|
507
|
+
try {
|
|
508
|
+
text = readFileSync(codexConfigPath(home), "utf8");
|
|
509
|
+
}
|
|
510
|
+
catch {
|
|
511
|
+
return "total";
|
|
512
|
+
}
|
|
513
|
+
const raw = topLevelValue(text, CODEX_COMPACT_SCOPE_KEY)?.raw.trim().replace(/^["']|["']$/g, "");
|
|
514
|
+
return raw === "body_after_prefix" ? "body_after_prefix" : "total";
|
|
515
|
+
}
|
|
386
516
|
/** What would keep a top-level limit from applying: a profile's own, a project's config.toml. */
|
|
387
517
|
export function codexCompactOverrides(home, cwd = process.cwd()) {
|
|
388
518
|
const out = [];
|
|
389
519
|
const p = codexConfigPath(home);
|
|
520
|
+
let user;
|
|
390
521
|
try {
|
|
391
|
-
|
|
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}`})`);
|
|
522
|
+
user = readFileSync(p, "utf8");
|
|
393
523
|
}
|
|
394
524
|
catch { /* none */ }
|
|
395
|
-
|
|
396
|
-
|
|
525
|
+
if (user !== undefined) {
|
|
526
|
+
for (const v of profileValues(user))
|
|
527
|
+
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}`})`);
|
|
528
|
+
}
|
|
529
|
+
// Closest folder first: the one whose value Codex applies last.
|
|
530
|
+
for (const dir of [...projectConfigFolders(cwd, rootMarkers(user))].reverse()) {
|
|
531
|
+
const project = join(dir, ".codex", "config.toml");
|
|
532
|
+
if (resolve(project) === resolve(p))
|
|
533
|
+
continue;
|
|
397
534
|
try {
|
|
398
535
|
const v = topLevelValue(readFileSync(project, "utf8"));
|
|
399
536
|
if (v)
|
|
400
|
-
out.push(`${CODEX_COMPACT_KEY} = ${v.raw} in ${tilde(project)} (this project's)`);
|
|
537
|
+
out.push(`${CODEX_COMPACT_KEY} = ${v.raw} in ${tilde(project)} (this project's, when Codex trusts it)`);
|
|
401
538
|
}
|
|
402
539
|
catch { /* none */ }
|
|
403
540
|
}
|
|
404
541
|
return out;
|
|
405
542
|
}
|
|
543
|
+
/** `project_root_markers` at the top of the user's config.toml (strings of a one-line array), else Codex's default, [".git"]. */
|
|
544
|
+
function rootMarkers(toml) {
|
|
545
|
+
const raw = toml === undefined ? undefined : topLevelValue(toml, "project_root_markers")?.raw.trim();
|
|
546
|
+
if (!raw || !raw.startsWith("[") || !raw.endsWith("]"))
|
|
547
|
+
return [".git"];
|
|
548
|
+
return [...raw.matchAll(/"([^"]*)"|'([^']*)'/g)].map((m) => m[1] ?? m[2]);
|
|
549
|
+
}
|
|
550
|
+
/**
|
|
551
|
+
* The folders whose `.codex/config.toml` Codex layers over the user's, root
|
|
552
|
+
* first (codex-rs config/src/loader/mod.rs, discover_project_layers): from
|
|
553
|
+
* the project root (the closest folder holding a root marker; a `.git`
|
|
554
|
+
* folder counts only with a HEAD in it) down to `cwd`; with no root, `cwd`
|
|
555
|
+
* alone.
|
|
556
|
+
*/
|
|
557
|
+
export function projectConfigFolders(cwd, markers = [".git"]) {
|
|
558
|
+
const dirs = [];
|
|
559
|
+
let dir = resolve(cwd);
|
|
560
|
+
for (;;) {
|
|
561
|
+
dirs.push(dir);
|
|
562
|
+
const isRoot = markers.some((m) => {
|
|
563
|
+
const at = join(dir, m);
|
|
564
|
+
try {
|
|
565
|
+
return m === ".git" && statSync(at).isDirectory() ? existsSync(join(at, "HEAD")) : existsSync(at);
|
|
566
|
+
}
|
|
567
|
+
catch {
|
|
568
|
+
return false;
|
|
569
|
+
}
|
|
570
|
+
});
|
|
571
|
+
if (isRoot)
|
|
572
|
+
return dirs.reverse();
|
|
573
|
+
const up = dirname(dir);
|
|
574
|
+
if (up === dir)
|
|
575
|
+
return [resolve(cwd)];
|
|
576
|
+
dir = up;
|
|
577
|
+
}
|
|
578
|
+
}
|
|
406
579
|
const usd = (n) => (Math.abs(n) >= 100 ? `$${Math.round(n).toLocaleString("en-US")}` : `$${n.toFixed(2)}`);
|
|
407
580
|
const k = (n) => `${Math.round(n / 1000)}k`;
|
|
408
581
|
/** The lines under the lever in `fix`: each limit tried. */
|