context-doctor 0.42.0 → 0.44.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 +6 -3
- package/dist/budget.d.ts +52 -0
- package/dist/budget.js +209 -59
- package/dist/cachettl.d.ts +5 -1
- package/dist/cachettl.js +10 -25
- package/dist/cli.js +33 -15
- package/dist/codexcompact.d.ts +137 -0
- package/dist/codexcompact.js +581 -0
- package/dist/compactwindow.js +2 -2
- package/dist/cursor.d.ts +10 -0
- package/dist/cursor.js +20 -0
- package/dist/doctor.d.ts +9 -0
- package/dist/doctor.js +55 -0
- package/dist/fanout.js +4 -2
- package/dist/fix.d.ts +38 -4
- package/dist/fix.js +249 -21
- package/dist/hook.js +65 -16
- package/dist/install.js +56 -19
- package/dist/ledger.d.ts +2 -1
- package/dist/ledger.js +1 -0
- package/dist/limits.d.ts +6 -2
- package/dist/limits.js +19 -16
- package/dist/mcp.js +63 -63
- package/dist/mcpclient.js +19 -19
- package/dist/mcpschema.js +5 -9
- package/dist/overhead.d.ts +7 -2
- package/dist/overhead.js +11 -3
- package/dist/pack.js +23 -3
- package/dist/pricing.d.ts +25 -5
- package/dist/pricing.js +157 -48
- package/dist/proxy.d.ts +15 -1
- package/dist/proxy.js +33 -5
- package/dist/prune.d.ts +8 -0
- package/dist/prune.js +20 -9
- package/dist/savings.js +2 -1
- package/dist/sessionprice.d.ts +77 -0
- package/dist/sessionprice.js +267 -0
- package/dist/settingsedit.js +3 -2
- package/dist/spend.d.ts +25 -3
- package/dist/spend.js +67 -19
- package/dist/subagentmodel.js +11 -1
- package/dist/subagentpay.d.ts +17 -0
- package/dist/subagentpay.js +41 -2
- package/dist/subagents.d.ts +24 -0
- package/dist/subagents.js +82 -17
- package/dist/tooloutput.d.ts +120 -0
- package/dist/tooloutput.js +357 -0
- package/package.json +1 -1
package/dist/hook.js
CHANGED
|
@@ -29,6 +29,7 @@ import { compactFacts, compactInstructions } from "./precompact.js";
|
|
|
29
29
|
import { fanoutHook, subagentCosts } from "./fanout.js";
|
|
30
30
|
import { claudeDir } from "./claudedir.js";
|
|
31
31
|
import { budgetVerdict } from "./budget.js";
|
|
32
|
+
import { renderSessionPrice, sessionPriceDue } from "./sessionprice.js";
|
|
32
33
|
/** Default nudge threshold; a project budget or env var can lower/raise it. */
|
|
33
34
|
const DEFAULT_WARN_TOKENS = 80_000;
|
|
34
35
|
/**
|
|
@@ -113,20 +114,45 @@ function readSessionState(sessionId) {
|
|
|
113
114
|
}
|
|
114
115
|
/** Keep the directory from growing without bound as sessions come and go. */
|
|
115
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
|
+
}
|
|
116
150
|
function writeSessionState(sessionId, state) {
|
|
117
151
|
const dir = stateDir();
|
|
118
152
|
mkdirSync(dir, { recursive: true });
|
|
119
153
|
writeFileSync(sessionStatePath(sessionId), JSON.stringify(state));
|
|
120
154
|
try {
|
|
121
|
-
|
|
122
|
-
if (files.length <= MAX_STATE_FILES)
|
|
123
|
-
return;
|
|
124
|
-
const byAge = files
|
|
125
|
-
.map((f) => ({ f, t: statSync(join(dir, f)).mtimeMs }))
|
|
126
|
-
.sort((a, b) => b.t - a.t)
|
|
127
|
-
.slice(MAX_STATE_FILES);
|
|
128
|
-
for (const { f } of byAge)
|
|
129
|
-
rmSync(join(dir, f), { force: true });
|
|
155
|
+
pruneStateDir(dir);
|
|
130
156
|
}
|
|
131
157
|
catch {
|
|
132
158
|
/* pruning is housekeeping, never worth failing a prompt over */
|
|
@@ -168,9 +194,10 @@ export function hookInput(raw) {
|
|
|
168
194
|
return out;
|
|
169
195
|
}
|
|
170
196
|
export async function runHook(app) {
|
|
171
|
-
// The spend budget's line for this prompt
|
|
172
|
-
//
|
|
173
|
-
// failure must still let it out, or it was lost for
|
|
197
|
+
// The spend budget's line for this prompt (and the session price's), until
|
|
198
|
+
// it is written. Each threshold is recorded as said before the rest of the
|
|
199
|
+
// hook runs, so a later failure must still let it out, or it was lost for
|
|
200
|
+
// the whole period (or session).
|
|
174
201
|
let budgetNote;
|
|
175
202
|
// A hook must never break the user's prompt: any failure exits silently.
|
|
176
203
|
try {
|
|
@@ -284,6 +311,23 @@ export async function runHook(app) {
|
|
|
284
311
|
}
|
|
285
312
|
budgetNote = v?.message;
|
|
286
313
|
}
|
|
314
|
+
// A session's own price (sessionprice.ts): once when it passes $25, $100
|
|
315
|
+
// and $500, a line to the user beside the budget's. Claimed before the
|
|
316
|
+
// rest of the hook runs, so it rides in `budgetNote` like the budget's.
|
|
317
|
+
let priceCold = false, priceSaid = false;
|
|
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)) {
|
|
319
|
+
try {
|
|
320
|
+
const sid = input.session_id ?? input.conversation_id ?? input.transcript_path;
|
|
321
|
+
const p = sessionPriceDue({ sessionId: sid, transcript: input.transcript_path, event: input.hook_event_name, model: input.model, rv: () => readSessionState(sid).rv });
|
|
322
|
+
if (p) {
|
|
323
|
+
budgetNote = [budgetNote, renderSessionPrice(p)].filter(Boolean).join("\n");
|
|
324
|
+
priceCold = p.coldUsd !== undefined;
|
|
325
|
+
priceSaid = true;
|
|
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 } : {}) });
|
|
327
|
+
}
|
|
328
|
+
}
|
|
329
|
+
catch { /* never worth a prompt */ }
|
|
330
|
+
}
|
|
287
331
|
const sayBudget = () => { if (budgetNote)
|
|
288
332
|
console.log(JSON.stringify({ systemMessage: budgetNote })); budgetNote = undefined; };
|
|
289
333
|
const transcriptPath = input.transcript_path;
|
|
@@ -322,10 +366,14 @@ export async function runHook(app) {
|
|
|
322
366
|
cold = undefined;
|
|
323
367
|
let cr = prev.cr;
|
|
324
368
|
if (cold && cold.lastReplyAt !== prev.cr) {
|
|
325
|
-
notes.push(renderColdResume(cold));
|
|
326
|
-
notice = [budgetNote, renderColdResumeNotice(cold)].filter(Boolean).join("\n");
|
|
327
369
|
cr = cold.lastReplyAt;
|
|
328
|
-
|
|
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
|
+
}
|
|
329
377
|
}
|
|
330
378
|
const emit = (lines) => {
|
|
331
379
|
if (lines.length === 0 && !notice)
|
|
@@ -418,7 +466,8 @@ export async function runHook(app) {
|
|
|
418
466
|
if (topFinding) {
|
|
419
467
|
lines.push(`Largest recoverable waste: ${topFinding.message} (${topFinding.suggestion})`);
|
|
420
468
|
}
|
|
421
|
-
|
|
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) {
|
|
422
471
|
lines.push(cursor
|
|
423
472
|
? "If the task changes, suggest the user start a new chat from a short summary of this one."
|
|
424
473
|
: "If it fits the flow, offer the user a compaction of the older history.");
|
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/ledger.d.ts
CHANGED
|
@@ -10,6 +10,7 @@
|
|
|
10
10
|
* proxy — proxy savings checkpoint {ev: "proxy", saved, usd?, requests?}
|
|
11
11
|
* rollup — totals folded in on rotation {ev: "rollup", ...carried sums}
|
|
12
12
|
* session_rules — a Copilot session start got the standing rules {ev: "session_rules", app}
|
|
13
|
+
* session_price — the hook said a session passed a price threshold {ev: "session_price", sid, usd, tok?, model?}
|
|
13
14
|
*
|
|
14
15
|
* The ledger is capped, and everything it feeds is a LIFETIME total. Simply
|
|
15
16
|
* dropping old lines made those totals go backwards — measured: 1,692,000
|
|
@@ -18,7 +19,7 @@
|
|
|
18
19
|
*/
|
|
19
20
|
export interface LedgerEntry {
|
|
20
21
|
ts: number;
|
|
21
|
-
ev?: "check" | "optimize" | "proxy" | "rollup" | "cold_resume" | "precompact" | "session_rules";
|
|
22
|
+
ev?: "check" | "optimize" | "proxy" | "rollup" | "cold_resume" | "precompact" | "session_rules" | "session_price";
|
|
22
23
|
sid?: string;
|
|
23
24
|
tok?: number;
|
|
24
25
|
warn?: boolean;
|
package/dist/ledger.js
CHANGED
|
@@ -10,6 +10,7 @@
|
|
|
10
10
|
* proxy — proxy savings checkpoint {ev: "proxy", saved, usd?, requests?}
|
|
11
11
|
* rollup — totals folded in on rotation {ev: "rollup", ...carried sums}
|
|
12
12
|
* session_rules — a Copilot session start got the standing rules {ev: "session_rules", app}
|
|
13
|
+
* session_price — the hook said a session passed a price threshold {ev: "session_price", sid, usd, tok?, model?}
|
|
13
14
|
*
|
|
14
15
|
* The ledger is capped, and everything it feeds is a LIFETIME total. Simply
|
|
15
16
|
* dropping old lines made those totals go backwards — measured: 1,692,000
|
package/dist/limits.d.ts
CHANGED
|
@@ -121,8 +121,9 @@ export interface ClaudeRequest extends UsagePoint {
|
|
|
121
121
|
* The requests of one Claude Code transcript between `since` and `until`,
|
|
122
122
|
* each reply once, its output settled on its last row. `runRows` is shared
|
|
123
123
|
* by every file of one report, so a fork's copy of its parent's replies is
|
|
124
|
-
* counted once, in the file met first (replyCounter).
|
|
125
|
-
*
|
|
124
|
+
* counted once, in the file met first (replyCounter). Replies on
|
|
125
|
+
* `<synthetic>` (isUnbilledModel) are left out. Throws when the transcript
|
|
126
|
+
* cannot be read.
|
|
126
127
|
*/
|
|
127
128
|
export declare function claudeFileUsage(file: string, since: number, until?: number, runRows?: Set<string>): ClaudeRequest[];
|
|
128
129
|
/**
|
|
@@ -134,7 +135,10 @@ export declare function claudeUsageFiles(since: number, tops?: string[]): Array<
|
|
|
134
135
|
file: string;
|
|
135
136
|
top: string;
|
|
136
137
|
subagent: boolean;
|
|
138
|
+
run?: string;
|
|
137
139
|
}>;
|
|
140
|
+
/** How long before a period a session may have been last written and still have subagents running into it. */
|
|
141
|
+
export declare const SUBAGENT_LOOKBACK_MS: number;
|
|
138
142
|
/**
|
|
139
143
|
* Every Claude Code request between `since` and `until`, main threads and
|
|
140
144
|
* 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 { openAIUsage, pricingFor, usageCost } from "./pricing.js";
|
|
36
|
+
import { isUnbilledModel, openAIUsage, pricingFor, usageCost } from "./pricing.js";
|
|
37
37
|
import { realModel } from "./tokens.js";
|
|
38
38
|
const MIN = 60_000;
|
|
39
39
|
const HOUR = 60 * MIN;
|
|
@@ -368,8 +368,9 @@ export const USAGE_ROWS = {
|
|
|
368
368
|
* The requests of one Claude Code transcript between `since` and `until`,
|
|
369
369
|
* each reply once, its output settled on its last row. `runRows` is shared
|
|
370
370
|
* by every file of one report, so a fork's copy of its parent's replies is
|
|
371
|
-
* counted once, in the file met first (replyCounter).
|
|
372
|
-
*
|
|
371
|
+
* counted once, in the file met first (replyCounter). Replies on
|
|
372
|
+
* `<synthetic>` (isUnbilledModel) are left out. Throws when the transcript
|
|
373
|
+
* cannot be read.
|
|
373
374
|
*/
|
|
374
375
|
export function claudeFileUsage(file, since, until = Infinity, runRows) {
|
|
375
376
|
const out = [];
|
|
@@ -394,6 +395,9 @@ export function claudeFileUsage(file, since, until = Infinity, runRows) {
|
|
|
394
395
|
if (seen !== "new")
|
|
395
396
|
return;
|
|
396
397
|
settle(e, true);
|
|
398
|
+
// A reply Claude Code made itself (an error, an interruption) never reached the API: no request, priced or not.
|
|
399
|
+
if (isUnbilledModel(m.model))
|
|
400
|
+
return;
|
|
397
401
|
const ts = Date.parse(String(e.timestamp ?? ""));
|
|
398
402
|
if (!Number.isFinite(ts) || ts < since || ts > until)
|
|
399
403
|
return;
|
|
@@ -425,22 +429,21 @@ export function claudeFileUsage(file, since, until = Infinity, runRows) {
|
|
|
425
429
|
* first), each followed by its subagents'.
|
|
426
430
|
*/
|
|
427
431
|
export function claudeUsageFiles(since, tops) {
|
|
428
|
-
|
|
432
|
+
// A session last written before `since` can still have subagents (a workflow run, a background
|
|
433
|
+
// agent) writing after it: those of the sessions written in the SUBAGENT_LOOKBACK_MS before count.
|
|
434
|
+
const listed = tops ? undefined : listSessions(10_000).filter((s) => isClaudeSession(s) && s.modifiedAt.getTime() >= since - SUBAGENT_LOOKBACK_MS);
|
|
435
|
+
const mains = tops ?? listed.map((s) => s.path);
|
|
429
436
|
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
|
-
}
|
|
437
|
+
for (const [i, t] of mains.entries()) {
|
|
438
|
+
if (!listed || listed[i].modifiedAt.getTime() >= since)
|
|
439
|
+
files.push({ file: t, top: t, subagent: false });
|
|
440
|
+
for (const f of subagentFiles(t, since))
|
|
441
|
+
files.push({ file: f.file, top: t, subagent: true, ...(f.run ? { run: f.run } : {}) });
|
|
441
442
|
}
|
|
442
443
|
return files;
|
|
443
444
|
}
|
|
445
|
+
/** How long before a period a session may have been last written and still have subagents running into it. */
|
|
446
|
+
export const SUBAGENT_LOOKBACK_MS = 2 * 86_400_000;
|
|
444
447
|
/**
|
|
445
448
|
* Every Claude Code request between `since` and `until`, main threads and
|
|
446
449
|
* subagents alike (both draw on the same limits), each reply once.
|