context-doctor 0.41.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 +7 -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 +54 -1
- package/dist/budget.js +207 -53
- package/dist/cachettl.js +12 -9
- package/dist/claudedir.d.ts +8 -0
- package/dist/claudedir.js +19 -0
- package/dist/cli.js +90 -15
- package/dist/codexcompact.d.ts +116 -0
- package/dist/codexcompact.js +415 -0
- 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 +42 -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 +33 -4
- package/dist/fix.js +221 -19
- package/dist/hook.js +35 -5
- package/dist/install.js +106 -47
- package/dist/ledger.d.ts +17 -1
- package/dist/ledger.js +31 -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/sessionprice.d.ts +71 -0
- package/dist/sessionprice.js +216 -0
- 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/dist/tooloutput.d.ts +118 -0
- package/dist/tooloutput.js +355 -0
- package/package.json +1 -1
package/dist/overhead.js
CHANGED
|
@@ -17,6 +17,7 @@
|
|
|
17
17
|
import { readdirSync, readFileSync, statSync } from "node:fs";
|
|
18
18
|
import { homedir } from "node:os";
|
|
19
19
|
import { dirname, isAbsolute, join, relative, resolve } from "node:path";
|
|
20
|
+
import { codexDir } from "./codexdir.js";
|
|
20
21
|
import { forEachLine, listSessions, replyCounter, textOf } from "./session.js";
|
|
21
22
|
import { estimateTokens, formatTokens, providerFor, realModel, tokensForLength } from "./tokens.js";
|
|
22
23
|
import { cacheWriteSplit, formatUsd, pricingFor, writeMultiplier as ttlWriteMultiplier } from "./pricing.js";
|
|
@@ -123,7 +124,7 @@ export function findMemoryFiles(cwd = process.cwd(), home = homedir()) {
|
|
|
123
124
|
if (auto)
|
|
124
125
|
add("Claude Code", autoMemoryPath(cwd, home), "auto memory", auto.split("\n").slice(0, 200).join("\n"));
|
|
125
126
|
// Codex: global AGENTS.md, then each directory down to cwd (it stops at the git root; root-ward extras are rare).
|
|
126
|
-
add("Codex", join(home, "
|
|
127
|
+
add("Codex", join(codexDir(home), "AGENTS.md"), "user");
|
|
127
128
|
for (const d of ancestors(cwd).reverse()) {
|
|
128
129
|
if (d === home)
|
|
129
130
|
continue;
|
package/dist/pack.js
CHANGED
|
@@ -18,7 +18,7 @@ import { existsSync, lstatSync, readdirSync, readFileSync, realpathSync, statSyn
|
|
|
18
18
|
import { homedir } from "node:os";
|
|
19
19
|
import { basename, extname, isAbsolute, join, relative, resolve, sep } from "node:path";
|
|
20
20
|
import { estimateTokens, formatTokens } from "./tokens.js";
|
|
21
|
-
import { EXTRACT_BUDGET_MS, EXTRACTABLE, extractText, extractTextAsync } from "./extract.js";
|
|
21
|
+
import { EXTRACT_BUDGET_MS, EXTRACTABLE, extractText, extractTextAsync, monotonicNow } from "./extract.js";
|
|
22
22
|
const DEFAULT_BUDGET = 4000;
|
|
23
23
|
const DEFAULT_CHUNK_TOKENS = 400;
|
|
24
24
|
/** Claude's tokenizer produces the most tokens per char; a budget in its terms never overruns another's. */
|
|
@@ -646,7 +646,8 @@ export function readSources(paths, cwdOrOptions = process.cwd()) {
|
|
|
646
646
|
export async function readSourcesAsync(paths, options = {}) {
|
|
647
647
|
const defer = [];
|
|
648
648
|
const { sources, skipped } = readSources(paths, { ...options, defer });
|
|
649
|
-
|
|
649
|
+
// One budget for every document, on the monotonic clock: a wall clock that jumps between two cannot end it.
|
|
650
|
+
const deadline = monotonicNow() + (options.budgetMs ?? EXTRACT_BUDGET_MS);
|
|
650
651
|
const failed = new Set();
|
|
651
652
|
for (const d of defer) {
|
|
652
653
|
const got = await extractTextAsync(d.path, deadline);
|
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"]);
|
package/dist/recall.js
CHANGED
|
@@ -21,6 +21,7 @@
|
|
|
21
21
|
import { closeSync, existsSync, openSync, readdirSync, readSync, statSync } from "node:fs";
|
|
22
22
|
import { homedir } from "node:os";
|
|
23
23
|
import { basename, dirname, isAbsolute, join, resolve } from "node:path";
|
|
24
|
+
import { codexDir } from "./codexdir.js";
|
|
24
25
|
import { claudeProjectDir, forEachLine } from "./session.js";
|
|
25
26
|
import { packContext } from "./pack.js";
|
|
26
27
|
import { maskSecrets, stripControls } from "./handoff.js";
|
|
@@ -242,7 +243,7 @@ function newestIn(dir) {
|
|
|
242
243
|
}
|
|
243
244
|
/** The newest Codex rollout of the last week that started in `cwd`. */
|
|
244
245
|
function newestCodexFor(cwd, home) {
|
|
245
|
-
const codexRoot = join(home, "
|
|
246
|
+
const codexRoot = join(codexDir(home), "sessions");
|
|
246
247
|
if (!existsSync(codexRoot))
|
|
247
248
|
return undefined;
|
|
248
249
|
const since = Date.now() - 7 * 86_400_000;
|
|
@@ -323,7 +324,7 @@ export function findSession(idOrPath, home = homedir()) {
|
|
|
323
324
|
if (existsSync(p))
|
|
324
325
|
return p;
|
|
325
326
|
}
|
|
326
|
-
const codexRoot = join(home, "
|
|
327
|
+
const codexRoot = join(codexDir(home), "sessions");
|
|
327
328
|
let hit;
|
|
328
329
|
const walk = (dir, depth) => {
|
|
329
330
|
if (hit)
|
package/dist/scan.d.ts
CHANGED
|
@@ -64,6 +64,8 @@ export interface Extractor<S = unknown> {
|
|
|
64
64
|
}
|
|
65
65
|
/** Where the cache lives (created only when something is written). */
|
|
66
66
|
export declare function scanCacheDir(env?: NodeJS.ProcessEnv): string;
|
|
67
|
+
/** A fingerprint of the bytes before `off` (its first and last few KB): what tells a file grown in place from one rewritten. */
|
|
68
|
+
export declare function anchorOf(fd: number, off: number): string;
|
|
67
69
|
/**
|
|
68
70
|
* Read every transcript once for all the extractors that need it (each job:
|
|
69
71
|
* an extractor set and its transcripts), so the analyses that follow find
|
package/dist/scan.js
CHANGED
|
@@ -153,7 +153,8 @@ function persist(e, file = entryFile(e.path, e.id)) {
|
|
|
153
153
|
catch { /* never written */ }
|
|
154
154
|
}
|
|
155
155
|
}
|
|
156
|
-
|
|
156
|
+
/** A fingerprint of the bytes before `off` (its first and last few KB): what tells a file grown in place from one rewritten. */
|
|
157
|
+
export function anchorOf(fd, off) {
|
|
157
158
|
const h = createHash("sha1");
|
|
158
159
|
const read = (start, len) => {
|
|
159
160
|
const buf = Buffer.alloc(len);
|
package/dist/session.js
CHANGED
|
@@ -14,6 +14,7 @@ import { readdirSync, readFileSync, statSync, existsSync, openSync, readSync, cl
|
|
|
14
14
|
import { StringDecoder } from "node:string_decoder";
|
|
15
15
|
import { homedir } from "node:os";
|
|
16
16
|
import { join } from "node:path";
|
|
17
|
+
import { codexDir } from "./codexdir.js";
|
|
17
18
|
import { isGeminiChat, listGeminiChats, parseGeminiChat } from "./gemini.js";
|
|
18
19
|
import { claudeDir } from "./claudedir.js";
|
|
19
20
|
/**
|
|
@@ -58,7 +59,7 @@ export function listSessions(limit = 20) {
|
|
|
58
59
|
}
|
|
59
60
|
}
|
|
60
61
|
// Codex keeps rollouts by date: ~/.codex/sessions/YYYY/MM/DD/rollout-*.jsonl.
|
|
61
|
-
const codexRoot = join(
|
|
62
|
+
const codexRoot = join(codexDir(), "sessions");
|
|
62
63
|
if (existsSync(codexRoot)) {
|
|
63
64
|
const walk = (dir, depth) => {
|
|
64
65
|
let entries;
|
|
@@ -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;
|
|
@@ -0,0 +1,216 @@
|
|
|
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 { existsSync, mkdirSync, readdirSync, readFileSync, writeFileSync } from "node:fs";
|
|
36
|
+
import { createHash } from "node:crypto";
|
|
37
|
+
import { basename, dirname, join } from "node:path";
|
|
38
|
+
import { statePath } from "./ledger.js";
|
|
39
|
+
import { refreshEntry, wellFormed, writeWhole } from "./budget.js";
|
|
40
|
+
import { codexFileSpend, geminiFileSpend } from "./spend.js";
|
|
41
|
+
import { isGeminiChat } from "./gemini.js";
|
|
42
|
+
import { subagentDir } from "./subagents.js";
|
|
43
|
+
import { tailUsage } from "./statusline.js";
|
|
44
|
+
import { autoCompactsAt, detectColdResume, withResumeVerdict } from "./coldresume.js";
|
|
45
|
+
import { formatUsd, pricingFor } from "./pricing.js";
|
|
46
|
+
import { formatTokens } from "./tokens.js";
|
|
47
|
+
/** Where the hook speaks unless CONTEXT_DOCTOR_SESSION_PRICE says otherwise. */
|
|
48
|
+
export const SESSION_PRICE_THRESHOLDS = [25, 100, 500];
|
|
49
|
+
/**
|
|
50
|
+
* The entries are written once a prompt has read this much: below it, the
|
|
51
|
+
* next prompt reading the same bytes again costs a few milliseconds, less
|
|
52
|
+
* than a write.
|
|
53
|
+
*/
|
|
54
|
+
const SAVE_BYTES = 512 * 1024;
|
|
55
|
+
/** The thresholds in force, ascending; none when switched off. */
|
|
56
|
+
export function sessionPriceThresholds(env = process.env) {
|
|
57
|
+
if (env.CONTEXT_DOCTOR_NO_SESSION_PRICE === "1")
|
|
58
|
+
return [];
|
|
59
|
+
const raw = env.CONTEXT_DOCTOR_SESSION_PRICE?.trim();
|
|
60
|
+
if (!raw)
|
|
61
|
+
return SESSION_PRICE_THRESHOLDS;
|
|
62
|
+
const set = raw.split(/[\s,]+/).map((v) => Number(v.replace(/^\$/, ""))).filter((v) => Number.isFinite(v) && v > 0);
|
|
63
|
+
// A value that is not a list of dollars is not a reason to go quiet: the defaults.
|
|
64
|
+
return set.length ? [...new Set(set)].sort((a, b) => a - b) : SESSION_PRICE_THRESHOLDS;
|
|
65
|
+
}
|
|
66
|
+
/** This session's files beside the hook's own state: one hash per session, as hook.ts and fanout.ts name them. */
|
|
67
|
+
function base(sessionId) {
|
|
68
|
+
return join(statePath().replace(/\.json$/, "") + ".d", createHash("sha1").update(sessionId).digest("hex").slice(0, 16));
|
|
69
|
+
}
|
|
70
|
+
const ledgerFile = (b) => `${b}.price.json`;
|
|
71
|
+
const claimFile = (b, usd) => `${b}.price-${usd}`;
|
|
72
|
+
/** True for exactly one caller per path: the file is created only if it is not there. */
|
|
73
|
+
function claim(path) {
|
|
74
|
+
for (let attempt = 0; attempt < 2; attempt++) {
|
|
75
|
+
try {
|
|
76
|
+
writeFileSync(path, "", { flag: "wx", mode: 0o600 });
|
|
77
|
+
return true;
|
|
78
|
+
}
|
|
79
|
+
catch (e) {
|
|
80
|
+
if (e.code !== "ENOENT" || attempt)
|
|
81
|
+
return false;
|
|
82
|
+
mkdirSync(dirname(path), { recursive: true });
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
return false;
|
|
86
|
+
}
|
|
87
|
+
/** The app a transcript belongs to. */
|
|
88
|
+
function appOf(transcript, event) {
|
|
89
|
+
if (event === "BeforeAgent" || isGeminiChat(transcript))
|
|
90
|
+
return "gemini";
|
|
91
|
+
return /^rollout-.*\.jsonl$/.test(basename(transcript)) ? "codex" : "claude";
|
|
92
|
+
}
|
|
93
|
+
/**
|
|
94
|
+
* The threshold this prompt is the first to pass, with what to say about
|
|
95
|
+
* it, or undefined (below the first, said already, or anything unreadable).
|
|
96
|
+
* Claims the threshold: a second call for the same one gets undefined.
|
|
97
|
+
*/
|
|
98
|
+
export function sessionPriceDue(input, now = Date.now(), env = process.env) {
|
|
99
|
+
const thresholds = sessionPriceThresholds(env);
|
|
100
|
+
if (!thresholds.length)
|
|
101
|
+
return undefined;
|
|
102
|
+
const b = base(input.sessionId);
|
|
103
|
+
// Everything said: one stat from now on.
|
|
104
|
+
if (existsSync(claimFile(b, thresholds[thresholds.length - 1])))
|
|
105
|
+
return undefined;
|
|
106
|
+
const app = appOf(input.transcript, input.event);
|
|
107
|
+
const files = [[input.transcript, false]];
|
|
108
|
+
if (app === "claude") {
|
|
109
|
+
// Subagents bill to the session that started them.
|
|
110
|
+
const dir = subagentDir(input.transcript);
|
|
111
|
+
try {
|
|
112
|
+
for (const f of readdirSync(dir))
|
|
113
|
+
if (f.endsWith(".jsonl"))
|
|
114
|
+
files.push([join(dir, f), true]);
|
|
115
|
+
}
|
|
116
|
+
catch { /* no subagents */ }
|
|
117
|
+
}
|
|
118
|
+
let saved = {};
|
|
119
|
+
try {
|
|
120
|
+
const raw = JSON.parse(readFileSync(ledgerFile(b), "utf8"))?.f;
|
|
121
|
+
if (raw && typeof raw === "object")
|
|
122
|
+
saved = raw;
|
|
123
|
+
}
|
|
124
|
+
catch { /* none yet, or damaged: read again */ }
|
|
125
|
+
const kept = {};
|
|
126
|
+
let read = 0;
|
|
127
|
+
for (const [file] of files) {
|
|
128
|
+
const prev = saved[file];
|
|
129
|
+
const r = refreshEntry(app, file, wellFormed(prev) && prev.t === app ? prev : undefined, 0, true);
|
|
130
|
+
if (!r)
|
|
131
|
+
continue;
|
|
132
|
+
kept[file] = r.e;
|
|
133
|
+
// Only a Claude Code entry saves a read: Codex's and Gemini's are read whole on a change (through the scan's cache).
|
|
134
|
+
if (app === "claude")
|
|
135
|
+
read += Math.max(0, r.read);
|
|
136
|
+
}
|
|
137
|
+
// Each reply once: a fork's copy shares its key with the reply it copied.
|
|
138
|
+
const seen = new Set();
|
|
139
|
+
let usd = 0, subagentUsd = 0;
|
|
140
|
+
for (const [file, sub] of files) {
|
|
141
|
+
const e = kept[file];
|
|
142
|
+
if (!e)
|
|
143
|
+
continue;
|
|
144
|
+
e.k.forEach((key, i) => {
|
|
145
|
+
if (key) {
|
|
146
|
+
if (seen.has(key))
|
|
147
|
+
return;
|
|
148
|
+
seen.add(key);
|
|
149
|
+
}
|
|
150
|
+
usd += e.d[i];
|
|
151
|
+
if (sub)
|
|
152
|
+
subagentUsd += e.d[i];
|
|
153
|
+
});
|
|
154
|
+
}
|
|
155
|
+
const save = () => { try {
|
|
156
|
+
writeWhole(ledgerFile(b), { f: kept });
|
|
157
|
+
}
|
|
158
|
+
catch { /* read again next time */ } };
|
|
159
|
+
const passed = thresholds.filter((t) => usd >= t);
|
|
160
|
+
const top = passed[passed.length - 1];
|
|
161
|
+
if (top === undefined || existsSync(claimFile(b, top)) || !claim(claimFile(b, top))) {
|
|
162
|
+
if (read >= SAVE_BYTES)
|
|
163
|
+
save();
|
|
164
|
+
return undefined;
|
|
165
|
+
}
|
|
166
|
+
// Passed two at once (a first look at a long session): said once, for the higher.
|
|
167
|
+
for (const t of passed.slice(0, -1))
|
|
168
|
+
claim(claimFile(b, t));
|
|
169
|
+
save();
|
|
170
|
+
return { app, threshold: top, usd, subagentUsd, ...perMessage(app, input, now) };
|
|
171
|
+
}
|
|
172
|
+
/** The main conversation's context now, and what the next message pays for it. */
|
|
173
|
+
function perMessage(app, input, now) {
|
|
174
|
+
try {
|
|
175
|
+
if (app !== "claude") {
|
|
176
|
+
// Codex and Gemini CLI: the last request's prompt, at the cached rate.
|
|
177
|
+
const items = app === "codex" ? codexFileSpend(input.transcript, 0) : geminiFileSpend(input.transcript, 0);
|
|
178
|
+
const last = items[items.length - 1];
|
|
179
|
+
const model = last?.model ?? input.model;
|
|
180
|
+
const p = pricingFor(model);
|
|
181
|
+
if (!last || !p)
|
|
182
|
+
return {};
|
|
183
|
+
const tokens = last.input + last.read + last.write;
|
|
184
|
+
return { tokens, model, readUsd: (tokens * p.cacheReadPerM) / 1e6 };
|
|
185
|
+
}
|
|
186
|
+
// Undefined right after a compaction: the new size is not known yet.
|
|
187
|
+
const live = tailUsage(input.transcript);
|
|
188
|
+
if (!live)
|
|
189
|
+
return {};
|
|
190
|
+
const model = live.model ?? input.model;
|
|
191
|
+
const p = pricingFor(model);
|
|
192
|
+
// Claude Code compacts this very prompt itself: the figure is about to be wrong.
|
|
193
|
+
if (!p || live.tokens >= (autoCompactsAt(model) ?? Infinity))
|
|
194
|
+
return {};
|
|
195
|
+
const cold = withResumeVerdict(detectColdResume(input.transcript, now, undefined, 0), input.rv?.(), now);
|
|
196
|
+
return { tokens: live.tokens, model, readUsd: (live.tokens * p.cacheReadPerM) / 1e6, ...(cold?.resumeUsd !== undefined ? { coldUsd: cold.resumeUsd } : {}) };
|
|
197
|
+
}
|
|
198
|
+
catch {
|
|
199
|
+
return {};
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
/** "$112", "$1,240", "$25.40": a session's cost as the line shows it. */
|
|
203
|
+
const dollars = (n) => (n >= 100 ? `$${Math.round(n).toLocaleString("en-US")}` : `$${n.toFixed(2)}`);
|
|
204
|
+
/** The line for the user (the hook's systemMessage). */
|
|
205
|
+
export function renderSessionPrice(p) {
|
|
206
|
+
const subs = p.subagentUsd >= 0.005 ? ` (${dollars(p.subagentUsd)} of it subagents)` : "";
|
|
207
|
+
const head = `context-doctor: this session has cost ${dollars(p.usd)} so far${subs}`;
|
|
208
|
+
if (p.tokens === undefined || p.readUsd === undefined)
|
|
209
|
+
return `${head}.`;
|
|
210
|
+
const compact = p.app === "gemini" ? "/compress" : "/compact";
|
|
211
|
+
const ctx = `~${formatTokens(p.tokens)} tokens`;
|
|
212
|
+
const each = p.coldUsd !== undefined
|
|
213
|
+
? `the cache expired while it was idle, so this message re-writes its ${ctx} (~${formatUsd(p.coldUsd)}), and each one after re-reads them (~${formatUsd(p.readUsd)})`
|
|
214
|
+
: `each message now re-reads ${ctx} (~${formatUsd(p.readUsd)})`;
|
|
215
|
+
return `${head}; ${each}. ${compact}, or a handoff to a new session, cuts that.`;
|
|
216
|
+
}
|
package/dist/settingsedit.d.ts
CHANGED
|
@@ -64,6 +64,10 @@ export declare function editJsonText(text: string | undefined, after: Record<str
|
|
|
64
64
|
export declare function writeAtomic(path: string, text: string): void;
|
|
65
65
|
/** Remove a file through a symbolic link: the target goes, the link would dangle, so the link goes too. */
|
|
66
66
|
export declare function removeFile(path: string): void;
|
|
67
|
+
/** The lock every context-doctor writer of Claude Code's settings.json takes (fix, cache-ttl, compact-window, autopilot): beside the file. */
|
|
68
|
+
export declare function settingsLockPath(settingsFile: string): string;
|
|
69
|
+
/** Run `fn` holding the lock of Claude Code's settings.json at `settingsFile` (its folder created if missing). */
|
|
70
|
+
export declare function withSettingsLock<T>(settingsFile: string, fn: () => T, waitMs?: number): T;
|
|
67
71
|
/**
|
|
68
72
|
* Run `fn` holding `lockPath` (created exclusively). Another context-doctor
|
|
69
73
|
* holding it is waited for, up to `waitMs`; a lock older than `staleMs` is
|
package/dist/settingsedit.js
CHANGED
|
@@ -10,7 +10,7 @@
|
|
|
10
10
|
* target (the target of a symbolic link, so the link stays), keeping the
|
|
11
11
|
* file's mode; a lock file serialises context-doctor's own writers.
|
|
12
12
|
*/
|
|
13
|
-
import { closeSync, existsSync, mkdirSync, openSync, readFileSync, realpathSync, renameSync, statSync, unlinkSync, writeFileSync } from "node:fs";
|
|
13
|
+
import { closeSync, existsSync, mkdirSync, openSync, readFileSync, realpathSync, renameSync, rmdirSync, statSync, unlinkSync, writeFileSync } from "node:fs";
|
|
14
14
|
import { basename, dirname, join } from "node:path";
|
|
15
15
|
import { tilde } from "./claudedir.js";
|
|
16
16
|
/** A refusal with a message fit for the user: nothing was changed. */
|
|
@@ -421,7 +421,7 @@ export function writeAtomic(path, text) {
|
|
|
421
421
|
const tmp = join(dirname(target), `.${basename(target)}.context-doctor-${process.pid}-${Date.now()}.tmp`);
|
|
422
422
|
writeFileSync(tmp, text, mode !== undefined ? { mode } : undefined);
|
|
423
423
|
try {
|
|
424
|
-
|
|
424
|
+
renameWithRetry(tmp, target);
|
|
425
425
|
}
|
|
426
426
|
catch (e) {
|
|
427
427
|
try {
|
|
@@ -431,6 +431,28 @@ export function writeAtomic(path, text) {
|
|
|
431
431
|
throw e;
|
|
432
432
|
}
|
|
433
433
|
}
|
|
434
|
+
/**
|
|
435
|
+
* renameSync, retried on Windows while another process has the target open:
|
|
436
|
+
* there a rename over a file someone is reading fails with EPERM, EACCES or
|
|
437
|
+
* EBUSY (Claude Code, an editor, or another context-doctor reading
|
|
438
|
+
* settings.json), where POSIX replaces it at once. Up to about 2 s, as
|
|
439
|
+
* graceful-fs does for npm.
|
|
440
|
+
*/
|
|
441
|
+
function renameWithRetry(from, to) {
|
|
442
|
+
const until = Date.now() + 2_000;
|
|
443
|
+
for (let wait = 5;; wait = Math.min(wait * 2, 100)) {
|
|
444
|
+
try {
|
|
445
|
+
renameSync(from, to);
|
|
446
|
+
return;
|
|
447
|
+
}
|
|
448
|
+
catch (e) {
|
|
449
|
+
const code = e.code;
|
|
450
|
+
if (process.platform !== "win32" || !["EPERM", "EACCES", "EBUSY"].includes(code ?? "") || Date.now() >= until)
|
|
451
|
+
throw e;
|
|
452
|
+
Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, wait);
|
|
453
|
+
}
|
|
454
|
+
}
|
|
455
|
+
}
|
|
434
456
|
/** Remove a file through a symbolic link: the target goes, the link would dangle, so the link goes too. */
|
|
435
457
|
export function removeFile(path) {
|
|
436
458
|
try {
|
|
@@ -447,12 +469,38 @@ export function removeFile(path) {
|
|
|
447
469
|
catch { /* gone */ }
|
|
448
470
|
}
|
|
449
471
|
const sleeper = new Int32Array(new SharedArrayBuffer(4));
|
|
472
|
+
/** Locks this process holds: a nested withLock of the same file runs inside the outer one instead of waiting on itself. */
|
|
473
|
+
const held = new Set();
|
|
474
|
+
/** The lock every context-doctor writer of Claude Code's settings.json takes (fix, cache-ttl, compact-window, autopilot): beside the file. */
|
|
475
|
+
export function settingsLockPath(settingsFile) {
|
|
476
|
+
return join(dirname(settingsFile), ".context-doctor-fixes.lock");
|
|
477
|
+
}
|
|
478
|
+
/** Run `fn` holding the lock of Claude Code's settings.json at `settingsFile` (its folder created if missing). */
|
|
479
|
+
export function withSettingsLock(settingsFile, fn, waitMs) {
|
|
480
|
+
const dir = dirname(settingsFile);
|
|
481
|
+
const created = !existsSync(dir);
|
|
482
|
+
if (created)
|
|
483
|
+
mkdirSync(dir, { recursive: true });
|
|
484
|
+
try {
|
|
485
|
+
return withLock(settingsLockPath(settingsFile), fn, waitMs);
|
|
486
|
+
}
|
|
487
|
+
finally {
|
|
488
|
+
// A folder made only to hold the lock goes again (a run that changed nothing leaves nothing).
|
|
489
|
+
if (created)
|
|
490
|
+
try {
|
|
491
|
+
rmdirSync(dir);
|
|
492
|
+
}
|
|
493
|
+
catch { /* it holds something now */ }
|
|
494
|
+
}
|
|
495
|
+
}
|
|
450
496
|
/**
|
|
451
497
|
* Run `fn` holding `lockPath` (created exclusively). Another context-doctor
|
|
452
498
|
* holding it is waited for, up to `waitMs`; a lock older than `staleMs` is
|
|
453
499
|
* taken over (its writer died).
|
|
454
500
|
*/
|
|
455
501
|
export function withLock(lockPath, fn, waitMs = 10_000, staleMs = 30_000) {
|
|
502
|
+
if (held.has(lockPath))
|
|
503
|
+
return fn();
|
|
456
504
|
const until = Date.now() + waitMs;
|
|
457
505
|
let fd;
|
|
458
506
|
for (;;) {
|
|
@@ -461,7 +509,15 @@ export function withLock(lockPath, fn, waitMs = 10_000, staleMs = 30_000) {
|
|
|
461
509
|
break;
|
|
462
510
|
}
|
|
463
511
|
catch (e) {
|
|
464
|
-
|
|
512
|
+
const code = e.code;
|
|
513
|
+
// Windows: a lock file the last holder is still deleting cannot be opened (EPERM, EACCES): it is held a moment longer.
|
|
514
|
+
if (process.platform === "win32" && (code === "EPERM" || code === "EACCES")) {
|
|
515
|
+
if (Date.now() > until)
|
|
516
|
+
throw new SettingsError(`another context-doctor is changing settings (${tilde(lockPath)}); try again. Nothing was changed.`);
|
|
517
|
+
Atomics.wait(sleeper, 0, 0, 25);
|
|
518
|
+
continue;
|
|
519
|
+
}
|
|
520
|
+
if (code !== "EEXIST")
|
|
465
521
|
throw e;
|
|
466
522
|
try {
|
|
467
523
|
if (Date.now() - statSync(lockPath).mtimeMs > staleMs) {
|
|
@@ -477,10 +533,12 @@ export function withLock(lockPath, fn, waitMs = 10_000, staleMs = 30_000) {
|
|
|
477
533
|
Atomics.wait(sleeper, 0, 0, 25);
|
|
478
534
|
}
|
|
479
535
|
}
|
|
536
|
+
held.add(lockPath);
|
|
480
537
|
try {
|
|
481
538
|
return fn();
|
|
482
539
|
}
|
|
483
540
|
finally {
|
|
541
|
+
held.delete(lockPath);
|
|
484
542
|
try {
|
|
485
543
|
closeSync(fd);
|
|
486
544
|
}
|
package/dist/spend.d.ts
CHANGED
|
@@ -55,7 +55,7 @@ export interface SpendItem {
|
|
|
55
55
|
priced: boolean;
|
|
56
56
|
/** Claude Code: run by a subagent. */
|
|
57
57
|
subagent?: boolean;
|
|
58
|
-
/** Claude Code: the reply's row uuid, which a fork's copy shares. */
|
|
58
|
+
/** Claude Code: the reply's row uuid, which a fork's copy shares. Codex: the event's codexEventKey, which a forked rollout's copy shares. */
|
|
59
59
|
key?: string;
|
|
60
60
|
}
|
|
61
61
|
/** A project's name as `savings` shows it: the folder's path with "-" for separators, less "-Users-<you>-". */
|
|
@@ -74,6 +74,7 @@ export declare const CODEX_SPEND_ROWS: Extractor<null>;
|
|
|
74
74
|
export declare function codexFileSpend(file: string, since: number, until?: number): SpendItem[];
|
|
75
75
|
/** Codex rollouts written since `since`: the live ones and the archived. */
|
|
76
76
|
export declare function codexFiles(since: number, home?: string): string[];
|
|
77
|
+
/** Every Codex request in the window, once: a forked rollout's copy of its parent's (codexEventKey) counts at the earliest time met. */
|
|
77
78
|
export declare function codexSpend(since: number, until?: number, home?: string): SpendItem[];
|
|
78
79
|
/**
|
|
79
80
|
* What `spend` takes from a Gemini CLI chat (JSONL): each `gemini` message's
|
|
@@ -164,6 +165,12 @@ export interface SpendOptions {
|
|
|
164
165
|
onProgress?: (done: number, total: number) => void;
|
|
165
166
|
now?: number;
|
|
166
167
|
}
|
|
168
|
+
/**
|
|
169
|
+
* The longest window: ten years, older than any history these tools keep.
|
|
170
|
+
* Unbounded, `--days 10000000` listed every empty day of it (51 s, and
|
|
171
|
+
* --json died on a string too long), and 1e9 days fell off the calendar.
|
|
172
|
+
*/
|
|
173
|
+
export declare const MAX_SPEND_DAYS = 3650;
|
|
167
174
|
/** The last `days` days, every tool on this machine. A tool with nothing on disk is just absent. */
|
|
168
175
|
export declare function spendReport(days?: number, opts?: SpendOptions): SpendReport;
|
|
169
176
|
export declare const usd: (n: number) => string;
|