context-doctor 0.41.0 → 0.42.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +5 -4
- package/dist/ab.js +3 -1
- package/dist/autopilot.d.ts +1 -1
- package/dist/autopilot.js +38 -24
- package/dist/budget.d.ts +12 -1
- package/dist/budget.js +153 -31
- package/dist/cachettl.js +12 -9
- package/dist/claudedir.d.ts +8 -0
- package/dist/claudedir.js +19 -0
- package/dist/cli.js +63 -9
- package/dist/codexdir.d.ts +11 -0
- package/dist/codexdir.js +20 -0
- package/dist/codexroute.d.ts +1 -0
- package/dist/codexroute.js +3 -1
- package/dist/compactwindow.js +12 -9
- package/dist/cursor.js +20 -5
- package/dist/doctor.d.ts +9 -0
- package/dist/doctor.js +32 -14
- package/dist/effective.d.ts +18 -0
- package/dist/effective.js +39 -4
- package/dist/extract.d.ts +12 -3
- package/dist/extract.js +39 -12
- package/dist/fileparams.d.ts +1 -1
- package/dist/fileparams.js +8 -8
- package/dist/fix.d.ts +3 -1
- package/dist/fix.js +31 -11
- package/dist/hook.js +15 -4
- package/dist/install.js +106 -47
- package/dist/ledger.d.ts +15 -0
- package/dist/ledger.js +30 -1
- package/dist/limits.d.ts +15 -1
- package/dist/limits.js +71 -28
- package/dist/mcp.js +58 -58
- package/dist/overhead.js +2 -1
- package/dist/pack.js +3 -2
- package/dist/proxy.d.ts +1 -1
- package/dist/proxy.js +1 -1
- package/dist/recall.js +3 -2
- package/dist/scan.d.ts +2 -0
- package/dist/scan.js +2 -1
- package/dist/session.js +2 -1
- package/dist/settingsedit.d.ts +4 -0
- package/dist/settingsedit.js +61 -3
- package/dist/spend.d.ts +8 -1
- package/dist/spend.js +27 -10
- package/dist/subagentmodel.d.ts +19 -4
- package/dist/subagentmodel.js +116 -28
- package/package.json +1 -1
package/dist/install.js
CHANGED
|
@@ -15,9 +15,11 @@ import { claudeCodeInstalls, describeInstalls, modelSwitchReadiness, PRE_MODEL_S
|
|
|
15
15
|
import { FANOUT_MATCHER } from "./fanout.js";
|
|
16
16
|
import { antigravityAllSkillDirs, antigravityMcpConfigPath, antigravityPresent, antigravitySkillDirs } from "./antigravity.js";
|
|
17
17
|
import { COPILOT_HOOK_EVENT, copilotHome, copilotHookFilePath, copilotMcpConfigPath, isOurCopilotEntry, vsCodePresent } from "./copilot.js";
|
|
18
|
-
import { claudeDir, claudeJsonPath } from "./claudedir.js";
|
|
18
|
+
import { claudeCodePresent, claudeDir, claudeJsonPath } from "./claudedir.js";
|
|
19
|
+
import { fallbackStateDir } from "./ledger.js";
|
|
20
|
+
import { codexDir as codexHomeDir } from "./codexdir.js";
|
|
19
21
|
import { scanCacheDir } from "./scan.js";
|
|
20
|
-
import { editJsonText, parseSettingsText, sameJson } from "./settingsedit.js";
|
|
22
|
+
import { editJsonText, parseSettingsText, sameJson, withSettingsLock, writeAtomic } from "./settingsedit.js";
|
|
21
23
|
function claudeDesktopConfigPath() {
|
|
22
24
|
switch (platform()) {
|
|
23
25
|
case "darwin": return join(homedir(), "Library", "Application Support", "Claude", "claude_desktop_config.json");
|
|
@@ -31,7 +33,7 @@ function targets() {
|
|
|
31
33
|
const cursor = join(homedir(), ".cursor", "mcp.json");
|
|
32
34
|
return [
|
|
33
35
|
{ name: "Claude Desktop", configPath: desktop, detect: () => existsSync(dirname(desktop)) },
|
|
34
|
-
{ name: "Claude Code", configPath: claudeCode, detect: () =>
|
|
36
|
+
{ name: "Claude Code", configPath: claudeCode, detect: () => claudeCodePresent() },
|
|
35
37
|
{ name: "Cursor", configPath: cursor, detect: () => existsSync(join(homedir(), ".cursor")) },
|
|
36
38
|
{ name: "Gemini CLI", configPath: geminiSettingsPath(), detect: geminiCliPresent },
|
|
37
39
|
// Antigravity's MCP file has Claude Desktop's shape (see antigravity.ts).
|
|
@@ -259,7 +261,17 @@ function readText(path) {
|
|
|
259
261
|
export function writeJsonWithBackup(path, data) {
|
|
260
262
|
mkdirSync(dirname(path), { recursive: true });
|
|
261
263
|
backupOnce(path);
|
|
262
|
-
|
|
264
|
+
// A temporary file renamed over the config: an app reading it mid-write never sees half of it.
|
|
265
|
+
writeAtomic(path, editJsonText(readText(path), data, allowsComments(path)));
|
|
266
|
+
}
|
|
267
|
+
/**
|
|
268
|
+
* Run a read-modify-write of `path` holding Claude Code's settings lock when
|
|
269
|
+
* `path` is its settings.json: the lock `fix`, `cache-ttl`, `compact-window`
|
|
270
|
+
* and autopilot hold, so an install running beside one of them loses
|
|
271
|
+
* neither's change. Other configs have no lock of theirs to share.
|
|
272
|
+
*/
|
|
273
|
+
function settingsUpdate(path, fn) {
|
|
274
|
+
return path === join(claudeDir(), "settings.json") ? withSettingsLock(path, fn) : fn();
|
|
263
275
|
}
|
|
264
276
|
/**
|
|
265
277
|
* Find an executable on PATH without shelling out (works on Windows too).
|
|
@@ -325,18 +337,20 @@ function cliCommand(subcommand) {
|
|
|
325
337
|
*/
|
|
326
338
|
export function installStatusLine() {
|
|
327
339
|
const settingsPath = join(claudeDir(), "settings.json");
|
|
328
|
-
if (!
|
|
340
|
+
if (!claudeCodePresent())
|
|
329
341
|
return "no-claude-code";
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
342
|
+
return settingsUpdate(settingsPath, () => {
|
|
343
|
+
const settings = readJson(settingsPath);
|
|
344
|
+
const want = cliCommand("statusline");
|
|
345
|
+
const current = settings.statusLine?.command;
|
|
346
|
+
if (current === want)
|
|
347
|
+
return "already";
|
|
348
|
+
if (current && !isOurStatusLine(current))
|
|
349
|
+
return "kept-foreign";
|
|
350
|
+
settings.statusLine = { type: "command", command: want };
|
|
351
|
+
writeJsonWithBackup(settingsPath, settings);
|
|
352
|
+
return "installed";
|
|
353
|
+
});
|
|
340
354
|
}
|
|
341
355
|
function isOurStatusLine(command) {
|
|
342
356
|
return /context-doctor|cli\.js"?\s+statusline\s*$/.test(command);
|
|
@@ -345,13 +359,15 @@ function uninstallStatusLine() {
|
|
|
345
359
|
const settingsPath = join(claudeDir(), "settings.json");
|
|
346
360
|
if (!existsSync(settingsPath))
|
|
347
361
|
return;
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
362
|
+
settingsUpdate(settingsPath, () => {
|
|
363
|
+
const settings = readJson(settingsPath);
|
|
364
|
+
const current = settings.statusLine?.command;
|
|
365
|
+
if (current && isOurStatusLine(current)) {
|
|
366
|
+
delete settings.statusLine;
|
|
367
|
+
writeUninstalled(settingsPath, settings);
|
|
368
|
+
done("✓ Claude Code status line removed");
|
|
369
|
+
}
|
|
370
|
+
});
|
|
355
371
|
}
|
|
356
372
|
/** True when the hook had to fall back to npx — worth telling the user. */
|
|
357
373
|
function hookUsesNpx() {
|
|
@@ -378,6 +394,8 @@ function isOurHookEntry(entry) {
|
|
|
378
394
|
* Claude Code query gets a context-size check. Idempotent.
|
|
379
395
|
*/
|
|
380
396
|
function installHook() {
|
|
397
|
+
if (!claudeCodePresent())
|
|
398
|
+
return null;
|
|
381
399
|
const settings = join(claudeDir(), "settings.json");
|
|
382
400
|
const path = installHookInto(settings, claudeDir());
|
|
383
401
|
// The same command also answers PreCompact (what each compaction's summary
|
|
@@ -401,6 +419,9 @@ function installHook() {
|
|
|
401
419
|
function installHookInto(settingsPath, gateDir, event = "UserPromptSubmit", opts = {}) {
|
|
402
420
|
if (!existsSync(gateDir))
|
|
403
421
|
return null; // that app is not on this machine
|
|
422
|
+
return settingsUpdate(settingsPath, () => addHookEntry(settingsPath, event, opts));
|
|
423
|
+
}
|
|
424
|
+
function addHookEntry(settingsPath, event, opts) {
|
|
404
425
|
const settings = readJson(settingsPath);
|
|
405
426
|
settings.hooks = settings.hooks ?? {};
|
|
406
427
|
const entries = settings.hooks[event] ?? [];
|
|
@@ -440,7 +461,7 @@ function uninstallHook(attempt) {
|
|
|
440
461
|
attempt("Claude Code session-start hook", () => uninstallHookFrom(claude, "Claude Code session-start hook", "SessionStart"));
|
|
441
462
|
attempt("Claude Code model-switch warning", () => uninstallHookFrom(claude, "Claude Code model-switch warning", "PreModelSwitch"));
|
|
442
463
|
attempt("Claude Code subagent price", () => uninstallHookFrom(claude, "Claude Code subagent price", "PreToolUse"));
|
|
443
|
-
attempt("Codex every-prompt hook", () => uninstallHookFrom(join(
|
|
464
|
+
attempt("Codex every-prompt hook", () => uninstallHookFrom(join(codexDir(), "hooks.json"), "Codex every-prompt hook"));
|
|
444
465
|
attempt("Gemini CLI every-prompt hook", () => uninstallHookFrom(geminiSettingsPath(), "Gemini CLI every-prompt hook", "BeforeAgent"));
|
|
445
466
|
attempt("Cursor hooks", () => uninstallCursorHook());
|
|
446
467
|
}
|
|
@@ -544,6 +565,9 @@ export function claudeCodeInstallsFromEnv() {
|
|
|
544
565
|
function uninstallHookFrom(settingsPath, label, event = "UserPromptSubmit") {
|
|
545
566
|
if (!existsSync(settingsPath))
|
|
546
567
|
return;
|
|
568
|
+
settingsUpdate(settingsPath, () => removeHookEntry(settingsPath, label, event));
|
|
569
|
+
}
|
|
570
|
+
function removeHookEntry(settingsPath, label, event) {
|
|
547
571
|
const settings = readJson(settingsPath);
|
|
548
572
|
const entries = settings.hooks?.[event];
|
|
549
573
|
if (!entries)
|
|
@@ -559,7 +583,7 @@ function uninstallHookFrom(settingsPath, label, event = "UserPromptSubmit") {
|
|
|
559
583
|
}
|
|
560
584
|
function installSkill() {
|
|
561
585
|
// Only where Claude Code is: making ~/.claude makes it look installed.
|
|
562
|
-
if (!
|
|
586
|
+
if (!claudeCodePresent())
|
|
563
587
|
return null;
|
|
564
588
|
return installSkillInto(join(claudeDir(), "skills", "context-doctor"), claudeDir());
|
|
565
589
|
}
|
|
@@ -580,10 +604,12 @@ function installSkillInto(skillDest, appHome) {
|
|
|
580
604
|
return null;
|
|
581
605
|
const missing = appHome ? skillFolders(appHome).filter((d) => !existsSync(d)) : [];
|
|
582
606
|
mkdirSync(skillDest, { recursive: true });
|
|
583
|
-
|
|
607
|
+
// Written whole and renamed into place: two installs at once (or Claude
|
|
608
|
+
// Code reading the skill) made Windows refuse a plain copy with EBUSY.
|
|
609
|
+
writeAtomic(join(skillDest, "SKILL.md"), readFileSync(skillSource, "utf8"));
|
|
584
610
|
if (appHome && missing.length > 0) {
|
|
585
611
|
const all = [...new Set([...createdSkillFolders(appHome), ...missing])];
|
|
586
|
-
|
|
612
|
+
writeAtomic(join(appHome, CREATED_MARKER), JSON.stringify({ created: all }) + "\n");
|
|
587
613
|
}
|
|
588
614
|
return join(skillDest, "SKILL.md");
|
|
589
615
|
}
|
|
@@ -624,7 +650,8 @@ function removeSkillFolders(appHome) {
|
|
|
624
650
|
// (~/.codex/skills/<name>/SKILL.md). One difference matters: Codex requires the
|
|
625
651
|
// user to trust a new hook once, via /hooks inside Codex, before it runs.
|
|
626
652
|
export function codexDir() {
|
|
627
|
-
|
|
653
|
+
// CODEX_HOME when set: where Codex reads its config, hooks and skills.
|
|
654
|
+
return codexHomeDir();
|
|
628
655
|
}
|
|
629
656
|
// Our key as TOML allows it to be written: bare or quoted, any spacing.
|
|
630
657
|
const OUR_KEY = String.raw `\s*mcp_servers\s*\.\s*(?:context-doctor|"context-doctor"|'context-doctor')\s*`;
|
|
@@ -1127,7 +1154,7 @@ export function runInstall(options = {}) {
|
|
|
1127
1154
|
console.error(`✗ Claude Code every-prompt hook: ${e.message}`);
|
|
1128
1155
|
failures.push("Claude Code hook");
|
|
1129
1156
|
}
|
|
1130
|
-
if (!viaPlugin &&
|
|
1157
|
+
if (!viaPlugin && claudeCodePresent()) {
|
|
1131
1158
|
try {
|
|
1132
1159
|
const readiness = modelSwitchReadiness(claudeCodeInstallsFromEnv());
|
|
1133
1160
|
switch (installModelSwitchHook(readiness)) {
|
|
@@ -1242,14 +1269,16 @@ async function uninstallAutopilot() {
|
|
|
1242
1269
|
// `off` restores only what a readable config describes. A damaged one
|
|
1243
1270
|
// leaves the proxy address in settings.json, which is the dead-port case.
|
|
1244
1271
|
try {
|
|
1245
|
-
|
|
1246
|
-
|
|
1247
|
-
|
|
1248
|
-
|
|
1249
|
-
|
|
1250
|
-
|
|
1251
|
-
|
|
1252
|
-
|
|
1272
|
+
withSettingsLock(paths.settings, () => {
|
|
1273
|
+
const settings = readJson(paths.settings);
|
|
1274
|
+
if (settings.env?.ANTHROPIC_BASE_URL === proxyUrl(port)) {
|
|
1275
|
+
delete settings.env.ANTHROPIC_BASE_URL;
|
|
1276
|
+
if (Object.keys(settings.env).length === 0)
|
|
1277
|
+
delete settings.env;
|
|
1278
|
+
writeJsonWithBackup(paths.settings, settings);
|
|
1279
|
+
console.log(`✓ Claude Code no longer routed through ${proxyUrl(port)} (autopilot's config could not say what address, if any, it had replaced)`);
|
|
1280
|
+
}
|
|
1281
|
+
});
|
|
1253
1282
|
}
|
|
1254
1283
|
catch (e) {
|
|
1255
1284
|
console.error(`✗ Autopilot: ${e.message}`);
|
|
@@ -1335,7 +1364,7 @@ function writeUninstalled(path, config, extraKeys = []) {
|
|
|
1335
1364
|
}
|
|
1336
1365
|
// An empty file before install is an empty file again, not "{}".
|
|
1337
1366
|
if (empty && isEmptyStub(config, extraKeys)) {
|
|
1338
|
-
|
|
1367
|
+
writeAtomic(path, "");
|
|
1339
1368
|
return;
|
|
1340
1369
|
}
|
|
1341
1370
|
// Exactly the file from before install when that is what is left (also
|
|
@@ -1344,12 +1373,12 @@ function writeUninstalled(path, config, extraKeys = []) {
|
|
|
1344
1373
|
const backup = readText(path + BACKUP_SUFFIX);
|
|
1345
1374
|
try {
|
|
1346
1375
|
if (backup?.trim() && sameJson(parseSettingsText(backup, allowsComments(path)), config)) {
|
|
1347
|
-
|
|
1376
|
+
writeAtomic(path, backup);
|
|
1348
1377
|
return;
|
|
1349
1378
|
}
|
|
1350
1379
|
}
|
|
1351
1380
|
catch { /* an unreadable backup: edit the file as it is */ }
|
|
1352
|
-
|
|
1381
|
+
writeAtomic(path, editJsonText(readText(path), config, allowsComments(path)));
|
|
1353
1382
|
}
|
|
1354
1383
|
/** Remove the SKILL.md install copied, and its folder once nothing else is in it. */
|
|
1355
1384
|
function removeSkill(dir, label) {
|
|
@@ -1421,6 +1450,9 @@ export async function runUninstall() {
|
|
|
1421
1450
|
};
|
|
1422
1451
|
// First: if anything below fails, Claude Code must still reach the API.
|
|
1423
1452
|
const hadAutopilot = existsSync(join(claudeDir(), ".context-doctor-autopilot.json"));
|
|
1453
|
+
// A ~/.claude with only our files in it (the budget, the ledger, the Codex
|
|
1454
|
+
// and Gemini CLI hooks' state) is a folder we made, not Claude Code's.
|
|
1455
|
+
const onlyOurFolder = existsSync(claudeDir()) && !claudeCodePresent() && !process.env.CLAUDE_CONFIG_DIR?.trim();
|
|
1424
1456
|
try {
|
|
1425
1457
|
await uninstallAutopilot();
|
|
1426
1458
|
if (hadAutopilot)
|
|
@@ -1455,15 +1487,22 @@ export async function runUninstall() {
|
|
|
1455
1487
|
attempt("GitHub Copilot folders", () => uninstallCopilotFolders());
|
|
1456
1488
|
// Remove our bookkeeping files too — uninstall means gone. The hook's
|
|
1457
1489
|
// per-session state is a directory, one small file per session.
|
|
1458
|
-
|
|
1459
|
-
|
|
1460
|
-
|
|
1461
|
-
|
|
1462
|
-
|
|
1463
|
-
|
|
1464
|
-
|
|
1465
|
-
|
|
1490
|
+
// In ~/.claude, and in the folder they live in on a machine without it (ledger.ts fallbackStateDir).
|
|
1491
|
+
for (const dir of [claudeDir(), fallbackStateDir()]) {
|
|
1492
|
+
for (const file of OUR_CLAUDE_FILES) {
|
|
1493
|
+
const p = join(dir, file);
|
|
1494
|
+
attempt(file, () => {
|
|
1495
|
+
if (existsSync(p)) {
|
|
1496
|
+
rmSync(p, { recursive: true, force: true });
|
|
1497
|
+
done(`✓ Removed ${file}`);
|
|
1498
|
+
}
|
|
1499
|
+
});
|
|
1500
|
+
}
|
|
1466
1501
|
}
|
|
1502
|
+
try {
|
|
1503
|
+
rmdirSync(fallbackStateDir());
|
|
1504
|
+
}
|
|
1505
|
+
catch { /* not empty, or never made */ }
|
|
1467
1506
|
// The reports' transcript cache (scan.ts): records taken from your transcripts, rebuilt by the next report.
|
|
1468
1507
|
attempt("transcript cache", () => {
|
|
1469
1508
|
const dir = join(scanCacheDir(), "transcripts");
|
|
@@ -1478,6 +1517,13 @@ export async function runUninstall() {
|
|
|
1478
1517
|
});
|
|
1479
1518
|
// Last: the folders install made for the skill, now empty.
|
|
1480
1519
|
attempt("Claude Code skill folders", () => removeSkillFolders(claudeDir()));
|
|
1520
|
+
// Left behind empty, it would read as Claude Code being installed.
|
|
1521
|
+
if (onlyOurFolder) {
|
|
1522
|
+
try {
|
|
1523
|
+
rmdirSync(claudeDir());
|
|
1524
|
+
}
|
|
1525
|
+
catch { /* not empty after all */ }
|
|
1526
|
+
}
|
|
1481
1527
|
if (deletedStubs.length > 0) {
|
|
1482
1528
|
console.log(`✓ Deleted ${deletedStubs.length === 1 ? "a file" : "files"} install had created, now empty: ${deletedStubs.map(tilde).join(", ")}`);
|
|
1483
1529
|
}
|
|
@@ -1496,4 +1542,17 @@ export async function runUninstall() {
|
|
|
1496
1542
|
console.log(` ${tilde(b)}`);
|
|
1497
1543
|
console.log("Delete them once you no longer need them.");
|
|
1498
1544
|
}
|
|
1545
|
+
// fix's changes live in the user's settings, not in anything install wrote:
|
|
1546
|
+
// uninstall leaves them (and their record, which `fix undo` reads). Read
|
|
1547
|
+
// here, not through fix.ts, which imports this module.
|
|
1548
|
+
let applied = [];
|
|
1549
|
+
try {
|
|
1550
|
+
const fixes = JSON.parse(readFileSync(join(claudeDir(), ".context-doctor-fixes.json"), "utf8")).fixes;
|
|
1551
|
+
if (Array.isArray(fixes))
|
|
1552
|
+
applied = fixes.filter((f) => f && typeof f.id === "string").map((f) => f.id);
|
|
1553
|
+
}
|
|
1554
|
+
catch { /* none, or damaged: fix undo says so */ }
|
|
1555
|
+
if (applied.length > 0) {
|
|
1556
|
+
console.log(`Fixes applied with \`context-doctor fix\` stay in your settings (${applied.join(", ")}): run \`npx context-doctor fix undo\` to revert them.`);
|
|
1557
|
+
}
|
|
1499
1558
|
}
|
package/dist/ledger.d.ts
CHANGED
|
@@ -55,6 +55,21 @@ export interface CarriedTotals {
|
|
|
55
55
|
* rotations rather than only the first.
|
|
56
56
|
*/
|
|
57
57
|
export declare function foldTotals(entries: LedgerEntry[]): CarriedTotals;
|
|
58
|
+
/**
|
|
59
|
+
* Where context-doctor keeps its own state on a machine without Claude Code's
|
|
60
|
+
* folder (Codex or Gemini CLI alone): $XDG_STATE_HOME/context-doctor,
|
|
61
|
+
* ~/.local/state/context-doctor, or %LOCALAPPDATA%\context-doctor on Windows.
|
|
62
|
+
* Creating ~/.claude for it (the budget, the hooks' ledger) made `install`
|
|
63
|
+
* see a Claude Code that is not there, and left the folder behind.
|
|
64
|
+
*/
|
|
65
|
+
export declare function fallbackStateDir(): string;
|
|
66
|
+
/**
|
|
67
|
+
* The folder our state files live in: ~/.claude (or CLAUDE_CONFIG_DIR) when
|
|
68
|
+
* it is there, as always; otherwise the fallback folder. Once the fallback
|
|
69
|
+
* holds our files it stays theirs, so a Claude Code installed later does not
|
|
70
|
+
* strand the ledger and the budget in it.
|
|
71
|
+
*/
|
|
72
|
+
export declare function stateDir(): string;
|
|
58
73
|
export declare function statePath(): string;
|
|
59
74
|
export declare function ledgerPath(): string;
|
|
60
75
|
/** Longest string field kept in a ledger entry (a model name, a session id). */
|
package/dist/ledger.js
CHANGED
|
@@ -17,6 +17,7 @@
|
|
|
17
17
|
* what it drops into a single rollup entry instead of discarding it.
|
|
18
18
|
*/
|
|
19
19
|
import { appendFileSync, existsSync, mkdirSync, readFileSync, statSync, writeFileSync } from "node:fs";
|
|
20
|
+
import { homedir } from "node:os";
|
|
20
21
|
import { dirname, join } from "node:path";
|
|
21
22
|
import { claudeDir } from "./claudedir.js";
|
|
22
23
|
const EMPTY_CARRIED = {
|
|
@@ -78,8 +79,36 @@ export function foldTotals(entries) {
|
|
|
78
79
|
}
|
|
79
80
|
return out;
|
|
80
81
|
}
|
|
82
|
+
/**
|
|
83
|
+
* Where context-doctor keeps its own state on a machine without Claude Code's
|
|
84
|
+
* folder (Codex or Gemini CLI alone): $XDG_STATE_HOME/context-doctor,
|
|
85
|
+
* ~/.local/state/context-doctor, or %LOCALAPPDATA%\context-doctor on Windows.
|
|
86
|
+
* Creating ~/.claude for it (the budget, the hooks' ledger) made `install`
|
|
87
|
+
* see a Claude Code that is not there, and left the folder behind.
|
|
88
|
+
*/
|
|
89
|
+
export function fallbackStateDir() {
|
|
90
|
+
const xdg = process.env.XDG_STATE_HOME?.trim();
|
|
91
|
+
if (xdg)
|
|
92
|
+
return join(xdg, "context-doctor");
|
|
93
|
+
if (process.platform === "win32")
|
|
94
|
+
return join(process.env.LOCALAPPDATA?.trim() || join(homedir(), "AppData", "Local"), "context-doctor");
|
|
95
|
+
return join(homedir(), ".local", "state", "context-doctor");
|
|
96
|
+
}
|
|
97
|
+
/**
|
|
98
|
+
* The folder our state files live in: ~/.claude (or CLAUDE_CONFIG_DIR) when
|
|
99
|
+
* it is there, as always; otherwise the fallback folder. Once the fallback
|
|
100
|
+
* holds our files it stays theirs, so a Claude Code installed later does not
|
|
101
|
+
* strand the ledger and the budget in it.
|
|
102
|
+
*/
|
|
103
|
+
export function stateDir() {
|
|
104
|
+
const fallback = fallbackStateDir();
|
|
105
|
+
if (existsSync(fallback))
|
|
106
|
+
return fallback;
|
|
107
|
+
const claude = claudeDir();
|
|
108
|
+
return existsSync(claude) ? claude : fallback;
|
|
109
|
+
}
|
|
81
110
|
export function statePath() {
|
|
82
|
-
return process.env.CONTEXT_DOCTOR_HOOK_STATE ?? join(
|
|
111
|
+
return process.env.CONTEXT_DOCTOR_HOOK_STATE ?? join(stateDir(), ".context-doctor-hook-state.json");
|
|
83
112
|
}
|
|
84
113
|
export function ledgerPath() {
|
|
85
114
|
return join(dirname(statePath()), ".context-doctor-ledger.jsonl");
|
package/dist/limits.d.ts
CHANGED
|
@@ -72,10 +72,24 @@ export declare function readClaudeReadings(since?: number, path?: string): Limit
|
|
|
72
72
|
export declare function codexSessionsRoot(home?: string): string;
|
|
73
73
|
/** Codex rollouts under `root` (YYYY/MM/DD folders, or flat) written since `since`. */
|
|
74
74
|
export declare function rolloutFiles(root: string, since: number): string[];
|
|
75
|
+
/** The token counts a Codex event's identity is made of, in its running total and its last request. */
|
|
76
|
+
export declare const CODEX_USAGE_FIELDS: readonly ["input_tokens", "cached_input_tokens", "output_tokens", "reasoning_output_tokens", "total_tokens"];
|
|
77
|
+
/**
|
|
78
|
+
* A Codex token_count event's identity: its running total and its last
|
|
79
|
+
* request. A forked rollout (a subagent's, a fork of a thread) begins with a
|
|
80
|
+
* copy of its parent's history, token_count events included, all stamped at
|
|
81
|
+
* the moment of the fork: seen on this machine, a subagent's rollout repeated
|
|
82
|
+
* 11 of its parent's 18 requests. The copy carries the same counts, so this
|
|
83
|
+
* key counts each request once, however many rollouts hold it. "" when the
|
|
84
|
+
* event has no running total (nothing to tell a copy by).
|
|
85
|
+
*/
|
|
86
|
+
export declare function codexEventKey(total: unknown, last: unknown): string;
|
|
75
87
|
/**
|
|
76
88
|
* Codex readings and usage since `since`. A token_count event repeats the
|
|
77
89
|
* last request's usage when only the limits were refreshed, so a request is
|
|
78
|
-
* counted when the running total moves.
|
|
90
|
+
* counted when the running total moves. A forked rollout's copy of its
|
|
91
|
+
* parent's events (codexEventKey) is counted once, at the earliest time met:
|
|
92
|
+
* the copy is stamped at the fork, its limits readings stale by then.
|
|
79
93
|
*/
|
|
80
94
|
export declare function codexLimitData(since: number, root?: string): {
|
|
81
95
|
readings: LimitReading[];
|
package/dist/limits.js
CHANGED
|
@@ -28,6 +28,7 @@
|
|
|
28
28
|
import { appendFileSync, closeSync, existsSync, mkdirSync, openSync, readdirSync, readFileSync, readSync, statSync, writeFileSync } from "node:fs";
|
|
29
29
|
import { homedir } from "node:os";
|
|
30
30
|
import { dirname, join } from "node:path";
|
|
31
|
+
import { codexDir } from "./codexdir.js";
|
|
31
32
|
import { statePath } from "./ledger.js";
|
|
32
33
|
import { forEachLine, listSessions, outputSettler, replyCounter, isClaudeSession } from "./session.js";
|
|
33
34
|
import { subagentDir } from "./subagents.js";
|
|
@@ -175,34 +176,41 @@ export function readClaudeReadings(since = 0, path = limitsLogPath()) {
|
|
|
175
176
|
// Codex: readings and usage, both from its rollouts
|
|
176
177
|
// ---------------------------------------------------------------------------
|
|
177
178
|
export function codexSessionsRoot(home = homedir()) {
|
|
178
|
-
return join(home, "
|
|
179
|
+
return join(codexDir(home), "sessions");
|
|
179
180
|
}
|
|
180
181
|
/** Codex rollouts under `root` (YYYY/MM/DD folders, or flat) written since `since`. */
|
|
181
182
|
export function rolloutFiles(root, since) {
|
|
182
183
|
const out = [];
|
|
183
184
|
const walk = (dir, depth) => {
|
|
184
|
-
let
|
|
185
|
+
let entries;
|
|
185
186
|
try {
|
|
186
|
-
|
|
187
|
+
entries = readdirSync(dir, { withFileTypes: true });
|
|
187
188
|
}
|
|
188
189
|
catch {
|
|
189
190
|
return;
|
|
190
191
|
}
|
|
191
|
-
for (const
|
|
192
|
-
const p = join(dir, name);
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
192
|
+
for (const e of entries) {
|
|
193
|
+
const p = join(dir, e.name);
|
|
194
|
+
// A folder needs no stat of its own; a symlink is stat'ed to see what it is.
|
|
195
|
+
let isDir = e.isDirectory();
|
|
196
|
+
if (e.isSymbolicLink()) {
|
|
197
|
+
try {
|
|
198
|
+
isDir = statSync(p).isDirectory();
|
|
199
|
+
}
|
|
200
|
+
catch {
|
|
201
|
+
continue;
|
|
202
|
+
}
|
|
199
203
|
}
|
|
200
|
-
if (
|
|
204
|
+
if (isDir) {
|
|
201
205
|
if (depth < 3)
|
|
202
206
|
walk(p, depth + 1);
|
|
203
207
|
}
|
|
204
|
-
else if (name.endsWith(".jsonl")
|
|
205
|
-
|
|
208
|
+
else if (e.name.endsWith(".jsonl")) {
|
|
209
|
+
try {
|
|
210
|
+
if (statSync(p).mtimeMs >= since)
|
|
211
|
+
out.push(p);
|
|
212
|
+
}
|
|
213
|
+
catch { /* vanished */ }
|
|
206
214
|
}
|
|
207
215
|
}
|
|
208
216
|
};
|
|
@@ -210,6 +218,25 @@ export function rolloutFiles(root, since) {
|
|
|
210
218
|
return out;
|
|
211
219
|
}
|
|
212
220
|
const num = (v) => (typeof v === "number" && Number.isFinite(v) && v > 0 ? v : 0);
|
|
221
|
+
/** The token counts a Codex event's identity is made of, in its running total and its last request. */
|
|
222
|
+
export const CODEX_USAGE_FIELDS = ["input_tokens", "cached_input_tokens", "output_tokens", "reasoning_output_tokens", "total_tokens"];
|
|
223
|
+
/**
|
|
224
|
+
* A Codex token_count event's identity: its running total and its last
|
|
225
|
+
* request. A forked rollout (a subagent's, a fork of a thread) begins with a
|
|
226
|
+
* copy of its parent's history, token_count events included, all stamped at
|
|
227
|
+
* the moment of the fork: seen on this machine, a subagent's rollout repeated
|
|
228
|
+
* 11 of its parent's 18 requests. The copy carries the same counts, so this
|
|
229
|
+
* key counts each request once, however many rollouts hold it. "" when the
|
|
230
|
+
* event has no running total (nothing to tell a copy by).
|
|
231
|
+
*/
|
|
232
|
+
export function codexEventKey(total, last) {
|
|
233
|
+
if (!total || typeof total !== "object" || !last || typeof last !== "object")
|
|
234
|
+
return "";
|
|
235
|
+
const t = total, l = last;
|
|
236
|
+
if (!num(t.total_tokens))
|
|
237
|
+
return "";
|
|
238
|
+
return `cx:${CODEX_USAGE_FIELDS.map((k) => num(t[k])).join(",")}/${CODEX_USAGE_FIELDS.map((k) => num(l[k])).join(",")}`;
|
|
239
|
+
}
|
|
213
240
|
/** "codex:300", "codex:10080"; a limit id other than "codex" is kept in the key. */
|
|
214
241
|
function codexWindow(limitId, minutes, plan) {
|
|
215
242
|
// The plan is part of the key: two sign-ins (a team plan, a free one) are two accounts' limits.
|
|
@@ -219,13 +246,16 @@ function codexWindow(limitId, minutes, plan) {
|
|
|
219
246
|
/**
|
|
220
247
|
* Codex readings and usage since `since`. A token_count event repeats the
|
|
221
248
|
* last request's usage when only the limits were refreshed, so a request is
|
|
222
|
-
* counted when the running total moves.
|
|
249
|
+
* counted when the running total moves. A forked rollout's copy of its
|
|
250
|
+
* parent's events (codexEventKey) is counted once, at the earliest time met:
|
|
251
|
+
* the copy is stamped at the fork, its limits readings stale by then.
|
|
223
252
|
*/
|
|
224
253
|
export function codexLimitData(since, root = codexSessionsRoot()) {
|
|
225
254
|
const readings = [];
|
|
226
255
|
const usage = [];
|
|
227
256
|
if (!existsSync(root))
|
|
228
257
|
return { readings, usage };
|
|
258
|
+
const events = [];
|
|
229
259
|
for (const file of rolloutFiles(root, since)) {
|
|
230
260
|
let model;
|
|
231
261
|
let total = -1;
|
|
@@ -255,33 +285,46 @@ export function codexLimitData(since, root = codexSessionsRoot()) {
|
|
|
255
285
|
return;
|
|
256
286
|
const runTotal = num(p.info?.total_token_usage?.total_tokens);
|
|
257
287
|
const last = p.info?.last_token_usage;
|
|
288
|
+
const ev = { ts, key: codexEventKey(p.info?.total_token_usage, last), file, readings: [] };
|
|
258
289
|
// No running total recorded: every event is a request.
|
|
259
290
|
if (last && num(last.input_tokens) > 0 && (runTotal === 0 || runTotal !== total)) {
|
|
260
291
|
total = runTotal;
|
|
261
292
|
const u = openAIUsage(last);
|
|
262
293
|
const price = pricingFor(model);
|
|
263
|
-
|
|
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 };
|
|
264
295
|
}
|
|
265
296
|
const rl = p.rate_limits;
|
|
266
|
-
if (
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
297
|
+
if (rl && typeof rl === "object") {
|
|
298
|
+
for (const slot of ["primary", "secondary"]) {
|
|
299
|
+
const w = rl[slot];
|
|
300
|
+
const pct = w?.used_percent;
|
|
301
|
+
const minutes = num(w?.window_minutes);
|
|
302
|
+
if (typeof pct !== "number" || !Number.isFinite(pct) || pct < 0 || pct > 1000 || !minutes)
|
|
303
|
+
continue;
|
|
304
|
+
const reset = num(w.resets_at);
|
|
305
|
+
ev.readings.push({ ts, app: "codex", window: codexWindow(rl.limit_id, minutes, rl.plan_type), pct, resetsAt: reset ? reset * 1000 : undefined, windowMs: minutes * MIN, plan: typeof rl.plan_type === "string" ? rl.plan_type.slice(0, 20) : undefined });
|
|
306
|
+
}
|
|
276
307
|
}
|
|
308
|
+
if (ev.point || ev.readings.length)
|
|
309
|
+
events.push(ev);
|
|
277
310
|
});
|
|
278
311
|
}
|
|
279
312
|
catch {
|
|
280
313
|
/* one unreadable rollout must not sink the report */
|
|
281
314
|
}
|
|
282
315
|
}
|
|
283
|
-
|
|
284
|
-
|
|
316
|
+
// A key belongs to the rollout that has it first; within it, a refresh of the limits shares its request's key.
|
|
317
|
+
const owner = new Map();
|
|
318
|
+
for (const ev of events.sort((a, b) => a.ts - b.ts)) {
|
|
319
|
+
if (ev.key) {
|
|
320
|
+
const first = owner.get(ev.key) ?? (owner.set(ev.key, ev.file), ev.file);
|
|
321
|
+
if (first !== ev.file)
|
|
322
|
+
continue;
|
|
323
|
+
}
|
|
324
|
+
if (ev.point)
|
|
325
|
+
usage.push(ev.point);
|
|
326
|
+
readings.push(...ev.readings);
|
|
327
|
+
}
|
|
285
328
|
return { readings, usage };
|
|
286
329
|
}
|
|
287
330
|
// ---------------------------------------------------------------------------
|