context-doctor 0.43.0 → 0.45.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 +23 -3
- package/dist/budget.js +184 -50
- package/dist/cache.js +5 -4
- package/dist/cachemisses.js +1 -1
- package/dist/cachettl.d.ts +5 -1
- package/dist/cachettl.js +16 -29
- package/dist/ci.js +18 -2
- package/dist/cli.js +16 -12
- package/dist/codexcompact.d.ts +24 -3
- package/dist/codexcompact.js +221 -48
- package/dist/coldresume.js +16 -8
- package/dist/compactwindow.js +14 -9
- package/dist/cursor.d.ts +10 -0
- package/dist/cursor.js +20 -0
- package/dist/doctor.d.ts +9 -0
- package/dist/doctor.js +52 -0
- package/dist/extract.d.ts +2 -2
- package/dist/extract.js +14 -3
- package/dist/fanout.js +4 -2
- package/dist/fix.d.ts +8 -1
- package/dist/fix.js +59 -13
- package/dist/hook.js +45 -15
- package/dist/httpguard.d.ts +9 -1
- package/dist/httpguard.js +5 -4
- package/dist/install.js +56 -19
- package/dist/lens.js +7 -7
- package/dist/limits.d.ts +17 -4
- package/dist/limits.js +41 -29
- package/dist/mcp.js +63 -63
- package/dist/mcpclient.js +19 -19
- package/dist/mcpschema.js +10 -12
- package/dist/overhead.d.ts +7 -2
- package/dist/overhead.js +11 -3
- package/dist/pack.js +87 -23
- package/dist/pricing.d.ts +125 -6
- package/dist/pricing.js +304 -59
- package/dist/proxy.d.ts +26 -1
- package/dist/proxy.js +45 -5
- package/dist/prune.d.ts +8 -0
- package/dist/prune.js +73 -10
- package/dist/savings.js +17 -9
- package/dist/scan.d.ts +7 -1
- package/dist/scan.js +19 -1
- package/dist/sessionprice.d.ts +9 -2
- package/dist/sessionprice.js +95 -36
- package/dist/settingsedit.js +3 -2
- package/dist/spend.d.ts +75 -10
- package/dist/spend.js +279 -37
- package/dist/statusline.d.ts +10 -2
- package/dist/statusline.js +17 -8
- package/dist/subagentmodel.d.ts +2 -2
- package/dist/subagentmodel.js +42 -25
- package/dist/subagentpay.d.ts +17 -0
- package/dist/subagentpay.js +41 -2
- package/dist/subagents.d.ts +24 -0
- package/dist/subagents.js +93 -27
- package/dist/tasks.js +9 -6
- package/dist/tooloutput.d.ts +2 -0
- package/dist/tooloutput.js +16 -5
- package/package.json +1 -1
package/dist/hook.js
CHANGED
|
@@ -114,20 +114,45 @@ function readSessionState(sessionId) {
|
|
|
114
114
|
}
|
|
115
115
|
/** Keep the directory from growing without bound as sessions come and go. */
|
|
116
116
|
const MAX_STATE_FILES = 200;
|
|
117
|
+
/**
|
|
118
|
+
* Past MAX_STATE_FILES, the sessions least recently touched go, each with
|
|
119
|
+
* all its files (named `<hash>.…`: its state, the session price's ledger and
|
|
120
|
+
* threshold markers, the subagent launch log). File by file, a live
|
|
121
|
+
* session's marker, written once when it passed $25, went first among
|
|
122
|
+
* newer files of other sessions, and the threshold was said again.
|
|
123
|
+
*/
|
|
124
|
+
function pruneStateDir(dir) {
|
|
125
|
+
const files = readdirSync(dir);
|
|
126
|
+
if (files.length <= MAX_STATE_FILES)
|
|
127
|
+
return;
|
|
128
|
+
const sessions = new Map();
|
|
129
|
+
for (const f of files) {
|
|
130
|
+
let t = 0;
|
|
131
|
+
try {
|
|
132
|
+
t = statSync(join(dir, f)).mtimeMs;
|
|
133
|
+
}
|
|
134
|
+
catch { /* gone meanwhile */ }
|
|
135
|
+
const key = f.split(".")[0];
|
|
136
|
+
const s = sessions.get(key) ?? { files: [], t: 0 };
|
|
137
|
+
s.files.push(f);
|
|
138
|
+
s.t = Math.max(s.t, t);
|
|
139
|
+
sessions.set(key, s);
|
|
140
|
+
}
|
|
141
|
+
let left = files.length;
|
|
142
|
+
for (const s of [...sessions.values()].sort((a, b) => a.t - b.t)) {
|
|
143
|
+
if (left <= MAX_STATE_FILES)
|
|
144
|
+
break;
|
|
145
|
+
for (const f of s.files)
|
|
146
|
+
rmSync(join(dir, f), { force: true });
|
|
147
|
+
left -= s.files.length;
|
|
148
|
+
}
|
|
149
|
+
}
|
|
117
150
|
function writeSessionState(sessionId, state) {
|
|
118
151
|
const dir = stateDir();
|
|
119
152
|
mkdirSync(dir, { recursive: true });
|
|
120
153
|
writeFileSync(sessionStatePath(sessionId), JSON.stringify(state));
|
|
121
154
|
try {
|
|
122
|
-
|
|
123
|
-
if (files.length <= MAX_STATE_FILES)
|
|
124
|
-
return;
|
|
125
|
-
const byAge = files
|
|
126
|
-
.map((f) => ({ f, t: statSync(join(dir, f)).mtimeMs }))
|
|
127
|
-
.sort((a, b) => b.t - a.t)
|
|
128
|
-
.slice(MAX_STATE_FILES);
|
|
129
|
-
for (const { f } of byAge)
|
|
130
|
-
rmSync(join(dir, f), { force: true });
|
|
155
|
+
pruneStateDir(dir);
|
|
131
156
|
}
|
|
132
157
|
catch {
|
|
133
158
|
/* pruning is housekeeping, never worth failing a prompt over */
|
|
@@ -289,7 +314,7 @@ export async function runHook(app) {
|
|
|
289
314
|
// A session's own price (sessionprice.ts): once when it passes $25, $100
|
|
290
315
|
// and $500, a line to the user beside the budget's. Claimed before the
|
|
291
316
|
// rest of the hook runs, so it rides in `budgetNote` like the budget's.
|
|
292
|
-
let priceCold = false;
|
|
317
|
+
let priceCold = false, priceSaid = false;
|
|
293
318
|
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
319
|
try {
|
|
295
320
|
const sid = input.session_id ?? input.conversation_id ?? input.transcript_path;
|
|
@@ -297,6 +322,7 @@ export async function runHook(app) {
|
|
|
297
322
|
if (p) {
|
|
298
323
|
budgetNote = [budgetNote, renderSessionPrice(p)].filter(Boolean).join("\n");
|
|
299
324
|
priceCold = p.coldUsd !== undefined;
|
|
325
|
+
priceSaid = true;
|
|
300
326
|
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
327
|
}
|
|
302
328
|
}
|
|
@@ -340,11 +366,14 @@ export async function runHook(app) {
|
|
|
340
366
|
cold = undefined;
|
|
341
367
|
let cr = prev.cr;
|
|
342
368
|
if (cold && cold.lastReplyAt !== prev.cr) {
|
|
343
|
-
notes.push(renderColdResume(cold));
|
|
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");
|
|
346
369
|
cr = cold.lastReplyAt;
|
|
347
|
-
|
|
370
|
+
// The session price's line already told the user this message re-writes the cache and that
|
|
371
|
+
// /compact cuts it: once is enough, so neither the notice nor the model's offer goes out too.
|
|
372
|
+
if (!priceCold) {
|
|
373
|
+
notes.push(renderColdResume(cold));
|
|
374
|
+
notice = [budgetNote, renderColdResumeNotice(cold)].filter(Boolean).join("\n");
|
|
375
|
+
recordLedger({ ev: "cold_resume", sid: sessionId.slice(0, 12), tok: cold.tokens, model: cold.model });
|
|
376
|
+
}
|
|
348
377
|
}
|
|
349
378
|
const emit = (lines) => {
|
|
350
379
|
if (lines.length === 0 && !notice)
|
|
@@ -437,7 +466,8 @@ export async function runHook(app) {
|
|
|
437
466
|
if (topFinding) {
|
|
438
467
|
lines.push(`Largest recoverable waste: ${topFinding.message} (${topFinding.suggestion})`);
|
|
439
468
|
}
|
|
440
|
-
|
|
469
|
+
// Not when the session price's line just said /compact to the user: the reply would say it again.
|
|
470
|
+
if (liveTokens > threshold * 2 && !priceSaid) {
|
|
441
471
|
lines.push(cursor
|
|
442
472
|
? "If the task changes, suggest the user start a new chat from a short summary of this one."
|
|
443
473
|
: "If it fits the flow, offer the user a compaction of the older history.");
|
package/dist/httpguard.d.ts
CHANGED
|
@@ -31,6 +31,12 @@ export interface HttpGuard {
|
|
|
31
31
|
/** Host names (lowercase, no port, no brackets) accepted in Host; "*" accepts any. */
|
|
32
32
|
hosts: Set<string> | "*";
|
|
33
33
|
origins: Set<string>;
|
|
34
|
+
/**
|
|
35
|
+
* Accept any IP address in Host too (the proxy): DNS rebinding needs a
|
|
36
|
+
* host name the attacker controls, and a client of a proxy published from
|
|
37
|
+
* a container may call it by its address.
|
|
38
|
+
*/
|
|
39
|
+
ipLiterals?: boolean;
|
|
34
40
|
}
|
|
35
41
|
/** A Host header's or URL's host name: lowercase, no port, no brackets, no trailing dot. */
|
|
36
42
|
export declare function hostName(hostHeader: string): string;
|
|
@@ -39,7 +45,9 @@ export declare function hostName(hostHeader: string): string;
|
|
|
39
45
|
* --allowed-origins (comma lists) and the CONTEXT_DOCTOR_ALLOWED_HOSTS and
|
|
40
46
|
* CONTEXT_DOCTOR_ALLOWED_ORIGINS environment variables.
|
|
41
47
|
*/
|
|
42
|
-
export declare function makeGuard(bindHost: string, allowedHosts?: string, allowedOrigins?: string, env?: NodeJS.ProcessEnv
|
|
48
|
+
export declare function makeGuard(bindHost: string, allowedHosts?: string, allowedOrigins?: string, env?: NodeJS.ProcessEnv, opts?: {
|
|
49
|
+
ipLiterals?: boolean;
|
|
50
|
+
}): HttpGuard;
|
|
43
51
|
/** Why this request may not reach /mcp, or undefined when it may. */
|
|
44
52
|
export declare function refusal(guard: HttpGuard, headers: IncomingMessage["headers"]): string | undefined;
|
|
45
53
|
/**
|
package/dist/httpguard.js
CHANGED
|
@@ -20,6 +20,7 @@
|
|
|
20
20
|
* then handed to the transport, so no request can make the server buffer
|
|
21
21
|
* an unbounded body.
|
|
22
22
|
*/
|
|
23
|
+
import { isIP } from "node:net";
|
|
23
24
|
export const HTTP_LIMITS = { bodyBytes: 10 * 1024 * 1024, bodyMs: 30_000 };
|
|
24
25
|
/** Origins a browser may call from without being listed: ChatGPT's. */
|
|
25
26
|
export const DEFAULT_ALLOWED_ORIGINS = ["https://chatgpt.com", "https://chat.openai.com"];
|
|
@@ -41,17 +42,17 @@ export function hostName(hostHeader) {
|
|
|
41
42
|
* --allowed-origins (comma lists) and the CONTEXT_DOCTOR_ALLOWED_HOSTS and
|
|
42
43
|
* CONTEXT_DOCTOR_ALLOWED_ORIGINS environment variables.
|
|
43
44
|
*/
|
|
44
|
-
export function makeGuard(bindHost, allowedHosts, allowedOrigins, env = process.env) {
|
|
45
|
+
export function makeGuard(bindHost, allowedHosts, allowedOrigins, env = process.env, opts = {}) {
|
|
45
46
|
const extra = [...list(allowedHosts), ...list(env.CONTEXT_DOCTOR_ALLOWED_HOSTS)];
|
|
46
47
|
const origins = new Set([...DEFAULT_ALLOWED_ORIGINS, ...list(allowedOrigins), ...list(env.CONTEXT_DOCTOR_ALLOWED_ORIGINS)].map((o) => o.toLowerCase().replace(/\/+$/, "")));
|
|
47
48
|
if (extra.includes("*"))
|
|
48
|
-
return { hosts: "*", origins };
|
|
49
|
+
return { hosts: "*", origins, ipLiterals: opts.ipLiterals };
|
|
49
50
|
const bind = hostName(bindHost);
|
|
50
51
|
const hosts = new Set([...LOOPBACK_HOSTS, ...extra.map(hostName)]);
|
|
51
52
|
// A specific bind address or name is one the server answers to; a wildcard is not a name.
|
|
52
53
|
if (bind && bind !== "0.0.0.0" && bind !== "::")
|
|
53
54
|
hosts.add(bind);
|
|
54
|
-
return { hosts, origins };
|
|
55
|
+
return { hosts, origins, ipLiterals: opts.ipLiterals };
|
|
55
56
|
}
|
|
56
57
|
/** Why this request may not reach /mcp, or undefined when it may. */
|
|
57
58
|
export function refusal(guard, headers) {
|
|
@@ -59,7 +60,7 @@ export function refusal(guard, headers) {
|
|
|
59
60
|
const host = hostName(String(headers.host ?? ""));
|
|
60
61
|
if (!host)
|
|
61
62
|
return "the request has no Host header";
|
|
62
|
-
if (!guard.hosts.has(host)) {
|
|
63
|
+
if (!guard.hosts.has(host) && !(guard.ipLiterals && isIP(host))) {
|
|
63
64
|
return `Host "${host}" is not one this server answers to. Behind a tunnel or under a host name, start it with --allowed-hosts ${host}`;
|
|
64
65
|
}
|
|
65
66
|
}
|
package/dist/install.js
CHANGED
|
@@ -250,6 +250,16 @@ function readText(path) {
|
|
|
250
250
|
return undefined;
|
|
251
251
|
}
|
|
252
252
|
}
|
|
253
|
+
/**
|
|
254
|
+
* Whether a step changed any of `paths`, by their text before it ran: a
|
|
255
|
+
* second install said "MCP server added" for every app it left exactly as
|
|
256
|
+
* it was. `said(done, kept)` picks the line's verb.
|
|
257
|
+
*/
|
|
258
|
+
function changeWatch(...paths) {
|
|
259
|
+
const before = paths.map(readText);
|
|
260
|
+
const changed = () => paths.some((p, i) => readText(p) !== before[i]);
|
|
261
|
+
return { changed, said: (done, kept = "already installed, unchanged") => (changed() ? done : kept) };
|
|
262
|
+
}
|
|
253
263
|
/**
|
|
254
264
|
* Write `data` into a JSON config the way a person would edit it: only the
|
|
255
265
|
* keys and list items that differ are changed in the text (settingsedit.ts),
|
|
@@ -606,7 +616,9 @@ function installSkillInto(skillDest, appHome) {
|
|
|
606
616
|
mkdirSync(skillDest, { recursive: true });
|
|
607
617
|
// Written whole and renamed into place: two installs at once (or Claude
|
|
608
618
|
// Code reading the skill) made Windows refuse a plain copy with EBUSY.
|
|
609
|
-
|
|
619
|
+
const skill = readFileSync(skillSource, "utf8");
|
|
620
|
+
if (readText(join(skillDest, "SKILL.md")) !== skill)
|
|
621
|
+
writeAtomic(join(skillDest, "SKILL.md"), skill);
|
|
610
622
|
if (appHome && missing.length > 0) {
|
|
611
623
|
const all = [...new Set([...createdSkillFolders(appHome), ...missing])];
|
|
612
624
|
writeAtomic(join(appHome, CREATED_MARKER), JSON.stringify({ created: all }) + "\n");
|
|
@@ -791,24 +803,28 @@ function installCodex(entry, failures) {
|
|
|
791
803
|
backupOnce(configPath);
|
|
792
804
|
writeFileSync(configPath, next);
|
|
793
805
|
}
|
|
794
|
-
console.log(`✓ Codex: MCP server added (${configPath})`);
|
|
806
|
+
console.log(`✓ Codex: MCP server ${next !== current ? "added" : "already installed, unchanged"} (${configPath})`);
|
|
795
807
|
}
|
|
796
808
|
catch (e) {
|
|
797
809
|
console.error(`✗ Codex MCP: ${e.message}`);
|
|
798
810
|
failures.push("Codex MCP");
|
|
799
811
|
}
|
|
800
812
|
try {
|
|
813
|
+
const watch = changeWatch(join(dir, "skills", "context-doctor", "SKILL.md"));
|
|
801
814
|
const skill = installSkillInto(join(dir, "skills", "context-doctor"), dir);
|
|
802
815
|
if (skill)
|
|
803
|
-
console.log(`✓ Agent Skill installed for Codex (${skill})`);
|
|
816
|
+
console.log(`✓ Agent Skill ${watch.said("installed", "already installed, up to date")} for Codex (${skill})`);
|
|
804
817
|
}
|
|
805
818
|
catch (e) {
|
|
806
819
|
console.error(`✗ Codex skill: ${e.message}`);
|
|
807
820
|
failures.push("Codex skill");
|
|
808
821
|
}
|
|
809
822
|
try {
|
|
823
|
+
const watch = changeWatch(join(dir, "hooks.json"));
|
|
810
824
|
const hook = installHookInto(join(dir, "hooks.json"), dir);
|
|
811
|
-
if (hook)
|
|
825
|
+
if (hook && !watch.changed())
|
|
826
|
+
console.log(`✓ Codex every-prompt hook already installed, unchanged (${hook})`);
|
|
827
|
+
else if (hook) {
|
|
812
828
|
console.log(`✓ Codex every-prompt hook installed (${hook})`);
|
|
813
829
|
console.log(" Codex runs a new hook only after you trust it once: open Codex, type /hooks, and trust context-doctor.");
|
|
814
830
|
}
|
|
@@ -935,12 +951,13 @@ function installCopilot(entry, failures) {
|
|
|
935
951
|
}
|
|
936
952
|
config.mcpServers = config.mcpServers ?? {};
|
|
937
953
|
const want = copilotMcpEntry(entry);
|
|
938
|
-
|
|
954
|
+
const stale = JSON.stringify(config.mcpServers["context-doctor"]) !== JSON.stringify(want);
|
|
955
|
+
if (stale) {
|
|
939
956
|
config.mcpServers["context-doctor"] = want;
|
|
940
957
|
writeJsonWithBackup(path, config);
|
|
941
958
|
}
|
|
942
959
|
mcpOk = true;
|
|
943
|
-
console.log(`✓ GitHub Copilot: MCP server added (${path})`);
|
|
960
|
+
console.log(`✓ GitHub Copilot: MCP server ${stale ? "added" : "already installed, unchanged"} (${path})`);
|
|
944
961
|
}
|
|
945
962
|
catch (e) {
|
|
946
963
|
console.error(`✗ GitHub Copilot MCP: ${e.message}`);
|
|
@@ -971,12 +988,15 @@ function installCopilot(entry, failures) {
|
|
|
971
988
|
const entries = current ?? [];
|
|
972
989
|
const want = copilotHookEntry();
|
|
973
990
|
const ours = entries.filter(isOurCopilotEntry);
|
|
974
|
-
|
|
991
|
+
const upToDate = ours.length === 1 && JSON.stringify(ours[0]) === JSON.stringify(want);
|
|
992
|
+
if (!upToDate) {
|
|
975
993
|
config.hooks[COPILOT_HOOK_EVENT] = [...entries.filter((e) => !isOurCopilotEntry(e)), want];
|
|
976
994
|
mkdirSync(dirname(path), { recursive: true });
|
|
977
995
|
writeFileSync(path, JSON.stringify(config, null, 2));
|
|
978
996
|
}
|
|
979
|
-
console.log(
|
|
997
|
+
console.log(upToDate
|
|
998
|
+
? `✓ GitHub Copilot session-start hook already installed, unchanged (${path})`
|
|
999
|
+
: `✓ GitHub Copilot session-start hook installed (${path}): each new or resumed session gets the standing context rules`);
|
|
980
1000
|
}
|
|
981
1001
|
catch (e) {
|
|
982
1002
|
console.error(`✗ GitHub Copilot hook: ${e.message}`);
|
|
@@ -1102,10 +1122,13 @@ export function runInstall(options = {}) {
|
|
|
1102
1122
|
if (config.mcpServers !== undefined && !isPlainObject(config.mcpServers))
|
|
1103
1123
|
throw new Error(`"mcpServers" in ${target.configPath} is not an object; fix it, then re-run. Nothing was changed.`);
|
|
1104
1124
|
config.mcpServers = config.mcpServers ?? {};
|
|
1105
|
-
//
|
|
1106
|
-
|
|
1107
|
-
|
|
1108
|
-
|
|
1125
|
+
// Overwrite a stale entry (re-running install is how one gets repaired); leave a current one, and its file, alone.
|
|
1126
|
+
const watch = changeWatch(target.configPath);
|
|
1127
|
+
if (JSON.stringify(config.mcpServers["context-doctor"]) !== JSON.stringify(entry)) {
|
|
1128
|
+
config.mcpServers["context-doctor"] = entry;
|
|
1129
|
+
writeJsonWithBackup(target.configPath, config);
|
|
1130
|
+
}
|
|
1131
|
+
console.log(`✓ ${target.name}: MCP server ${watch.said("added")} (${target.configPath})`);
|
|
1109
1132
|
}
|
|
1110
1133
|
catch (e) {
|
|
1111
1134
|
console.error(`✗ ${target.name}: ${e.message}`);
|
|
@@ -1113,9 +1136,10 @@ export function runInstall(options = {}) {
|
|
|
1113
1136
|
}
|
|
1114
1137
|
}
|
|
1115
1138
|
try {
|
|
1139
|
+
const watch = changeWatch(join(claudeDir(), "skills", "context-doctor", "SKILL.md"));
|
|
1116
1140
|
const skillPath = viaPlugin ? null : installSkill();
|
|
1117
1141
|
if (skillPath)
|
|
1118
|
-
console.log(`✓ Agent Skill installed for Claude Code (${skillPath})`);
|
|
1142
|
+
console.log(`✓ Agent Skill ${watch.said("installed", "already installed, up to date")} for Claude Code (${skillPath})`);
|
|
1119
1143
|
}
|
|
1120
1144
|
catch (e) {
|
|
1121
1145
|
console.error(`✗ Agent Skill: ${e.message}`);
|
|
@@ -1127,9 +1151,10 @@ export function runInstall(options = {}) {
|
|
|
1127
1151
|
// A skills folder Antigravity did not have yet is ours to remove again.
|
|
1128
1152
|
if (!existsSync(dirname(dir)))
|
|
1129
1153
|
rememberAntigravityFolder(dirname(dir));
|
|
1154
|
+
const watch = changeWatch(join(dir, "SKILL.md"));
|
|
1130
1155
|
const skillPath = installSkillInto(dir);
|
|
1131
1156
|
if (skillPath)
|
|
1132
|
-
console.log(`✓ Antigravity skill installed (${
|
|
1157
|
+
console.log(`✓ Antigravity skill ${watch.said("installed", "already installed, up to date")} (${skillPath})`);
|
|
1133
1158
|
}
|
|
1134
1159
|
catch (e) {
|
|
1135
1160
|
console.error(`✗ Antigravity skill: ${e.message}`);
|
|
@@ -1138,9 +1163,12 @@ export function runInstall(options = {}) {
|
|
|
1138
1163
|
}
|
|
1139
1164
|
}
|
|
1140
1165
|
try {
|
|
1166
|
+
const watch = changeWatch(join(claudeDir(), "settings.json"));
|
|
1141
1167
|
const hookPath = viaPlugin ? null : installHook();
|
|
1142
1168
|
if (hookPath) {
|
|
1143
|
-
console.log(
|
|
1169
|
+
console.log(watch.changed()
|
|
1170
|
+
? `✓ Claude Code every-prompt hook installed (${hookPath}) — heavy sessions get automatic hygiene guidance`
|
|
1171
|
+
: `✓ Claude Code hooks already installed, unchanged (${hookPath})`);
|
|
1144
1172
|
// npx resolves the package on every single prompt; a global install makes
|
|
1145
1173
|
// the hook a plain exec instead, which is both faster and update-proof.
|
|
1146
1174
|
if (hookUsesNpx()) {
|
|
@@ -1157,9 +1185,12 @@ export function runInstall(options = {}) {
|
|
|
1157
1185
|
if (!viaPlugin && claudeCodePresent()) {
|
|
1158
1186
|
try {
|
|
1159
1187
|
const readiness = modelSwitchReadiness(claudeCodeInstallsFromEnv());
|
|
1188
|
+
const watch = changeWatch(join(claudeDir(), "settings.json"));
|
|
1160
1189
|
switch (installModelSwitchHook(readiness)) {
|
|
1161
1190
|
case "installed":
|
|
1162
|
-
console.log(
|
|
1191
|
+
console.log(watch.changed()
|
|
1192
|
+
? "✓ Claude Code model-switch warning installed (PreModelSwitch): before /model switches, the price of re-writing this context into the new model's cache"
|
|
1193
|
+
: "✓ Claude Code model-switch warning already installed, unchanged");
|
|
1163
1194
|
break;
|
|
1164
1195
|
case "old":
|
|
1165
1196
|
console.log(`– Claude Code model-switch warning skipped: ${describeInstalls(readiness.old)} predates PreModelSwitch (${PRE_MODEL_SWITCH_SINCE}) and would`);
|
|
@@ -1176,9 +1207,13 @@ export function runInstall(options = {}) {
|
|
|
1176
1207
|
}
|
|
1177
1208
|
}
|
|
1178
1209
|
try {
|
|
1210
|
+
const watch = changeWatch(cursorHooksPath());
|
|
1179
1211
|
const cursorHook = installCursorHook();
|
|
1180
|
-
if (cursorHook)
|
|
1181
|
-
console.log(
|
|
1212
|
+
if (cursorHook) {
|
|
1213
|
+
console.log(watch.changed()
|
|
1214
|
+
? `✓ Cursor hooks installed (${cursorHook}: after each tool call, after a failed one, at chat start) — Cursor's agent gets the same guidance in heavy sessions`
|
|
1215
|
+
: `✓ Cursor hooks already installed, unchanged (${cursorHook})`);
|
|
1216
|
+
}
|
|
1182
1217
|
}
|
|
1183
1218
|
catch (e) {
|
|
1184
1219
|
console.error(`✗ Cursor hook: ${e.message}`);
|
|
@@ -1188,9 +1223,10 @@ export function runInstall(options = {}) {
|
|
|
1188
1223
|
installCopilot(entry, failures);
|
|
1189
1224
|
if (geminiCliPresent()) {
|
|
1190
1225
|
try {
|
|
1226
|
+
const watch = changeWatch(geminiSettingsPath());
|
|
1191
1227
|
const hook = installHookInto(geminiSettingsPath(), join(homedir(), ".gemini"), "BeforeAgent");
|
|
1192
1228
|
if (hook)
|
|
1193
|
-
console.log(`✓ Gemini CLI every-prompt hook installed (${hook})`);
|
|
1229
|
+
console.log(`✓ Gemini CLI every-prompt hook ${watch.said("installed")} (${hook})`);
|
|
1194
1230
|
}
|
|
1195
1231
|
catch (e) {
|
|
1196
1232
|
console.error(`✗ Gemini CLI hook: ${e.message}`);
|
|
@@ -1425,6 +1461,7 @@ const OUR_CLAUDE_FILES = [
|
|
|
1425
1461
|
".context-doctor-subagent-costs.json",
|
|
1426
1462
|
".context-doctor-budget.json",
|
|
1427
1463
|
".context-doctor-budget-state.json",
|
|
1464
|
+
".context-doctor-budget-said.d",
|
|
1428
1465
|
];
|
|
1429
1466
|
export async function runUninstall() {
|
|
1430
1467
|
changes = 0;
|
package/dist/lens.js
CHANGED
|
@@ -17,7 +17,7 @@
|
|
|
17
17
|
import { createHash } from "node:crypto";
|
|
18
18
|
import { forEachLine, listSessions, replyCounter, isClaudeSession } from "./session.js";
|
|
19
19
|
import { rowsOf, slimUsage } from "./scan.js";
|
|
20
|
-
import { openAIUsage,
|
|
20
|
+
import { openAIUsage, requestCost } from "./pricing.js";
|
|
21
21
|
import { formatTokens, realModel } from "./tokens.js";
|
|
22
22
|
const num = (v) => (typeof v === "number" && Number.isFinite(v) && v > 0 ? v : 0);
|
|
23
23
|
class Acc {
|
|
@@ -25,11 +25,11 @@ class Acc {
|
|
|
25
25
|
polls = new Map();
|
|
26
26
|
pollContext = 0;
|
|
27
27
|
sessions = 0;
|
|
28
|
-
request(model, u, reasoning) {
|
|
28
|
+
request(model, u, reasoning, at) {
|
|
29
29
|
const name = model ?? "unknown";
|
|
30
30
|
const m = this.models.get(name) ?? { model: name, requests: 0, outputTokens: 0, reasoningTokens: 0, outputUsd: 0, totalUsd: 0 };
|
|
31
|
-
|
|
32
|
-
const cost =
|
|
31
|
+
// As billed (requestCost): fast mode, US-only, a long prompt's tier, web searches.
|
|
32
|
+
const cost = requestCost(model, u, Number.isFinite(at) ? at : undefined);
|
|
33
33
|
m.requests++;
|
|
34
34
|
m.outputTokens += num(u.output_tokens);
|
|
35
35
|
m.reasoningTokens += Math.min(num(u.output_tokens), reasoning);
|
|
@@ -61,7 +61,7 @@ const callKey = (name, input) => `${name}\u0000${typeof input === "string" ? inp
|
|
|
61
61
|
/** A call's identity, as a hash: equal calls stay equal, and the cache keeps no command or input. */
|
|
62
62
|
const callId = (key) => createHash("sha1").update(key).digest("base64");
|
|
63
63
|
export const LENS_ROWS = {
|
|
64
|
-
id: "lens.
|
|
64
|
+
id: "lens.2",
|
|
65
65
|
init: () => null,
|
|
66
66
|
line(line, row, out) {
|
|
67
67
|
const prompt = line.includes('"type":"user"') && !line.includes('"tool_result"');
|
|
@@ -118,7 +118,7 @@ function scanClaude(path, acc, since, runRows) {
|
|
|
118
118
|
const seen = sighting({ message: { id }, uuid: r.uuid });
|
|
119
119
|
if (seen === "new" && inPeriod) {
|
|
120
120
|
const u = r.u;
|
|
121
|
-
const usd = acc.request(r.model, u, num(u.output_tokens_details?.thinking_tokens));
|
|
121
|
+
const usd = acc.request(r.model, u, num(u.output_tokens_details?.thinking_tokens), at);
|
|
122
122
|
if (id)
|
|
123
123
|
costOf.set(id, { usd, context: num(r.u.input_tokens) + num(r.u.cache_read_input_tokens) + num(r.u.cache_creation_input_tokens) });
|
|
124
124
|
}
|
|
@@ -176,7 +176,7 @@ function scanCodex(path, acc, since) {
|
|
|
176
176
|
return;
|
|
177
177
|
}
|
|
178
178
|
const u = openAIUsage(last);
|
|
179
|
-
const usd = acc.request(model, u, num(last.reasoning_output_tokens));
|
|
179
|
+
const usd = acc.request(model, u, num(last.reasoning_output_tokens), at);
|
|
180
180
|
pending.forEach((name, i) => acc.poll(name, i === 0 ? usd : 0, i === 0 ? num(last.input_tokens) : 0));
|
|
181
181
|
pending = [];
|
|
182
182
|
}
|
package/dist/limits.d.ts
CHANGED
|
@@ -26,6 +26,7 @@
|
|
|
26
26
|
* instead of printing a number.
|
|
27
27
|
*/
|
|
28
28
|
import { type Extractor } from "./scan.js";
|
|
29
|
+
import { type ModelPricing, type Modifiers } from "./pricing.js";
|
|
29
30
|
/** Claude Code's two windows, as its status line input names them. */
|
|
30
31
|
export declare const CLAUDE_WINDOWS: readonly ["five_hour", "seven_day"];
|
|
31
32
|
/** One reading of one window: how much of it was used at `ts`. */
|
|
@@ -116,13 +117,22 @@ export interface ClaudeRequest extends UsagePoint {
|
|
|
116
117
|
sidechain?: boolean;
|
|
117
118
|
/** The prompt's part of `usd` (input, cache writes, cache reads): what `savings` bills. */
|
|
118
119
|
promptUsd: number;
|
|
120
|
+
/** The rates it billed at (requestCost: its tier, fast mode, US-only, its date); absent when unpriced. */
|
|
121
|
+
rates?: ModelPricing;
|
|
122
|
+
/** What fast mode, US-only, a long prompt's tier and web searches added to its list price, inside `usd`. */
|
|
123
|
+
modifiers: Modifiers;
|
|
124
|
+
/** Priced by family, or past the day its row's price changed: an estimate. */
|
|
125
|
+
estimated?: boolean;
|
|
126
|
+
/** Its row's price changed on this day, before the request. */
|
|
127
|
+
changedOn?: string;
|
|
119
128
|
}
|
|
120
129
|
/**
|
|
121
130
|
* The requests of one Claude Code transcript between `since` and `until`,
|
|
122
|
-
* each reply once, its output settled on its last row
|
|
123
|
-
*
|
|
124
|
-
*
|
|
125
|
-
*
|
|
131
|
+
* each reply once, its output settled on its last row (billed at the
|
|
132
|
+
* reply's own rates, requestCost's). `runRows` is shared by every file of
|
|
133
|
+
* one report, so a fork's copy of its parent's replies is counted once, in
|
|
134
|
+
* the file met first (replyCounter). Replies on `<synthetic>`
|
|
135
|
+
* (isUnbilledModel) are left out. Throws when the transcript cannot be read.
|
|
126
136
|
*/
|
|
127
137
|
export declare function claudeFileUsage(file: string, since: number, until?: number, runRows?: Set<string>): ClaudeRequest[];
|
|
128
138
|
/**
|
|
@@ -134,7 +144,10 @@ export declare function claudeUsageFiles(since: number, tops?: string[]): Array<
|
|
|
134
144
|
file: string;
|
|
135
145
|
top: string;
|
|
136
146
|
subagent: boolean;
|
|
147
|
+
run?: string;
|
|
137
148
|
}>;
|
|
149
|
+
/** How long before a period a session may have been last written and still have subagents running into it. */
|
|
150
|
+
export declare const SUBAGENT_LOOKBACK_MS: number;
|
|
138
151
|
/**
|
|
139
152
|
* Every Claude Code request between `since` and `until`, main threads and
|
|
140
153
|
* subagents alike (both draw on the same limits), each reply once.
|
package/dist/limits.js
CHANGED
|
@@ -31,9 +31,9 @@ import { dirname, join } from "node:path";
|
|
|
31
31
|
import { codexDir } from "./codexdir.js";
|
|
32
32
|
import { statePath } from "./ledger.js";
|
|
33
33
|
import { forEachLine, listSessions, outputSettler, replyCounter, isClaudeSession } from "./session.js";
|
|
34
|
-
import {
|
|
34
|
+
import { subagentFiles } from "./subagents.js";
|
|
35
35
|
import { pick, rowsOf, slimUsage } from "./scan.js";
|
|
36
|
-
import {
|
|
36
|
+
import { isUnbilledModel, NO_MODIFIERS, openAIUsage, requestCost } from "./pricing.js";
|
|
37
37
|
import { realModel } from "./tokens.js";
|
|
38
38
|
const MIN = 60_000;
|
|
39
39
|
const HOUR = 60 * MIN;
|
|
@@ -290,8 +290,7 @@ export function codexLimitData(since, root = codexSessionsRoot()) {
|
|
|
290
290
|
if (last && num(last.input_tokens) > 0 && (runTotal === 0 || runTotal !== total)) {
|
|
291
291
|
total = runTotal;
|
|
292
292
|
const u = openAIUsage(last);
|
|
293
|
-
|
|
294
|
-
ev.point = { ts, app: "codex", model, input: num(u.input_tokens), read: num(u.cache_read_input_tokens), write: num(u.cache_creation_input_tokens), output: num(u.output_tokens), usd: price ? usageCost(u, price).totalUsd : 0 };
|
|
293
|
+
ev.point = { ts, app: "codex", model, input: num(u.input_tokens), read: num(u.cache_read_input_tokens), write: num(u.cache_creation_input_tokens), output: num(u.output_tokens), usd: requestCost(model, u, ts)?.totalUsd ?? 0 };
|
|
295
294
|
}
|
|
296
295
|
const rl = p.rate_limits;
|
|
297
296
|
if (rl && typeof rl === "object") {
|
|
@@ -339,7 +338,7 @@ export function codexLimitData(since, root = codexSessionsRoot()) {
|
|
|
339
338
|
* main thread.
|
|
340
339
|
*/
|
|
341
340
|
export const USAGE_ROWS = {
|
|
342
|
-
id: "usage.
|
|
341
|
+
id: "usage.3",
|
|
343
342
|
init: () => ({ ids: {} }),
|
|
344
343
|
line(line, row, out, st) {
|
|
345
344
|
if (!line.includes('"usage"'))
|
|
@@ -366,10 +365,11 @@ export const USAGE_ROWS = {
|
|
|
366
365
|
};
|
|
367
366
|
/**
|
|
368
367
|
* The requests of one Claude Code transcript between `since` and `until`,
|
|
369
|
-
* each reply once, its output settled on its last row
|
|
370
|
-
*
|
|
371
|
-
*
|
|
372
|
-
*
|
|
368
|
+
* each reply once, its output settled on its last row (billed at the
|
|
369
|
+
* reply's own rates, requestCost's). `runRows` is shared by every file of
|
|
370
|
+
* one report, so a fork's copy of its parent's replies is counted once, in
|
|
371
|
+
* the file met first (replyCounter). Replies on `<synthetic>`
|
|
372
|
+
* (isUnbilledModel) are left out. Throws when the transcript cannot be read.
|
|
373
373
|
*/
|
|
374
374
|
export function claudeFileUsage(file, since, until = Infinity, runRows) {
|
|
375
375
|
const out = [];
|
|
@@ -385,20 +385,28 @@ export function claudeFileUsage(file, since, until = Infinity, runRows) {
|
|
|
385
385
|
const known = typeof m.id === "string" ? byId.get(m.id) : undefined;
|
|
386
386
|
const more = settle(e, false);
|
|
387
387
|
if (known && more) {
|
|
388
|
-
known.point
|
|
389
|
-
|
|
390
|
-
|
|
388
|
+
const p = known.point;
|
|
389
|
+
p.output += more;
|
|
390
|
+
if (p.rates) {
|
|
391
|
+
p.usd += (more * p.rates.outputPerM) / 1e6;
|
|
392
|
+
// What the modifiers added grows with the output: priced again whole.
|
|
393
|
+
if (p.modifiers.fastUsd || p.modifiers.geoUsd || p.modifiers.longUsd)
|
|
394
|
+
p.modifiers = requestCost(p.model, { ...known.u, output_tokens: p.output }, p.ts).modifiers;
|
|
395
|
+
}
|
|
391
396
|
}
|
|
392
397
|
return;
|
|
393
398
|
}
|
|
394
399
|
if (seen !== "new")
|
|
395
400
|
return;
|
|
396
401
|
settle(e, true);
|
|
402
|
+
// A reply Claude Code made itself (an error, an interruption) never reached the API: no request, priced or not.
|
|
403
|
+
if (isUnbilledModel(m.model))
|
|
404
|
+
return;
|
|
397
405
|
const ts = Date.parse(String(e.timestamp ?? ""));
|
|
398
406
|
if (!Number.isFinite(ts) || ts < since || ts > until)
|
|
399
407
|
return;
|
|
400
408
|
const u = m.usage;
|
|
401
|
-
const point = { ts, app: "claude", model: realModel(m.model), input: num(u.input_tokens), read: num(u.cache_read_input_tokens), write: num(u.cache_creation_input_tokens), output: num(u.output_tokens), usd: 0, promptUsd: 0 };
|
|
409
|
+
const point = { ts, app: "claude", model: realModel(m.model), input: num(u.input_tokens), read: num(u.cache_read_input_tokens), write: num(u.cache_creation_input_tokens), output: num(u.output_tokens), usd: 0, promptUsd: 0, modifiers: { ...NO_MODIFIERS } };
|
|
402
410
|
if (point.input + point.read + point.write === 0)
|
|
403
411
|
return;
|
|
404
412
|
if (typeof e.uuid === "string")
|
|
@@ -407,15 +415,20 @@ export function claudeFileUsage(file, since, until = Infinity, runRows) {
|
|
|
407
415
|
point.id = m.id;
|
|
408
416
|
if (e.isSidechain === true)
|
|
409
417
|
point.sidechain = true;
|
|
410
|
-
const
|
|
411
|
-
if (
|
|
412
|
-
const c = usageCost(u, price);
|
|
418
|
+
const c = requestCost(point.model, u, ts);
|
|
419
|
+
if (c) {
|
|
413
420
|
point.usd = c.totalUsd;
|
|
414
421
|
point.promptUsd = c.promptUsd;
|
|
422
|
+
point.rates = c.rates;
|
|
423
|
+
point.modifiers = c.modifiers;
|
|
424
|
+
if (c.estimated)
|
|
425
|
+
point.estimated = true;
|
|
426
|
+
if (c.changedOn)
|
|
427
|
+
point.changedOn = c.changedOn;
|
|
415
428
|
}
|
|
416
429
|
out.push(point);
|
|
417
430
|
if (typeof m.id === "string")
|
|
418
|
-
byId.set(m.id, { point,
|
|
431
|
+
byId.set(m.id, { point, u });
|
|
419
432
|
});
|
|
420
433
|
return out;
|
|
421
434
|
}
|
|
@@ -425,22 +438,21 @@ export function claudeFileUsage(file, since, until = Infinity, runRows) {
|
|
|
425
438
|
* first), each followed by its subagents'.
|
|
426
439
|
*/
|
|
427
440
|
export function claudeUsageFiles(since, tops) {
|
|
428
|
-
|
|
441
|
+
// A session last written before `since` can still have subagents (a workflow run, a background
|
|
442
|
+
// agent) writing after it: those of the sessions written in the SUBAGENT_LOOKBACK_MS before count.
|
|
443
|
+
const listed = tops ? undefined : listSessions(10_000).filter((s) => isClaudeSession(s) && s.modifiedAt.getTime() >= since - SUBAGENT_LOOKBACK_MS);
|
|
444
|
+
const mains = tops ?? listed.map((s) => s.path);
|
|
429
445
|
const files = [];
|
|
430
|
-
for (const t of mains) {
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
if (f.endsWith(".jsonl") && statSync(join(dir, f)).mtimeMs >= since)
|
|
436
|
-
files.push({ file: join(dir, f), top: t, subagent: true });
|
|
437
|
-
}
|
|
438
|
-
catch {
|
|
439
|
-
/* no subagents */
|
|
440
|
-
}
|
|
446
|
+
for (const [i, t] of mains.entries()) {
|
|
447
|
+
if (!listed || listed[i].modifiedAt.getTime() >= since)
|
|
448
|
+
files.push({ file: t, top: t, subagent: false });
|
|
449
|
+
for (const f of subagentFiles(t, since))
|
|
450
|
+
files.push({ file: f.file, top: t, subagent: true, ...(f.run ? { run: f.run } : {}) });
|
|
441
451
|
}
|
|
442
452
|
return files;
|
|
443
453
|
}
|
|
454
|
+
/** How long before a period a session may have been last written and still have subagents running into it. */
|
|
455
|
+
export const SUBAGENT_LOOKBACK_MS = 2 * 86_400_000;
|
|
444
456
|
/**
|
|
445
457
|
* Every Claude Code request between `since` and `until`, main threads and
|
|
446
458
|
* subagents alike (both draw on the same limits), each reply once.
|