context-doctor 0.33.0 → 0.35.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 +13 -10
- package/dist/autoclear.d.ts +5 -2
- package/dist/autoclear.js +57 -19
- package/dist/autopilot.d.ts +0 -6
- package/dist/autopilot.js +37 -2
- package/dist/cachekey.d.ts +25 -0
- package/dist/cachekey.js +73 -0
- package/dist/cachemisses.d.ts +88 -0
- package/dist/cachemisses.js +325 -0
- package/dist/cacheplan.d.ts +30 -10
- package/dist/cacheplan.js +157 -32
- package/dist/cli.js +68 -19
- 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 +2 -0
- package/dist/compactquality.js +21 -3
- package/dist/compactwindow.d.ts +2 -0
- package/dist/compactwindow.js +30 -7
- package/dist/config.d.ts +11 -0
- package/dist/config.js +117 -4
- package/dist/dashboard.js +15 -1
- package/dist/doctor.d.ts +23 -0
- package/dist/doctor.js +133 -10
- package/dist/hook.d.ts +18 -0
- package/dist/hook.js +58 -8
- package/dist/impact.js +32 -4
- package/dist/index.d.ts +2 -0
- package/dist/index.js +2 -0
- package/dist/install.d.ts +25 -0
- package/dist/install.js +148 -45
- package/dist/ledger.d.ts +2 -0
- package/dist/mcp.js +56 -53
- package/dist/modelswitch.d.ts +76 -0
- package/dist/modelswitch.js +184 -0
- package/dist/optimize.js +40 -6
- package/dist/pack.d.ts +32 -3
- package/dist/pack.js +176 -24
- package/dist/parse.d.ts +3 -1
- package/dist/parse.js +123 -3
- package/dist/pricing.js +8 -0
- package/dist/profile.js +60 -17
- package/dist/proxy.d.ts +22 -1
- package/dist/proxy.js +89 -12
- package/dist/report.js +8 -2
- package/dist/savings.d.ts +15 -2
- package/dist/savings.js +9 -11
- package/dist/session.js +19 -3
- package/dist/sketch.d.ts +2 -0
- package/dist/sketch.js +10 -1
- package/dist/tokens.js +20 -9
- package/dist/wrap.js +27 -5
- package/package.json +1 -1
|
@@ -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;
|
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 });
|
|
@@ -41,7 +42,7 @@ 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();
|
|
@@ -86,6 +87,13 @@ export function compactionQuality(days = 60, paths, onProgress) {
|
|
|
86
87
|
cur = undefined;
|
|
87
88
|
return;
|
|
88
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
|
+
}
|
|
89
97
|
// Typed while the agent worked: a user message recorded only as an
|
|
90
98
|
// attachment, and the likeliest moment for a "no, stop" to arrive.
|
|
91
99
|
const queued = queuedUserPrompt(e);
|
|
@@ -148,6 +156,8 @@ export function compactionQuality(days = 60, paths, onProgress) {
|
|
|
148
156
|
add(q.before, before, earlier);
|
|
149
157
|
add(q.after, after, readBefore);
|
|
150
158
|
q.compactions++;
|
|
159
|
+
if (b.idle)
|
|
160
|
+
q.idle++;
|
|
151
161
|
counted = true;
|
|
152
162
|
if (shapedAt.some((t) => Math.abs(t - b.at) < 10 * 60_000)) {
|
|
153
163
|
shaped.compactions++;
|
|
@@ -180,7 +190,7 @@ export function renderCompactionQuality(q, days = 60) {
|
|
|
180
190
|
const pct = (x) => `${(x * 100).toFixed(1)}%`;
|
|
181
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))}`;
|
|
182
192
|
const thin = q.before.reads + q.after.reads < 50;
|
|
183
|
-
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));
|
|
184
194
|
if (q.shaped) {
|
|
185
195
|
const sb = rates(q.shaped.before), sa = rates(q.shaped.after);
|
|
186
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)}.`);
|
|
@@ -192,8 +202,16 @@ export function renderCompactionQuality(q, days = 60) {
|
|
|
192
202
|
// Rounded: an average below 1k otherwise printed as "~237.46428571428572".
|
|
193
203
|
out.push(`Compacting forgets files: each compaction is followed by ~${formatTokens(Math.round(q.extraRereadTokensPerCompaction))} tokens of extra re-reads. compact-window charges that to every compaction it simulates.`);
|
|
194
204
|
}
|
|
205
|
+
// "No higher" only when neither went up: 0% before and 4.8% after is under
|
|
206
|
+
// the margin for "worse", and it is still higher, so it is said as such.
|
|
207
|
+
const higher = [
|
|
208
|
+
a.error - b.error > 0.0005 ? `tool errors ${pct(b.error)} → ${pct(a.error)}` : "",
|
|
209
|
+
a.correction - b.correction > 0.0005 ? `corrections ${pct(b.correction)} → ${pct(a.correction)}` : "",
|
|
210
|
+
].filter(Boolean);
|
|
195
211
|
out.push(worse
|
|
196
212
|
? "Sessions also work worse after compacting (more tool errors or corrections): compact less often, and let the PreCompact hook tell each summary what to keep."
|
|
197
|
-
:
|
|
213
|
+
: higher.length === 0
|
|
214
|
+
? "No sign of worse work after compacting: tool errors and corrections are no higher. The cost of compacting here is tokens, not quality."
|
|
215
|
+
: `Little sign of worse work after compacting: ${higher.join(" and ")}, up by less than the margin counted as worse here (3 points for errors, 5 for corrections). The cost of compacting here is mostly tokens.`);
|
|
198
216
|
return out.join("\n");
|
|
199
217
|
}
|
package/dist/compactwindow.d.ts
CHANGED
|
@@ -42,6 +42,8 @@ export interface CompactWindowReport {
|
|
|
42
42
|
transcripts: number;
|
|
43
43
|
/** Compactions that actually happened over the period (Claude Code's own, or /compact). */
|
|
44
44
|
actualCompactions: number;
|
|
45
|
+
/** Of those, Claude Code's idle compactions (a quiet session compacted before its cache expired). */
|
|
46
|
+
idleCompactions?: number;
|
|
45
47
|
estimates: WindowEstimate[];
|
|
46
48
|
/** Re-read tokens charged to each simulated compaction (0 when not measured). */
|
|
47
49
|
rereadTokens?: number;
|
package/dist/compactwindow.js
CHANGED
|
@@ -28,6 +28,7 @@ import { cacheWriteSplit, pricingFor, usageCost, writeMultiplier } from "./prici
|
|
|
28
28
|
import { realModel } from "./tokens.js";
|
|
29
29
|
import { readJson, writeJsonWithBackup } from "./install.js";
|
|
30
30
|
import { withInvocation } from "./invocation.js";
|
|
31
|
+
import { idleCompactMinTokens, isIdleCompactNotice } from "./coldresume.js";
|
|
31
32
|
/** Claude Code compacts at about this share of the window (970k of 1M, measured). */
|
|
32
33
|
const TRIGGER_SHARE = 0.97;
|
|
33
34
|
/** Context right after a compaction: system prompt, tools and the summary (median 75,447, measured). */
|
|
@@ -66,6 +67,13 @@ function readRequests(path, runRows) {
|
|
|
66
67
|
reqs.push({ compact: true, copy });
|
|
67
68
|
return;
|
|
68
69
|
}
|
|
70
|
+
// Claude Code's idle compaction marks its boundary with a notice row.
|
|
71
|
+
if (isIdleCompactNotice(e)) {
|
|
72
|
+
const last = reqs[reqs.length - 1];
|
|
73
|
+
if (last && "compact" in last)
|
|
74
|
+
last.idle = true;
|
|
75
|
+
return;
|
|
76
|
+
}
|
|
69
77
|
if (e.type !== "assistant" || !e.message)
|
|
70
78
|
return;
|
|
71
79
|
const seen = sighting(e);
|
|
@@ -100,13 +108,25 @@ function readRequests(path, runRows) {
|
|
|
100
108
|
* summary dropped them (measured by `context-doctor compactions`). Each
|
|
101
109
|
* simulated compaction writes them to the cache and carries them onward.
|
|
102
110
|
*/
|
|
103
|
-
function replay(reqs, window, since, reread = 0, writeMult = 1.25) {
|
|
104
|
-
let base = 0, sim = 0, extra = 0, actual = 0;
|
|
111
|
+
function replay(reqs, window, since, reread = 0, writeMult = 1.25, idleMin = idleCompactMinTokens()) {
|
|
112
|
+
let base = 0, sim = 0, extra = 0, actual = 0, idle = 0;
|
|
105
113
|
let removed = 0, prevActual, prevSim, prevAt;
|
|
106
114
|
for (const r of reqs) {
|
|
107
115
|
if ("compact" in r) {
|
|
108
|
-
if (prevAt !== undefined && prevAt >= since && !r.copy)
|
|
116
|
+
if (prevAt !== undefined && prevAt >= since && !r.copy) {
|
|
109
117
|
actual++;
|
|
118
|
+
if (r.idle)
|
|
119
|
+
idle++;
|
|
120
|
+
}
|
|
121
|
+
// An idle compaction acts only on a context of idleMin or more: where
|
|
122
|
+
// the smaller window had already left less, Claude Code would not have
|
|
123
|
+
// compacted the simulated session here. It keeps its own context (now
|
|
124
|
+
// larger than the real one, so `removed` turns negative), and its cache.
|
|
125
|
+
if (r.idle && removed > 0 && prevSim !== undefined && prevSim < idleMin) {
|
|
126
|
+
removed = AFTER_COMPACT - prevSim;
|
|
127
|
+
prevActual = undefined;
|
|
128
|
+
continue;
|
|
129
|
+
}
|
|
110
130
|
// A real compaction in the transcript: the simulated arm compacts there too.
|
|
111
131
|
if (prevAt !== undefined && prevAt >= since && removed === 0 && !r.copy)
|
|
112
132
|
extra++;
|
|
@@ -150,13 +170,13 @@ function replay(reqs, window, since, reread = 0, writeMult = 1.25) {
|
|
|
150
170
|
prevSim = ctx;
|
|
151
171
|
prevAt = r.at;
|
|
152
172
|
}
|
|
153
|
-
return { base, sim, extra, actual };
|
|
173
|
+
return { base, sim, extra, actual, idle };
|
|
154
174
|
}
|
|
155
175
|
export function estimateCompactWindows(windows, days = 30, paths, rereadTokens = 0, onProgress) {
|
|
156
176
|
const since = Date.now() - days * 86_400_000;
|
|
157
177
|
const targets = paths ?? listSessions(10_000).filter((s) => s.path.includes(".claude") && s.modifiedAt.getTime() >= since).map((s) => s.path);
|
|
158
178
|
const acc = windows.map((w) => ({ window: w, billed: 0, saved: 0, replayBase: 0, extra: 0 }));
|
|
159
|
-
let sessions = 0, actualCompactions = 0;
|
|
179
|
+
let sessions = 0, actualCompactions = 0, idleCompactions = 0;
|
|
160
180
|
// Shared by every transcript of the run, so a fork's copy counts once.
|
|
161
181
|
const runRows = new Set();
|
|
162
182
|
for (const [i, p] of targets.entries()) {
|
|
@@ -175,7 +195,9 @@ export function estimateCompactWindows(windows, days = 30, paths, rereadTokens =
|
|
|
175
195
|
continue;
|
|
176
196
|
sessions++;
|
|
177
197
|
const billed = counted.reduce((n, r) => n + r.billedUsd, 0);
|
|
178
|
-
|
|
198
|
+
const asNow = replay(parsed.reqs, Number.MAX_SAFE_INTEGER, since, 0, parsed.writeMult);
|
|
199
|
+
actualCompactions += asNow.actual;
|
|
200
|
+
idleCompactions += asNow.idle;
|
|
179
201
|
for (const a of acc) {
|
|
180
202
|
const r = replay(parsed.reqs, a.window, since, rereadTokens, parsed.writeMult);
|
|
181
203
|
// The replay's share saved, applied to what this session was billed.
|
|
@@ -192,6 +214,7 @@ export function estimateCompactWindows(windows, days = 30, paths, rereadTokens =
|
|
|
192
214
|
sessions,
|
|
193
215
|
transcripts: targets.length,
|
|
194
216
|
actualCompactions,
|
|
217
|
+
idleCompactions,
|
|
195
218
|
rereadTokens,
|
|
196
219
|
estimates: acc.map((a) => ({
|
|
197
220
|
window: a.window,
|
|
@@ -274,7 +297,7 @@ export function renderCompactWindows(r, current) {
|
|
|
274
297
|
const mark = current === e.window ? " ← current" : "";
|
|
275
298
|
lines.push(` ${k(e.window).padStart(6)} ${usd(e.withWindowUsd).padStart(10)} ${(usd(e.savedUsd) + ` (${Math.round(e.savedPct * 100)}%)`).padEnd(16)} ${String(e.compactions).padStart(4)} (${((e.compactions / r.days) * 7).toFixed(1)}/week)${mark}`);
|
|
276
299
|
}
|
|
277
|
-
lines.push(` as now ${usd(r.estimates[0]?.baselineUsd ?? 0).padStart(10)} ${String(r.actualCompactions).padStart(4)} (${((r.actualCompactions / r.days) * 7).toFixed(1)}/week)`);
|
|
300
|
+
lines.push(` as now ${usd(r.estimates[0]?.baselineUsd ?? 0).padStart(10)} ${String(r.actualCompactions).padStart(4)} (${((r.actualCompactions / r.days) * 7).toFixed(1)}/week${r.idleCompactions ? `; ${r.idleCompactions} while idle` : ""})`);
|
|
278
301
|
lines.push("");
|
|
279
302
|
lines.push("\"as now\" is what you were billed (transcript usage at list price, as in");
|
|
280
303
|
lines.push("`context-doctor savings`); each window saves the replay's share of it.");
|
package/dist/config.d.ts
CHANGED
|
@@ -60,6 +60,17 @@ export interface LoadedConfig {
|
|
|
60
60
|
* doing nothing is the worst available behaviour.
|
|
61
61
|
*/
|
|
62
62
|
export declare function validateConfig(config: unknown, path: string): string[];
|
|
63
|
+
/** Warnings for the entries of a `routes` array (rc file or `proxy --config`). */
|
|
64
|
+
export declare function validateRoutes(routes: unknown[], path: string): string[];
|
|
65
|
+
/** The valid routes of a raw `routes` value, each with only its valid settings. */
|
|
66
|
+
export declare function sanitizeRoutes(value: unknown): ContextDoctorConfig["routes"];
|
|
67
|
+
/**
|
|
68
|
+
* The settings of a parsed rc file that are actually in effect: exactly the
|
|
69
|
+
* values validateConfig does not call ignored. Returning the raw object, as
|
|
70
|
+
* this once did, warned that `keepRecent: -5` was ignored and then applied
|
|
71
|
+
* it, which cut the live tool result in `optimize` and the proxy.
|
|
72
|
+
*/
|
|
73
|
+
export declare function sanitizeConfig(config: unknown): ContextDoctorConfig;
|
|
63
74
|
export declare function loadConfig(startDir?: string, onWarn?: (msg: string) => void): LoadedConfig;
|
|
64
75
|
export interface BudgetVerdict {
|
|
65
76
|
/** True when any configured limit is exceeded. */
|