context-doctor 0.42.0 → 0.43.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +4 -2
- package/dist/budget.d.ts +42 -0
- package/dist/budget.js +58 -26
- package/dist/cli.js +27 -6
- package/dist/codexcompact.d.ts +116 -0
- package/dist/codexcompact.js +415 -0
- package/dist/doctor.js +10 -0
- package/dist/fix.d.ts +30 -3
- package/dist/fix.js +193 -11
- package/dist/hook.js +23 -4
- package/dist/ledger.d.ts +2 -1
- package/dist/ledger.js +1 -0
- package/dist/mcp.js +1 -1
- package/dist/proxy.d.ts +1 -1
- package/dist/proxy.js +1 -1
- package/dist/sessionprice.d.ts +71 -0
- package/dist/sessionprice.js +216 -0
- package/dist/tooloutput.d.ts +118 -0
- package/dist/tooloutput.js +355 -0
- package/package.json +1 -1
package/dist/fix.js
CHANGED
|
@@ -24,25 +24,31 @@
|
|
|
24
24
|
* priced);
|
|
25
25
|
* - autopilot: what the proxy recorded saving since (its own ledger);
|
|
26
26
|
* - the subagents' model: the requests it moved, priced at the model they
|
|
27
|
-
* ran on before against as billed (the same token counts: an estimate)
|
|
27
|
+
* ran on before against as billed (the same token counts: an estimate);
|
|
28
|
+
* - long Bash output: the results moved to a file that the cap before left
|
|
29
|
+
* inline, priced at the requests that re-read them no more (an estimate:
|
|
30
|
+
* a file the model opens again is not counted).
|
|
28
31
|
*
|
|
29
32
|
* The subagents' model is the one lever with a quality cost `fix` cannot
|
|
30
33
|
* measure: it is offered with that said, applied only when named (never by
|
|
31
34
|
* `--apply all`), and never over a value the user set.
|
|
32
35
|
*/
|
|
33
|
-
import { existsSync, mkdirSync, readFileSync } from "node:fs";
|
|
36
|
+
import { existsSync, mkdirSync, readFileSync, rmdirSync } from "node:fs";
|
|
37
|
+
import { homedir } from "node:os";
|
|
34
38
|
import { dirname, join } from "node:path";
|
|
35
39
|
import { forEachLine, listSessions, isClaudeSession } from "./session.js";
|
|
36
40
|
import { pricingFor } from "./pricing.js";
|
|
37
41
|
import { contextWindowFor, realModel } from "./tokens.js";
|
|
38
42
|
import { adviseTtl, estimateCacheTtl } from "./cachettl.js";
|
|
39
|
-
import { ABSENT, getPath, parseSettingsText, readSettings, removeFile, sameJson, setJsonPath, SettingsError, settingsLockPath, withLock, writeAtomic } from "./settingsedit.js";
|
|
43
|
+
import { ABSENT, getPath, parseSettingsText, readSettings, removeFile, sameJson, setJsonPath, SettingsError, settingsLockPath, withLock, withSettingsLock, writeAtomic } from "./settingsedit.js";
|
|
40
44
|
import { compactWindowOverrides, processEnvWhere, settingsSources, shellSet, ttlOverrides } from "./effective.js";
|
|
41
45
|
import { tilde } from "./claudedir.js";
|
|
42
46
|
import { applyPrune, undoPrune } from "./prune.js";
|
|
43
|
-
import { readLedger } from "./ledger.js";
|
|
47
|
+
import { fallbackStateDir, readLedger } from "./ledger.js";
|
|
44
48
|
import { claudeDir } from "./claudedir.js";
|
|
45
49
|
import { movedFromNames, renderSubagentTypes, subagentModelSavedSince, SUBAGENT_CANDIDATE, SUBAGENT_CANDIDATE_NAME, SUBAGENT_MODEL_ENV } from "./subagentmodel.js";
|
|
50
|
+
import { BASH_OUTPUT_DEFAULT, BASH_OUTPUT_KEY, breakEven, renderToolOutputCaps, toolOutputSavedSince } from "./tooloutput.js";
|
|
51
|
+
import { CODEX_COMPACT_KEY, CODEX_COMPACT_LIMIT, codexCompactOverrides, codexCompactSavedSince, codexConfigPath, renderCodexLimits, setTopLevelInt, topLevelValue } from "./codexcompact.js";
|
|
46
52
|
/** Below this a priced fix is not worth a setting. */
|
|
47
53
|
const MIN_USD = 1;
|
|
48
54
|
const money = (n) => (n >= 100 ? `$${Math.round(n).toLocaleString("en-US")}` : `$${n.toFixed(2)}`);
|
|
@@ -167,6 +173,53 @@ export function planFixes(i) {
|
|
|
167
173
|
detail: renderSubagentTypes(sm),
|
|
168
174
|
});
|
|
169
175
|
}
|
|
176
|
+
const to = i.toolOutput;
|
|
177
|
+
const toSet = i.toolOutputSet;
|
|
178
|
+
const best = to?.bash.find((b) => b.cap === to.recommended);
|
|
179
|
+
if (toSet) {
|
|
180
|
+
// A cap at or under the default is one: applied. A larger one, or the read-back variable, is a choice to see more: left alone.
|
|
181
|
+
const capped = toSet.name === BASH_OUTPUT_KEY && Number(toSet.value) <= BASH_OUTPUT_DEFAULT;
|
|
182
|
+
const less = best && best.savedUsd >= MIN_USD ? ` (a cap of ${k(best.cap)} characters would have cost ${money(best.savedUsd)} less)` : "";
|
|
183
|
+
fixes.push({ id: "tool-output", title: "Long Bash output", basis: "set", quality: "", change: BASH_OUTPUT_KEY, state: capped ? "applied" : "not-here", note: `${toSet.name}=${toSet.value} in ${toSet.where}${capped ? "" : `: left as you set it${less}`}`, value: toSet.value });
|
|
184
|
+
}
|
|
185
|
+
else if (to && best && best.savedUsd >= MIN_USD && to.billedUsd > 0 && best.savedUsd / to.billedUsd >= 0.02) {
|
|
186
|
+
const each = best.moved ? best.openUsd / best.moved : 0;
|
|
187
|
+
fixes.push({
|
|
188
|
+
id: "tool-output",
|
|
189
|
+
title: `Long Bash output to a file past ${k(best.cap)} characters`,
|
|
190
|
+
savedUsd: best.savedUsd,
|
|
191
|
+
savedShare: best.savedUsd / to.billedUsd,
|
|
192
|
+
// Main conversations and subagents alike: the cap applies to both.
|
|
193
|
+
shareOf: "of input, subagents included",
|
|
194
|
+
basis: `${best.moved.toLocaleString("en-US")} of ${best.results.toLocaleString("en-US")} Bash results were longer; the tokens past a 2,000-character preview priced at each later request that re-read them until a compaction (cache reads, one write); an estimate: a file the model opens again costs about ${money(each)} a time and is not counted, and the saving covers it opening up to ${pct(breakEven(best))} of them`,
|
|
195
|
+
quality: "long output goes to a file the model can still open; it sees the first 2,000 characters and the path, as it already does past 30,000",
|
|
196
|
+
change: `${where}: ${BASH_OUTPUT_KEY} = ${best.cap} (Claude Code 2.1.261+)`,
|
|
197
|
+
state: "available",
|
|
198
|
+
value: best.cap,
|
|
199
|
+
detail: renderToolOutputCaps(to),
|
|
200
|
+
});
|
|
201
|
+
}
|
|
202
|
+
const cx = i.codexCompact;
|
|
203
|
+
const cxOffer = cx?.estimates.find((e) => e.limit === CODEX_COMPACT_LIMIT);
|
|
204
|
+
if (i.codexCompactSet) {
|
|
205
|
+
fixes.push({ id: "codex-compact", title: "Codex: auto-compact limit", basis: "set", quality: "", change: CODEX_COMPACT_KEY, state: "applied", note: `${CODEX_COMPACT_KEY} = ${i.codexCompactSet.raw} in ${i.codexCompactSet.where}`, value: i.codexCompactSet.raw });
|
|
206
|
+
}
|
|
207
|
+
else if (cx && cxOffer && cxOffer.savedUsd >= MIN_USD && cxOffer.savedShare >= 0.02) {
|
|
208
|
+
const weeks = cx.days / 7;
|
|
209
|
+
fixes.push({
|
|
210
|
+
id: "codex-compact",
|
|
211
|
+
title: `Codex: compact earlier, at ${k(CODEX_COMPACT_LIMIT)} tokens`,
|
|
212
|
+
savedUsd: cxOffer.savedUsd,
|
|
213
|
+
savedShare: cxOffer.savedShare,
|
|
214
|
+
shareOf: "of Codex input",
|
|
215
|
+
basis: `your ${cx.requests.toLocaleString("en-US")} Codex requests replayed at a ${k(CODEX_COMPACT_LIMIT)} limit: ${(cxOffer.compactions / weeks).toFixed(1)} compactions a week instead of ${(cx.actualCompactions / weeks).toFixed(1)}, each paying a request and a ${k(5_000)}-token summary (an estimate: Codex does not record its compactions' own usage)`,
|
|
216
|
+
quality: "each compaction replaces the history with a summary: detail for money",
|
|
217
|
+
change: `${tilde(codexConfigPath())}: ${CODEX_COMPACT_KEY} = ${CODEX_COMPACT_LIMIT}`,
|
|
218
|
+
state: "available",
|
|
219
|
+
value: CODEX_COMPACT_LIMIT,
|
|
220
|
+
detail: renderCodexLimits(cx, CODEX_COMPACT_LIMIT),
|
|
221
|
+
});
|
|
222
|
+
}
|
|
170
223
|
for (const f of fixes) {
|
|
171
224
|
const o = i.overrides?.[f.id];
|
|
172
225
|
if (o?.length && f.state === "available")
|
|
@@ -175,12 +228,26 @@ export function planFixes(i) {
|
|
|
175
228
|
const rank = (f) => (f.state === "available" ? 0 : f.state === "applied" ? 2 : 3) + (f.savedUsd === undefined ? 1 : 0);
|
|
176
229
|
return fixes.sort((a, b) => rank(a) - rank(b) || (b.savedUsd ?? 0) - (a.savedUsd ?? 0));
|
|
177
230
|
}
|
|
231
|
+
const RECORD_FILE = ".context-doctor-fixes.json";
|
|
232
|
+
/**
|
|
233
|
+
* ~/.claude/.context-doctor-fixes.json, as always. On a machine with no
|
|
234
|
+
* ~/.claude (Codex only), the state folder the ledger falls back to: `fix`
|
|
235
|
+
* must not make a ~/.claude there. Once records are in that folder they stay
|
|
236
|
+
* there, so a Claude Code installed later does not strand them.
|
|
237
|
+
*/
|
|
178
238
|
export function fixRecordPath(home) {
|
|
179
|
-
|
|
239
|
+
const claude = claudeDir(home);
|
|
240
|
+
const own = join(claude, RECORD_FILE);
|
|
241
|
+
const fallback = join(home === undefined || home === homedir() ? fallbackStateDir() : join(home, ".local", "state", "context-doctor"), RECORD_FILE);
|
|
242
|
+
if (existsSync(own))
|
|
243
|
+
return own;
|
|
244
|
+
if (existsSync(fallback))
|
|
245
|
+
return fallback;
|
|
246
|
+
return existsSync(claude) ? own : fallback;
|
|
180
247
|
}
|
|
181
|
-
/** The lock of the user's settings.json, which cache-ttl, compact-window and autopilot take too. */
|
|
248
|
+
/** The lock beside the records: in ~/.claude, the one of the user's settings.json, which cache-ttl, compact-window and autopilot take too. */
|
|
182
249
|
function lockPath(home) {
|
|
183
|
-
return settingsLockPath(
|
|
250
|
+
return settingsLockPath(fixRecordPath(home));
|
|
184
251
|
}
|
|
185
252
|
/**
|
|
186
253
|
* The records, strictly: an absent file is none; a file that is not ours to
|
|
@@ -223,11 +290,17 @@ const KEY_PATH = {
|
|
|
223
290
|
"cache-ttl-subagents": ["subagentPromptCacheTtl"],
|
|
224
291
|
"tool-search": ["env", "ENABLE_TOOL_SEARCH"],
|
|
225
292
|
"subagent-model": ["env", SUBAGENT_MODEL_ENV],
|
|
293
|
+
"tool-output": [BASH_OUTPUT_KEY],
|
|
226
294
|
};
|
|
295
|
+
/** Fixes that never overwrite a value already there: the user set it. */
|
|
296
|
+
const YOURS = new Set(["subagent-model", "tool-output"]);
|
|
227
297
|
/** Fixes with a quality cost not measured here: applied only when named, never by `--apply all`. */
|
|
228
298
|
const NAMED_ONLY = new Set(["subagent-model"]);
|
|
229
299
|
/** What would keep this fix's value from taking effect, as Claude Code merges settings. */
|
|
230
300
|
export function fixOverrides(id, deps = {}) {
|
|
301
|
+
// Codex reads its own config.toml: a profile's value, or a project's file.
|
|
302
|
+
if (id === "codex-compact")
|
|
303
|
+
return codexCompactOverrides(deps.home, deps.cwd);
|
|
231
304
|
const env = deps.env ?? process.env;
|
|
232
305
|
const sources = settingsSources({ home: deps.home, cwd: deps.cwd, env });
|
|
233
306
|
if (id === "compact-window")
|
|
@@ -251,6 +324,10 @@ export function fixOverrides(id, deps = {}) {
|
|
|
251
324
|
out.push(`${SUBAGENT_MODEL_ENV}=${s.settings.env[SUBAGENT_MODEL_ENV]} in ${tilde(s.path)} env`);
|
|
252
325
|
return out;
|
|
253
326
|
}
|
|
327
|
+
if (id === "tool-output") {
|
|
328
|
+
// Merged settings: a project's or managed value wins over the user's (BASH_MAX_OUTPUT_LENGTH does not: the setting replaces it).
|
|
329
|
+
return sources.filter((s) => s.name !== "user" && s.settings[BASH_OUTPUT_KEY] !== undefined).map((s) => `${BASH_OUTPUT_KEY} ${JSON.stringify(s.settings[BASH_OUTPUT_KEY])} in ${tilde(s.path)}`);
|
|
330
|
+
}
|
|
254
331
|
return [];
|
|
255
332
|
}
|
|
256
333
|
/** Set one key of the user's settings.json, under the lock, and record it (the first record's previous value is kept). */
|
|
@@ -270,7 +347,7 @@ function applySetting(fix, home, at, extra) {
|
|
|
270
347
|
if (sameJson(now, fix.value))
|
|
271
348
|
return [`${key.join(".")} is already ${JSON.stringify(fix.value)} in ${tilde(file)}: nothing to change.`];
|
|
272
349
|
const old = records.find((r) => r.id === fix.id);
|
|
273
|
-
if (
|
|
350
|
+
if (YOURS.has(fix.id) && now !== undefined && !old)
|
|
274
351
|
throw new SettingsError(`${key.join(".")} is ${JSON.stringify(now)} in ${tilde(file)}, a value you set: left as it is. Nothing was changed.`);
|
|
275
352
|
const after = setJsonPath(cur.text, key, fix.value);
|
|
276
353
|
writeAtomic(file, after);
|
|
@@ -294,6 +371,84 @@ function applySetting(fix, home, at, extra) {
|
|
|
294
371
|
return [`✓ ${fix.change}`];
|
|
295
372
|
});
|
|
296
373
|
}
|
|
374
|
+
/**
|
|
375
|
+
* Set Codex's limit at the top of config.toml, under the records' lock and
|
|
376
|
+
* config.toml's own, and record it. A value already there is the user's:
|
|
377
|
+
* refused. The file's other bytes are left as they were.
|
|
378
|
+
*/
|
|
379
|
+
function applyCodexCompact(fix, home, at) {
|
|
380
|
+
const file = codexConfigPath(home);
|
|
381
|
+
const recordDir = dirname(fixRecordPath(home));
|
|
382
|
+
const made = !existsSync(recordDir);
|
|
383
|
+
mkdirSync(recordDir, { recursive: true });
|
|
384
|
+
try {
|
|
385
|
+
return withLock(lockPath(home), () => withSettingsLock(file, () => {
|
|
386
|
+
const records = loadFixRecords(home);
|
|
387
|
+
let text;
|
|
388
|
+
try {
|
|
389
|
+
text = readFileSync(file, "utf8");
|
|
390
|
+
}
|
|
391
|
+
catch (e) {
|
|
392
|
+
if (e.code !== "ENOENT")
|
|
393
|
+
throw e;
|
|
394
|
+
}
|
|
395
|
+
const now = text === undefined ? undefined : topLevelValue(text);
|
|
396
|
+
const old = records.find((r) => r.id === fix.id);
|
|
397
|
+
if (now?.value === fix.value)
|
|
398
|
+
return [`${CODEX_COMPACT_KEY} is already ${fix.value} in ${tilde(file)}: nothing to change.`];
|
|
399
|
+
if (now && !old)
|
|
400
|
+
throw new SettingsError(`${CODEX_COMPACT_KEY} is ${now.raw} in ${tilde(file)}, a value you set: left as it is. Nothing was changed.`);
|
|
401
|
+
const after = setTopLevelInt(text, CODEX_COMPACT_KEY, Number(fix.value));
|
|
402
|
+
writeAtomic(file, after);
|
|
403
|
+
const before = text ?? null;
|
|
404
|
+
const rec = {
|
|
405
|
+
id: fix.id, at: old?.at ?? at, value: fix.value, file, key: [CODEX_COMPACT_KEY],
|
|
406
|
+
previous: old ? old.previous : now?.raw,
|
|
407
|
+
hadPrevious: old ? old.hadPrevious : now !== undefined,
|
|
408
|
+
before: old ? (old.after === before ? old.before : undefined) : before,
|
|
409
|
+
after,
|
|
410
|
+
};
|
|
411
|
+
writeFixRecords([...records.filter((r) => r.id !== fix.id), rec], home);
|
|
412
|
+
return [`✓ ${fix.change}`];
|
|
413
|
+
}));
|
|
414
|
+
}
|
|
415
|
+
catch (e) {
|
|
416
|
+
// A folder made for the record of a change that did not happen goes again.
|
|
417
|
+
if (made)
|
|
418
|
+
try {
|
|
419
|
+
rmdirSync(recordDir);
|
|
420
|
+
}
|
|
421
|
+
catch { /* it holds something */ }
|
|
422
|
+
throw e;
|
|
423
|
+
}
|
|
424
|
+
}
|
|
425
|
+
/** Undo Codex's limit: the whole file back when nothing touched it since, else the key, if it still holds fix's value. */
|
|
426
|
+
function undoCodexCompact(r, home) {
|
|
427
|
+
const file = r.file ?? codexConfigPath(home);
|
|
428
|
+
return withSettingsLock(file, () => {
|
|
429
|
+
let text;
|
|
430
|
+
try {
|
|
431
|
+
text = readFileSync(file, "utf8");
|
|
432
|
+
}
|
|
433
|
+
catch (e) {
|
|
434
|
+
if (e.code !== "ENOENT")
|
|
435
|
+
throw e;
|
|
436
|
+
}
|
|
437
|
+
if (r.after !== undefined && r.before !== undefined && text === r.after) {
|
|
438
|
+
if (r.before === null)
|
|
439
|
+
removeFile(file);
|
|
440
|
+
else
|
|
441
|
+
writeAtomic(file, r.before);
|
|
442
|
+
return `✓ ${CODEX_COMPACT_KEY} ${r.hadPrevious ? `back to ${r.previous}` : "removed"}${r.before === null ? ` (and the ${tilde(file)} fix created)` : ""}`;
|
|
443
|
+
}
|
|
444
|
+
const now = text === undefined ? undefined : topLevelValue(text);
|
|
445
|
+
if (now?.value !== r.value)
|
|
446
|
+
return `– ${CODEX_COMPACT_KEY} was changed since fix set it (now ${now ? now.raw : "not set"}): left as it is`;
|
|
447
|
+
const prev = r.hadPrevious ? Number(String(r.previous).replace(/_/g, "")) : undefined;
|
|
448
|
+
writeAtomic(file, setTopLevelInt(text, CODEX_COMPACT_KEY, prev !== undefined && Number.isFinite(prev) ? prev : undefined));
|
|
449
|
+
return `✓ ${CODEX_COMPACT_KEY} ${r.hadPrevious ? `back to ${r.previous}` : "removed"}`;
|
|
450
|
+
});
|
|
451
|
+
}
|
|
297
452
|
/** Apply one fix; record it unless it changed nothing. Refusals (a damaged settings file, a damaged record) change nothing. */
|
|
298
453
|
export async function applyFix(fix, deps = {}, context = {}) {
|
|
299
454
|
const home = deps.home;
|
|
@@ -314,6 +469,13 @@ export async function applyFix(fix, deps = {}, context = {}) {
|
|
|
314
469
|
lines.push(` ⚠ written, but it will not take effect while ${over.join("; ")} ${over.length === 1 ? "overrides" : "override"} it.`);
|
|
315
470
|
return { ok: over.length === 0, lines };
|
|
316
471
|
}
|
|
472
|
+
if (fix.id === "codex-compact") {
|
|
473
|
+
const lines = applyCodexCompact(fix, home, at);
|
|
474
|
+
const over = fixOverrides(fix.id, deps);
|
|
475
|
+
if (over.length)
|
|
476
|
+
lines.push(` ⚠ written, but it will not take effect while ${over.join("; ")} ${over.length === 1 ? "sets" : "set"} it too.`);
|
|
477
|
+
return { ok: over.length === 0, lines };
|
|
478
|
+
}
|
|
317
479
|
if (fix.id === "autopilot") {
|
|
318
480
|
if (!deps.autopilotOn)
|
|
319
481
|
return { ok: false, lines: ["autopilot: run context-doctor autopilot on"] };
|
|
@@ -414,6 +576,9 @@ export async function undoFixes(ids, deps = {}) {
|
|
|
414
576
|
if (KEY_PATH[r.id]) {
|
|
415
577
|
lines.push(withLock(lockPath(home), () => undoSetting(r, home)));
|
|
416
578
|
}
|
|
579
|
+
else if (r.id === "codex-compact") {
|
|
580
|
+
lines.push(withLock(lockPath(home), () => undoCodexCompact(r, home)));
|
|
581
|
+
}
|
|
417
582
|
else if (r.id === "autopilot") {
|
|
418
583
|
if (deps.autopilotOff)
|
|
419
584
|
lines.push(...(await deps.autopilotOff()));
|
|
@@ -542,6 +707,15 @@ export function savedSince(records, opts = {}) {
|
|
|
542
707
|
const s = subagentModelSavedSince(r.at, r.modelsBefore, opts.subagentPaths);
|
|
543
708
|
out.push({ id: r.id, at: r.at, savedUsd: s.requests ? s.usd : undefined, detail: s.requests ? `estimated: ${s.requests.toLocaleString("en-US")} subagent requests, priced at the model they ran on before (${movedFromNames(r.modelsBefore ?? {})}) against as billed, the same token counts` : r.modelsBefore ? "no subagent requests it moves yet" : "applied; not priced" });
|
|
544
709
|
}
|
|
710
|
+
else if (r.id === "codex-compact") {
|
|
711
|
+
const c = codexCompactSavedSince(r.at, typeof r.previous === "string" && Number.isFinite(Number(r.previous.replace(/_/g, ""))) ? Number(r.previous.replace(/_/g, "")) : undefined, opts.codexPaths);
|
|
712
|
+
out.push({ id: r.id, at: r.at, savedUsd: c.compactions ? c.usd : undefined, detail: c.compactions ? `${c.compactions} earlier Codex compaction${c.compactions === 1 ? "" : "s"}, the context each removed from later requests (estimated; what the summary dropped is not priced)` : "no earlier Codex compaction yet" });
|
|
713
|
+
}
|
|
714
|
+
else if (r.id === "tool-output") {
|
|
715
|
+
const paths = opts.paths || opts.subagentPaths ? [...(opts.paths ?? []), ...(opts.subagentPaths ?? [])] : undefined;
|
|
716
|
+
const s = toolOutputSavedSince(r.at, typeof r.previous === "number" ? r.previous : BASH_OUTPUT_DEFAULT, paths);
|
|
717
|
+
out.push({ id: r.id, at: r.at, savedUsd: s.moved ? s.savedUsd : undefined, detail: s.moved ? `estimated: ${s.moved.toLocaleString("en-US")} Bash results moved to a file that were inline before, priced at the requests that would have re-read them; files the model opened again not counted` : "no Bash output over the cap since" });
|
|
718
|
+
}
|
|
545
719
|
else if (r.id === "autopilot") {
|
|
546
720
|
const ledger = opts.ledger ?? readLedger();
|
|
547
721
|
const ev = ledger.filter((e) => e.ev === "proxy" && e.ts >= r.at);
|
|
@@ -563,18 +737,26 @@ const LABEL = {
|
|
|
563
737
|
"tool-search": "MCP tool search",
|
|
564
738
|
prune: "Unused MCP servers and skills",
|
|
565
739
|
"subagent-model": "Subagent model",
|
|
740
|
+
"tool-output": "Long Bash output",
|
|
741
|
+
"codex-compact": "Codex auto-compact limit",
|
|
566
742
|
};
|
|
567
|
-
export function renderFixPlan(days, billedUsd, fixes, since, command = (s) => `context-doctor ${s}`, coldResume, recordProblem) {
|
|
743
|
+
export function renderFixPlan(days, billedUsd, fixes, since, command = (s) => `context-doctor ${s}`, coldResume, recordProblem, codexBilledUsd = 0) {
|
|
568
744
|
const out = [];
|
|
569
745
|
if (recordProblem)
|
|
570
746
|
out.push(`⚠ ${recordProblem}`);
|
|
571
747
|
out.push("context-doctor fix: what to change, ranked by what it saves you");
|
|
572
|
-
|
|
748
|
+
// Codex's input named beside Claude Code's when there is some; alone on a machine with only Codex.
|
|
749
|
+
if (codexBilledUsd > 0 && billedUsd > 0)
|
|
750
|
+
out.push(`Last ${days} days of your sessions: Claude Code ${money(billedUsd)} of input, Codex ${money(codexBilledUsd)}, at list prices`);
|
|
751
|
+
else if (codexBilledUsd > 0)
|
|
752
|
+
out.push(`Last ${days} days of your Codex sessions, ${money(codexBilledUsd)} of input at list prices`);
|
|
753
|
+
else
|
|
754
|
+
out.push(`Last ${days} days of your Claude Code sessions, ${money(billedUsd)} of input at list prices`);
|
|
573
755
|
out.push("─".repeat(66));
|
|
574
756
|
const avail = fixes.filter((f) => f.state === "available");
|
|
575
757
|
// No input billed: there is no history to measure, which is not "all applied".
|
|
576
758
|
if (avail.length === 0)
|
|
577
|
-
out.push(...(billedUsd > 0 ? ["Nothing left to fix here: every lever that pays on your history is applied."] : noHistory(days, command)));
|
|
759
|
+
out.push(...(billedUsd + codexBilledUsd > 0 ? ["Nothing left to fix here: every lever that pays on your history is applied."] : noHistory(days, command)));
|
|
578
760
|
avail.forEach((f, n) => {
|
|
579
761
|
const usd = f.savedUsd !== undefined ? `${money(f.savedUsd)}${share(f)}` : "not priced";
|
|
580
762
|
const head = `${n + 1}. ${f.title}`;
|
package/dist/hook.js
CHANGED
|
@@ -29,6 +29,7 @@ import { compactFacts, compactInstructions } from "./precompact.js";
|
|
|
29
29
|
import { fanoutHook, subagentCosts } from "./fanout.js";
|
|
30
30
|
import { claudeDir } from "./claudedir.js";
|
|
31
31
|
import { budgetVerdict } from "./budget.js";
|
|
32
|
+
import { renderSessionPrice, sessionPriceDue } from "./sessionprice.js";
|
|
32
33
|
/** Default nudge threshold; a project budget or env var can lower/raise it. */
|
|
33
34
|
const DEFAULT_WARN_TOKENS = 80_000;
|
|
34
35
|
/**
|
|
@@ -168,9 +169,10 @@ export function hookInput(raw) {
|
|
|
168
169
|
return out;
|
|
169
170
|
}
|
|
170
171
|
export async function runHook(app) {
|
|
171
|
-
// The spend budget's line for this prompt
|
|
172
|
-
//
|
|
173
|
-
// failure must still let it out, or it was lost for
|
|
172
|
+
// The spend budget's line for this prompt (and the session price's), until
|
|
173
|
+
// it is written. Each threshold is recorded as said before the rest of the
|
|
174
|
+
// hook runs, so a later failure must still let it out, or it was lost for
|
|
175
|
+
// the whole period (or session).
|
|
174
176
|
let budgetNote;
|
|
175
177
|
// A hook must never break the user's prompt: any failure exits silently.
|
|
176
178
|
try {
|
|
@@ -284,6 +286,22 @@ export async function runHook(app) {
|
|
|
284
286
|
}
|
|
285
287
|
budgetNote = v?.message;
|
|
286
288
|
}
|
|
289
|
+
// A session's own price (sessionprice.ts): once when it passes $25, $100
|
|
290
|
+
// and $500, a line to the user beside the budget's. Claimed before the
|
|
291
|
+
// rest of the hook runs, so it rides in `budgetNote` like the budget's.
|
|
292
|
+
let priceCold = false;
|
|
293
|
+
if (!cursor && (input.hook_event_name === undefined || input.hook_event_name === "UserPromptSubmit" || input.hook_event_name === "BeforeAgent") && input.transcript_path && existsSync(input.transcript_path)) {
|
|
294
|
+
try {
|
|
295
|
+
const sid = input.session_id ?? input.conversation_id ?? input.transcript_path;
|
|
296
|
+
const p = sessionPriceDue({ sessionId: sid, transcript: input.transcript_path, event: input.hook_event_name, model: input.model, rv: () => readSessionState(sid).rv });
|
|
297
|
+
if (p) {
|
|
298
|
+
budgetNote = [budgetNote, renderSessionPrice(p)].filter(Boolean).join("\n");
|
|
299
|
+
priceCold = p.coldUsd !== undefined;
|
|
300
|
+
recordLedger({ ev: "session_price", sid: sid.slice(0, 12), usd: Math.round(p.usd * 100) / 100, ...(p.tokens !== undefined ? { tok: p.tokens } : {}), ...(p.model ? { model: p.model } : {}) });
|
|
301
|
+
}
|
|
302
|
+
}
|
|
303
|
+
catch { /* never worth a prompt */ }
|
|
304
|
+
}
|
|
287
305
|
const sayBudget = () => { if (budgetNote)
|
|
288
306
|
console.log(JSON.stringify({ systemMessage: budgetNote })); budgetNote = undefined; };
|
|
289
307
|
const transcriptPath = input.transcript_path;
|
|
@@ -323,7 +341,8 @@ export async function runHook(app) {
|
|
|
323
341
|
let cr = prev.cr;
|
|
324
342
|
if (cold && cold.lastReplyAt !== prev.cr) {
|
|
325
343
|
notes.push(renderColdResume(cold));
|
|
326
|
-
|
|
344
|
+
// The session price's line already said this message re-writes the cache: once is enough.
|
|
345
|
+
notice = [budgetNote, priceCold ? undefined : renderColdResumeNotice(cold)].filter(Boolean).join("\n");
|
|
327
346
|
cr = cold.lastReplyAt;
|
|
328
347
|
recordLedger({ ev: "cold_resume", sid: sessionId.slice(0, 12), tok: cold.tokens, model: cold.model });
|
|
329
348
|
}
|
package/dist/ledger.d.ts
CHANGED
|
@@ -10,6 +10,7 @@
|
|
|
10
10
|
* proxy — proxy savings checkpoint {ev: "proxy", saved, usd?, requests?}
|
|
11
11
|
* rollup — totals folded in on rotation {ev: "rollup", ...carried sums}
|
|
12
12
|
* session_rules — a Copilot session start got the standing rules {ev: "session_rules", app}
|
|
13
|
+
* session_price — the hook said a session passed a price threshold {ev: "session_price", sid, usd, tok?, model?}
|
|
13
14
|
*
|
|
14
15
|
* The ledger is capped, and everything it feeds is a LIFETIME total. Simply
|
|
15
16
|
* dropping old lines made those totals go backwards — measured: 1,692,000
|
|
@@ -18,7 +19,7 @@
|
|
|
18
19
|
*/
|
|
19
20
|
export interface LedgerEntry {
|
|
20
21
|
ts: number;
|
|
21
|
-
ev?: "check" | "optimize" | "proxy" | "rollup" | "cold_resume" | "precompact" | "session_rules";
|
|
22
|
+
ev?: "check" | "optimize" | "proxy" | "rollup" | "cold_resume" | "precompact" | "session_rules" | "session_price";
|
|
22
23
|
sid?: string;
|
|
23
24
|
tok?: number;
|
|
24
25
|
warn?: boolean;
|
package/dist/ledger.js
CHANGED
|
@@ -10,6 +10,7 @@
|
|
|
10
10
|
* proxy — proxy savings checkpoint {ev: "proxy", saved, usd?, requests?}
|
|
11
11
|
* rollup — totals folded in on rotation {ev: "rollup", ...carried sums}
|
|
12
12
|
* session_rules — a Copilot session start got the standing rules {ev: "session_rules", app}
|
|
13
|
+
* session_price — the hook said a session passed a price threshold {ev: "session_price", sid, usd, tok?, model?}
|
|
13
14
|
*
|
|
14
15
|
* The ledger is capped, and everything it feeds is a LIFETIME total. Simply
|
|
15
16
|
* dropping old lines made those totals go backwards — measured: 1,692,000
|
package/dist/mcp.js
CHANGED
|
@@ -107,7 +107,7 @@ data:
|
|
|
107
107
|
${i.text.slice(-e)}`,masked:r.count+i.count+o}}function Ox(t,e){let r=e??{},n=["command","file_path","path","pattern","url","query","cmd","description","prompt"].find(s=>typeof r[s]=="string"),o=n?String(r[n]):typeof e=="string"?e:JSON.stringify(e??"");return`${t}: ${o.slice(0,2e3)}`}function sN(t,e=rN){let r=[],n=0,o=0,s=0,i=0,a=/[\\/]subagents[\\/]agent-[^\\/]*\.jsonl$/.test(t)||void 0,c=new Map,u=(m,p,f)=>{let g=f.trim();if(!g)return;s++;let h=nN(g);for(r.push({n:s,at:typeof m=="string"?m:void 0,kind:p,raw:h,compactedBy:0,c:i}),o+=Ax(h);o>e&&n<r.length-1;)o-=Ax(r[n].raw),r[n].raw={whole:""},n++;n>1024&&(r.splice(0,n),n=0),c.size>1e5&&c.clear()};Ep(t,m=>{let p;try{p=JSON.parse(m)}catch{return}if(!p||typeof p!="object")return;if(p.payload&&typeof p.payload=="object"&&typeof p.type=="string"&&!p.message){let h=p.payload;if(p.type==="compacted"||h.type==="context_compacted"){i++;return}if(p.type!=="response_item")return;if(h.type==="message"&&(h.role==="user"||h.role==="assistant"))return u(p.timestamp,h.role,zp(h.content));if(h.type==="function_call"||h.type==="custom_tool_call"||h.type==="local_shell_call"){let _=String(h.name??(h.type==="local_shell_call"?"shell":h.type));typeof h.call_id=="string"&&c.set(h.call_id,_);let v=h.arguments??h.input??h.action;if(typeof v=="string")try{v=JSON.parse(v)}catch{}return u(p.timestamp,"tool call",Ox(_,v))}return/_call_output$/.test(String(h.type))?u(p.timestamp,`tool output (${c.get(h.call_id)??"tool"})`,zp(h.output)):void 0}if(p.type==="system"&&p.subtype==="compact_boundary"){i++;return}if(p.isCompactSummary)return;let f=p.message;if(!f||(a===void 0&&(a=p.isSidechain===!0),p.isSidechain&&!a))return;let g=f.content;if(p.type==="user"){if(typeof g=="string")return u(p.timestamp,"user",g);if(!Array.isArray(g))return;for(let h of g)h?.type==="tool_result"?u(p.timestamp,`tool output (${c.get(h.tool_use_id)??"tool"})`,zp(h.content)):typeof h?.text=="string"&&u(p.timestamp,"user",h.text);return}if(p.type==="assistant"&&Array.isArray(g))for(let h of g)h?.type==="text"?u(p.timestamp,"assistant",String(h.text??"")):h?.type==="tool_use"&&(typeof h.id=="string"&&c.set(h.id,String(h.name??"tool")),u(p.timestamp,"tool call",Ox(String(h.name??"tool"),h.input)))});let l=0;return{entries:r.slice(n).map(({c:m,raw:p,...f})=>{let g=oN(p);return l+=g.masked,{...f,text:g.text,compactedBy:i-m}}),total:s,compactions:i,masked:l}}function iN(t){try{let e=YO(t,"r");try{let r=Buffer.alloc(65536),n=QO(e,r,0,r.length,0),o=r.subarray(0,n).toString("utf8").split(`
|
|
108
108
|
`)[0],s=JSON.parse(o)?.payload?.cwd;return typeof s=="string"?s:void 0}finally{XO(e)}}catch{return}}function Nx(t){let e;try{for(let r of Wa(t)){if(!r.endsWith(".jsonl"))continue;let n=vn(t,r),o=Rp(n).mtimeMs;(!e||o>e.at)&&(e={path:n,at:o})}}catch{}return e}function aN(t,e){let r=vn(Va(e),"sessions");if(!Ja(r))return;let n=Date.now()-7*864e5,o=[],s=(i,a)=>{let c;try{c=Wa(i)}catch{return}for(let u of c){let l=vn(i,u),d;try{d=Rp(l)}catch{continue}d.isDirectory()?a<3&&s(l,a+1):u.endsWith(".jsonl")&&d.mtimeMs>=n&&o.push({path:l,at:d.mtimeMs})}};return s(r,0),o.sort((i,a)=>a.at-i.at).find(i=>iN(i.path)===jx(t))}function Zx(t=process.env,e=process.cwd(),r=Pp(),n={}){let o=t.CLAUDE_CODE_SESSION_ID?.trim();if(o&&/^[\w.-]+$/.test(o)){let a=cN(o,r);if(a&&a.endsWith(`${o}.jsonl`)){if(n.envMayBeStale){let c=Nx(eN(a));if(c&&c.path!==a&&c.at>Rp(a).mtimeMs)return{path:c.path,how:`the newest Claude Code session in this project (${Mx(c.path,".jsonl")}; CLAUDE_CODE_SESSION_ID still names ${o}, as after /clear)`}}return{path:a,how:`this Claude Code session (${o})`}}}let s=Nx(Ix(e,r)),i=aN(e,r);return i&&(!s||i.at>s.at)?{path:i.path,how:"the newest Codex session started in this folder"}:s?{path:s.path,how:"the newest Claude Code session in this folder"}:void 0}function cN(t,e=Pp()){if((tN(t)||t.includes("/")||t.includes("\\"))&&Ja(t))return jx(t);if(!/^[\w.-]+$/.test(t))return;let r=vn(ao(e),"projects"),n=[];try{n=Wa(r)}catch{}for(let a of n){let c=vn(r,a,`${t}.jsonl`);if(Ja(c))return c}let o=vn(Va(e),"sessions"),s,i=(a,c)=>{if(s)return;let u;try{u=Wa(a)}catch{return}for(let l of u){let d=vn(a,l);if(l.endsWith(".jsonl")&&l.includes(t)){s=d;return}c<3&&!l.includes(".")&&i(d,c+1)}};return Ja(o)&&i(o,0),s}function Dx(t,e,r={}){let n=sN(t),{entries:o,compactions:s}=n,i=new Map,a=o.map(p=>{let f=`#${p.n}`;return i.set(f,p),{name:f,text:p.text}}),c=Math.max(200,r.budget??2e3),u=ex(a,{query:e,budget:c,maxChunkTokens:300}),l=p=>p.compactedBy===0?"in context":`before compaction ${s-p.compactedBy+1} of ${s}`,d=[...u.selected].sort((p,f)=>f.score-p.score).map(p=>{let f=i.get(p.source);return{id:p.id,n:f.n,at:f.at,kind:f.kind,where:l(f),tokens:p.tokens,score:p.score,text:p.text}}),m=u.chunks.filter(p=>p.score>0&&!u.selected.includes(p)).length;return{path:t,how:r.how??"the session named",query:e,entries:n.total,compactions:s,totalTokens:u.totalTokens,hits:d,masked:n.masked,more:m,leftOut:n.total-o.length}}function Lx(t,e=Pp()){let r=Mx(t.path).replace(/\.jsonl$/,"").slice(0,48),n=[`RECALL from ${t.how}${t.how.includes(r)?"":` (${r})`}: ${t.entries} entries, ~${z(t.totalTokens)} tokens, ${t.compactions} compaction${t.compactions===1?"":"s"}.`];if(!t.hits.length)return n.push(`Nothing in it matches "${t.query}". Try the words the output itself would use (a file name, an error, a command).`),n.join(`
|
|
109
109
|
`);n.push(`Best ${t.hits.length} excerpt${t.hits.length===1?"":"s"} for "${t.query}", best first${t.more?` (${t.more} more matched; a narrower query or a larger max_tokens gets them)`:""}:`),t.masked&&n.push(`${t.masked} secret-looking string${t.masked===1?"":"s"} masked.`),t.leftOut&&n.push(`The oldest ${t.leftOut} entries were not searched: the transcript is that large.`);for(let o of t.hits){let s=o.at?o.at.slice(0,16).replace("T"," ")+" UTC":"time not recorded";n.push("",`\u2500\u2500 entry ${o.n} of ${t.entries} \xB7 ${s} \xB7 ${o.kind} \xB7 ${o.where} \xB7 ~${z(o.tokens)}`,o.text)}return n.join(`
|
|
110
|
-
`).replaceAll(e,"~")}var eM=["dedupe","trim-tool-results","trim-tool-calls","strip-base64","prune-history"],tM={approx_tokens:1e7,approx_lines:1e6,approx_words:5e6,approx_chars:4e7};function Hp(t,e,r){if(ax(t)==="full")return{content:[{type:"text",text:e}]};let n=r();return{content:[{type:"text",text:n.text}],structuredContent:n.structured,_meta:n.meta}}async function Tb(t,e,r){if(!t.server.getClientCapabilities()?.elicitation?.form)return{asked:!1};try{let n=await t.server.elicitInput({mode:"form",message:e,requestedSchema:{type:"object",properties:r}},{timeout:12e4});return n.action==="accept"?{asked:!0,ok:!0,content:n.content??{}}:{asked:!0,ok:!1,content:{},why:n.action==="decline"?"the user declined":"the user dismissed the prompt"}}catch(n){return n instanceof I&&n.code===A.RequestTimeout?{asked:!0,ok:!1,content:{},why:"no answer within two minutes"}:{asked:!0,ok:!1,content:{},why:"the consent form failed, so nothing was assumed"}}}function Eb({http:t=!1,storeHandoffs:e=!t}={}){let r=!t,n=new ka({name:"context-doctor",version:"0.
|
|
110
|
+
`).replaceAll(e,"~")}var eM=["dedupe","trim-tool-results","trim-tool-calls","strip-base64","prune-history"],tM={approx_tokens:1e7,approx_lines:1e6,approx_words:5e6,approx_chars:4e7};function Hp(t,e,r){if(ax(t)==="full")return{content:[{type:"text",text:e}]};let n=r();return{content:[{type:"text",text:n.text}],structuredContent:n.structured,_meta:n.meta}}async function Tb(t,e,r){if(!t.server.getClientCapabilities()?.elicitation?.form)return{asked:!1};try{let n=await t.server.elicitInput({mode:"form",message:e,requestedSchema:{type:"object",properties:r}},{timeout:12e4});return n.action==="accept"?{asked:!0,ok:!0,content:n.content??{}}:{asked:!0,ok:!1,content:{},why:n.action==="decline"?"the user declined":"the user dismissed the prompt"}}catch(n){return n instanceof I&&n.code===A.RequestTimeout?{asked:!0,ok:!1,content:{},why:"no answer within two minutes"}:{asked:!0,ok:!1,content:{},why:"the consent form failed, so nothing was assumed"}}}function Eb({http:t=!1,storeHandoffs:e=!t}={}){let r=!t,n=new ka({name:"context-doctor",version:"0.43.0"},{instructions:ix,maxToolInputElements:1e4});n.tool("profile_context","Profile a conversation's context: token breakdown, largest blocks, wasted context. Pass `conversation` (JSON or text) or, in a chat app, a `sketch` (~120 tokens). Call it when the user asks about tokens, cost, speed or limits, and once past ~30 turns or 3+ large pastes. Act on the top finding.",{conversation:Z.string().optional().describe("JSON or text; in a chat app pass `sketch`"),sketch:Z.object({turns:Z.number().int().nonnegative().describe("Exchanges so far"),model:Z.string().optional(),blocks:Z.array(Z.object({turn:Z.number().int().positive(),kind:Z.enum(["paste","code","tool_result","image","base64","text"]),label:Z.string().describe("Short name"),approx_tokens:Z.number().optional(),approx_lines:Z.number().optional(),approx_words:Z.number().optional(),approx_chars:Z.number().optional(),repeated:Z.number().int().optional().describe("Times it appears (2+ = duplicate)"),stale:Z.boolean().optional().describe("Acted on, no longer needed")})).describe("Only blocks over ~500 tokens, repeated, or images.")}).optional().describe("For chat apps. One size hint per block: lines for code, words for prose, chars for logs."),model:Z.string().optional().describe("e.g. claude-sonnet-5")},{title:"Profile context",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},async({conversation:i,sketch:a,model:c},u)=>{if(a){let m=h=>({isError:!0,content:[{type:"text",text:h}]});if(a.turns>1e5)return m(`sketch.turns is ${a.turns}; the most that makes sense is 100000.`);if(a.blocks.length>500)return m(`sketch.blocks has ${a.blocks.length} blocks; list at most 500 (only those over ~500 tokens, repeated, or images).`);for(let[h,_]of a.blocks.entries()){if(_.turn>1e5)return m(`sketch.blocks[${h}].turn is ${_.turn}; the most that makes sense is 100000.`);if(_.repeated!==void 0&&(_.repeated<1||_.repeated>1e3))return m(`sketch.blocks[${h}].repeated is ${_.repeated}; give 1 to 1000.`);for(let[v,y]of Object.entries(tM)){let x=_[v];if(typeof x=="number"&&!(x>0))return m(`sketch.blocks[${h}].${v} is ${x}; a size is above 0.`);if(typeof x=="number"&&x>y)return m(`sketch.blocks[${h}].${v} is ${x}; the most that makes sense is ${y}. Give a rough size of the block itself.`)}}let p=i?"Note: both `conversation` and `sketch` were passed; profiled the sketch only. Pass one.\n\n":"",f=Rv({...a,model:a.model??c},{record:!t}),g=p+zv(f);return Hp(u?._meta,g,()=>{let h=ux(f,g);return{...h,text:p+h.text}})}if(!i)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 l=vv(iv(i),c),d=Sv(l);return Hp(u?._meta,d,()=>cx(l,d))}),n.tool("optimize_context","Rewrite a conversation to reclaim tokens (dedupe, trim stale tool results, strip base64; prune-history is lossy). Returns slimmed JSON and the savings. Use after profile_context finds waste the user wants fixed; prune-history only with the user's consent, then write the summary the result asks for.",{conversation:Z.string().describe("Conversation JSON"),strategies:Z.array(Z.enum(eM)).optional().describe("Default: dedupe, trim-tool-results, strip-base64"),keep_recent:Z.number().int().nonnegative().optional().describe("Tail messages kept (default 6)"),max_tool_result_tokens:Z.number().int().positive().optional().describe("Per trimmed result (default 300)")},{title:"Optimize context",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},async({conversation:i,strategies:a,keep_recent:c,max_tool_result_tokens:u})=>{let l="";if(a?.includes("prune-history")){let _=await Tb(n,`Prune old turns from this conversation? It is lossy: all but the last ${Math.max(2,c??6)} messages are replaced by a summary the assistant writes.`,{prune:{type:"boolean",title:"Replace old turns with a summary",default:!0}});_.asked&&(!_.ok||_.content.prune===!1)&&(a=a.filter(v=>v!=="prune-history"),l=`
|
|
111
111
|
prune-history skipped: ${_.ok?"the user unticked it":_.why}.`)}let d=$v(i,{strategies:a,keepRecent:c,maxToolResultTokens:u}),m=d.tokensBefore-d.tokensAfter;m>0&&!t&&Ia({ev:"optimize",src:"mcp",saved:m,model:d.conversation?.model});let p=`Saved ~${z(m)} tokens (${z(d.tokensBefore)} \u2192 ${z(d.tokensAfter)}) via ${d.applied.length} change(s):
|
|
112
112
|
`+d.applied.map(_=>`- [${_.strategy}] message #${_.messageIndex}: ${_.note} (~${z(_.tokensSaved)})`).join(`
|
|
113
113
|
`)+l,f=1e5,g=JSON.stringify(d.conversation),h=[{type:"text",text:p},g.length<=f?{type:"text",text:g}:{type:"text",text:`[optimized conversation is ${g.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 d.prunedDigest&&h.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.
|
package/dist/proxy.d.ts
CHANGED
|
@@ -65,7 +65,7 @@ export interface ProxyOptions extends OptimizeOptions {
|
|
|
65
65
|
/** Default request body cap: far above any real request (a 1M-token context is ~4 MB of JSON, images aside). */
|
|
66
66
|
export declare const DEFAULT_MAX_BODY_BYTES: number;
|
|
67
67
|
/** Reported by /health so `autopilot status` can tell an outdated service from a current one. */
|
|
68
|
-
export declare const PROXY_VERSION = "0.
|
|
68
|
+
export declare const PROXY_VERSION = "0.43.0";
|
|
69
69
|
/**
|
|
70
70
|
* Remove a leading `/t/<token>` from a request path, or return undefined when
|
|
71
71
|
* the prefix is absent or the token differs. The comparison is constant time
|
package/dist/proxy.js
CHANGED
|
@@ -24,7 +24,7 @@ import { withPromptCacheKey } from "./cachekey.js";
|
|
|
24
24
|
/** Default request body cap: far above any real request (a 1M-token context is ~4 MB of JSON, images aside). */
|
|
25
25
|
export const DEFAULT_MAX_BODY_BYTES = 100 * 1024 * 1024;
|
|
26
26
|
/** Reported by /health so `autopilot status` can tell an outdated service from a current one. */
|
|
27
|
-
export const PROXY_VERSION = "0.
|
|
27
|
+
export const PROXY_VERSION = "0.43.0";
|
|
28
28
|
/** Connection-level headers that must not be forwarded. */
|
|
29
29
|
const SKIP_REQUEST_HEADERS = new Set(["host", "content-length", "connection", "transfer-encoding", "accept-encoding", "expect"]);
|
|
30
30
|
const SKIP_RESPONSE_HEADERS = new Set(["content-length", "content-encoding", "transfer-encoding", "connection"]);
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A session's own price, said once while it runs.
|
|
3
|
+
*
|
|
4
|
+
* The budget counts a day across tools; one session can cost $2,000 on its
|
|
5
|
+
* own without anyone noticing that each message now re-reads ~470k tokens
|
|
6
|
+
* (the author's `gantry-ai` audit: 2,795 requests, 1.3B cached tokens read).
|
|
7
|
+
* So before each prompt (Claude Code's and Codex's UserPromptSubmit, Gemini
|
|
8
|
+
* CLI's BeforeAgent) the hook adds up what this session has cost, subagents
|
|
9
|
+
* included (they bill to it), and when it passes $25, $100 and $500 says so
|
|
10
|
+
* to the user once: the cost so far, what each message of the main
|
|
11
|
+
* conversation now costs at the model's cache-read rate (or, after an idle
|
|
12
|
+
* that expired the cache, the re-write this message pays), and that
|
|
13
|
+
* /compact or a handoff to a new session cuts it.
|
|
14
|
+
*
|
|
15
|
+
* To the user, not the model: compacting or moving to a new session is the
|
|
16
|
+
* person's decision about their money, and only they can run /compact. The
|
|
17
|
+
* cold-resume offer measured how a model-delivered offer fares (acted on 1
|
|
18
|
+
* time in 33 before it got a line of its own), and a note in the model's
|
|
19
|
+
* context costs every later request and can pull it off the task. The
|
|
20
|
+
* heavy-context note already asks the model to offer a compaction.
|
|
21
|
+
*
|
|
22
|
+
* Fast and quiet. The cost is the budget ledger's per-transcript entry
|
|
23
|
+
* (budget.ts refreshEntry), with the period starting at 0: a prompt reads
|
|
24
|
+
* only what was appended since the last read. The entries are kept beside
|
|
25
|
+
* the hook's per-session state, but written only once enough was read to be
|
|
26
|
+
* worth keeping (SAVE_BYTES) or a threshold was said, so a session below
|
|
27
|
+
* the first threshold costs a read of its last turns and writes nothing.
|
|
28
|
+
* Each threshold is claimed by creating a file that must not exist yet
|
|
29
|
+
* (`wx`), which exactly one of several hooks running at once can do. Once
|
|
30
|
+
* the top threshold is said, the check is one stat.
|
|
31
|
+
*
|
|
32
|
+
* Thresholds: CONTEXT_DOCTOR_SESSION_PRICE (dollars, e.g. "50,200");
|
|
33
|
+
* off: CONTEXT_DOCTOR_NO_SESSION_PRICE=1.
|
|
34
|
+
*/
|
|
35
|
+
import { type Tool } from "./spend.js";
|
|
36
|
+
import { type ResumeVerdict } from "./coldresume.js";
|
|
37
|
+
/** Where the hook speaks unless CONTEXT_DOCTOR_SESSION_PRICE says otherwise. */
|
|
38
|
+
export declare const SESSION_PRICE_THRESHOLDS: number[];
|
|
39
|
+
/** The thresholds in force, ascending; none when switched off. */
|
|
40
|
+
export declare function sessionPriceThresholds(env?: NodeJS.ProcessEnv): number[];
|
|
41
|
+
export interface SessionPrice {
|
|
42
|
+
app: Tool;
|
|
43
|
+
/** The threshold just passed. */
|
|
44
|
+
threshold: number;
|
|
45
|
+
usd: number;
|
|
46
|
+
/** Subagents' part of `usd`. */
|
|
47
|
+
subagentUsd: number;
|
|
48
|
+
/** The main conversation's context at its last request, and its model. */
|
|
49
|
+
tokens?: number;
|
|
50
|
+
model?: string;
|
|
51
|
+
/** What the next message pays to re-read that context from the cache. */
|
|
52
|
+
readUsd?: number;
|
|
53
|
+
/** The cache expired while idle: what this message pays to write it again. */
|
|
54
|
+
coldUsd?: number;
|
|
55
|
+
}
|
|
56
|
+
export interface SessionPriceInput {
|
|
57
|
+
sessionId: string;
|
|
58
|
+
transcript: string;
|
|
59
|
+
event?: string;
|
|
60
|
+
model?: string;
|
|
61
|
+
/** Claude Code's SessionStart verdict on a resumed cache, from the hook's state (read only when a threshold is due). */
|
|
62
|
+
rv?: () => ResumeVerdict | undefined;
|
|
63
|
+
}
|
|
64
|
+
/**
|
|
65
|
+
* The threshold this prompt is the first to pass, with what to say about
|
|
66
|
+
* it, or undefined (below the first, said already, or anything unreadable).
|
|
67
|
+
* Claims the threshold: a second call for the same one gets undefined.
|
|
68
|
+
*/
|
|
69
|
+
export declare function sessionPriceDue(input: SessionPriceInput, now?: number, env?: NodeJS.ProcessEnv): SessionPrice | undefined;
|
|
70
|
+
/** The line for the user (the hook's systemMessage). */
|
|
71
|
+
export declare function renderSessionPrice(p: SessionPrice): string;
|