context-doctor 0.41.0 → 0.42.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 +5 -4
- package/dist/ab.js +3 -1
- package/dist/autopilot.d.ts +1 -1
- package/dist/autopilot.js +38 -24
- package/dist/budget.d.ts +12 -1
- package/dist/budget.js +153 -31
- package/dist/cachettl.js +12 -9
- package/dist/claudedir.d.ts +8 -0
- package/dist/claudedir.js +19 -0
- package/dist/cli.js +63 -9
- package/dist/codexdir.d.ts +11 -0
- package/dist/codexdir.js +20 -0
- package/dist/codexroute.d.ts +1 -0
- package/dist/codexroute.js +3 -1
- package/dist/compactwindow.js +12 -9
- package/dist/cursor.js +20 -5
- package/dist/doctor.d.ts +9 -0
- package/dist/doctor.js +32 -14
- package/dist/effective.d.ts +18 -0
- package/dist/effective.js +39 -4
- package/dist/extract.d.ts +12 -3
- package/dist/extract.js +39 -12
- package/dist/fileparams.d.ts +1 -1
- package/dist/fileparams.js +8 -8
- package/dist/fix.d.ts +3 -1
- package/dist/fix.js +31 -11
- package/dist/hook.js +15 -4
- package/dist/install.js +106 -47
- package/dist/ledger.d.ts +15 -0
- package/dist/ledger.js +30 -1
- package/dist/limits.d.ts +15 -1
- package/dist/limits.js +71 -28
- package/dist/mcp.js +58 -58
- package/dist/overhead.js +2 -1
- package/dist/pack.js +3 -2
- package/dist/proxy.d.ts +1 -1
- package/dist/proxy.js +1 -1
- package/dist/recall.js +3 -2
- package/dist/scan.d.ts +2 -0
- package/dist/scan.js +2 -1
- package/dist/session.js +2 -1
- package/dist/settingsedit.d.ts +4 -0
- package/dist/settingsedit.js +61 -3
- package/dist/spend.d.ts +8 -1
- package/dist/spend.js +27 -10
- package/dist/subagentmodel.d.ts +19 -4
- package/dist/subagentmodel.js +116 -28
- package/package.json +1 -1
package/dist/extract.js
CHANGED
|
@@ -101,14 +101,34 @@ export function extractText(path) {
|
|
|
101
101
|
}
|
|
102
102
|
/** Default time budget for one extraction call in the MCP server. */
|
|
103
103
|
export const EXTRACT_BUDGET_MS = 20_000;
|
|
104
|
+
/**
|
|
105
|
+
* Milliseconds on a monotonic clock. The budget is counted on it, never on
|
|
106
|
+
* Date.now(): a wall clock can jump forward (time sync after a boot), and a
|
|
107
|
+
* jump read as the budget running out.
|
|
108
|
+
*/
|
|
109
|
+
export const monotonicNow = () => performance.now();
|
|
110
|
+
/**
|
|
111
|
+
* The longest one tool may run: half the time left (at least 2 s), and never
|
|
112
|
+
* more than the 30 s the synchronous path gives a tool. One form of
|
|
113
|
+
* pdftotext hanging used to take the whole budget, so the next form was
|
|
114
|
+
* never tried: Windows runners reported a PDF as "not read: the time ran
|
|
115
|
+
* out" inside a 60 s budget that the synchronous read of the same file
|
|
116
|
+
* (30 s a tool) got through.
|
|
117
|
+
*/
|
|
118
|
+
function toolCap(left) {
|
|
119
|
+
return Math.min(left, 30_000, Math.max(2_000, left / 2));
|
|
120
|
+
}
|
|
104
121
|
/**
|
|
105
122
|
* A command's stdout, or undefined, without blocking the event loop: killed
|
|
106
|
-
* (SIGKILL) when
|
|
123
|
+
* (SIGKILL) when its share of the time (toolCap) runs out. `timedOut` is set
|
|
124
|
+
* only when `end` (on the monotonic clock) has passed: a tool stopped
|
|
125
|
+
* earlier is a failed tool, and the next one is tried.
|
|
107
126
|
*/
|
|
108
|
-
function runAsync(cmd, args,
|
|
109
|
-
const
|
|
110
|
-
if (
|
|
127
|
+
function runAsync(cmd, args, end) {
|
|
128
|
+
const left = Math.ceil(end - monotonicNow());
|
|
129
|
+
if (left <= 0)
|
|
111
130
|
return Promise.resolve({ timedOut: true });
|
|
131
|
+
const timeout = Math.ceil(toolCap(left));
|
|
112
132
|
return new Promise((resolve) => {
|
|
113
133
|
let settled = false;
|
|
114
134
|
const finish = (r) => {
|
|
@@ -124,7 +144,7 @@ function runAsync(cmd, args, deadline) {
|
|
|
124
144
|
// deadline whatever the pipes do.
|
|
125
145
|
const timer = setTimeout(() => {
|
|
126
146
|
child?.kill("SIGKILL");
|
|
127
|
-
finish({ timedOut:
|
|
147
|
+
finish({ timedOut: monotonicNow() >= end - 50 });
|
|
128
148
|
}, timeout);
|
|
129
149
|
try {
|
|
130
150
|
child = execFile(cmd, args, { encoding: "utf8", timeout, killSignal: "SIGKILL", maxBuffer: 64 * 1024 * 1024, windowsHide: true }, (err, stdout) => {
|
|
@@ -132,10 +152,14 @@ function runAsync(cmd, args, deadline) {
|
|
|
132
152
|
// reason (seen on Windows runners, well inside a 60 s budget) is a
|
|
133
153
|
// failed tool, and the next one is tried.
|
|
134
154
|
if (err)
|
|
135
|
-
return finish({ timedOut:
|
|
155
|
+
return finish({ timedOut: monotonicNow() >= end - 50 });
|
|
136
156
|
finish({ out: typeof stdout === "string" && stdout.trim() ? stdout : undefined, timedOut: false });
|
|
137
157
|
});
|
|
138
158
|
child.on("error", () => finish({ timedOut: false }));
|
|
159
|
+
// No input, as spawnSync gives the synchronous path: a converter that
|
|
160
|
+
// reads stdin gets end-of-file instead of waiting out the budget.
|
|
161
|
+
child.stdin?.on("error", () => { });
|
|
162
|
+
child.stdin?.end();
|
|
139
163
|
}
|
|
140
164
|
catch {
|
|
141
165
|
finish({ timedOut: false });
|
|
@@ -143,10 +167,13 @@ function runAsync(cmd, args, deadline) {
|
|
|
143
167
|
});
|
|
144
168
|
}
|
|
145
169
|
/**
|
|
146
|
-
* extractText for a server: asynchronous, and bounded by `
|
|
147
|
-
*
|
|
170
|
+
* extractText for a server: asynchronous, and bounded by `end` (on the
|
|
171
|
+
* monotonic clock, monotonicNow()) across every tool it tries. Past it the
|
|
172
|
+
* reason says so. A caller with one budget for several documents sets one
|
|
173
|
+
* `end` on the same clock: a deadline on the wall clock, converted per
|
|
174
|
+
* document, let a clock jump between two documents cut the later ones short.
|
|
148
175
|
*/
|
|
149
|
-
export async function extractTextAsync(path,
|
|
176
|
+
export async function extractTextAsync(path, end = monotonicNow() + EXTRACT_BUDGET_MS) {
|
|
150
177
|
const ext = extname(path).toLowerCase();
|
|
151
178
|
const mac = process.platform === "darwin";
|
|
152
179
|
let text;
|
|
@@ -154,7 +181,7 @@ export async function extractTextAsync(path, deadline = Date.now() + EXTRACT_BUD
|
|
|
154
181
|
const tryRun = async (cmd, args) => {
|
|
155
182
|
if (text || timedOut)
|
|
156
183
|
return;
|
|
157
|
-
const r = await runAsync(cmd, args,
|
|
184
|
+
const r = await runAsync(cmd, args, end);
|
|
158
185
|
if (r.timedOut)
|
|
159
186
|
timedOut = true;
|
|
160
187
|
else
|
|
@@ -167,7 +194,7 @@ export async function extractTextAsync(path, deadline = Date.now() + EXTRACT_BUD
|
|
|
167
194
|
if (!text && !timedOut) {
|
|
168
195
|
const out = join(mkdtempSync(join(tmpdir(), "cd-pdf-")), "out.txt");
|
|
169
196
|
try {
|
|
170
|
-
const r = await runAsync("pdftotext", [path, out],
|
|
197
|
+
const r = await runAsync("pdftotext", [path, out], end);
|
|
171
198
|
if (r.timedOut)
|
|
172
199
|
timedOut = true;
|
|
173
200
|
else if (existsSync(out))
|
|
@@ -192,7 +219,7 @@ export async function extractTextAsync(path, deadline = Date.now() + EXTRACT_BUD
|
|
|
192
219
|
if (!text && !timedOut) {
|
|
193
220
|
const members = ext === ".docx" ? ["word/document.xml"] : ext === ".pptx" ? ["ppt/slides/*.xml"] : ext === ".odt" ? ["content.xml"] : [];
|
|
194
221
|
if (members.length) {
|
|
195
|
-
const r = await runAsync("unzip", ["-p", path, ...members],
|
|
222
|
+
const r = await runAsync("unzip", ["-p", path, ...members], end);
|
|
196
223
|
if (r.timedOut)
|
|
197
224
|
timedOut = true;
|
|
198
225
|
else if (r.out)
|
package/dist/fileparams.d.ts
CHANGED
|
@@ -43,7 +43,7 @@ export declare function checkFileUrl(raw: string, env?: NodeJS.ProcessEnv): {
|
|
|
43
43
|
};
|
|
44
44
|
/**
|
|
45
45
|
* Download one file, following at most FILE_LIMITS.redirects https redirects,
|
|
46
|
-
* within FILE_LIMITS.timeoutMs (or the caller's earlier `deadline
|
|
46
|
+
* within FILE_LIMITS.timeoutMs (or the caller's earlier `deadline`, on the monotonic clock: monotonicNow()) and
|
|
47
47
|
* `maxBytes` (default the per-file limit). Never throws.
|
|
48
48
|
*/
|
|
49
49
|
export declare function downloadFile(raw: string, env?: NodeJS.ProcessEnv, { deadline: callDeadline, maxBytes }?: {
|
package/dist/fileparams.js
CHANGED
|
@@ -24,7 +24,7 @@ import { isIP } from "node:net";
|
|
|
24
24
|
import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
|
|
25
25
|
import { tmpdir } from "node:os";
|
|
26
26
|
import { extname, join } from "node:path";
|
|
27
|
-
import { EXTRACT_BUDGET_MS, EXTRACTABLE, extractTextAsync } from "./extract.js";
|
|
27
|
+
import { EXTRACT_BUDGET_MS, EXTRACTABLE, extractTextAsync, monotonicNow } from "./extract.js";
|
|
28
28
|
/** Per file: bytes and time. Per call: files, bytes and time (downloads and extraction together). */
|
|
29
29
|
export const FILE_LIMITS = { files: 10, bytes: 5 * 1024 * 1024, totalBytes: 20 * 1024 * 1024, timeoutMs: 20_000, redirects: 3, callMs: 60_000 };
|
|
30
30
|
const MIME_EXT = {
|
|
@@ -169,7 +169,7 @@ function getOnce(url, env, deadline, maxBytes) {
|
|
|
169
169
|
clearTimeout(overall);
|
|
170
170
|
resolve(r);
|
|
171
171
|
};
|
|
172
|
-
const timeout = Math.max(1, deadline -
|
|
172
|
+
const timeout = Math.max(1, deadline - monotonicNow());
|
|
173
173
|
// The socket timeout is an idle timeout; a server dripping a byte at a
|
|
174
174
|
// time would never trip it. This one bounds the whole download.
|
|
175
175
|
const overall = setTimeout(() => {
|
|
@@ -220,18 +220,18 @@ function getOnce(url, env, deadline, maxBytes) {
|
|
|
220
220
|
}
|
|
221
221
|
/**
|
|
222
222
|
* Download one file, following at most FILE_LIMITS.redirects https redirects,
|
|
223
|
-
* within FILE_LIMITS.timeoutMs (or the caller's earlier `deadline
|
|
223
|
+
* within FILE_LIMITS.timeoutMs (or the caller's earlier `deadline`, on the monotonic clock: monotonicNow()) and
|
|
224
224
|
* `maxBytes` (default the per-file limit). Never throws.
|
|
225
225
|
*/
|
|
226
226
|
export async function downloadFile(raw, env = process.env, { deadline: callDeadline, maxBytes = FILE_LIMITS.bytes } = {}) {
|
|
227
|
-
const deadline = Math.min(
|
|
227
|
+
const deadline = Math.min(monotonicNow() + FILE_LIMITS.timeoutMs, callDeadline ?? Infinity);
|
|
228
228
|
const limit = Math.max(0, Math.min(maxBytes, FILE_LIMITS.bytes));
|
|
229
229
|
let current = raw;
|
|
230
230
|
for (let hop = 0; hop <= FILE_LIMITS.redirects; hop++) {
|
|
231
231
|
const checked = checkFileUrl(current, env);
|
|
232
232
|
if ("error" in checked)
|
|
233
233
|
return { error: hop === 0 ? `refused: ${checked.error}` : `refused a redirect: ${checked.error}` };
|
|
234
|
-
if (
|
|
234
|
+
if (monotonicNow() >= deadline)
|
|
235
235
|
return { error: "timed out" };
|
|
236
236
|
const r = await getOnce(checked.url, env, deadline, limit);
|
|
237
237
|
if (r.error)
|
|
@@ -263,10 +263,10 @@ export async function sourcesFromOpenAiFiles(files, env = process.env) {
|
|
|
263
263
|
const skipped = [];
|
|
264
264
|
let total = 0;
|
|
265
265
|
// One budget for the whole call, downloads and extraction together.
|
|
266
|
-
const callDeadline =
|
|
266
|
+
const callDeadline = monotonicNow() + FILE_LIMITS.callMs;
|
|
267
267
|
for (const f of files.slice(0, FILE_LIMITS.files)) {
|
|
268
268
|
const name = safeName(f);
|
|
269
|
-
if (
|
|
269
|
+
if (monotonicNow() >= callDeadline) {
|
|
270
270
|
skipped.push(`${name}: not read, the ${FILE_LIMITS.callMs / 1000} s allowed for one call ran out`);
|
|
271
271
|
continue;
|
|
272
272
|
}
|
|
@@ -285,7 +285,7 @@ export async function sourcesFromOpenAiFiles(files, env = process.env) {
|
|
|
285
285
|
const path = join(dir, `upload${docExt}`);
|
|
286
286
|
writeFileSync(path, got.body, { mode: 0o600 });
|
|
287
287
|
// Asynchronous and bounded: a hostile document cannot hold the server.
|
|
288
|
-
const text = await extractTextAsync(path, Math.min(
|
|
288
|
+
const text = await extractTextAsync(path, Math.min(monotonicNow() + EXTRACT_BUDGET_MS, callDeadline));
|
|
289
289
|
if ("error" in text)
|
|
290
290
|
skipped.push(`${name}: ${text.error}`);
|
|
291
291
|
else
|
package/dist/fix.d.ts
CHANGED
|
@@ -41,6 +41,8 @@ export interface Fix {
|
|
|
41
41
|
/** Saved over the measured period, when it can be priced. */
|
|
42
42
|
savedUsd?: number;
|
|
43
43
|
savedShare?: number;
|
|
44
|
+
/** What the share is of, when it is not the input the plan's first line names ("of subagents"). */
|
|
45
|
+
shareOf?: string;
|
|
44
46
|
/** How the figure was measured. */
|
|
45
47
|
basis: string;
|
|
46
48
|
/** What it costs in quality, plainly. */
|
|
@@ -124,7 +126,7 @@ export interface FixRecord {
|
|
|
124
126
|
oneHourShareBefore?: number;
|
|
125
127
|
/** For prune: the project folder. */
|
|
126
128
|
cwd?: string;
|
|
127
|
-
/** For subagent-model: the models the moved subagents ran on before the change, each one's share of their
|
|
129
|
+
/** For subagent-model: the models the moved types' subagents ran on before the change, each one's share of their tokens (Sonnet-or-cheaper ones included): the baseline "since" compares against. */
|
|
128
130
|
modelsBefore?: Record<string, number>;
|
|
129
131
|
}
|
|
130
132
|
export declare function fixRecordPath(home?: string): string;
|
package/dist/fix.js
CHANGED
|
@@ -36,8 +36,8 @@ import { forEachLine, listSessions, isClaudeSession } from "./session.js";
|
|
|
36
36
|
import { pricingFor } from "./pricing.js";
|
|
37
37
|
import { contextWindowFor, realModel } from "./tokens.js";
|
|
38
38
|
import { adviseTtl, estimateCacheTtl } from "./cachettl.js";
|
|
39
|
-
import { ABSENT, getPath, readSettings, removeFile, sameJson, setJsonPath, SettingsError, withLock, writeAtomic } from "./settingsedit.js";
|
|
40
|
-
import { compactWindowOverrides, settingsSources, ttlOverrides } from "./effective.js";
|
|
39
|
+
import { ABSENT, getPath, parseSettingsText, readSettings, removeFile, sameJson, setJsonPath, SettingsError, settingsLockPath, withLock, writeAtomic } from "./settingsedit.js";
|
|
40
|
+
import { compactWindowOverrides, processEnvWhere, settingsSources, shellSet, ttlOverrides } from "./effective.js";
|
|
41
41
|
import { tilde } from "./claudedir.js";
|
|
42
42
|
import { applyPrune, undoPrune } from "./prune.js";
|
|
43
43
|
import { readLedger } from "./ledger.js";
|
|
@@ -48,6 +48,8 @@ const MIN_USD = 1;
|
|
|
48
48
|
const money = (n) => (n >= 100 ? `$${Math.round(n).toLocaleString("en-US")}` : `$${n.toFixed(2)}`);
|
|
49
49
|
const pct = (x) => `${Math.round(x * 100)}%`;
|
|
50
50
|
const k = (n) => `${Math.round(n / 1000)}k`;
|
|
51
|
+
/** " (48%)", or " (37% of subagents)" for a share of something else. */
|
|
52
|
+
const share = (f) => (f.savedShare !== undefined ? ` (${pct(f.savedShare)}${f.shareOf ? ` ${f.shareOf}` : ""})` : "");
|
|
51
53
|
export function planFixes(i) {
|
|
52
54
|
const fixes = [];
|
|
53
55
|
const where = tilde(join(claudeDir(), "settings.json"));
|
|
@@ -142,9 +144,10 @@ export function planFixes(i) {
|
|
|
142
144
|
const sm = i.subagentModel;
|
|
143
145
|
const set = i.subagentModelSet;
|
|
144
146
|
if (set) {
|
|
145
|
-
|
|
147
|
+
// Blank reads as unset in Claude Code: subagents inherit, as with "inherit".
|
|
148
|
+
const inherit = /^(inherit|default|)$/i.test(set.value.trim());
|
|
146
149
|
const less = sm && sm.savedUsd >= MIN_USD ? ` (${SUBAGENT_CANDIDATE_NAME} would have cost ${money(sm.savedUsd)} less)` : "";
|
|
147
|
-
fixes.push({ id: "subagent-model", title: "Subagent model", basis: "set", quality: "", change: `env.${SUBAGENT_MODEL_ENV}`, state: inherit ? "not-here" : "applied", note: `${SUBAGENT_MODEL_ENV}=${set.value} in ${set.where}${inherit ? `: left as you set it${less}` : ""}`, value: set.value });
|
|
150
|
+
fixes.push({ id: "subagent-model", title: "Subagent model", basis: "set", quality: "", change: `env.${SUBAGENT_MODEL_ENV}`, state: inherit ? "not-here" : "applied", note: `${SUBAGENT_MODEL_ENV}=${set.value.trim() ? set.value : JSON.stringify(set.value)} in ${set.where}${inherit ? `: left as you set it${less}` : ""}`, value: set.value });
|
|
148
151
|
}
|
|
149
152
|
else if (sm && sm.savedUsd >= MIN_USD) {
|
|
150
153
|
const moved = sm.byType.filter((t) => t.moves);
|
|
@@ -154,6 +157,8 @@ export function planFixes(i) {
|
|
|
154
157
|
title: `Subagents on ${SUBAGENT_CANDIDATE_NAME}${movedFromNames(sm.movedFrom) ? `, not ${movedFromNames(sm.movedFrom)}` : ""}`,
|
|
155
158
|
savedUsd: sm.savedUsd,
|
|
156
159
|
savedShare: sm.billedUsd > 0 ? sm.savedUsd / sm.billedUsd : undefined,
|
|
160
|
+
// The subagents' own bill, not the main conversations' input the plan's first line names.
|
|
161
|
+
shareOf: "of subagents",
|
|
157
162
|
basis: `${reqs.toLocaleString("en-US")} subagent requests priced at ${SUBAGENT_CANDIDATE_NAME} with the token counts they had (${money(sm.billedUsd)} billed for all ${sm.agents} subagents); an estimate: another model tokenizes and works differently`,
|
|
158
163
|
quality: `this changes the model your subagents run on (${moved.map((t) => t.type).join(", ")}); the quality cost is not measured here: context-doctor ab can measure it (its tasks with --model ${SUBAGENT_CANDIDATE} and without)`,
|
|
159
164
|
change: `${where}: env.${SUBAGENT_MODEL_ENV} = "${SUBAGENT_CANDIDATE}"`,
|
|
@@ -173,8 +178,9 @@ export function planFixes(i) {
|
|
|
173
178
|
export function fixRecordPath(home) {
|
|
174
179
|
return join(claudeDir(home), ".context-doctor-fixes.json");
|
|
175
180
|
}
|
|
181
|
+
/** The lock of the user's settings.json, which cache-ttl, compact-window and autopilot take too. */
|
|
176
182
|
function lockPath(home) {
|
|
177
|
-
return join(claudeDir(home), ".
|
|
183
|
+
return settingsLockPath(join(claudeDir(home), "settings.json"));
|
|
178
184
|
}
|
|
179
185
|
/**
|
|
180
186
|
* The records, strictly: an absent file is none; a file that is not ours to
|
|
@@ -297,9 +303,11 @@ export async function applyFix(fix, deps = {}, context = {}) {
|
|
|
297
303
|
try {
|
|
298
304
|
if (KEY_PATH[fix.id]) {
|
|
299
305
|
// The environment Claude Code starts in is the user's too: a value there is theirs (settings.json would override it).
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
306
|
+
// Not a value Claude Code copied from a settings file into the session this runs in, nor fix's own left from before an undo.
|
|
307
|
+
const env = deps.env ?? process.env;
|
|
308
|
+
const shell = fix.id === "subagent-model" && shellSet(SUBAGENT_MODEL_ENV, settingsSources({ home: deps.home, cwd: deps.cwd, env }), env, String(fix.value)) ? env[SUBAGENT_MODEL_ENV] : undefined;
|
|
309
|
+
if (shell)
|
|
310
|
+
return { ok: false, lines: [`✗ ${fix.id}: ${processEnvWhere(SUBAGENT_MODEL_ENV, shell, env)}, a value you set: left as it is. Nothing was changed.`] };
|
|
303
311
|
const lines = applySetting(fix, home, at, { oneHourShareBefore: context.oneHourShare, modelsBefore: context.modelsBefore });
|
|
304
312
|
const over = fixOverrides(fix.id, deps);
|
|
305
313
|
if (over.length)
|
|
@@ -353,7 +361,19 @@ function undoSetting(r, home) {
|
|
|
353
361
|
if (!sameJson(now, r.value)) {
|
|
354
362
|
return `– ${name} was changed since fix set it (now ${now === undefined ? "not set" : JSON.stringify(now)}): left as it is`;
|
|
355
363
|
}
|
|
356
|
-
|
|
364
|
+
let next = setJsonPath(cur.text, key, r.hadPrevious ? r.previous : ABSENT);
|
|
365
|
+
// The object fix created to hold the key (`env`), now empty, goes too.
|
|
366
|
+
if (!r.hadPrevious && key.length > 1 && r.before !== undefined) {
|
|
367
|
+
const parent = key.slice(0, -1);
|
|
368
|
+
let had = true;
|
|
369
|
+
try {
|
|
370
|
+
had = r.before !== null && getPath(parseSettingsText(r.before), parent) !== undefined;
|
|
371
|
+
}
|
|
372
|
+
catch { /* unreadable: keep it */ }
|
|
373
|
+
const left = getPath(parseSettingsText(next), parent);
|
|
374
|
+
if (!had && left && typeof left === "object" && Object.keys(left).length === 0)
|
|
375
|
+
next = setJsonPath(next, parent, ABSENT);
|
|
376
|
+
}
|
|
357
377
|
// A file fix created and that is now an empty object goes again.
|
|
358
378
|
if (r.before === null && !r.hadPrevious) {
|
|
359
379
|
try {
|
|
@@ -556,7 +576,7 @@ export function renderFixPlan(days, billedUsd, fixes, since, command = (s) => `c
|
|
|
556
576
|
if (avail.length === 0)
|
|
557
577
|
out.push(...(billedUsd > 0 ? ["Nothing left to fix here: every lever that pays on your history is applied."] : noHistory(days, command)));
|
|
558
578
|
avail.forEach((f, n) => {
|
|
559
|
-
const usd = f.savedUsd !== undefined ? `${money(f.savedUsd)}${
|
|
579
|
+
const usd = f.savedUsd !== undefined ? `${money(f.savedUsd)}${share(f)}` : "not priced";
|
|
560
580
|
const head = `${n + 1}. ${f.title}`;
|
|
561
581
|
out.push(head.length < 52 ? head.padEnd(52) + usd.padStart(14) : `${head} ${usd}`);
|
|
562
582
|
out.push(` measured: ${f.basis}`);
|
|
@@ -612,7 +632,7 @@ export function renderFixShare(days, billedUsd, fixes) {
|
|
|
612
632
|
const avail = fixes.filter((f) => f.state === "available" && f.savedUsd !== undefined);
|
|
613
633
|
const lines = [`context-doctor fix on my last ${days} days of Claude Code (${money(billedUsd)} of input at list price):`];
|
|
614
634
|
for (const f of avail)
|
|
615
|
-
lines.push(`- ${LABEL[f.id]}: ${money(f.savedUsd)}${
|
|
635
|
+
lines.push(`- ${LABEL[f.id]}: ${money(f.savedUsd)}${share(f)}`);
|
|
616
636
|
if (avail.length === 0)
|
|
617
637
|
lines.push(billedUsd > 0 ? "- nothing left to fix" : "- no Claude Code sessions to measure yet");
|
|
618
638
|
if (avail.length > 1)
|
package/dist/hook.js
CHANGED
|
@@ -168,6 +168,10 @@ export function hookInput(raw) {
|
|
|
168
168
|
return out;
|
|
169
169
|
}
|
|
170
170
|
export async function runHook(app) {
|
|
171
|
+
// The spend budget's line for this prompt, until it is written. The ledger
|
|
172
|
+
// records a threshold as said before the rest of the hook runs, so a later
|
|
173
|
+
// failure must still let it out, or it was lost for the whole period.
|
|
174
|
+
let budgetNote;
|
|
171
175
|
// A hook must never break the user's prompt: any failure exits silently.
|
|
172
176
|
try {
|
|
173
177
|
// GitHub Copilot (`hook copilot`, its sessionStart): the standing rules,
|
|
@@ -231,7 +235,9 @@ export async function runHook(app) {
|
|
|
231
235
|
// re-caching costs. Kept for the first prompt, which decides the offer
|
|
232
236
|
// (an offer before any message would come before the rebuild it prices).
|
|
233
237
|
if (input.hook_event_name === "SessionStart") {
|
|
234
|
-
|
|
238
|
+
// Its idle seconds are as of when Claude Code started this hook: count from this process's
|
|
239
|
+
// start, not from now, after loading (seconds on a loaded machine, past the 5 s match).
|
|
240
|
+
const verdict = resumeVerdict(input, Math.round(performance.timeOrigin));
|
|
235
241
|
if (verdict && input.session_id)
|
|
236
242
|
writeSessionState(input.session_id, { ...readSessionState(input.session_id), rv: verdict });
|
|
237
243
|
return;
|
|
@@ -264,7 +270,6 @@ export async function runHook(app) {
|
|
|
264
270
|
// A spend budget (budget.ts), before each prompt in Claude Code, Codex and
|
|
265
271
|
// Gemini CLI: a line to the user at 50%, 80% and 100%, and with --block,
|
|
266
272
|
// over it, the prompt held. No budget set: one failed read.
|
|
267
|
-
let budgetNote;
|
|
268
273
|
if (!cursor && (input.hook_event_name === undefined || input.hook_event_name === "UserPromptSubmit" || input.hook_event_name === "BeforeAgent")) {
|
|
269
274
|
let v;
|
|
270
275
|
try {
|
|
@@ -280,7 +285,7 @@ export async function runHook(app) {
|
|
|
280
285
|
budgetNote = v?.message;
|
|
281
286
|
}
|
|
282
287
|
const sayBudget = () => { if (budgetNote)
|
|
283
|
-
console.log(JSON.stringify({ systemMessage: budgetNote })); };
|
|
288
|
+
console.log(JSON.stringify({ systemMessage: budgetNote })); budgetNote = undefined; };
|
|
284
289
|
const transcriptPath = input.transcript_path;
|
|
285
290
|
if (!transcriptPath || !existsSync(transcriptPath)) {
|
|
286
291
|
sayBudget();
|
|
@@ -341,6 +346,7 @@ export async function runHook(app) {
|
|
|
341
346
|
if (lines.length > 0)
|
|
342
347
|
out.hookSpecificOutput = { hookEventName: event, additionalContext: block };
|
|
343
348
|
console.log(JSON.stringify(out));
|
|
349
|
+
budgetNote = undefined; // in `notice`, now said
|
|
344
350
|
};
|
|
345
351
|
if (prev.b > 0 && sizeBytes < prev.b * REGROWTH_FACTOR) {
|
|
346
352
|
if (cr !== prev.cr)
|
|
@@ -420,6 +426,11 @@ export async function runHook(app) {
|
|
|
420
426
|
emit([...notes, ...lines]);
|
|
421
427
|
}
|
|
422
428
|
catch {
|
|
423
|
-
|
|
429
|
+
// Silent — never disturb the prompt; but a budget line already recorded as said goes out.
|
|
430
|
+
try {
|
|
431
|
+
if (budgetNote)
|
|
432
|
+
process.stdout.write(JSON.stringify({ systemMessage: budgetNote }) + "\n");
|
|
433
|
+
}
|
|
434
|
+
catch { /* nothing more to do */ }
|
|
424
435
|
}
|
|
425
436
|
}
|