context-doctor 0.32.0 → 0.34.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 +84 -694
- package/dist/autoclear.js +4 -1
- package/dist/autopilot.d.ts +20 -6
- package/dist/autopilot.js +105 -7
- package/dist/cachekey.d.ts +25 -0
- package/dist/cachekey.js +73 -0
- package/dist/cacheplan.d.ts +29 -9
- package/dist/cacheplan.js +110 -29
- package/dist/ci.js +9 -1
- package/dist/cli.js +359 -247
- package/dist/clihelp.d.ts +24 -0
- package/dist/clihelp.js +116 -0
- package/dist/codexroute.d.ts +46 -0
- package/dist/codexroute.js +122 -0
- package/dist/coldresume.d.ts +62 -0
- package/dist/coldresume.js +85 -6
- package/dist/compactquality.d.ts +3 -1
- package/dist/compactquality.js +15 -4
- package/dist/compactwindow.d.ts +31 -5
- package/dist/compactwindow.js +80 -25
- package/dist/diff.js +24 -2
- package/dist/doctor.d.ts +8 -2
- package/dist/doctor.js +138 -35
- package/dist/hook.js +23 -4
- package/dist/install.d.ts +35 -0
- package/dist/install.js +280 -48
- package/dist/invocation.d.ts +18 -0
- package/dist/invocation.js +49 -0
- package/dist/ledger.d.ts +2 -0
- package/dist/mcp.d.ts +5 -2
- package/dist/mcp.js +93 -299
- package/dist/mcpclient.js +45 -0
- package/dist/mcpschema.d.ts +1 -1
- package/dist/mcpschema.js +11 -8
- package/dist/optimize.d.ts +2 -0
- package/dist/optimize.js +2 -0
- package/dist/overhead.d.ts +12 -1
- package/dist/overhead.js +31 -7
- package/dist/preferences.d.ts +1 -1
- package/dist/preferences.js +5 -5
- package/dist/proxy.d.ts +14 -1
- package/dist/proxy.js +45 -4
- package/dist/savings.d.ts +17 -1
- package/dist/savings.js +12 -13
- package/dist/session.d.ts +15 -0
- package/dist/session.js +43 -0
- package/dist/subagentpay.d.ts +1 -1
- package/dist/subagentpay.js +3 -2
- package/package.json +5 -8
- package/skills/context-doctor/SKILL.md +3 -3
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Helpers for the CLI's argument errors and per-command help: a "did you
|
|
3
|
+
* mean" suggestion for a mistyped flag or command, and one command's lines
|
|
4
|
+
* cut out of the full help text. Kept apart from cli.ts, which runs on
|
|
5
|
+
* import, so they can be tested directly.
|
|
6
|
+
*/
|
|
7
|
+
/** Edit distance (insert, delete, substitute; each 1). */
|
|
8
|
+
export declare function levenshtein(a: string, b: string): number;
|
|
9
|
+
/**
|
|
10
|
+
* The closest candidate, when it is close enough to be a typo: within a
|
|
11
|
+
* third of the word's length (at least 2 edits), or one the word is a
|
|
12
|
+
* prefix of (`--strat` for `--strategy`).
|
|
13
|
+
*/
|
|
14
|
+
export declare function suggest(word: string, candidates: readonly string[]): string | undefined;
|
|
15
|
+
/** "Did you mean …?" or nothing. */
|
|
16
|
+
export declare function didYouMean(word: string, candidates: readonly string[]): string;
|
|
17
|
+
/** Every command the help text documents, in order. */
|
|
18
|
+
export declare function documentedCommands(help: string): string[];
|
|
19
|
+
/**
|
|
20
|
+
* One command's help, cut from the full text: its usage line(s), the options
|
|
21
|
+
* scoped to it, and its examples. Undefined when the help has no usage line
|
|
22
|
+
* for it.
|
|
23
|
+
*/
|
|
24
|
+
export declare function commandHelp(help: string, cmd: string): string | undefined;
|
package/dist/clihelp.js
ADDED
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Helpers for the CLI's argument errors and per-command help: a "did you
|
|
3
|
+
* mean" suggestion for a mistyped flag or command, and one command's lines
|
|
4
|
+
* cut out of the full help text. Kept apart from cli.ts, which runs on
|
|
5
|
+
* import, so they can be tested directly.
|
|
6
|
+
*/
|
|
7
|
+
/** Edit distance (insert, delete, substitute; each 1). */
|
|
8
|
+
export function levenshtein(a, b) {
|
|
9
|
+
if (a === b)
|
|
10
|
+
return 0;
|
|
11
|
+
let prev = Array.from({ length: b.length + 1 }, (_, j) => j);
|
|
12
|
+
for (let i = 1; i <= a.length; i++) {
|
|
13
|
+
const cur = [i];
|
|
14
|
+
for (let j = 1; j <= b.length; j++) {
|
|
15
|
+
cur[j] = Math.min(prev[j] + 1, cur[j - 1] + 1, prev[j - 1] + (a[i - 1] === b[j - 1] ? 0 : 1));
|
|
16
|
+
}
|
|
17
|
+
prev = cur;
|
|
18
|
+
}
|
|
19
|
+
return prev[b.length];
|
|
20
|
+
}
|
|
21
|
+
/**
|
|
22
|
+
* The closest candidate, when it is close enough to be a typo: within a
|
|
23
|
+
* third of the word's length (at least 2 edits), or one the word is a
|
|
24
|
+
* prefix of (`--strat` for `--strategy`).
|
|
25
|
+
*/
|
|
26
|
+
export function suggest(word, candidates) {
|
|
27
|
+
let best;
|
|
28
|
+
for (const c of candidates) {
|
|
29
|
+
const d = levenshtein(word, c);
|
|
30
|
+
if (!best || d < best.d)
|
|
31
|
+
best = { c, d };
|
|
32
|
+
}
|
|
33
|
+
if (!best)
|
|
34
|
+
return undefined;
|
|
35
|
+
if (best.d <= Math.max(2, Math.floor(word.length / 3)))
|
|
36
|
+
return best.c;
|
|
37
|
+
const bare = word.replace(/^-+/, "");
|
|
38
|
+
return bare.length >= 3 ? candidates.find((c) => c.replace(/^-+/, "").startsWith(bare)) : undefined;
|
|
39
|
+
}
|
|
40
|
+
/** "Did you mean …?" or nothing. */
|
|
41
|
+
export function didYouMean(word, candidates) {
|
|
42
|
+
const s = suggest(word, candidates);
|
|
43
|
+
return s ? ` Did you mean ${s}?` : "";
|
|
44
|
+
}
|
|
45
|
+
/** Split help text into entries: a line indented 2 spaces, plus the deeper-indented lines under it. */
|
|
46
|
+
function entries(help) {
|
|
47
|
+
const out = [];
|
|
48
|
+
let section = "";
|
|
49
|
+
let cur;
|
|
50
|
+
for (const line of help.split("\n")) {
|
|
51
|
+
if (/^\S.*:\s*$/.test(line)) {
|
|
52
|
+
section = line.trim().replace(/:$/, "");
|
|
53
|
+
cur = undefined;
|
|
54
|
+
}
|
|
55
|
+
else if (/^\S/.test(line)) {
|
|
56
|
+
section = "";
|
|
57
|
+
cur = undefined;
|
|
58
|
+
}
|
|
59
|
+
else if (/^ {2}\S/.test(line)) {
|
|
60
|
+
cur = { section, lines: [line] };
|
|
61
|
+
out.push(cur);
|
|
62
|
+
}
|
|
63
|
+
else if (/^ {3,}\S/.test(line) && cur) {
|
|
64
|
+
cur.lines.push(line);
|
|
65
|
+
}
|
|
66
|
+
else if (line.trim() === "") {
|
|
67
|
+
cur = undefined;
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
return out;
|
|
71
|
+
}
|
|
72
|
+
/** Commands a usage line documents: ` context-doctor <cmd> …`. */
|
|
73
|
+
function usageCommand(line) {
|
|
74
|
+
return /^ {2}context-doctor\s+([a-z][\w-]*)/.exec(line)?.[1];
|
|
75
|
+
}
|
|
76
|
+
/** Does an option's text scope it to `cmd`, as in "(savings, compact-window)" or "(analyze/session)"? */
|
|
77
|
+
function optionScoped(text, cmd) {
|
|
78
|
+
for (const m of text.matchAll(/\(([^)]*)\)/g)) {
|
|
79
|
+
const names = m[1].split(/[,/]/).map((s) => s.trim().split(/\s+/)[0]);
|
|
80
|
+
if (names.includes(cmd))
|
|
81
|
+
return true;
|
|
82
|
+
}
|
|
83
|
+
return false;
|
|
84
|
+
}
|
|
85
|
+
/** Every command the help text documents, in order. */
|
|
86
|
+
export function documentedCommands(help) {
|
|
87
|
+
const seen = new Set();
|
|
88
|
+
for (const e of entries(help)) {
|
|
89
|
+
if (e.section === "Options" || e.section === "Examples")
|
|
90
|
+
continue;
|
|
91
|
+
const c = usageCommand(e.lines[0]);
|
|
92
|
+
if (c)
|
|
93
|
+
seen.add(c);
|
|
94
|
+
}
|
|
95
|
+
return [...seen];
|
|
96
|
+
}
|
|
97
|
+
/**
|
|
98
|
+
* One command's help, cut from the full text: its usage line(s), the options
|
|
99
|
+
* scoped to it, and its examples. Undefined when the help has no usage line
|
|
100
|
+
* for it.
|
|
101
|
+
*/
|
|
102
|
+
export function commandHelp(help, cmd) {
|
|
103
|
+
const all = entries(help);
|
|
104
|
+
const usage = all.filter((e) => e.section !== "Options" && e.section !== "Examples" && usageCommand(e.lines[0]) === cmd);
|
|
105
|
+
if (usage.length === 0)
|
|
106
|
+
return undefined;
|
|
107
|
+
const options = all.filter((e) => e.section === "Options" && optionScoped(e.lines.join(" "), cmd));
|
|
108
|
+
const examples = all.filter((e) => e.section === "Examples" && usageCommand(e.lines[0]) === cmd);
|
|
109
|
+
const out = ["Usage:", ...usage.flatMap((e) => e.lines)];
|
|
110
|
+
if (options.length)
|
|
111
|
+
out.push("", "Options:", ...options.flatMap((e) => e.lines));
|
|
112
|
+
if (examples.length)
|
|
113
|
+
out.push("", "Examples:", ...examples.flatMap((e) => e.lines));
|
|
114
|
+
out.push("", "All commands and options: context-doctor --help");
|
|
115
|
+
return out.join("\n");
|
|
116
|
+
}
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Codex on an API key, through autopilot.
|
|
3
|
+
*
|
|
4
|
+
* Verified 2026-10-18 against codex-cli 0.153.4 (the ChatGPT app's) and
|
|
5
|
+
* 0.154.0-alpha (the IDE extension's), and openai/codex main:
|
|
6
|
+
* - The built-in `openai` provider's address is `openai_base_url`, a
|
|
7
|
+
* top-level key of the user's ~/.codex/config.toml (Codex ignores it in a
|
|
8
|
+
* project's .codex/config.toml). The OPENAI_BASE_URL environment variable
|
|
9
|
+
* no longer routes it: with only the variable set, Codex went straight to
|
|
10
|
+
* wss://api.openai.com. With the key set, `codex exec` on an API key sent
|
|
11
|
+
* its requests through the proxy and they showed in /stats.
|
|
12
|
+
* - The key applies whatever the sign-in. With ChatGPT sign-in Codex
|
|
13
|
+
* otherwise talks to chatgpt.com/backend-api/codex, so autopilot sets it
|
|
14
|
+
* only when ~/.codex/auth.json says "apikey", and the every-prompt hook's
|
|
15
|
+
* self-heal takes it out again if the sign-in changes. A ChatGPT-signed-in
|
|
16
|
+
* Codex that reads the same file anyway (the ChatGPT app's Codex tab) is
|
|
17
|
+
* relayed by the proxy to chatgpt.com unedited (see proxy.ts).
|
|
18
|
+
* - Codex tries Responses over WebSocket first; the proxy answers 426, and
|
|
19
|
+
* Codex switches to HTTP for the session at once.
|
|
20
|
+
*
|
|
21
|
+
* config.toml is the user's file: only our one top-level line is ever
|
|
22
|
+
* added, replaced or removed, and a value someone else set is left alone.
|
|
23
|
+
*/
|
|
24
|
+
export declare function codexHomeIn(home: string): string;
|
|
25
|
+
/** How Codex signs in, from auth.json: "apikey", "chatgpt", another mode, or undefined (none yet). */
|
|
26
|
+
export declare function codexAuthMode(codexHome: string): string | undefined;
|
|
27
|
+
/** A top-level string value (before the first [table]), or undefined. */
|
|
28
|
+
export declare function topLevelString(toml: string, key: string): string | undefined;
|
|
29
|
+
/** Set (or with undefined, remove) a top-level string key, touching no other line. */
|
|
30
|
+
export declare function setTopLevelString(toml: string, key: string, value: string | undefined): string;
|
|
31
|
+
export interface CodexRoute {
|
|
32
|
+
/** We wrote our address into config.toml. */
|
|
33
|
+
routed: boolean;
|
|
34
|
+
/** One line for the user, or undefined when Codex is not on this machine. */
|
|
35
|
+
line?: string;
|
|
36
|
+
}
|
|
37
|
+
/** Point Codex at the proxy when, and only when, it signs in with an API key. */
|
|
38
|
+
export declare function routeCodex(home: string, url: string, isOurs: (u: string) => boolean): CodexRoute;
|
|
39
|
+
/** Take our address out of config.toml. True when there was one to take out. */
|
|
40
|
+
export declare function unrouteCodex(home: string, isOurs: (u: string) => boolean): boolean;
|
|
41
|
+
/** What config.toml routes Codex to now, and how Codex signs in. */
|
|
42
|
+
export declare function codexRouting(home: string): {
|
|
43
|
+
present: boolean;
|
|
44
|
+
baseUrl?: string;
|
|
45
|
+
auth?: string;
|
|
46
|
+
};
|
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Codex on an API key, through autopilot.
|
|
3
|
+
*
|
|
4
|
+
* Verified 2026-10-18 against codex-cli 0.153.4 (the ChatGPT app's) and
|
|
5
|
+
* 0.154.0-alpha (the IDE extension's), and openai/codex main:
|
|
6
|
+
* - The built-in `openai` provider's address is `openai_base_url`, a
|
|
7
|
+
* top-level key of the user's ~/.codex/config.toml (Codex ignores it in a
|
|
8
|
+
* project's .codex/config.toml). The OPENAI_BASE_URL environment variable
|
|
9
|
+
* no longer routes it: with only the variable set, Codex went straight to
|
|
10
|
+
* wss://api.openai.com. With the key set, `codex exec` on an API key sent
|
|
11
|
+
* its requests through the proxy and they showed in /stats.
|
|
12
|
+
* - The key applies whatever the sign-in. With ChatGPT sign-in Codex
|
|
13
|
+
* otherwise talks to chatgpt.com/backend-api/codex, so autopilot sets it
|
|
14
|
+
* only when ~/.codex/auth.json says "apikey", and the every-prompt hook's
|
|
15
|
+
* self-heal takes it out again if the sign-in changes. A ChatGPT-signed-in
|
|
16
|
+
* Codex that reads the same file anyway (the ChatGPT app's Codex tab) is
|
|
17
|
+
* relayed by the proxy to chatgpt.com unedited (see proxy.ts).
|
|
18
|
+
* - Codex tries Responses over WebSocket first; the proxy answers 426, and
|
|
19
|
+
* Codex switches to HTTP for the session at once.
|
|
20
|
+
*
|
|
21
|
+
* config.toml is the user's file: only our one top-level line is ever
|
|
22
|
+
* added, replaced or removed, and a value someone else set is left alone.
|
|
23
|
+
*/
|
|
24
|
+
import { existsSync, readFileSync, writeFileSync, copyFileSync } from "node:fs";
|
|
25
|
+
import { join } from "node:path";
|
|
26
|
+
const KEY = "openai_base_url";
|
|
27
|
+
const ANY_HEADER = /^\s*\[/;
|
|
28
|
+
const keyLine = (key) => new RegExp(String.raw `^\s*(?:${key}|"${key}"|'${key}')\s*=\s*(?:"([^"]*)"|'([^']*)')\s*(?:#.*)?$`);
|
|
29
|
+
export function codexHomeIn(home) {
|
|
30
|
+
return join(home, ".codex");
|
|
31
|
+
}
|
|
32
|
+
/** How Codex signs in, from auth.json: "apikey", "chatgpt", another mode, or undefined (none yet). */
|
|
33
|
+
export function codexAuthMode(codexHome) {
|
|
34
|
+
try {
|
|
35
|
+
const auth = JSON.parse(readFileSync(join(codexHome, "auth.json"), "utf8"));
|
|
36
|
+
if (typeof auth?.auth_mode === "string")
|
|
37
|
+
return auth.auth_mode;
|
|
38
|
+
// Older files carry only the key.
|
|
39
|
+
if (typeof auth?.OPENAI_API_KEY === "string" && auth.OPENAI_API_KEY && !auth.tokens)
|
|
40
|
+
return "apikey";
|
|
41
|
+
}
|
|
42
|
+
catch {
|
|
43
|
+
/* no auth.json */
|
|
44
|
+
}
|
|
45
|
+
return undefined;
|
|
46
|
+
}
|
|
47
|
+
/** A top-level string value (before the first [table]), or undefined. */
|
|
48
|
+
export function topLevelString(toml, key) {
|
|
49
|
+
const re = keyLine(key);
|
|
50
|
+
for (const line of toml.split("\n")) {
|
|
51
|
+
if (ANY_HEADER.test(line))
|
|
52
|
+
return undefined;
|
|
53
|
+
const m = re.exec(line);
|
|
54
|
+
if (m)
|
|
55
|
+
return m[1] ?? m[2];
|
|
56
|
+
}
|
|
57
|
+
return undefined;
|
|
58
|
+
}
|
|
59
|
+
/** Set (or with undefined, remove) a top-level string key, touching no other line. */
|
|
60
|
+
export function setTopLevelString(toml, key, value) {
|
|
61
|
+
const lines = toml.length ? toml.split("\n") : [];
|
|
62
|
+
const re = keyLine(key);
|
|
63
|
+
const header = lines.findIndex((l) => ANY_HEADER.test(l));
|
|
64
|
+
const end = header === -1 ? lines.length : header;
|
|
65
|
+
const at = lines.slice(0, end).findIndex((l) => re.test(l));
|
|
66
|
+
const line = value === undefined ? undefined : `${key} = ${JSON.stringify(value)}`;
|
|
67
|
+
if (at >= 0) {
|
|
68
|
+
if (line === undefined)
|
|
69
|
+
lines.splice(at, 1);
|
|
70
|
+
else
|
|
71
|
+
lines[at] = line;
|
|
72
|
+
}
|
|
73
|
+
else if (line !== undefined) {
|
|
74
|
+
lines.splice(end, 0, line);
|
|
75
|
+
}
|
|
76
|
+
return lines.join("\n");
|
|
77
|
+
}
|
|
78
|
+
/** Point Codex at the proxy when, and only when, it signs in with an API key. */
|
|
79
|
+
export function routeCodex(home, url, isOurs) {
|
|
80
|
+
const dir = codexHomeIn(home);
|
|
81
|
+
if (!existsSync(dir))
|
|
82
|
+
return { routed: false };
|
|
83
|
+
const path = join(dir, "config.toml");
|
|
84
|
+
const toml = existsSync(path) ? readFileSync(path, "utf8") : "";
|
|
85
|
+
const auth = codexAuthMode(dir);
|
|
86
|
+
if (auth !== "apikey") {
|
|
87
|
+
return { routed: false, line: ` Codex ${auth === "chatgpt" ? "signs in with ChatGPT" : "has no API key sign-in"}: left untouched (its traffic goes to OpenAI's ChatGPT servers, which autopilot does not proxy).` };
|
|
88
|
+
}
|
|
89
|
+
const provider = topLevelString(toml, "model_provider");
|
|
90
|
+
if (provider && provider !== "openai")
|
|
91
|
+
return { routed: false, line: ` Codex uses the "${provider}" provider: left untouched.` };
|
|
92
|
+
const current = topLevelString(toml, KEY);
|
|
93
|
+
if (current && !isOurs(current))
|
|
94
|
+
return { routed: false, line: `! Codex already sends its requests to ${current} (openai_base_url): left as it is.` };
|
|
95
|
+
if (current !== url) {
|
|
96
|
+
if (existsSync(path))
|
|
97
|
+
copyFileSync(path, `${path}.context-doctor.backup`);
|
|
98
|
+
writeFileSync(path, setTopLevelString(toml, KEY, url));
|
|
99
|
+
}
|
|
100
|
+
return { routed: true, line: `✓ Codex (API key) routed through it (openai_base_url in ${path}; new Codex sessions)` };
|
|
101
|
+
}
|
|
102
|
+
/** Take our address out of config.toml. True when there was one to take out. */
|
|
103
|
+
export function unrouteCodex(home, isOurs) {
|
|
104
|
+
const path = join(codexHomeIn(home), "config.toml");
|
|
105
|
+
if (!existsSync(path))
|
|
106
|
+
return false;
|
|
107
|
+
const toml = readFileSync(path, "utf8");
|
|
108
|
+
const current = topLevelString(toml, KEY);
|
|
109
|
+
if (!current || !isOurs(current))
|
|
110
|
+
return false;
|
|
111
|
+
writeFileSync(path, setTopLevelString(toml, KEY, undefined));
|
|
112
|
+
return true;
|
|
113
|
+
}
|
|
114
|
+
/** What config.toml routes Codex to now, and how Codex signs in. */
|
|
115
|
+
export function codexRouting(home) {
|
|
116
|
+
const dir = codexHomeIn(home);
|
|
117
|
+
if (!existsSync(dir))
|
|
118
|
+
return { present: false };
|
|
119
|
+
const path = join(dir, "config.toml");
|
|
120
|
+
const toml = existsSync(path) ? readFileSync(path, "utf8") : "";
|
|
121
|
+
return { present: true, baseUrl: topLevelString(toml, KEY), auth: codexAuthMode(dir) };
|
|
122
|
+
}
|
package/dist/coldresume.d.ts
CHANGED
|
@@ -25,6 +25,41 @@
|
|
|
25
25
|
* host-orchestrated and drops a settings-file ANTHROPIC_BASE_URL, but it runs
|
|
26
26
|
* the every-prompt hook, which is where this is called from.
|
|
27
27
|
*/
|
|
28
|
+
/**
|
|
29
|
+
* Claude Code's own idle compaction (2.1.290+, account-gated by a server
|
|
30
|
+
* flag; the `idleCompaction` setting can only turn it off). Read from the
|
|
31
|
+
* 2.1.295 and 2.1.299 binaries: while a session sits idle on the 1-hour
|
|
32
|
+
* cache, it compacts at 90% of the cache's lifetime (~54 minutes), while the
|
|
33
|
+
* cache is still warm, when the context holds at least
|
|
34
|
+
* CLAUDE_CODE_IDLE_COMPACT_MIN_TOKENS (floor 100k; default 200,000). It
|
|
35
|
+
* skips 5-minute caches ("not_one_hour"), smaller sessions ("small"), a cache
|
|
36
|
+
* that already lapsed (a machine asleep) and sessions near a usage limit.
|
|
37
|
+
* The compact boundary it writes says trigger "auto", the same as a full
|
|
38
|
+
* window, and is followed by an informational row with this text; the
|
|
39
|
+
* headless host's variant (CLAUDE_CODE_SLEEP_COMPACT) queues a hidden
|
|
40
|
+
* `/compact` instead. Either way a compaction ends the idle period, so the
|
|
41
|
+
* cold-resume offer below stays silent after it, and keeps covering what
|
|
42
|
+
* idle compaction skips: 5-minute caches, sessions of 150k-200k tokens, and
|
|
43
|
+
* returns after the machine slept through the compaction moment.
|
|
44
|
+
*/
|
|
45
|
+
export declare const IDLE_COMPACT_NOTICE = "Compacted while idle";
|
|
46
|
+
/** Claude Code's idle-compaction minimum when CLAUDE_CODE_IDLE_COMPACT_MIN_TOKENS is unset (2.1.299). */
|
|
47
|
+
export declare const IDLE_COMPACT_MIN_TOKENS = 200000;
|
|
48
|
+
/** The row Claude Code writes after an idle compaction's boundary. */
|
|
49
|
+
export declare function isIdleCompactNotice(e: any): boolean;
|
|
50
|
+
/** The context at which Claude Code's idle compaction acts, as it reads the environment. */
|
|
51
|
+
export declare function idleCompactMinTokens(env?: NodeJS.ProcessEnv): number;
|
|
52
|
+
/**
|
|
53
|
+
* The context at which Claude Code is certain to compact before sending:
|
|
54
|
+
* its auto-compact window, which is the model's, or smaller when
|
|
55
|
+
* CLAUDE_CODE_AUTO_COMPACT_WINDOW or the `autoCompactWindow` setting says
|
|
56
|
+
* so. Not a share of it: on the author's history, cold returns at 95-99% of
|
|
57
|
+
* a 1M window went on for 2 to 51 requests before Claude Code compacted, so
|
|
58
|
+
* an offer there still paid; the one that compacted on the spot came at 96%.
|
|
59
|
+
* The note to the model covers that case instead. Undefined when
|
|
60
|
+
* auto-compaction is off or the window is unknown.
|
|
61
|
+
*/
|
|
62
|
+
export declare function autoCompactsAt(model: string | undefined, home?: string, env?: NodeJS.ProcessEnv): number | undefined;
|
|
28
63
|
/** Just past Claude Code's one-hour cache, as Claude Code's own idle clearing uses. */
|
|
29
64
|
export declare const COLD_IDLE_MS: number;
|
|
30
65
|
/** Below this, a rebuilt cache is cheap and compaction is not worth the interruption. */
|
|
@@ -40,7 +75,34 @@ export interface ColdResume {
|
|
|
40
75
|
resumeUsd?: number;
|
|
41
76
|
/** Each later message's cost to re-read the context, at list price. */
|
|
42
77
|
perMessageUsd?: number;
|
|
78
|
+
/** `resumeUsd` is Claude Code's own estimate (SessionStart), which honours a managed modelPricing. */
|
|
79
|
+
claudeCodePriced?: boolean;
|
|
80
|
+
}
|
|
81
|
+
/**
|
|
82
|
+
* What Claude Code's SessionStart hook says on a resume (2.1.29x):
|
|
83
|
+
* `seconds_since_last_response`, `context_tokens`,
|
|
84
|
+
* `prompt_cache_likely_expired` (idle past the TTL the transcript wrote at)
|
|
85
|
+
* and `estimated_cache_write_usd` (re-caching context_tokens at that TTL, at
|
|
86
|
+
* the managed modelPricing when set, otherwise list price). The hook keeps
|
|
87
|
+
* it with the session's state, and the first prompt after the resume uses
|
|
88
|
+
* it: Claude Code's verdict and price over the transcript's inference.
|
|
89
|
+
*/
|
|
90
|
+
export interface ResumeVerdict {
|
|
91
|
+
/** When the resumed transcript's last reply was written (now - seconds_since_last_response). */
|
|
92
|
+
replyAt: number;
|
|
93
|
+
/** When the session started (the verdict's moment). */
|
|
94
|
+
at: number;
|
|
95
|
+
expired: boolean;
|
|
96
|
+
usd?: number;
|
|
43
97
|
}
|
|
98
|
+
export declare function resumeVerdict(input: any, now?: number): ResumeVerdict | undefined;
|
|
99
|
+
/**
|
|
100
|
+
* Apply Claude Code's resume verdict to what the transcript showed. It
|
|
101
|
+
* describes this idle period when its reply time matches (seconds are
|
|
102
|
+
* rounded); a "still warm" verdict holds only for the cache's shortest life
|
|
103
|
+
* after it was given. Undefined: no offer.
|
|
104
|
+
*/
|
|
105
|
+
export declare function withResumeVerdict(c: ColdResume | undefined, v: ResumeVerdict | undefined, now?: number): ColdResume | undefined;
|
|
44
106
|
/**
|
|
45
107
|
* Is the prompt being submitted now a return to a large, cache-cold session?
|
|
46
108
|
* Reads only the transcript's tail. Undefined when not (or when unreadable).
|
package/dist/coldresume.js
CHANGED
|
@@ -25,10 +25,67 @@
|
|
|
25
25
|
* host-orchestrated and drops a settings-file ANTHROPIC_BASE_URL, but it runs
|
|
26
26
|
* the every-prompt hook, which is where this is called from.
|
|
27
27
|
*/
|
|
28
|
-
import { closeSync, openSync, readSync, statSync } from "node:fs";
|
|
28
|
+
import { closeSync, openSync, readFileSync, readSync, statSync } from "node:fs";
|
|
29
|
+
import { homedir } from "node:os";
|
|
30
|
+
import { join } from "node:path";
|
|
29
31
|
import { forEachLine, replyCounter } from "./session.js";
|
|
30
32
|
import { cacheWriteSplit, pricingFor, formatUsd, writeMultiplier } from "./pricing.js";
|
|
31
|
-
import { formatTokens, realModel } from "./tokens.js";
|
|
33
|
+
import { contextWindowFor, formatTokens, realModel } from "./tokens.js";
|
|
34
|
+
/**
|
|
35
|
+
* Claude Code's own idle compaction (2.1.290+, account-gated by a server
|
|
36
|
+
* flag; the `idleCompaction` setting can only turn it off). Read from the
|
|
37
|
+
* 2.1.295 and 2.1.299 binaries: while a session sits idle on the 1-hour
|
|
38
|
+
* cache, it compacts at 90% of the cache's lifetime (~54 minutes), while the
|
|
39
|
+
* cache is still warm, when the context holds at least
|
|
40
|
+
* CLAUDE_CODE_IDLE_COMPACT_MIN_TOKENS (floor 100k; default 200,000). It
|
|
41
|
+
* skips 5-minute caches ("not_one_hour"), smaller sessions ("small"), a cache
|
|
42
|
+
* that already lapsed (a machine asleep) and sessions near a usage limit.
|
|
43
|
+
* The compact boundary it writes says trigger "auto", the same as a full
|
|
44
|
+
* window, and is followed by an informational row with this text; the
|
|
45
|
+
* headless host's variant (CLAUDE_CODE_SLEEP_COMPACT) queues a hidden
|
|
46
|
+
* `/compact` instead. Either way a compaction ends the idle period, so the
|
|
47
|
+
* cold-resume offer below stays silent after it, and keeps covering what
|
|
48
|
+
* idle compaction skips: 5-minute caches, sessions of 150k-200k tokens, and
|
|
49
|
+
* returns after the machine slept through the compaction moment.
|
|
50
|
+
*/
|
|
51
|
+
export const IDLE_COMPACT_NOTICE = "Compacted while idle";
|
|
52
|
+
/** Claude Code's idle-compaction minimum when CLAUDE_CODE_IDLE_COMPACT_MIN_TOKENS is unset (2.1.299). */
|
|
53
|
+
export const IDLE_COMPACT_MIN_TOKENS = 200_000;
|
|
54
|
+
/** The row Claude Code writes after an idle compaction's boundary. */
|
|
55
|
+
export function isIdleCompactNotice(e) {
|
|
56
|
+
return e?.type === "system" && typeof e.content === "string" && e.content.startsWith(IDLE_COMPACT_NOTICE);
|
|
57
|
+
}
|
|
58
|
+
/** The context at which Claude Code's idle compaction acts, as it reads the environment. */
|
|
59
|
+
export function idleCompactMinTokens(env = process.env) {
|
|
60
|
+
const n = Number(env.CLAUDE_CODE_IDLE_COMPACT_MIN_TOKENS);
|
|
61
|
+
return env.CLAUDE_CODE_IDLE_COMPACT_MIN_TOKENS && Number.isFinite(n) ? Math.max(100_000, n) : IDLE_COMPACT_MIN_TOKENS;
|
|
62
|
+
}
|
|
63
|
+
/**
|
|
64
|
+
* The context at which Claude Code is certain to compact before sending:
|
|
65
|
+
* its auto-compact window, which is the model's, or smaller when
|
|
66
|
+
* CLAUDE_CODE_AUTO_COMPACT_WINDOW or the `autoCompactWindow` setting says
|
|
67
|
+
* so. Not a share of it: on the author's history, cold returns at 95-99% of
|
|
68
|
+
* a 1M window went on for 2 to 51 requests before Claude Code compacted, so
|
|
69
|
+
* an offer there still paid; the one that compacted on the spot came at 96%.
|
|
70
|
+
* The note to the model covers that case instead. Undefined when
|
|
71
|
+
* auto-compaction is off or the window is unknown.
|
|
72
|
+
*/
|
|
73
|
+
export function autoCompactsAt(model, home = homedir(), env = process.env) {
|
|
74
|
+
if (env.DISABLE_AUTO_COMPACT || env.DISABLE_COMPACT)
|
|
75
|
+
return undefined;
|
|
76
|
+
let settings = {};
|
|
77
|
+
try {
|
|
78
|
+
settings = JSON.parse(readFileSync(join(home, ".claude", "settings.json"), "utf8")) ?? {};
|
|
79
|
+
}
|
|
80
|
+
catch { /* no settings */ }
|
|
81
|
+
if (settings.autoCompactEnabled === false)
|
|
82
|
+
return undefined;
|
|
83
|
+
const window = contextWindowFor(model);
|
|
84
|
+
const fromEnv = Number(env.CLAUDE_CODE_AUTO_COMPACT_WINDOW);
|
|
85
|
+
const set = fromEnv > 0 ? fromEnv : typeof settings.autoCompactWindow === "number" && settings.autoCompactWindow > 0 ? settings.autoCompactWindow : undefined;
|
|
86
|
+
const effective = set !== undefined ? Math.min(window ?? set, set) : window;
|
|
87
|
+
return effective;
|
|
88
|
+
}
|
|
32
89
|
/** Just past Claude Code's one-hour cache, as Claude Code's own idle clearing uses. */
|
|
33
90
|
export const COLD_IDLE_MS = 65 * 60_000;
|
|
34
91
|
/** Margin past a cache's lifetime before a return counts as cold. */
|
|
@@ -63,6 +120,28 @@ export const COLD_MIN_TOKENS = 150_000;
|
|
|
63
120
|
const AFTER_COMPACT_TOKENS = 45_000;
|
|
64
121
|
/** Output tokens a compaction summary costs, at the model's output price. */
|
|
65
122
|
const SUMMARY_OUTPUT_TOKENS = 8_000;
|
|
123
|
+
export function resumeVerdict(input, now = Date.now()) {
|
|
124
|
+
if (input?.hook_event_name !== "SessionStart" || (input.source !== "resume" && input.source !== "fork"))
|
|
125
|
+
return undefined;
|
|
126
|
+
const secs = input.seconds_since_last_response;
|
|
127
|
+
if (typeof input.prompt_cache_likely_expired !== "boolean" || typeof secs !== "number" || !Number.isFinite(secs))
|
|
128
|
+
return undefined;
|
|
129
|
+
const usd = input.estimated_cache_write_usd;
|
|
130
|
+
return { replyAt: now - secs * 1000, at: now, expired: input.prompt_cache_likely_expired, usd: typeof usd === "number" && Number.isFinite(usd) ? usd : undefined };
|
|
131
|
+
}
|
|
132
|
+
/**
|
|
133
|
+
* Apply Claude Code's resume verdict to what the transcript showed. It
|
|
134
|
+
* describes this idle period when its reply time matches (seconds are
|
|
135
|
+
* rounded); a "still warm" verdict holds only for the cache's shortest life
|
|
136
|
+
* after it was given. Undefined: no offer.
|
|
137
|
+
*/
|
|
138
|
+
export function withResumeVerdict(c, v, now = Date.now()) {
|
|
139
|
+
if (!c || !v || Math.abs(c.lastReplyAt - v.replyAt) > 5_000)
|
|
140
|
+
return c;
|
|
141
|
+
if (!v.expired)
|
|
142
|
+
return now - v.at < FIVE_MIN_MS ? undefined : c;
|
|
143
|
+
return v.usd !== undefined ? { ...c, resumeUsd: v.usd, claudeCodePriced: true } : c;
|
|
144
|
+
}
|
|
66
145
|
function tailLines(path, bytes = 256 * 1024) {
|
|
67
146
|
const size = statSync(path).size;
|
|
68
147
|
const n = Math.min(size, bytes);
|
|
@@ -96,7 +175,7 @@ export function detectColdResume(path, now = Date.now(), idleMs, minTokens = COL
|
|
|
96
175
|
// context, and there is nothing large left to warn about.
|
|
97
176
|
if (e?.type === "system" && e.subtype === "compact_boundary")
|
|
98
177
|
return undefined;
|
|
99
|
-
if (e?.isCompactSummary)
|
|
178
|
+
if (e?.isCompactSummary || isIdleCompactNotice(e))
|
|
100
179
|
return undefined;
|
|
101
180
|
if (e?.type !== "assistant" || e.isSidechain)
|
|
102
181
|
continue;
|
|
@@ -203,19 +282,19 @@ function duration(ms) {
|
|
|
203
282
|
*/
|
|
204
283
|
export function renderColdResumeNotice(c) {
|
|
205
284
|
const cheaper = Math.max(0, Math.round((1 - AFTER_COMPACT_TOKENS / c.tokens) * 100));
|
|
206
|
-
const money = c.resumeUsd !== undefined ? ` (~${formatUsd(c.resumeUsd)} at list price)` : "";
|
|
285
|
+
const money = c.resumeUsd !== undefined ? ` (~${formatUsd(c.resumeUsd)} ${c.claudeCodePriced ? "by Claude Code's estimate" : "at list price"})` : "";
|
|
207
286
|
return `context-doctor: idle ${duration(c.idleMs)}, so this message re-sent the whole ~${formatTokens(c.tokens)}-token context${money}. If you keep working here, /compact now makes each later message ~${cheaper}% cheaper.`;
|
|
208
287
|
}
|
|
209
288
|
/** The note the hook hands the model: the numbers, and one sentence to say. */
|
|
210
289
|
export function renderColdResume(c) {
|
|
211
290
|
const cheaper = Math.max(0, Math.round((1 - AFTER_COMPACT_TOKENS / c.tokens) * 100));
|
|
212
291
|
const money = c.resumeUsd !== undefined
|
|
213
|
-
? ` (~${formatUsd(c.resumeUsd)} at list price), and every later message re-reads it (~${formatUsd(c.perMessageUsd)} each)`
|
|
292
|
+
? ` (~${formatUsd(c.resumeUsd)} ${c.claudeCodePriced ? "by Claude Code's estimate" : "at list price"}), and every later message re-reads it${c.perMessageUsd !== undefined ? ` (~${formatUsd(c.perMessageUsd)} each)` : ""}`
|
|
214
293
|
: ", and every later message re-reads it";
|
|
215
294
|
return [
|
|
216
295
|
`This session was idle for ${duration(c.idleMs)}, longer than the prompt cache lasts, so this message re-sends the whole ~${formatTokens(c.tokens)}-token context at the full cache-write rate${money}.`,
|
|
217
296
|
`If the user is going to keep working in this session, running /compact now restarts it from a short summary and makes each later message roughly ${cheaper}% cheaper; the cache is being rebuilt anyway, so now is when compaction costs least.`,
|
|
218
|
-
"Begin your reply with one short sentence offering that (only the user can run /compact), then answer the request normally. Do not raise it again this session unless it goes idle again.",
|
|
297
|
+
"Begin your reply with one short sentence offering that (only the user can run /compact), then answer the request normally; if the conversation was compacted just before this message, say nothing about it. Do not raise it again this session unless it goes idle again.",
|
|
219
298
|
].join("\n");
|
|
220
299
|
}
|
|
221
300
|
/**
|
package/dist/compactquality.d.ts
CHANGED
|
@@ -28,6 +28,8 @@ interface Signals {
|
|
|
28
28
|
}
|
|
29
29
|
export interface CompactionQuality {
|
|
30
30
|
compactions: number;
|
|
31
|
+
/** Of those, Claude Code's idle compactions: a quiet session compacted before its cache expired, not a full window. */
|
|
32
|
+
idle: number;
|
|
31
33
|
/** Tokens re-read after a compaction beyond the before-window rate, per compaction. */
|
|
32
34
|
extraRereadTokensPerCompaction: number;
|
|
33
35
|
sessions: number;
|
|
@@ -40,6 +42,6 @@ export interface CompactionQuality {
|
|
|
40
42
|
after: Signals;
|
|
41
43
|
};
|
|
42
44
|
}
|
|
43
|
-
export declare function compactionQuality(days?: number, paths?: string[]): CompactionQuality;
|
|
45
|
+
export declare function compactionQuality(days?: number, paths?: string[], onProgress?: (done: number, total: number) => void): CompactionQuality;
|
|
44
46
|
export declare function renderCompactionQuality(q: CompactionQuality, days?: number): string;
|
|
45
47
|
export {};
|
package/dist/compactquality.js
CHANGED
|
@@ -18,6 +18,7 @@
|
|
|
18
18
|
import { forEachLine, listSessions, queuedUserPrompt } from "./session.js";
|
|
19
19
|
import { readLedger } from "./ledger.js";
|
|
20
20
|
import { estimateTokens, formatTokens } from "./tokens.js";
|
|
21
|
+
import { isIdleCompactNotice } from "./coldresume.js";
|
|
21
22
|
const WINDOW = 15;
|
|
22
23
|
const CORRECTION = /^(no\b|nope\b|wrong\b|that'?s (not|wrong)|not what i|you forgot|i (said|told you|asked)|revert\b|undo\b|stop\b|again\??$|why did you)/i;
|
|
23
24
|
const empty = () => ({ requests: 0, rereads: 0, rereadTokens: 0, reads: 0, calls: 0, errors: 0, userMsgs: 0, corrections: 0 });
|
|
@@ -37,15 +38,16 @@ function add(s, reqs, readBefore) {
|
|
|
37
38
|
});
|
|
38
39
|
}
|
|
39
40
|
}
|
|
40
|
-
export function compactionQuality(days = 60, paths) {
|
|
41
|
+
export function compactionQuality(days = 60, paths, onProgress) {
|
|
41
42
|
const since = Date.now() - days * 86_400_000;
|
|
42
43
|
const files = paths ?? listSessions(10_000).filter((s) => s.path.includes(".claude") && s.modifiedAt.getTime() >= since).map((s) => s.path);
|
|
43
44
|
const shapedAt = readLedger().filter((e) => e.ev === "precompact").map((e) => e.ts);
|
|
44
|
-
const q = { compactions: 0, extraRereadTokensPerCompaction: 0, sessions: 0, before: empty(), after: empty() };
|
|
45
|
+
const q = { compactions: 0, idle: 0, extraRereadTokensPerCompaction: 0, sessions: 0, before: empty(), after: empty() };
|
|
45
46
|
const shaped = { compactions: 0, before: empty(), after: empty() };
|
|
46
47
|
// A forked session copies its parent's compactions (same row uuid): one compaction, counted once.
|
|
47
48
|
const countedBoundaries = new Set();
|
|
48
|
-
for (const path of files) {
|
|
49
|
+
for (const [fileIndex, path] of files.entries()) {
|
|
50
|
+
onProgress?.(fileIndex, files.length);
|
|
49
51
|
const reqs = [];
|
|
50
52
|
/** `at` is NaN when the row carries no timestamp. */
|
|
51
53
|
const boundaries = [];
|
|
@@ -85,6 +87,13 @@ export function compactionQuality(days = 60, paths) {
|
|
|
85
87
|
cur = undefined;
|
|
86
88
|
return;
|
|
87
89
|
}
|
|
90
|
+
// Claude Code's idle compaction writes this right after its boundary.
|
|
91
|
+
if (isIdleCompactNotice(e)) {
|
|
92
|
+
const last = boundaries[boundaries.length - 1];
|
|
93
|
+
if (last && last.index === reqs.length)
|
|
94
|
+
last.idle = true;
|
|
95
|
+
return;
|
|
96
|
+
}
|
|
88
97
|
// Typed while the agent worked: a user message recorded only as an
|
|
89
98
|
// attachment, and the likeliest moment for a "no, stop" to arrive.
|
|
90
99
|
const queued = queuedUserPrompt(e);
|
|
@@ -147,6 +156,8 @@ export function compactionQuality(days = 60, paths) {
|
|
|
147
156
|
add(q.before, before, earlier);
|
|
148
157
|
add(q.after, after, readBefore);
|
|
149
158
|
q.compactions++;
|
|
159
|
+
if (b.idle)
|
|
160
|
+
q.idle++;
|
|
150
161
|
counted = true;
|
|
151
162
|
if (shapedAt.some((t) => Math.abs(t - b.at) < 10 * 60_000)) {
|
|
152
163
|
shaped.compactions++;
|
|
@@ -179,7 +190,7 @@ export function renderCompactionQuality(q, days = 60) {
|
|
|
179
190
|
const pct = (x) => `${(x * 100).toFixed(1)}%`;
|
|
180
191
|
const row = (label, x, y) => ` ${label.padEnd(36)} ${pct(x).padStart(7)} ${pct(y).padStart(7)} ${y - x > 0.0005 ? "+" : y - x < -0.0005 ? "−" : " "}${pct(Math.abs(y - x))}`;
|
|
181
192
|
const thin = q.before.reads + q.after.reads < 50;
|
|
182
|
-
out.push(`${q.compactions} compactions in ${q.sessions} sessions, last ${days} days; ${WINDOW} requests before vs after each
|
|
193
|
+
out.push(`${q.compactions} compactions in ${q.sessions} sessions, last ${days} days; ${WINDOW} requests before vs after each.${q.idle ? ` ${q.idle} of them were Claude Code's idle compactions (a quiet session compacted before its cache expired).` : ""}`, `Sample: ${q.before.reads} file reads before, ${q.after.reads} after; ${q.before.calls} and ${q.after.calls} tool calls; ${q.before.userMsgs} and ${q.after.userMsgs} of your messages.${thin ? " Few reads: the re-read figure is a weak signal." : ""}`, "", ` ${"".padEnd(36)} ${"before".padStart(7)} ${"after".padStart(7)} change`, row("files re-read (forgotten)", b.reread, a.reread), row("tool calls that errored", b.error, a.error), row("your messages correcting course", b.correction, a.correction));
|
|
183
194
|
if (q.shaped) {
|
|
184
195
|
const sb = rates(q.shaped.before), sa = rates(q.shaped.after);
|
|
185
196
|
out.push("", `Shaped by context-doctor's PreCompact hook (${q.shaped.compactions}): re-reads ${pct(sb.reread)} → ${pct(sa.reread)}, errors ${pct(sb.error)} → ${pct(sa.error)}, corrections ${pct(sb.correction)} → ${pct(sa.correction)}.`);
|