context-doctor 0.33.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 +9 -9
- 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/cacheplan.d.ts +29 -9
- package/dist/cacheplan.js +110 -29
- package/dist/cli.js +5 -3
- 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 +12 -2
- package/dist/compactwindow.d.ts +2 -0
- package/dist/compactwindow.js +30 -7
- package/dist/doctor.d.ts +5 -0
- package/dist/doctor.js +62 -9
- package/dist/hook.js +23 -4
- package/dist/install.d.ts +10 -0
- package/dist/install.js +45 -21
- package/dist/ledger.d.ts +2 -0
- package/dist/mcp.js +5 -5
- package/dist/proxy.d.ts +14 -1
- package/dist/proxy.js +45 -4
- package/dist/savings.d.ts +14 -1
- package/dist/savings.js +3 -10
- package/package.json +1 -1
package/dist/doctor.js
CHANGED
|
@@ -12,8 +12,10 @@ import { accessSync, constants as fsConstants, existsSync, readFileSync } from "
|
|
|
12
12
|
import { homedir, platform } from "node:os";
|
|
13
13
|
import { dirname, join } from "node:path";
|
|
14
14
|
import { fileURLToPath } from "node:url";
|
|
15
|
-
import { ledgerPath } from "./ledger.js";
|
|
15
|
+
import { ledgerPath, readLedger } from "./ledger.js";
|
|
16
16
|
import { loadConfig } from "./config.js";
|
|
17
|
+
import { codexRouting } from "./codexroute.js";
|
|
18
|
+
import { CURSOR_HOOK_EVENTS } from "./install.js";
|
|
17
19
|
import { binOnPath, claudeInstalledCopies, codexMcpEntry, geminiCliPresent, geminiSettingsPath, isEmptyStub, isOurPluginKey, launcherNamesMissingPackage } from "./install.js";
|
|
18
20
|
import { describeDesktopUsage, desktopUsage } from "./desktopusage.js";
|
|
19
21
|
import { withInvocation } from "./invocation.js";
|
|
@@ -287,6 +289,19 @@ export async function runDoctor() {
|
|
|
287
289
|
catch (e) {
|
|
288
290
|
checks.push({ label: "Codex hook", status: "fail", detail: `~/.codex/hooks.json unreadable (${e.message})` });
|
|
289
291
|
}
|
|
292
|
+
// Autopilot reaches Codex through openai_base_url (OPENAI_BASE_URL no
|
|
293
|
+
// longer routes it), and only on an API key.
|
|
294
|
+
const route = codexRouting(homedir());
|
|
295
|
+
const local = route.baseUrl && /^http:\/\/(127\.0\.0\.1|localhost):\d+\/v1\/?$/.test(route.baseUrl);
|
|
296
|
+
if (local && route.auth !== "apikey") {
|
|
297
|
+
checks.push({ label: "Codex autopilot", status: "warn", detail: `openai_base_url points at ${route.baseUrl} while Codex signs in ${route.auth === "chatgpt" ? "with ChatGPT" : "without an API key"}: autopilot routes Codex only on an API key (the proxy relays ChatGPT traffic unedited meanwhile); remove the line from ~/.codex/config.toml` });
|
|
298
|
+
}
|
|
299
|
+
else if (local) {
|
|
300
|
+
checks.push({ label: "Codex autopilot", status: "ok", detail: `Codex (API key) sends its requests through ${route.baseUrl}` });
|
|
301
|
+
}
|
|
302
|
+
else if (process.env.OPENAI_BASE_URL && route.auth === "apikey") {
|
|
303
|
+
checks.push({ label: "Codex autopilot", status: "warn", detail: "OPENAI_BASE_URL is set, but Codex no longer reads it: `context-doctor autopilot on` sets openai_base_url in ~/.codex/config.toml" });
|
|
304
|
+
}
|
|
290
305
|
}
|
|
291
306
|
else {
|
|
292
307
|
checks.push({ label: "Codex", status: "skip", detail: "not detected (ChatGPT's Codex agent, IDE extension or CLI)" });
|
|
@@ -324,19 +339,32 @@ export async function runDoctor() {
|
|
|
324
339
|
else {
|
|
325
340
|
checks.push({ label: "Gemini CLI", status: "skip", detail: "not detected" });
|
|
326
341
|
}
|
|
327
|
-
// Cursor: its agent gets the guidance through
|
|
328
|
-
//
|
|
342
|
+
// Cursor: its agent gets the guidance through native hooks (the Claude
|
|
343
|
+
// Code hook it also runs cannot add context there). Whether the text then
|
|
344
|
+
// reaches the model depends on the Cursor version, and Cursor logs only
|
|
345
|
+
// that the hook ran, so this says what is known rather than "✓".
|
|
329
346
|
if (existsSync(join(homedir(), ".cursor"))) {
|
|
330
347
|
const hooksPath = join(homedir(), ".cursor", "hooks.json");
|
|
331
348
|
try {
|
|
332
349
|
const hooks = readConfig(hooksPath, ["version"]) ?? {};
|
|
333
|
-
const
|
|
350
|
+
const oursIn = (event) => (hooks.hooks?.[event] ?? []).map((e) => e.command ?? "").find((c) => /(cli\.js|context-doctor(\.cmd|\.exe|\.bat)?)"?\s+hook\s*$/.test(c));
|
|
351
|
+
const ours = oursIn("postToolUse");
|
|
334
352
|
const missing = ours ? hookBinaryMissing(ours) : undefined;
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
353
|
+
const fallbacks = CURSOR_HOOK_EVENTS.filter((e) => !oursIn(e));
|
|
354
|
+
if (!ours)
|
|
355
|
+
checks.push(missingHook("Cursor hook", cursorMcp));
|
|
356
|
+
else if (missing)
|
|
357
|
+
checks.push({ label: "Cursor hook", status: "fail", detail: `registered, but ${missing} no longer exists — re-run: context-doctor install` });
|
|
358
|
+
else {
|
|
359
|
+
const v = cursorVersion();
|
|
360
|
+
const delivered = v ? versionAtLeast(v, 3, 17) : undefined;
|
|
361
|
+
const where = `registered in ~/.cursor/hooks.json for ${CURSOR_HOOK_EVENTS.filter((e) => oursIn(e)).join(", ")}`;
|
|
362
|
+
checks.push(delivered === false
|
|
363
|
+
? { label: "Cursor hook", status: "warn", detail: `${where}, but Cursor ${v} drops hook additional_context before the model (confirmed by Cursor staff, March 2026; reported through 3.10): update Cursor to 3.17 or later; until then the MCP tools are the way in` }
|
|
364
|
+
: fallbacks.length
|
|
365
|
+
? { label: "Cursor hook", status: "warn", detail: `${where}; re-run context-doctor install to add ${fallbacks.join(" and ")} (the fallbacks Cursor 3.17+ delivers)` }
|
|
366
|
+
: { label: "Cursor hook", status: "ok", detail: `${where}. ${v ? `Cursor ${v}` : "Cursor 3.17 and later"} attaches their additional_context to the tool result; Cursor does not log what the model saw: in a long chat, ask its agent what context-doctor said` });
|
|
367
|
+
}
|
|
340
368
|
}
|
|
341
369
|
catch (e) {
|
|
342
370
|
checks.push({ label: "Cursor hook", status: "fail", detail: `~/.cursor/hooks.json unreadable (${e.message})` });
|
|
@@ -485,3 +513,28 @@ export async function runDoctor() {
|
|
|
485
513
|
? `No problems; ${warns.length} note(s) marked ! above.`
|
|
486
514
|
: "All good.");
|
|
487
515
|
}
|
|
516
|
+
/** "3.18.25" >= major.minor. */
|
|
517
|
+
function versionAtLeast(v, major, minor) {
|
|
518
|
+
const m = /^(\d+)\.(\d+)/.exec(v);
|
|
519
|
+
if (!m)
|
|
520
|
+
return true;
|
|
521
|
+
return Number(m[1]) > major || (Number(m[1]) === major && Number(m[2]) >= minor);
|
|
522
|
+
}
|
|
523
|
+
/**
|
|
524
|
+
* The Cursor version here: the newest one that ran the hook (its input
|
|
525
|
+
* carries cursor_version, on every platform), else the macOS app bundle.
|
|
526
|
+
*/
|
|
527
|
+
export function cursorVersion() {
|
|
528
|
+
const fromLedger = readLedger().reverse().find((e) => typeof e.cv === "string")?.cv;
|
|
529
|
+
if (fromLedger)
|
|
530
|
+
return fromLedger;
|
|
531
|
+
for (const plist of ["/Applications/Cursor.app/Contents/Info.plist", join(homedir(), "Applications", "Cursor.app", "Contents", "Info.plist")]) {
|
|
532
|
+
try {
|
|
533
|
+
const m = /<key>CFBundleShortVersionString<\/key>\s*<string>([^<]+)<\/string>/.exec(readFileSync(plist, "utf8"));
|
|
534
|
+
if (m)
|
|
535
|
+
return m[1];
|
|
536
|
+
}
|
|
537
|
+
catch { /* not there */ }
|
|
538
|
+
}
|
|
539
|
+
return undefined;
|
|
540
|
+
}
|
package/dist/hook.js
CHANGED
|
@@ -21,7 +21,7 @@ import { profileConversation } from "./profile.js";
|
|
|
21
21
|
import { parseSessionFile } from "./session.js";
|
|
22
22
|
import { formatTokens, CHARS_PER_TOKEN, LARGEST_WINDOW } from "./tokens.js";
|
|
23
23
|
import { ensureProxyUp } from "./autopilot.js";
|
|
24
|
-
import { detectColdResume, renderColdResume, renderColdResumeNotice, sessionWriteMultiplier } from "./coldresume.js";
|
|
24
|
+
import { autoCompactsAt, detectColdResume, renderColdResume, renderColdResumeNotice, resumeVerdict, sessionWriteMultiplier, withResumeVerdict } from "./coldresume.js";
|
|
25
25
|
import { formatUsd, pricingFor } from "./pricing.js";
|
|
26
26
|
import { checkBudget, loadConfig } from "./config.js";
|
|
27
27
|
import { compactFacts, compactInstructions } from "./precompact.js";
|
|
@@ -158,6 +158,15 @@ export async function runHook() {
|
|
|
158
158
|
}
|
|
159
159
|
const input = JSON.parse(await readStdin());
|
|
160
160
|
await heal;
|
|
161
|
+
// A resumed session: Claude Code says whether its cache expired and what
|
|
162
|
+
// re-caching costs. Kept for the first prompt, which decides the offer
|
|
163
|
+
// (an offer before any message would come before the rebuild it prices).
|
|
164
|
+
if (input.hook_event_name === "SessionStart") {
|
|
165
|
+
const verdict = resumeVerdict(input);
|
|
166
|
+
if (verdict && input.session_id)
|
|
167
|
+
writeSessionState(input.session_id, { ...readSessionState(input.session_id), rv: verdict });
|
|
168
|
+
return;
|
|
169
|
+
}
|
|
161
170
|
// Before a compaction: tell the summary what this session cannot lose.
|
|
162
171
|
// Claude Code adds a PreCompact hook's plain-text output to the
|
|
163
172
|
// compaction's instructions (auto and manual alike).
|
|
@@ -178,7 +187,9 @@ export async function runHook() {
|
|
|
178
187
|
// Cursor marks every hook input with cursor_version; any of its events but
|
|
179
188
|
// postToolUse would only spend the once-per-growth warning on output Cursor
|
|
180
189
|
// drops.
|
|
181
|
-
|
|
190
|
+
// postToolUseFailure and sessionStart carry additional_context too: the
|
|
191
|
+
// first serves a chat whose tool calls fail, the second a resumed heavy chat.
|
|
192
|
+
const cursor = input.hook_event_name === "postToolUse" || input.hook_event_name === "postToolUseFailure" || input.hook_event_name === "sessionStart";
|
|
182
193
|
if (input.hook_event_name === "beforeSubmitPrompt" || (input.cursor_version && !cursor))
|
|
183
194
|
return;
|
|
184
195
|
const transcriptPath = input.transcript_path;
|
|
@@ -202,7 +213,15 @@ export async function runHook() {
|
|
|
202
213
|
// Once per idle period; the tail read is ~1 ms and only on large files.
|
|
203
214
|
const notes = [];
|
|
204
215
|
let notice;
|
|
205
|
-
|
|
216
|
+
// Silent when Claude Code compacts this very prompt itself (the context
|
|
217
|
+
// is past its auto-compact window, e.g. one set smaller since): an offer
|
|
218
|
+
// would arrive after the compaction it proposes. Below the window the
|
|
219
|
+
// note tells the model to stay quiet if a compaction came first (seen
|
|
220
|
+
// once in 516 cold returns: a 964k session compacted, then the reply
|
|
221
|
+
// offered /compact on the fresh summary).
|
|
222
|
+
let cold = withResumeVerdict(detectColdResume(transcriptPath), prev.rv);
|
|
223
|
+
if (cold && cold.tokens >= (autoCompactsAt(cold.model ?? input.model) ?? Infinity))
|
|
224
|
+
cold = undefined;
|
|
206
225
|
let cr = prev.cr;
|
|
207
226
|
if (cold && cold.lastReplyAt !== prev.cr) {
|
|
208
227
|
notes.push(renderColdResume(cold));
|
|
@@ -253,7 +272,7 @@ export async function runHook() {
|
|
|
253
272
|
// warning needed 1.4x a size the session no longer had (seen: warned at
|
|
254
273
|
// 843k, compacted, then regrew to 809k without a word).
|
|
255
274
|
writeSessionState(sessionId, { t: shouldWarn ? liveTokens : Math.min(prev.t, liveTokens), b: sizeBytes, cr });
|
|
256
|
-
recordLedger({ ev: "check", sid: sessionId.slice(0, 12), tok: liveTokens, warn: shouldWarn });
|
|
275
|
+
recordLedger({ ev: "check", sid: sessionId.slice(0, 12), tok: liveTokens, warn: shouldWarn, ...(input.cursor_version ? { cv: input.cursor_version } : {}) });
|
|
257
276
|
if (!shouldWarn) {
|
|
258
277
|
emit(notes);
|
|
259
278
|
return;
|
package/dist/install.d.ts
CHANGED
|
@@ -91,6 +91,16 @@ export declare function installStatusLine(): "installed" | "already" | "kept-for
|
|
|
91
91
|
* tool call, which the hook's stat-only fast path and regrowth gate make cheap.
|
|
92
92
|
*/
|
|
93
93
|
export declare function cursorHooksPath(): string;
|
|
94
|
+
export declare const isOurCursorEntry: (e: unknown) => boolean;
|
|
95
|
+
/**
|
|
96
|
+
* Cursor's events whose `additional_context` can reach its agent: after a
|
|
97
|
+
* tool call, after a failed one, and at the start of a chat. Cursor 3.18's
|
|
98
|
+
* agent runtime attaches the first two to the tool result (Cursor confirmed
|
|
99
|
+
* postToolUseFailure delivery in 3.17.8); before 3.17 it dropped postToolUse
|
|
100
|
+
* output (staff-confirmed, March 2026). sessionStart is the documented way
|
|
101
|
+
* to add context to a chat's start, and serves a resumed heavy chat.
|
|
102
|
+
*/
|
|
103
|
+
export declare const CURSOR_HOOK_EVENTS: readonly ["postToolUse", "postToolUseFailure", "sessionStart"];
|
|
94
104
|
export declare function installCursorHook(): string | null;
|
|
95
105
|
export declare function codexDir(): string;
|
|
96
106
|
/**
|
package/dist/install.js
CHANGED
|
@@ -135,7 +135,7 @@ export function claudeInstalledCopies(home = homedir()) {
|
|
|
135
135
|
catch { /* unreadable: not ours to judge here */ }
|
|
136
136
|
try {
|
|
137
137
|
const hooks = readJson(join(home, ".claude", "settings.json")).hooks ?? {};
|
|
138
|
-
if (["UserPromptSubmit", "PreCompact"].some((ev) => (hooks[ev] ?? []).some?.(isOurHookEntry)))
|
|
138
|
+
if (["UserPromptSubmit", "PreCompact", "SessionStart"].some((ev) => (hooks[ev] ?? []).some?.(isOurHookEntry)))
|
|
139
139
|
found.push("hooks in ~/.claude/settings.json");
|
|
140
140
|
}
|
|
141
141
|
catch { /* unreadable */ }
|
|
@@ -306,9 +306,12 @@ function isOurHookEntry(entry) {
|
|
|
306
306
|
function installHook() {
|
|
307
307
|
const settings = join(homedir(), ".claude", "settings.json");
|
|
308
308
|
const path = installHookInto(settings, join(homedir(), ".claude"));
|
|
309
|
-
// The same command also answers PreCompact
|
|
310
|
-
|
|
309
|
+
// The same command also answers PreCompact (what each compaction's summary
|
|
310
|
+
// must keep) and SessionStart (Claude Code's verdict on a resumed cache).
|
|
311
|
+
if (path) {
|
|
311
312
|
installHookInto(settings, join(homedir(), ".claude"), "PreCompact");
|
|
313
|
+
installHookInto(settings, join(homedir(), ".claude"), "SessionStart");
|
|
314
|
+
}
|
|
312
315
|
return path;
|
|
313
316
|
}
|
|
314
317
|
/**
|
|
@@ -350,6 +353,7 @@ function installHookInto(settingsPath, gateDir, event = "UserPromptSubmit") {
|
|
|
350
353
|
function uninstallHook() {
|
|
351
354
|
uninstallHookFrom(join(homedir(), ".claude", "settings.json"), "Claude Code every-prompt hook");
|
|
352
355
|
uninstallHookFrom(join(homedir(), ".claude", "settings.json"), "Claude Code compaction hook", "PreCompact");
|
|
356
|
+
uninstallHookFrom(join(homedir(), ".claude", "settings.json"), "Claude Code session-start hook", "SessionStart");
|
|
353
357
|
uninstallHookFrom(join(homedir(), ".codex", "hooks.json"), "Codex every-prompt hook");
|
|
354
358
|
uninstallHookFrom(geminiSettingsPath(), "Gemini CLI every-prompt hook", "BeforeAgent");
|
|
355
359
|
uninstallCursorHook();
|
|
@@ -365,7 +369,16 @@ function uninstallHook() {
|
|
|
365
369
|
export function cursorHooksPath() {
|
|
366
370
|
return join(homedir(), ".cursor", "hooks.json");
|
|
367
371
|
}
|
|
368
|
-
const isOurCursorEntry = (e) => /(cli\.js|context-doctor(\.cmd|\.exe|\.bat)?)"?\s+hook\s*$/.test(String(e?.command ?? ""));
|
|
372
|
+
export const isOurCursorEntry = (e) => /(cli\.js|context-doctor(\.cmd|\.exe|\.bat)?)"?\s+hook\s*$/.test(String(e?.command ?? ""));
|
|
373
|
+
/**
|
|
374
|
+
* Cursor's events whose `additional_context` can reach its agent: after a
|
|
375
|
+
* tool call, after a failed one, and at the start of a chat. Cursor 3.18's
|
|
376
|
+
* agent runtime attaches the first two to the tool result (Cursor confirmed
|
|
377
|
+
* postToolUseFailure delivery in 3.17.8); before 3.17 it dropped postToolUse
|
|
378
|
+
* output (staff-confirmed, March 2026). sessionStart is the documented way
|
|
379
|
+
* to add context to a chat's start, and serves a resumed heavy chat.
|
|
380
|
+
*/
|
|
381
|
+
export const CURSOR_HOOK_EVENTS = ["postToolUse", "postToolUseFailure", "sessionStart"];
|
|
369
382
|
export function installCursorHook() {
|
|
370
383
|
if (!existsSync(join(homedir(), ".cursor")))
|
|
371
384
|
return null;
|
|
@@ -373,13 +386,18 @@ export function installCursorHook() {
|
|
|
373
386
|
const config = readJson(path);
|
|
374
387
|
config.version = config.version ?? 1;
|
|
375
388
|
config.hooks = config.hooks ?? {};
|
|
376
|
-
const entries = config.hooks.postToolUse ?? [];
|
|
377
389
|
const want = hookCommand();
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
390
|
+
let changed = false;
|
|
391
|
+
for (const event of CURSOR_HOOK_EVENTS) {
|
|
392
|
+
const entries = config.hooks[event] ?? [];
|
|
393
|
+
const ours = entries.filter(isOurCursorEntry);
|
|
394
|
+
if (ours.length === 1 && ours[0].command === want)
|
|
395
|
+
continue; // already correct
|
|
396
|
+
config.hooks[event] = [...entries.filter((e) => !isOurCursorEntry(e)), { command: want, timeout: 10 }];
|
|
397
|
+
changed = true;
|
|
398
|
+
}
|
|
399
|
+
if (changed)
|
|
400
|
+
writeJsonWithBackup(path, config);
|
|
383
401
|
return path;
|
|
384
402
|
}
|
|
385
403
|
function uninstallCursorHook() {
|
|
@@ -387,18 +405,24 @@ function uninstallCursorHook() {
|
|
|
387
405
|
if (!existsSync(path))
|
|
388
406
|
return;
|
|
389
407
|
const config = readJson(path);
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
408
|
+
let removed = false;
|
|
409
|
+
for (const event of CURSOR_HOOK_EVENTS) {
|
|
410
|
+
const entries = config.hooks?.[event];
|
|
411
|
+
if (!entries)
|
|
412
|
+
continue;
|
|
413
|
+
const filtered = entries.filter((e) => !isOurCursorEntry(e));
|
|
414
|
+
if (filtered.length === entries.length)
|
|
415
|
+
continue;
|
|
416
|
+
removed = true;
|
|
417
|
+
if (filtered.length === 0)
|
|
418
|
+
delete config.hooks[event];
|
|
419
|
+
else
|
|
420
|
+
config.hooks[event] = filtered;
|
|
421
|
+
}
|
|
422
|
+
if (!removed)
|
|
395
423
|
return;
|
|
396
|
-
if (filtered.length === 0)
|
|
397
|
-
delete config.hooks.postToolUse;
|
|
398
|
-
else
|
|
399
|
-
config.hooks.postToolUse = filtered;
|
|
400
424
|
writeUninstalled(path, config, ["version"]);
|
|
401
|
-
done("✓ Cursor
|
|
425
|
+
done("✓ Cursor hooks removed");
|
|
402
426
|
}
|
|
403
427
|
function uninstallHookFrom(settingsPath, label, event = "UserPromptSubmit") {
|
|
404
428
|
if (!existsSync(settingsPath))
|
|
@@ -720,7 +744,7 @@ export function runInstall(options = {}) {
|
|
|
720
744
|
try {
|
|
721
745
|
const cursorHook = installCursorHook();
|
|
722
746
|
if (cursorHook)
|
|
723
|
-
console.log(`✓ Cursor
|
|
747
|
+
console.log(`✓ Cursor hooks installed (${cursorHook}: after each tool call, after a failed one, at chat start) — Cursor's agent gets the same guidance in heavy sessions`);
|
|
724
748
|
}
|
|
725
749
|
catch (e) {
|
|
726
750
|
console.error(`✗ Cursor hook: ${e.message}`);
|
package/dist/ledger.d.ts
CHANGED
|
@@ -26,6 +26,8 @@ export interface LedgerEntry {
|
|
|
26
26
|
requests?: number;
|
|
27
27
|
saved?: number;
|
|
28
28
|
model?: string;
|
|
29
|
+
/** The Cursor version that ran the hook (its input's cursor_version), for `doctor`. */
|
|
30
|
+
cv?: string;
|
|
29
31
|
/** rollup only: sums carried forward from entries rotation removed. */
|
|
30
32
|
carried?: CarriedTotals;
|
|
31
33
|
}
|
package/dist/mcp.js
CHANGED
|
@@ -82,11 +82,11 @@ data:
|
|
|
82
82
|
`);if(r.push(`PACKED ~${te(t.packedTokens)} of ~${te(t.totalTokens)} tokens (${n}%) from ${o}: ${t.selected.length} of ${t.chunks.length} chunks`+(t.query?` for "${t.query}"`:"")+`, budget ${te(t.budget)}.`),t.missingIds.length&&r.push(`Unknown ids: ${t.missingIds.join(", ")}.`),t.semanticNote&&r.push(`(${t.semanticNote})`),t.selected.length===0)return r.push("No chunk matched. Choose from the outline by id, or rephrase with words the document would use."),r.push(...Av(t.chunks,e)),r.join(`
|
|
83
83
|
`);for(let i of t.selected)r.push("",`\u2500\u2500 ${i.id} \xB7 L${i.startLine}-${i.endLine}${i.heading?` \xB7 ${i.heading}`:""} \xB7 ~${te(i.tokens)}`,i.text);let s=t.chunks.length-t.selected.length;if(s>0){let i=t.chunks.filter(a=>a.score>0&&!t.selected.includes(a)).sort((a,c)=>c.score-a.score).slice(0,5);r.push("",`Not included: ${s} chunk(s). `+(i.length?`Next best: ${i.map(a=>`${a.id} (${a.heading||`L${a.startLine}`})`).join("; ")}.`:"Ask for the outline to see them."))}return r.join(`
|
|
84
84
|
`)}var Z1=new Set(["node_modules",".git","dist","build",".next","target","__pycache__",".venv","venv","vendor"]),ca={files:500,fileBytes:5*1024*1024,totalBytes:50*1024*1024};function D1(t){try{let e=Nv("git",["-C",t,"ls-files","-z","--cached","--others","--exclude-standard"],{encoding:"utf8",maxBuffer:67108864,timeout:3e4});return e.status!==0||typeof e.stdout!="string"?void 0:e.stdout.split("\0").filter(r=>r&&Mv(wf(t,r))).sort()}catch{return}}function q1(t){let e=Nv("git",["-C",t,"ls-files","-z","--others","--ignored","--exclude-standard","--directory"],{encoding:"utf8",maxBuffer:67108864,timeout:3e4});return e.status===0&&typeof e.stdout=="string"&&e.stdout.length>0}function L1(t,e){let r=Zv(t,e);return r===""||r!==".."&&!r.startsWith(".."+$1)&&!w1(r)}function Lv(t,e=process.cwd()){let r=[],n=[],o=0,s=new Set,i="",a=(c,u)=>{if(r.length>=ca.files){(u||n.length<20)&&n.push(`${c}: over ${ca.files} files`);return}let l;try{l=u?b1(c):_1(c)}catch{n.push(`${c}: not found`);return}if(l.isSymbolicLink()){let h;try{h=bf(c)}catch{return}L1(i,h)||n.push(`${c}: symlink pointing outside the folder (not followed)`);return}if(l.isDirectory()){if(!u&&(Z1.has(Iv(c))||Iv(c).startsWith(".")))return;let h=u?D1(c):void 0;if(h){h.length===0&&q1(c)&&n.push(`${c}: ignored by git (.gitignore); pack reads folders as git does, so ignored files stay out. Name a file to pack it anyway`);for(let y of h)a(wf(c,y),!1);return}for(let y of v1(c).sort())a(wf(c,y),!1);return}if(!l.isFile())return;let d;try{d=bf(c)}catch{d=Ov(c)}if(s.has(d))return;if(l.size>ca.fileBytes||o+l.size>ca.totalBytes){n.push(`${c}: too large (${Math.round(l.size/1024)} KB)`);return}let m=Zv(e,c),p=m&&!m.startsWith("..")?m:c;if(wv.has(jv(c).toLowerCase())){let h=kv(c);"error"in h?n.push(`${c}: ${h.error}`):(o+=l.size,s.add(d),r.push({name:p,text:h.text}));return}let f=x1(c);if(f.subarray(0,8e3).includes(0)){u&&n.push(`${c}: binary (pack reads text, PDF and Word/PowerPoint/ODT files)`);return}o+=l.size,s.add(d),r.push({name:p,text:f.toString("utf8")})};for(let c of t){if(!Mv(c)){n.push(`${c}: not found`);continue}try{i=bf(c)}catch{i=Ov(c)}a(c,!0)}return{sources:r,skipped:n}}var CO=`Context hygiene rules (always on):
|
|
85
|
-
1.
|
|
86
|
-
2.
|
|
87
|
-
3.
|
|
88
|
-
4.
|
|
89
|
-
5.
|
|
85
|
+
1. When asked about tokens, cost, speed or limits, and once at ~30 turns or 3+ large pastes: call profile_context BEFORE answering; act on its top finding. In a chat app pass a \`sketch\` (turns + big blocks). Do not estimate token counts yourself.
|
|
86
|
+
2. Summarize any paste or tool result over ~2k tokens into the points you need; keep it verbatim only to edit or quote it exactly.
|
|
87
|
+
3. Refer to earlier content by name; never re-quote it or inline base64.
|
|
88
|
+
4. To answer from a big file or folder you won't edit, call pack_context with the question; don't read it whole.
|
|
89
|
+
5. If optimize_context returns a pruned-turns digest, write its \u2264150-token summary.`,AO=["dedupe","trim-tool-results","trim-tool-calls","strip-base64","prune-history"];function $0({fileAccess:t=!0}={}){let e=new Xi({name:"context-doctor",version:"0.34.0"},{instructions:CO});return e.tool("profile_context","Profile an LLM conversation or prompt: token breakdown, largest blocks, and findings about wasted context (duplicates, oversized pastes or tool results, base64 blobs, long history). Pass ONE input: `conversation` (full OpenAI/Anthropic JSON or raw text) or `sketch` (chat apps such as Claude Desktop or ChatGPT, where you cannot export the conversation: the turn count plus the few blocks that matter, ~120 tokens). Call it whenever the user asks about token usage, context size, cost, speed or limits, and once on your own when the conversation first passes ~30 turns or 3+ large pastes. Act on the top finding.",{conversation:Y.string().optional().describe("Conversation JSON (OpenAI or Anthropic format, or bare message array) or raw prompt text. Omit in chat apps and pass `sketch`."),sketch:Y.object({turns:Y.number().int().nonnegative().max(1e5).describe("User+assistant exchanges so far"),model:Y.string().optional().describe("Model this chat runs as, e.g. claude-sonnet-5, gpt-5"),blocks:Y.array(Y.object({turn:Y.number().int().positive().max(1e5).describe("1-based turn the block sits in"),kind:Y.enum(["paste","code","tool_result","image","base64","text"]),label:Y.string().describe("Short name you can refer to later, e.g. 'the nginx config'"),approx_tokens:Y.number().positive().max(1e7).optional(),approx_lines:Y.number().positive().max(1e6).optional(),approx_words:Y.number().positive().max(5e6).optional(),approx_chars:Y.number().positive().max(4e7).optional(),repeated:Y.number().int().positive().max(1e3).optional().describe("Times this same content appears (2+ = duplicate)"),stale:Y.boolean().optional().describe("Already acted on; nothing in it is still needed")})).max(500).describe("Only the blocks over ~500 tokens, repeated, or images. Plain turns need not be listed.")}).optional().describe("Coarse description of the conversation for chat apps. One size hint per block: lines for code, words for prose, chars (or tokens) for logs and tool output, which vary most per line."),model:Y.string().optional().describe("Target model name for context-window math, e.g. claude-sonnet-5 or gpt-4o")},{title:"Profile context",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},async({conversation:r,sketch:n,model:o})=>{if(n)return{content:[{type:"text",text:vv({...n,model:n.model??o})}]};if(!r)return{isError:!0,content:[{type:"text",text:"Pass either `conversation` (full JSON or text) or `sketch` (turns + large/repeated blocks). In a chat app, use `sketch`."}]};let s=lv(ev(r),o);return{content:[{type:"text",text:gv(s)}]}}),e.tool("optimize_context","Rewrite a conversation to reclaim tokens with deterministic strategies (dedupe, trim stale tool results, strip base64; prune-history is optional and lossy). Returns the slimmed JSON and a savings summary; no LLM calls. Results over 100k chars are not echoed back (summary and a CLI command instead). Use after profile_context finds waste the user wants fixed. Add prune-history only with the user's consent, then write the replacement summary as the result instructs.",{conversation:Y.string().describe("Conversation JSON (OpenAI or Anthropic format, or bare message array)"),strategies:Y.array(Y.enum(AO)).optional().describe("Default: dedupe, trim-tool-results, strip-base64. Add trim-tool-calls for big inline file writes, prune-history for lossy compaction of old turns."),keep_recent:Y.number().int().nonnegative().optional().describe("Messages at the tail to leave untouched (default 6; 0 = none)"),max_tool_result_tokens:Y.number().int().positive().optional().describe("Token budget for trimmed tool results (default 300)")},{title:"Optimize context",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},async({conversation:r,strategies:n,keep_recent:o,max_tool_result_tokens:s})=>{let i=mv(r,{strategies:n,keepRecent:o,maxToolResultTokens:s}),a=i.tokensBefore-i.tokensAfter;a>0&&oa({ev:"optimize",src:"mcp",saved:a,model:i.conversation?.model});let c=`Saved ~${te(a)} tokens (${te(i.tokensBefore)} \u2192 ${te(i.tokensAfter)}) via ${i.applied.length} change(s):
|
|
90
90
|
`+i.applied.map(m=>`- [${m.strategy}] message #${m.messageIndex}: ${m.note} (~${te(m.tokensSaved)})`).join(`
|
|
91
91
|
`),u=1e5,l=JSON.stringify(i.conversation),d=[{type:"text",text:c},l.length<=u?{type:"text",text:l}:{type:"text",text:`[optimized conversation is ${l.length} chars \u2014 too large to echo into this context. Tell the user the savings above and that \`npx context-doctor optimize <file> --out slim.json\` produces the file directly.]`}];return i.prunedDigest&&d.push({type:"text",text:`ACTION REQUIRED (you, the assistant calling this tool): the pruned turns are digested below. Write a dense factual summary of them (\u2264150 tokens: decisions, current state, open items, key identifiers) and replace the '[context-doctor: ... pruned]' stub message in the conversation above with your summary before presenting the result.
|
|
92
92
|
|
package/dist/proxy.d.ts
CHANGED
|
@@ -46,9 +46,18 @@ export interface ProxyOptions extends OptimizeOptions {
|
|
|
46
46
|
anthropicUpstream?: string;
|
|
47
47
|
openaiUpstream?: string;
|
|
48
48
|
googleUpstream?: string;
|
|
49
|
+
/** Where Codex signed in with ChatGPT is relayed (testing); see the handler. */
|
|
50
|
+
chatgptUpstream?: string;
|
|
51
|
+
/**
|
|
52
|
+
* Add a conversation prompt_cache_key to OpenAI requests that lack one
|
|
53
|
+
* (cachekey.ts). Default: on toward api.openai.com, off toward any other
|
|
54
|
+
* OpenAI-compatible upstream, which may reject the field;
|
|
55
|
+
* CONTEXT_DOCTOR_CACHE_KEY=0 or 1 overrides.
|
|
56
|
+
*/
|
|
57
|
+
promptCacheKey?: boolean;
|
|
49
58
|
}
|
|
50
59
|
/** Reported by /health so `autopilot status` can tell an outdated service from a current one. */
|
|
51
|
-
export declare const PROXY_VERSION = "0.
|
|
60
|
+
export declare const PROXY_VERSION = "0.34.0";
|
|
52
61
|
/**
|
|
53
62
|
* Remove a leading `/t/<token>` from a request path, or return undefined when
|
|
54
63
|
* the prefix is absent or the token differs. The comparison is constant time
|
|
@@ -92,6 +101,10 @@ export interface ProxyStats {
|
|
|
92
101
|
/** Cache reads/writes reported upstream (Anthropic), so autopilot's effect on the cache is visible. */
|
|
93
102
|
upstreamCacheReadTokens: number;
|
|
94
103
|
upstreamCacheWriteTokens: number;
|
|
104
|
+
/** OpenAI's cached_tokens: the part of upstreamInputTokens its responses say was read from cache. */
|
|
105
|
+
openaiCachedTokens: number;
|
|
106
|
+
/** OpenAI requests sent with a conversation prompt_cache_key the proxy added (cachekey.ts). */
|
|
107
|
+
cacheKeysAdded: number;
|
|
95
108
|
autopilot?: {
|
|
96
109
|
enabled: boolean;
|
|
97
110
|
paused: boolean;
|
package/dist/proxy.js
CHANGED
|
@@ -20,8 +20,9 @@ import { formatTokens, CHARS_PER_TOKEN, providerFor } from "./tokens.js";
|
|
|
20
20
|
import { formatUsd, inputCostUsd, pricingFor } from "./pricing.js";
|
|
21
21
|
import { recordLedger } from "./ledger.js";
|
|
22
22
|
import { minCacheableTokens } from "./cacheplan.js";
|
|
23
|
+
import { withPromptCacheKey } from "./cachekey.js";
|
|
23
24
|
/** Reported by /health so `autopilot status` can tell an outdated service from a current one. */
|
|
24
|
-
export const PROXY_VERSION = "0.
|
|
25
|
+
export const PROXY_VERSION = "0.34.0";
|
|
25
26
|
/** Connection-level headers that must not be forwarded. */
|
|
26
27
|
const SKIP_REQUEST_HEADERS = new Set(["host", "content-length", "connection", "transfer-encoding", "accept-encoding", "expect"]);
|
|
27
28
|
const SKIP_RESPONSE_HEADERS = new Set(["content-length", "content-encoding", "transfer-encoding", "connection"]);
|
|
@@ -185,6 +186,9 @@ export function startProxy(opts = {}) {
|
|
|
185
186
|
else
|
|
186
187
|
refusing.add(account);
|
|
187
188
|
};
|
|
189
|
+
const openaiBase = opts.openaiUpstream ?? "https://api.openai.com";
|
|
190
|
+
const keyEnv = process.env.CONTEXT_DOCTOR_CACHE_KEY;
|
|
191
|
+
const addCacheKeys = opts.promptCacheKey ?? (keyEnv === "0" ? false : keyEnv === "1" ? true : /^https:\/\/api\.openai\.com\/?$/.test(openaiBase));
|
|
188
192
|
const stats = {
|
|
189
193
|
startedAt: new Date().toISOString(),
|
|
190
194
|
requests: 0,
|
|
@@ -198,6 +202,8 @@ export function startProxy(opts = {}) {
|
|
|
198
202
|
advice: [],
|
|
199
203
|
upstreamCacheReadTokens: 0,
|
|
200
204
|
upstreamCacheWriteTokens: 0,
|
|
205
|
+
openaiCachedTokens: 0,
|
|
206
|
+
cacheKeysAdded: 0,
|
|
201
207
|
autopilot: opts.autopilot
|
|
202
208
|
? { enabled: true, paused: false, requests: 0, changedRequests: 0, batches: 0, coldBatches: 0, resultsCleared: 0, tokensRemoved: 0, lastReason: "" }
|
|
203
209
|
: undefined,
|
|
@@ -248,7 +254,16 @@ export function startProxy(opts = {}) {
|
|
|
248
254
|
res.end(JSON.stringify({ ...stats, estUsdSaved: Number(stats.estUsdSaved.toFixed(4)) }, null, 2));
|
|
249
255
|
return;
|
|
250
256
|
}
|
|
251
|
-
|
|
257
|
+
// Codex signed in with ChatGPT, reading a config.toml whose
|
|
258
|
+
// openai_base_url points here (the ChatGPT app's Codex tab shares
|
|
259
|
+
// ~/.codex with a CLI on an API key): without its address it would
|
|
260
|
+
// talk to ChatGPT's Codex backend, so it is relayed there byte for
|
|
261
|
+
// byte. Its path loses the /v1 the OpenAI routes carry, and no rule
|
|
262
|
+
// below matches it: it is never edited.
|
|
263
|
+
const chatgpt = typeof req.headers["chatgpt-account-id"] === "string" && url.startsWith("/v1/");
|
|
264
|
+
if (chatgpt)
|
|
265
|
+
url = url.slice(3);
|
|
266
|
+
const upstreamBase = chatgpt ? (opts.chatgptUpstream ?? "https://chatgpt.com/backend-api/codex") : upstreamFor(url, opts, req.headers);
|
|
252
267
|
if (!upstreamBase) {
|
|
253
268
|
res.statusCode = 404;
|
|
254
269
|
res.setHeader("content-type", "application/json");
|
|
@@ -372,7 +387,7 @@ export function startProxy(opts = {}) {
|
|
|
372
387
|
? `the last entry in "tools" (tools come before system in the cached prefix)`
|
|
373
388
|
: `the last block of "system"`;
|
|
374
389
|
advise(`~${stablePrefixTokens}+ tokens of stable system/tools on ${requestModel} without cache_control. ` +
|
|
375
|
-
`Add {"cache_control":{"type":"ephemeral"}} to ${where}; everything before it then bills at
|
|
390
|
+
`Add {"cache_control":{"type":"ephemeral"}} to ${where}; everything before it then bills at the cache-read rate (2.5-10% of input) on every call`);
|
|
376
391
|
}
|
|
377
392
|
const fp = fnv1a(stablePrefix);
|
|
378
393
|
const prev = prefixFingerprints.get(requestModel);
|
|
@@ -399,7 +414,8 @@ export function startProxy(opts = {}) {
|
|
|
399
414
|
const stableTokens = Math.round(stableChars / CHARS_PER_TOKEN[providerFor(requestModel)].code);
|
|
400
415
|
if (stableTokens >= minCacheable) {
|
|
401
416
|
advise(`messages #0-#${stable - 1} (~${stableTokens} tokens) were identical to the previous ${requestModel} request and carry no cache_control. ` +
|
|
402
|
-
`
|
|
417
|
+
`Simplest: a top-level "cache_control":{"type":"ephemeral"} (automatic caching marks the last block and moves it forward each turn); ` +
|
|
418
|
+
`or put {"cache_control":{"type":"ephemeral"}} on the last content block of message #${stable - 1}. That run then reads from cache instead of re-billing each turn`);
|
|
403
419
|
}
|
|
404
420
|
}
|
|
405
421
|
}
|
|
@@ -442,6 +458,18 @@ export function startProxy(opts = {}) {
|
|
|
442
458
|
/* not a conversation payload — forward as-is */
|
|
443
459
|
}
|
|
444
460
|
}
|
|
461
|
+
// A stable prompt_cache_key per conversation, where the app sent none
|
|
462
|
+
// and the model routes by it (GPT before 5.6): its requests then land
|
|
463
|
+
// on one cache. Added after autopilot, so its view of the conversation
|
|
464
|
+
// is the app's own.
|
|
465
|
+
if (addCacheKeys && !chatgpt && req.method === "POST" && body && /^\/v1\/(chat\/completions|responses)(\?|$)/.test(url) && upstreamBase === openaiBase) {
|
|
466
|
+
const keyed = withPromptCacheKey(body);
|
|
467
|
+
if (keyed) {
|
|
468
|
+
body = keyed.body;
|
|
469
|
+
stats.cacheKeysAdded++;
|
|
470
|
+
note += `; prompt_cache_key ${keyed.key.slice(0, 11)}…`;
|
|
471
|
+
}
|
|
472
|
+
}
|
|
445
473
|
const headers = {};
|
|
446
474
|
for (const [key, value] of Object.entries(req.headers)) {
|
|
447
475
|
if (!SKIP_REQUEST_HEADERS.has(key.toLowerCase()) && typeof value === "string")
|
|
@@ -515,6 +543,7 @@ export function startProxy(opts = {}) {
|
|
|
515
543
|
v = Number(m[1]); return v; };
|
|
516
544
|
stats.upstreamCacheReadTokens += lastNum(/"cache_read_input_tokens"\s*:\s*(\d+)/g);
|
|
517
545
|
stats.upstreamCacheWriteTokens += lastNum(/"cache_creation_input_tokens"\s*:\s*(\d+)/g);
|
|
546
|
+
stats.openaiCachedTokens += lastNum(/"cached_tokens"\s*:\s*(\d+)/g);
|
|
518
547
|
}
|
|
519
548
|
}
|
|
520
549
|
res.end();
|
|
@@ -578,6 +607,18 @@ export function startProxy(opts = {}) {
|
|
|
578
607
|
};
|
|
579
608
|
liveServers.add(drain);
|
|
580
609
|
installSignalHandlers();
|
|
610
|
+
// A WebSocket upgrade cannot be relayed (or edited) here. Codex tries
|
|
611
|
+
// Responses over WebSocket first and, on anything but 426, retries five
|
|
612
|
+
// times (~15 s) before it falls back to HTTP; 426 Upgrade Required makes it
|
|
613
|
+
// switch to HTTP for the session at once (codex-rs core/src/client.rs).
|
|
614
|
+
// Answered on the raw socket, which is then closed: handled as an ordinary
|
|
615
|
+
// request, the upgrade left the connection in a state where the client's
|
|
616
|
+
// next request on it never got an answer.
|
|
617
|
+
server.on("upgrade", (_req, socket) => {
|
|
618
|
+
const body = JSON.stringify({ error: "context-doctor proxy: WebSocket transport is not supported here; send the request over HTTP" });
|
|
619
|
+
socket.on("error", () => { });
|
|
620
|
+
socket.end(`HTTP/1.1 426 Upgrade Required\r\nContent-Type: application/json\r\nContent-Length: ${Buffer.byteLength(body)}\r\nConnection: close\r\n\r\n${body}`);
|
|
621
|
+
});
|
|
581
622
|
server.on("close", () => {
|
|
582
623
|
liveServers.delete(drain);
|
|
583
624
|
checkpoint();
|
package/dist/savings.d.ts
CHANGED
|
@@ -63,6 +63,19 @@ export interface SavingsReport {
|
|
|
63
63
|
coldResumes: number;
|
|
64
64
|
coldResumeNetUsd: number;
|
|
65
65
|
}
|
|
66
|
+
/**
|
|
67
|
+
* One arm of the replay: the history as sent, priced incrementally at each
|
|
68
|
+
* request's own model. Reads are priced as they go; writes are kept at the
|
|
69
|
+
* input price and multiplied by the session's write TTL mix at the end
|
|
70
|
+
* (`usd(writeMult)`), since the mix is only known once the whole transcript
|
|
71
|
+
* has been read.
|
|
72
|
+
*/
|
|
73
|
+
/** What an arm needs from a clearer: autopilot's AutoClearer, or the simulated server-side rule (serverclear.ts). */
|
|
74
|
+
export interface ReplayClearer {
|
|
75
|
+
apply(body: Record<string, unknown>, now: number): {
|
|
76
|
+
firstChanged: number;
|
|
77
|
+
};
|
|
78
|
+
}
|
|
66
79
|
/**
|
|
67
80
|
* Replay one Claude Code transcript. Undefined when it holds too few requests
|
|
68
81
|
* to mean anything. `runRows` is shared by every transcript of one report: a
|
|
@@ -71,7 +84,7 @@ export interface SavingsReport {
|
|
|
71
84
|
* `coldRows` does the same for the cold-resume count, which reads the
|
|
72
85
|
* transcript again after the replay has added its rows to `runRows`.
|
|
73
86
|
*/
|
|
74
|
-
export declare function replaySession(path: string, options?: AutoClearOptions, since?: number, runRows?: Set<string>, coldRows?: Set<string
|
|
87
|
+
export declare function replaySession(path: string, options?: AutoClearOptions, since?: number, runRows?: Set<string>, coldRows?: Set<string>, makeClearer?: (model?: string) => ReplayClearer): SessionSavings | undefined;
|
|
75
88
|
export declare function estimateSavings(days?: number, options?: AutoClearOptions, paths?: string[], onProgress?: (done: number, total: number) => void): SavingsReport;
|
|
76
89
|
/** Optional third lever, computed by compactwindow.ts and passed in by the CLI. */
|
|
77
90
|
export interface CompactWindowLine {
|
package/dist/savings.js
CHANGED
|
@@ -33,13 +33,6 @@ export function autopilotReaches(entrypoint) {
|
|
|
33
33
|
}
|
|
34
34
|
/** Without a price on file the arms still need relative weights: Claude's usual 10% read rate. */
|
|
35
35
|
const UNPRICED = { inputPerM: 1, outputPerM: 5, cacheReadPerM: 0.1 };
|
|
36
|
-
/**
|
|
37
|
-
* One arm of the replay: the history as sent, priced incrementally at each
|
|
38
|
-
* request's own model. Reads are priced as they go; writes are kept at the
|
|
39
|
-
* input price and multiplied by the session's write TTL mix at the end
|
|
40
|
-
* (`usd(writeMult)`), since the mix is only known once the whole transcript
|
|
41
|
-
* has been read.
|
|
42
|
-
*/
|
|
43
36
|
function arm(model, clearer) {
|
|
44
37
|
const msgs = [];
|
|
45
38
|
const tok = [];
|
|
@@ -90,9 +83,9 @@ function arm(model, clearer) {
|
|
|
90
83
|
* `coldRows` does the same for the cold-resume count, which reads the
|
|
91
84
|
* transcript again after the replay has added its rows to `runRows`.
|
|
92
85
|
*/
|
|
93
|
-
export function replaySession(path, options = {}, since = 0, runRows, coldRows) {
|
|
86
|
+
export function replaySession(path, options = {}, since = 0, runRows, coldRows, makeClearer = () => new AutoClearer(options)) {
|
|
94
87
|
let model;
|
|
95
|
-
let base = arm(undefined, null), auto = arm(undefined,
|
|
88
|
+
let base = arm(undefined, null), auto = arm(undefined, makeClearer());
|
|
96
89
|
let baseUsd = 0, autoUsd = 0, baseRaw = 0, autoRaw = 0;
|
|
97
90
|
let entrypoint;
|
|
98
91
|
let billed = 0, billedUsd = 0, billedRaw = 0, requests = 0, lastId, lastTs = null;
|
|
@@ -118,7 +111,7 @@ export function replaySession(path, options = {}, since = 0, runRows, coldRows)
|
|
|
118
111
|
// Compaction replaces the history in both arms alike: start fresh.
|
|
119
112
|
flush();
|
|
120
113
|
base = arm(model, null);
|
|
121
|
-
auto = arm(model,
|
|
114
|
+
auto = arm(model, makeClearer(model));
|
|
122
115
|
return;
|
|
123
116
|
}
|
|
124
117
|
if (e.type === "assistant" && e.message) {
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "context-doctor",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.34.0",
|
|
4
4
|
"description": "Context and token optimizer for LLM agents: see where Claude Code, Cursor, Codex and Gemini CLI tokens go, then cut them: an every-prompt hook, smarter compaction, an autopilot proxy that edits history only when the prompt cache is cold, RAG chunk packing and an MCP server. Local, no API key. By gAI Ventures.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"agent",
|