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/overhead.js
CHANGED
|
@@ -17,6 +17,7 @@
|
|
|
17
17
|
import { readdirSync, readFileSync, statSync } from "node:fs";
|
|
18
18
|
import { homedir } from "node:os";
|
|
19
19
|
import { dirname, isAbsolute, join, relative, resolve } from "node:path";
|
|
20
|
+
import { codexDir } from "./codexdir.js";
|
|
20
21
|
import { forEachLine, listSessions, replyCounter, textOf } from "./session.js";
|
|
21
22
|
import { estimateTokens, formatTokens, providerFor, realModel, tokensForLength } from "./tokens.js";
|
|
22
23
|
import { cacheWriteSplit, formatUsd, pricingFor, writeMultiplier as ttlWriteMultiplier } from "./pricing.js";
|
|
@@ -123,7 +124,7 @@ export function findMemoryFiles(cwd = process.cwd(), home = homedir()) {
|
|
|
123
124
|
if (auto)
|
|
124
125
|
add("Claude Code", autoMemoryPath(cwd, home), "auto memory", auto.split("\n").slice(0, 200).join("\n"));
|
|
125
126
|
// Codex: global AGENTS.md, then each directory down to cwd (it stops at the git root; root-ward extras are rare).
|
|
126
|
-
add("Codex", join(home, "
|
|
127
|
+
add("Codex", join(codexDir(home), "AGENTS.md"), "user");
|
|
127
128
|
for (const d of ancestors(cwd).reverse()) {
|
|
128
129
|
if (d === home)
|
|
129
130
|
continue;
|
package/dist/pack.js
CHANGED
|
@@ -18,7 +18,7 @@ import { existsSync, lstatSync, readdirSync, readFileSync, realpathSync, statSyn
|
|
|
18
18
|
import { homedir } from "node:os";
|
|
19
19
|
import { basename, extname, isAbsolute, join, relative, resolve, sep } from "node:path";
|
|
20
20
|
import { estimateTokens, formatTokens } from "./tokens.js";
|
|
21
|
-
import { EXTRACT_BUDGET_MS, EXTRACTABLE, extractText, extractTextAsync } from "./extract.js";
|
|
21
|
+
import { EXTRACT_BUDGET_MS, EXTRACTABLE, extractText, extractTextAsync, monotonicNow } from "./extract.js";
|
|
22
22
|
const DEFAULT_BUDGET = 4000;
|
|
23
23
|
const DEFAULT_CHUNK_TOKENS = 400;
|
|
24
24
|
/** Claude's tokenizer produces the most tokens per char; a budget in its terms never overruns another's. */
|
|
@@ -646,7 +646,8 @@ export function readSources(paths, cwdOrOptions = process.cwd()) {
|
|
|
646
646
|
export async function readSourcesAsync(paths, options = {}) {
|
|
647
647
|
const defer = [];
|
|
648
648
|
const { sources, skipped } = readSources(paths, { ...options, defer });
|
|
649
|
-
|
|
649
|
+
// One budget for every document, on the monotonic clock: a wall clock that jumps between two cannot end it.
|
|
650
|
+
const deadline = monotonicNow() + (options.budgetMs ?? EXTRACT_BUDGET_MS);
|
|
650
651
|
const failed = new Set();
|
|
651
652
|
for (const d of defer) {
|
|
652
653
|
const got = await extractTextAsync(d.path, deadline);
|
package/dist/proxy.d.ts
CHANGED
|
@@ -65,7 +65,7 @@ export interface ProxyOptions extends OptimizeOptions {
|
|
|
65
65
|
/** Default request body cap: far above any real request (a 1M-token context is ~4 MB of JSON, images aside). */
|
|
66
66
|
export declare const DEFAULT_MAX_BODY_BYTES: number;
|
|
67
67
|
/** Reported by /health so `autopilot status` can tell an outdated service from a current one. */
|
|
68
|
-
export declare const PROXY_VERSION = "0.
|
|
68
|
+
export declare const PROXY_VERSION = "0.42.0";
|
|
69
69
|
/**
|
|
70
70
|
* Remove a leading `/t/<token>` from a request path, or return undefined when
|
|
71
71
|
* the prefix is absent or the token differs. The comparison is constant time
|
package/dist/proxy.js
CHANGED
|
@@ -24,7 +24,7 @@ import { withPromptCacheKey } from "./cachekey.js";
|
|
|
24
24
|
/** Default request body cap: far above any real request (a 1M-token context is ~4 MB of JSON, images aside). */
|
|
25
25
|
export const DEFAULT_MAX_BODY_BYTES = 100 * 1024 * 1024;
|
|
26
26
|
/** Reported by /health so `autopilot status` can tell an outdated service from a current one. */
|
|
27
|
-
export const PROXY_VERSION = "0.
|
|
27
|
+
export const PROXY_VERSION = "0.42.0";
|
|
28
28
|
/** Connection-level headers that must not be forwarded. */
|
|
29
29
|
const SKIP_REQUEST_HEADERS = new Set(["host", "content-length", "connection", "transfer-encoding", "accept-encoding", "expect"]);
|
|
30
30
|
const SKIP_RESPONSE_HEADERS = new Set(["content-length", "content-encoding", "transfer-encoding", "connection"]);
|
package/dist/recall.js
CHANGED
|
@@ -21,6 +21,7 @@
|
|
|
21
21
|
import { closeSync, existsSync, openSync, readdirSync, readSync, statSync } from "node:fs";
|
|
22
22
|
import { homedir } from "node:os";
|
|
23
23
|
import { basename, dirname, isAbsolute, join, resolve } from "node:path";
|
|
24
|
+
import { codexDir } from "./codexdir.js";
|
|
24
25
|
import { claudeProjectDir, forEachLine } from "./session.js";
|
|
25
26
|
import { packContext } from "./pack.js";
|
|
26
27
|
import { maskSecrets, stripControls } from "./handoff.js";
|
|
@@ -242,7 +243,7 @@ function newestIn(dir) {
|
|
|
242
243
|
}
|
|
243
244
|
/** The newest Codex rollout of the last week that started in `cwd`. */
|
|
244
245
|
function newestCodexFor(cwd, home) {
|
|
245
|
-
const codexRoot = join(home, "
|
|
246
|
+
const codexRoot = join(codexDir(home), "sessions");
|
|
246
247
|
if (!existsSync(codexRoot))
|
|
247
248
|
return undefined;
|
|
248
249
|
const since = Date.now() - 7 * 86_400_000;
|
|
@@ -323,7 +324,7 @@ export function findSession(idOrPath, home = homedir()) {
|
|
|
323
324
|
if (existsSync(p))
|
|
324
325
|
return p;
|
|
325
326
|
}
|
|
326
|
-
const codexRoot = join(home, "
|
|
327
|
+
const codexRoot = join(codexDir(home), "sessions");
|
|
327
328
|
let hit;
|
|
328
329
|
const walk = (dir, depth) => {
|
|
329
330
|
if (hit)
|
package/dist/scan.d.ts
CHANGED
|
@@ -64,6 +64,8 @@ export interface Extractor<S = unknown> {
|
|
|
64
64
|
}
|
|
65
65
|
/** Where the cache lives (created only when something is written). */
|
|
66
66
|
export declare function scanCacheDir(env?: NodeJS.ProcessEnv): string;
|
|
67
|
+
/** A fingerprint of the bytes before `off` (its first and last few KB): what tells a file grown in place from one rewritten. */
|
|
68
|
+
export declare function anchorOf(fd: number, off: number): string;
|
|
67
69
|
/**
|
|
68
70
|
* Read every transcript once for all the extractors that need it (each job:
|
|
69
71
|
* an extractor set and its transcripts), so the analyses that follow find
|
package/dist/scan.js
CHANGED
|
@@ -153,7 +153,8 @@ function persist(e, file = entryFile(e.path, e.id)) {
|
|
|
153
153
|
catch { /* never written */ }
|
|
154
154
|
}
|
|
155
155
|
}
|
|
156
|
-
|
|
156
|
+
/** A fingerprint of the bytes before `off` (its first and last few KB): what tells a file grown in place from one rewritten. */
|
|
157
|
+
export function anchorOf(fd, off) {
|
|
157
158
|
const h = createHash("sha1");
|
|
158
159
|
const read = (start, len) => {
|
|
159
160
|
const buf = Buffer.alloc(len);
|
package/dist/session.js
CHANGED
|
@@ -14,6 +14,7 @@ import { readdirSync, readFileSync, statSync, existsSync, openSync, readSync, cl
|
|
|
14
14
|
import { StringDecoder } from "node:string_decoder";
|
|
15
15
|
import { homedir } from "node:os";
|
|
16
16
|
import { join } from "node:path";
|
|
17
|
+
import { codexDir } from "./codexdir.js";
|
|
17
18
|
import { isGeminiChat, listGeminiChats, parseGeminiChat } from "./gemini.js";
|
|
18
19
|
import { claudeDir } from "./claudedir.js";
|
|
19
20
|
/**
|
|
@@ -58,7 +59,7 @@ export function listSessions(limit = 20) {
|
|
|
58
59
|
}
|
|
59
60
|
}
|
|
60
61
|
// Codex keeps rollouts by date: ~/.codex/sessions/YYYY/MM/DD/rollout-*.jsonl.
|
|
61
|
-
const codexRoot = join(
|
|
62
|
+
const codexRoot = join(codexDir(), "sessions");
|
|
62
63
|
if (existsSync(codexRoot)) {
|
|
63
64
|
const walk = (dir, depth) => {
|
|
64
65
|
let entries;
|
package/dist/settingsedit.d.ts
CHANGED
|
@@ -64,6 +64,10 @@ export declare function editJsonText(text: string | undefined, after: Record<str
|
|
|
64
64
|
export declare function writeAtomic(path: string, text: string): void;
|
|
65
65
|
/** Remove a file through a symbolic link: the target goes, the link would dangle, so the link goes too. */
|
|
66
66
|
export declare function removeFile(path: string): void;
|
|
67
|
+
/** The lock every context-doctor writer of Claude Code's settings.json takes (fix, cache-ttl, compact-window, autopilot): beside the file. */
|
|
68
|
+
export declare function settingsLockPath(settingsFile: string): string;
|
|
69
|
+
/** Run `fn` holding the lock of Claude Code's settings.json at `settingsFile` (its folder created if missing). */
|
|
70
|
+
export declare function withSettingsLock<T>(settingsFile: string, fn: () => T, waitMs?: number): T;
|
|
67
71
|
/**
|
|
68
72
|
* Run `fn` holding `lockPath` (created exclusively). Another context-doctor
|
|
69
73
|
* holding it is waited for, up to `waitMs`; a lock older than `staleMs` is
|
package/dist/settingsedit.js
CHANGED
|
@@ -10,7 +10,7 @@
|
|
|
10
10
|
* target (the target of a symbolic link, so the link stays), keeping the
|
|
11
11
|
* file's mode; a lock file serialises context-doctor's own writers.
|
|
12
12
|
*/
|
|
13
|
-
import { closeSync, existsSync, mkdirSync, openSync, readFileSync, realpathSync, renameSync, statSync, unlinkSync, writeFileSync } from "node:fs";
|
|
13
|
+
import { closeSync, existsSync, mkdirSync, openSync, readFileSync, realpathSync, renameSync, rmdirSync, statSync, unlinkSync, writeFileSync } from "node:fs";
|
|
14
14
|
import { basename, dirname, join } from "node:path";
|
|
15
15
|
import { tilde } from "./claudedir.js";
|
|
16
16
|
/** A refusal with a message fit for the user: nothing was changed. */
|
|
@@ -421,7 +421,7 @@ export function writeAtomic(path, text) {
|
|
|
421
421
|
const tmp = join(dirname(target), `.${basename(target)}.context-doctor-${process.pid}-${Date.now()}.tmp`);
|
|
422
422
|
writeFileSync(tmp, text, mode !== undefined ? { mode } : undefined);
|
|
423
423
|
try {
|
|
424
|
-
|
|
424
|
+
renameWithRetry(tmp, target);
|
|
425
425
|
}
|
|
426
426
|
catch (e) {
|
|
427
427
|
try {
|
|
@@ -431,6 +431,28 @@ export function writeAtomic(path, text) {
|
|
|
431
431
|
throw e;
|
|
432
432
|
}
|
|
433
433
|
}
|
|
434
|
+
/**
|
|
435
|
+
* renameSync, retried on Windows while another process has the target open:
|
|
436
|
+
* there a rename over a file someone is reading fails with EPERM, EACCES or
|
|
437
|
+
* EBUSY (Claude Code, an editor, or another context-doctor reading
|
|
438
|
+
* settings.json), where POSIX replaces it at once. Up to about 2 s, as
|
|
439
|
+
* graceful-fs does for npm.
|
|
440
|
+
*/
|
|
441
|
+
function renameWithRetry(from, to) {
|
|
442
|
+
const until = Date.now() + 2_000;
|
|
443
|
+
for (let wait = 5;; wait = Math.min(wait * 2, 100)) {
|
|
444
|
+
try {
|
|
445
|
+
renameSync(from, to);
|
|
446
|
+
return;
|
|
447
|
+
}
|
|
448
|
+
catch (e) {
|
|
449
|
+
const code = e.code;
|
|
450
|
+
if (process.platform !== "win32" || !["EPERM", "EACCES", "EBUSY"].includes(code ?? "") || Date.now() >= until)
|
|
451
|
+
throw e;
|
|
452
|
+
Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, wait);
|
|
453
|
+
}
|
|
454
|
+
}
|
|
455
|
+
}
|
|
434
456
|
/** Remove a file through a symbolic link: the target goes, the link would dangle, so the link goes too. */
|
|
435
457
|
export function removeFile(path) {
|
|
436
458
|
try {
|
|
@@ -447,12 +469,38 @@ export function removeFile(path) {
|
|
|
447
469
|
catch { /* gone */ }
|
|
448
470
|
}
|
|
449
471
|
const sleeper = new Int32Array(new SharedArrayBuffer(4));
|
|
472
|
+
/** Locks this process holds: a nested withLock of the same file runs inside the outer one instead of waiting on itself. */
|
|
473
|
+
const held = new Set();
|
|
474
|
+
/** The lock every context-doctor writer of Claude Code's settings.json takes (fix, cache-ttl, compact-window, autopilot): beside the file. */
|
|
475
|
+
export function settingsLockPath(settingsFile) {
|
|
476
|
+
return join(dirname(settingsFile), ".context-doctor-fixes.lock");
|
|
477
|
+
}
|
|
478
|
+
/** Run `fn` holding the lock of Claude Code's settings.json at `settingsFile` (its folder created if missing). */
|
|
479
|
+
export function withSettingsLock(settingsFile, fn, waitMs) {
|
|
480
|
+
const dir = dirname(settingsFile);
|
|
481
|
+
const created = !existsSync(dir);
|
|
482
|
+
if (created)
|
|
483
|
+
mkdirSync(dir, { recursive: true });
|
|
484
|
+
try {
|
|
485
|
+
return withLock(settingsLockPath(settingsFile), fn, waitMs);
|
|
486
|
+
}
|
|
487
|
+
finally {
|
|
488
|
+
// A folder made only to hold the lock goes again (a run that changed nothing leaves nothing).
|
|
489
|
+
if (created)
|
|
490
|
+
try {
|
|
491
|
+
rmdirSync(dir);
|
|
492
|
+
}
|
|
493
|
+
catch { /* it holds something now */ }
|
|
494
|
+
}
|
|
495
|
+
}
|
|
450
496
|
/**
|
|
451
497
|
* Run `fn` holding `lockPath` (created exclusively). Another context-doctor
|
|
452
498
|
* holding it is waited for, up to `waitMs`; a lock older than `staleMs` is
|
|
453
499
|
* taken over (its writer died).
|
|
454
500
|
*/
|
|
455
501
|
export function withLock(lockPath, fn, waitMs = 10_000, staleMs = 30_000) {
|
|
502
|
+
if (held.has(lockPath))
|
|
503
|
+
return fn();
|
|
456
504
|
const until = Date.now() + waitMs;
|
|
457
505
|
let fd;
|
|
458
506
|
for (;;) {
|
|
@@ -461,7 +509,15 @@ export function withLock(lockPath, fn, waitMs = 10_000, staleMs = 30_000) {
|
|
|
461
509
|
break;
|
|
462
510
|
}
|
|
463
511
|
catch (e) {
|
|
464
|
-
|
|
512
|
+
const code = e.code;
|
|
513
|
+
// Windows: a lock file the last holder is still deleting cannot be opened (EPERM, EACCES): it is held a moment longer.
|
|
514
|
+
if (process.platform === "win32" && (code === "EPERM" || code === "EACCES")) {
|
|
515
|
+
if (Date.now() > until)
|
|
516
|
+
throw new SettingsError(`another context-doctor is changing settings (${tilde(lockPath)}); try again. Nothing was changed.`);
|
|
517
|
+
Atomics.wait(sleeper, 0, 0, 25);
|
|
518
|
+
continue;
|
|
519
|
+
}
|
|
520
|
+
if (code !== "EEXIST")
|
|
465
521
|
throw e;
|
|
466
522
|
try {
|
|
467
523
|
if (Date.now() - statSync(lockPath).mtimeMs > staleMs) {
|
|
@@ -477,10 +533,12 @@ export function withLock(lockPath, fn, waitMs = 10_000, staleMs = 30_000) {
|
|
|
477
533
|
Atomics.wait(sleeper, 0, 0, 25);
|
|
478
534
|
}
|
|
479
535
|
}
|
|
536
|
+
held.add(lockPath);
|
|
480
537
|
try {
|
|
481
538
|
return fn();
|
|
482
539
|
}
|
|
483
540
|
finally {
|
|
541
|
+
held.delete(lockPath);
|
|
484
542
|
try {
|
|
485
543
|
closeSync(fd);
|
|
486
544
|
}
|
package/dist/spend.d.ts
CHANGED
|
@@ -55,7 +55,7 @@ export interface SpendItem {
|
|
|
55
55
|
priced: boolean;
|
|
56
56
|
/** Claude Code: run by a subagent. */
|
|
57
57
|
subagent?: boolean;
|
|
58
|
-
/** Claude Code: the reply's row uuid, which a fork's copy shares. */
|
|
58
|
+
/** Claude Code: the reply's row uuid, which a fork's copy shares. Codex: the event's codexEventKey, which a forked rollout's copy shares. */
|
|
59
59
|
key?: string;
|
|
60
60
|
}
|
|
61
61
|
/** A project's name as `savings` shows it: the folder's path with "-" for separators, less "-Users-<you>-". */
|
|
@@ -74,6 +74,7 @@ export declare const CODEX_SPEND_ROWS: Extractor<null>;
|
|
|
74
74
|
export declare function codexFileSpend(file: string, since: number, until?: number): SpendItem[];
|
|
75
75
|
/** Codex rollouts written since `since`: the live ones and the archived. */
|
|
76
76
|
export declare function codexFiles(since: number, home?: string): string[];
|
|
77
|
+
/** Every Codex request in the window, once: a forked rollout's copy of its parent's (codexEventKey) counts at the earliest time met. */
|
|
77
78
|
export declare function codexSpend(since: number, until?: number, home?: string): SpendItem[];
|
|
78
79
|
/**
|
|
79
80
|
* What `spend` takes from a Gemini CLI chat (JSONL): each `gemini` message's
|
|
@@ -164,6 +165,12 @@ export interface SpendOptions {
|
|
|
164
165
|
onProgress?: (done: number, total: number) => void;
|
|
165
166
|
now?: number;
|
|
166
167
|
}
|
|
168
|
+
/**
|
|
169
|
+
* The longest window: ten years, older than any history these tools keep.
|
|
170
|
+
* Unbounded, `--days 10000000` listed every empty day of it (51 s, and
|
|
171
|
+
* --json died on a string too long), and 1e9 days fell off the calendar.
|
|
172
|
+
*/
|
|
173
|
+
export declare const MAX_SPEND_DAYS = 3650;
|
|
167
174
|
/** The last `days` days, every tool on this machine. A tool with nothing on disk is just absent. */
|
|
168
175
|
export declare function spendReport(days?: number, opts?: SpendOptions): SpendReport;
|
|
169
176
|
export declare const usd: (n: number) => string;
|
package/dist/spend.js
CHANGED
|
@@ -31,9 +31,10 @@
|
|
|
31
31
|
* subagents too; on the requests both count, the dollars are the same.
|
|
32
32
|
*/
|
|
33
33
|
import { basename, dirname, join } from "node:path";
|
|
34
|
+
import { codexDir } from "./codexdir.js";
|
|
34
35
|
import { homedir } from "node:os";
|
|
35
36
|
import { existsSync, statSync } from "node:fs";
|
|
36
|
-
import { claudeFileUsage, claudeUsageFiles, codexSessionsRoot, rolloutFiles } from "./limits.js";
|
|
37
|
+
import { claudeFileUsage, claudeUsageFiles, codexEventKey, codexSessionsRoot, rolloutFiles } from "./limits.js";
|
|
37
38
|
import { listGeminiChats, readGeminiMessages } from "./gemini.js";
|
|
38
39
|
import { cursorUsage, SqliteUnavailableError } from "./cursor.js";
|
|
39
40
|
import { openAIUsage, pricingFor, usageCost } from "./pricing.js";
|
|
@@ -111,7 +112,7 @@ export function claudeSpend(since, until = Infinity, tops, onProgress) {
|
|
|
111
112
|
* and every token_count event's last request and running total.
|
|
112
113
|
*/
|
|
113
114
|
export const CODEX_SPEND_ROWS = {
|
|
114
|
-
id: "codex-spend.
|
|
115
|
+
id: "codex-spend.2",
|
|
115
116
|
init: () => null,
|
|
116
117
|
line(line, row, out) {
|
|
117
118
|
if (!line.includes('"token_count"') && !line.includes('"turn_context"') && !line.includes('"session_meta"'))
|
|
@@ -139,7 +140,7 @@ export const CODEX_SPEND_ROWS = {
|
|
|
139
140
|
if (!last || typeof last !== "object")
|
|
140
141
|
return;
|
|
141
142
|
const total = p.info?.total_token_usage?.total_tokens;
|
|
142
|
-
out.push({ k: "t", ts: String(e.timestamp ?? ""), total: typeof total === "number" ? total : 0, u: pick(last, ["input_tokens", "cached_input_tokens", "cache_write_input_tokens", "output_tokens", "input_tokens_details", "prompt_tokens", "prompt_tokens_details", "completion_tokens"]) });
|
|
143
|
+
out.push({ k: "t", ts: String(e.timestamp ?? ""), total: typeof total === "number" ? total : 0, key: codexEventKey(p.info?.total_token_usage, last), u: pick(last, ["input_tokens", "cached_input_tokens", "cache_write_input_tokens", "output_tokens", "input_tokens_details", "prompt_tokens", "prompt_tokens_details", "completion_tokens"]) });
|
|
143
144
|
},
|
|
144
145
|
};
|
|
145
146
|
const num = (v) => (typeof v === "number" && Number.isFinite(v) && v > 0 ? v : 0);
|
|
@@ -166,24 +167,26 @@ export function codexFileSpend(file, since, until = Infinity) {
|
|
|
166
167
|
if (!Number.isFinite(ts) || ts < since || ts > until)
|
|
167
168
|
continue;
|
|
168
169
|
const u = openAIUsage(r.u);
|
|
169
|
-
out.push(priced({ tool: "codex", ts, project: cwd ? projectName(cwd) : "codex", session: basename(file, ".jsonl"), ...(model ? { 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) }, u));
|
|
170
|
+
out.push(priced({ tool: "codex", ts, project: cwd ? projectName(cwd) : "codex", session: basename(file, ".jsonl"), ...(model ? { 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), ...(r.key ? { key: r.key } : {}) }, u));
|
|
170
171
|
}
|
|
171
172
|
return out;
|
|
172
173
|
}
|
|
173
174
|
/** Codex rollouts written since `since`: the live ones and the archived. */
|
|
174
175
|
export function codexFiles(since, home = homedir()) {
|
|
175
|
-
const roots = [codexSessionsRoot(home), join(home, "
|
|
176
|
+
const roots = [codexSessionsRoot(home), join(codexDir(home), "archived_sessions")];
|
|
176
177
|
return roots.filter((r) => existsSync(r)).flatMap((r) => rolloutFiles(r, since));
|
|
177
178
|
}
|
|
179
|
+
/** Every Codex request in the window, once: a forked rollout's copy of its parent's (codexEventKey) counts at the earliest time met. */
|
|
178
180
|
export function codexSpend(since, until = Infinity, home = homedir()) {
|
|
179
|
-
const
|
|
181
|
+
const all = [];
|
|
180
182
|
for (const f of codexFiles(since, home)) {
|
|
181
183
|
try {
|
|
182
|
-
|
|
184
|
+
all.push(...codexFileSpend(f, since, until));
|
|
183
185
|
}
|
|
184
186
|
catch { /* unreadable: skipped */ }
|
|
185
187
|
}
|
|
186
|
-
|
|
188
|
+
const seen = new Set();
|
|
189
|
+
return all.sort((a, b) => a.ts - b.ts).filter((it) => !it.key || (!seen.has(it.key) && Boolean(seen.add(it.key))));
|
|
187
190
|
}
|
|
188
191
|
// ---------------------------------------------------------------------------
|
|
189
192
|
// Gemini CLI
|
|
@@ -364,8 +367,15 @@ export function summarizeSpend(items, days, since, until, skipped = []) {
|
|
|
364
367
|
skipped,
|
|
365
368
|
};
|
|
366
369
|
}
|
|
370
|
+
/**
|
|
371
|
+
* The longest window: ten years, older than any history these tools keep.
|
|
372
|
+
* Unbounded, `--days 10000000` listed every empty day of it (51 s, and
|
|
373
|
+
* --json died on a string too long), and 1e9 days fell off the calendar.
|
|
374
|
+
*/
|
|
375
|
+
export const MAX_SPEND_DAYS = 3650;
|
|
367
376
|
/** The last `days` days, every tool on this machine. A tool with nothing on disk is just absent. */
|
|
368
377
|
export function spendReport(days = 30, opts = {}) {
|
|
378
|
+
days = Math.min(days, MAX_SPEND_DAYS);
|
|
369
379
|
const until = opts.now ?? Date.now();
|
|
370
380
|
const since = until - days * DAY;
|
|
371
381
|
const home = opts.home ?? homedir();
|
|
@@ -402,7 +412,8 @@ export function renderSpend(r, top = 8) {
|
|
|
402
412
|
lines.push("─".repeat(60));
|
|
403
413
|
for (const t of r.tools) {
|
|
404
414
|
const unit = t.tool === "cursor" ? "replies" : "requests";
|
|
405
|
-
const
|
|
415
|
+
const notes = [t.estimate ? "estimate, no cache split" : t.subagentUsd ? `subagents ${usd(t.subagentUsd)}` : "", t.unpriced ? `${t.unpriced.toLocaleString("en-US")} not priced` : ""].filter(Boolean);
|
|
416
|
+
const note = notes.length ? ` ${notes.join(", ")}` : "";
|
|
406
417
|
lines.push(`${t.name.padEnd(14)}${`${t.estimate ? "~" : ""}${usd(t.usd)}`.padStart(11)} ${`${t.requests.toLocaleString("en-US")} ${unit}`.padEnd(16)}${note}`);
|
|
407
418
|
}
|
|
408
419
|
if (r.tools.length > 1)
|
|
@@ -416,7 +427,9 @@ export function renderSpend(r, top = 8) {
|
|
|
416
427
|
};
|
|
417
428
|
const toolsOf = (byTool) => (r.tools.length > 1 ? TOOLS.filter((t) => (byTool[t] ?? 0) > 0).map((t) => TOOL_NAME[t]).join(", ") : undefined);
|
|
418
429
|
list("By project", r.projects.slice(0, top).map((p) => ({ name: p.project, usd: p.usd, tail: toolsOf(p.byTool) })), r.projects.length - top);
|
|
419
|
-
|
|
430
|
+
// A model with no list price reads "not priced", not a $0.00 that looks free.
|
|
431
|
+
const unpricedModels = new Set(r.tools.flatMap((t) => t.unpricedModels));
|
|
432
|
+
list("By model", r.models.slice(0, top).map((m) => ({ name: m.model, usd: m.usd, ...(m.usd === 0 && unpricedModels.has(m.model) ? { tail: `not priced, ${m.requests.toLocaleString("en-US")} ${m.requests === 1 ? "request" : "requests"}` } : {}) })), r.models.length - top);
|
|
420
433
|
// The last two weeks of the window, a bar each, scaled to the busiest.
|
|
421
434
|
const recent = r.daily.slice(-14);
|
|
422
435
|
const peak = Math.max(...recent.map((d) => d.usd), 0);
|
|
@@ -466,6 +479,10 @@ export function renderSpendShare(r) {
|
|
|
466
479
|
const claude = r.tools.find((t) => t.tool === "claude");
|
|
467
480
|
if (claude?.subagentUsd)
|
|
468
481
|
lines.push(`Claude Code subagents: ${usd(claude.subagentUsd)} of it.`);
|
|
482
|
+
// Requests on a model with no list price are not in the total: said, so the total is not read as all of it.
|
|
483
|
+
const unpriced = r.tools.reduce((n, t) => n + t.unpriced, 0);
|
|
484
|
+
if (unpriced)
|
|
485
|
+
lines.push(`Not in it: ${unpriced.toLocaleString("en-US")} ${unpriced === 1 ? "request" : "requests"} (${formatTokens(r.tools.reduce((n, t) => n + t.unpricedTokens, 0))} tokens) on models with no list price.`);
|
|
469
486
|
const parts = [["cache writes", r.parts.writeUsd], ["cache reads", r.parts.readUsd], ["output", r.parts.outputUsd], ["uncached input", r.parts.inputUsd]];
|
|
470
487
|
const [bigPart, bigUsd] = parts.sort((a, b) => b[1] - a[1])[0];
|
|
471
488
|
const busiest = [...r.daily].sort((a, b) => b.usd - a.usd)[0];
|
package/dist/subagentmodel.d.ts
CHANGED
|
@@ -11,7 +11,9 @@
|
|
|
11
11
|
* built-ins: Explore, Plan and fork say "inherit", claude-code-guide
|
|
12
12
|
* "haiku", statusline-setup "sonnet"; general-purpose and claude name
|
|
13
13
|
* none);
|
|
14
|
-
* 3. CLAUDE_CODE_SUBAGENT_MODEL, unless it is
|
|
14
|
+
* 3. CLAUDE_CODE_SUBAGENT_MODEL, unless it is empty or "inherit" (this
|
|
15
|
+
* function treats "default" as a model name; Claude Code's fallback
|
|
16
|
+
* chain treats it like "inherit");
|
|
15
17
|
* 4. the main conversation's model.
|
|
16
18
|
* So the variable moves only the agents whose definition names no model
|
|
17
19
|
* (general-purpose, claude, agents of your own without `model:`).
|
|
@@ -49,6 +51,12 @@ export interface AgentDefinition {
|
|
|
49
51
|
model?: string;
|
|
50
52
|
where: string;
|
|
51
53
|
}
|
|
54
|
+
/**
|
|
55
|
+
* The agent definitions Claude Code uses in `cwd`, as 2.1.309 merges them,
|
|
56
|
+
* lowest first: the user's (~/.claude/agents), the project's (outer folders
|
|
57
|
+
* first), then managed. Plugin agents are not read.
|
|
58
|
+
*/
|
|
59
|
+
export declare function agentDefinitions(cwd: string | undefined, home?: string, env?: NodeJS.ProcessEnv): Map<string, AgentDefinition>;
|
|
52
60
|
/** How a type's model is chosen: whether CLAUDE_CODE_SUBAGENT_MODEL moves it, and why not. */
|
|
53
61
|
export declare function variableMoves(type: string, defs: Map<string, AgentDefinition>, force?: boolean): {
|
|
54
62
|
moves: boolean;
|
|
@@ -77,8 +85,15 @@ export interface SubagentModelReplay {
|
|
|
77
85
|
atCandidateUsd: number;
|
|
78
86
|
/** billed - at candidate. */
|
|
79
87
|
savedUsd: number;
|
|
80
|
-
/** The moved requests' bill by the model they ran on
|
|
88
|
+
/** The moved requests' bill by the model they ran on (the names in the plan's title). */
|
|
81
89
|
movedFrom: Record<string, number>;
|
|
90
|
+
/**
|
|
91
|
+
* Every request of the types the variable moves, Sonnet-or-cheaper ones
|
|
92
|
+
* included, by the model it ran on, weighted by its tokens (priced at the
|
|
93
|
+
* candidate's rates): the mix "saved since" prices those types at after
|
|
94
|
+
* the change, when every one of them is on the candidate.
|
|
95
|
+
*/
|
|
96
|
+
before: Record<string, number>;
|
|
82
97
|
/** Requests on models with no price (left out of the dollars). */
|
|
83
98
|
unpriced: number;
|
|
84
99
|
byType: TypeReplay[];
|
|
@@ -91,7 +106,7 @@ export interface SubagentModelOptions {
|
|
|
91
106
|
candidate?: string;
|
|
92
107
|
/** CLAUDE_CODE_SUBAGENT_MODEL_FORCE is on: the variable moves every type but forks. */
|
|
93
108
|
force?: boolean;
|
|
94
|
-
/** Agent definitions (default:
|
|
109
|
+
/** Agent definitions for every subagent (default: per subagent's folder, as agentDefinitions merges them). */
|
|
95
110
|
definitions?: Map<string, AgentDefinition>;
|
|
96
111
|
home?: string;
|
|
97
112
|
/** Price every moved request at this mix of models (shares adding to 1) instead of the candidate: "saved since". */
|
|
@@ -109,7 +124,7 @@ export declare function agentTypeOf(transcript: string): string;
|
|
|
109
124
|
export declare function replaySubagentModels(opts: SubagentModelOptions): SubagentModelReplay;
|
|
110
125
|
/** The models the moved requests ran on, for people: the one or two that carry 10%+ of the bill ("Fable 5.1 or Opus 5.5"). */
|
|
111
126
|
export declare function movedFromNames(movedFrom: Record<string, number>): string | undefined;
|
|
112
|
-
/** Each model's share of a
|
|
127
|
+
/** Each model's share of a total by model (a fix record keeps the shares of `before` as the baseline). */
|
|
113
128
|
export declare function shares(byModel: Record<string, number>): Record<string, number>;
|
|
114
129
|
/** A model id for people: "claude-opus-5-5" as "Opus 5.5". */
|
|
115
130
|
export declare function modelName(model: string | undefined): string;
|