context-doctor 0.40.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.
Files changed (53) hide show
  1. package/README.md +12 -4
  2. package/dist/ab.js +3 -1
  3. package/dist/autopilot.d.ts +1 -1
  4. package/dist/autopilot.js +38 -24
  5. package/dist/budget.d.ts +102 -0
  6. package/dist/budget.js +550 -0
  7. package/dist/cachettl.js +12 -9
  8. package/dist/claudedir.d.ts +8 -0
  9. package/dist/claudedir.js +19 -0
  10. package/dist/cli.js +145 -15
  11. package/dist/codexdir.d.ts +11 -0
  12. package/dist/codexdir.js +20 -0
  13. package/dist/codexroute.d.ts +1 -0
  14. package/dist/codexroute.js +3 -1
  15. package/dist/compactwindow.js +12 -9
  16. package/dist/cursor.d.ts +23 -0
  17. package/dist/cursor.js +140 -6
  18. package/dist/doctor.d.ts +9 -0
  19. package/dist/doctor.js +49 -12
  20. package/dist/effective.d.ts +18 -0
  21. package/dist/effective.js +39 -4
  22. package/dist/extract.d.ts +12 -3
  23. package/dist/extract.js +39 -12
  24. package/dist/fileparams.d.ts +1 -1
  25. package/dist/fileparams.js +8 -8
  26. package/dist/fix.d.ts +23 -2
  27. package/dist/fix.js +86 -10
  28. package/dist/hook.js +45 -7
  29. package/dist/install.js +108 -47
  30. package/dist/ledger.d.ts +15 -0
  31. package/dist/ledger.js +30 -1
  32. package/dist/limits.d.ts +53 -6
  33. package/dist/limits.js +152 -77
  34. package/dist/mcp.js +58 -58
  35. package/dist/overhead.js +2 -1
  36. package/dist/pack.js +3 -2
  37. package/dist/proxy.d.ts +1 -1
  38. package/dist/proxy.js +1 -1
  39. package/dist/recall.js +3 -2
  40. package/dist/scan.d.ts +10 -0
  41. package/dist/scan.js +23 -1
  42. package/dist/session.js +2 -1
  43. package/dist/settingsedit.d.ts +4 -0
  44. package/dist/settingsedit.js +61 -3
  45. package/dist/spend.d.ts +183 -0
  46. package/dist/spend.js +493 -0
  47. package/dist/statusline.d.ts +9 -2
  48. package/dist/statusline.js +20 -4
  49. package/dist/subagentmodel.d.ts +141 -0
  50. package/dist/subagentmodel.js +408 -0
  51. package/dist/subagentpay.d.ts +11 -0
  52. package/dist/subagentpay.js +23 -4
  53. 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, ".codex", "AGENTS.md"), "user");
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
- const deadline = Date.now() + (options.budgetMs ?? EXTRACT_BUDGET_MS);
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.40.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.40.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, ".codex", "sessions");
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, ".codex", "sessions");
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
@@ -83,6 +85,14 @@ export declare function prescan(jobs: Array<{
83
85
  export declare function rowsOf<R = any>(path: string, ex: Extractor<any>, opts?: {
84
86
  keep?: boolean;
85
87
  }): R[];
88
+ /**
89
+ * A report's own record for a source that is not a transcript (Cursor's
90
+ * database), kept beside the transcripts' entries: written the same way,
91
+ * pruned with them when its source is gone or untouched for 120 days, and
92
+ * removed by `uninstall`. Undefined when none is kept or it is damaged.
93
+ */
94
+ export declare function readSideEntry<T>(path: string, id: string): T | undefined;
95
+ export declare function writeSideEntry(path: string, id: string, value: unknown): void;
86
96
  /** Forget this run's records (tests). */
87
97
  export declare function clearScanMemo(): void;
88
98
  /**
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
- function anchorOf(fd, off) {
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);
@@ -357,6 +358,27 @@ export function rowsOf(path, ex, opts = {}) {
357
358
  }
358
359
  return (e.tail.length ? e.rows.concat(e.tail) : e.rows);
359
360
  }
361
+ /**
362
+ * A report's own record for a source that is not a transcript (Cursor's
363
+ * database), kept beside the transcripts' entries: written the same way,
364
+ * pruned with them when its source is gone or untouched for 120 days, and
365
+ * removed by `uninstall`. Undefined when none is kept or it is damaged.
366
+ */
367
+ export function readSideEntry(path, id) {
368
+ if (disabled())
369
+ return undefined;
370
+ try {
371
+ const v = JSON.parse(readFileSync(entryFile(path, id), "utf8"));
372
+ return v?.path === path && v.id === id ? v.value : undefined;
373
+ }
374
+ catch {
375
+ return undefined;
376
+ }
377
+ }
378
+ export function writeSideEntry(path, id, value) {
379
+ // "path" first: pruning reads it from the file's head.
380
+ persist({ path, id, value }, entryFile(path, id));
381
+ }
360
382
  /** Forget this run's records (tests). */
361
383
  export function clearScanMemo() {
362
384
  memo.clear();
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(homedir(), ".codex", "sessions");
62
+ const codexRoot = join(codexDir(), "sessions");
62
63
  if (existsSync(codexRoot)) {
63
64
  const walk = (dir, depth) => {
64
65
  let entries;
@@ -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
@@ -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
- renameSync(tmp, target);
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
- if (e.code !== "EEXIST")
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
  }
@@ -0,0 +1,183 @@
1
+ /**
2
+ * `context-doctor spend`: one bill across every AI coding tool on this
3
+ * machine, at list prices.
4
+ *
5
+ * Each tool keeps its own record of what it sent, and none adds them up:
6
+ *
7
+ * - Claude Code: every reply's `usage` in its transcripts, the main
8
+ * conversation and each subagent's (`<session>/subagents/agent-*.jsonl`),
9
+ * read as `limits` reads them (claudeFileUsage): each reply once, its
10
+ * output settled on its last row, a fork's copy of its parent counted once.
11
+ * - Codex: the `token_count` events of its rollouts (~/.codex/sessions and
12
+ * archived_sessions), a request each time the running total moves, as
13
+ * `limits` counts them; the model from `turn_context`, the folder from
14
+ * `session_meta`.
15
+ * - Gemini CLI: each `gemini` message's `tokens` in ~/.gemini/tmp/<project>/chats,
16
+ * the last copy of a message written twice. A message later rewound was
17
+ * still billed, so it is counted.
18
+ * - Cursor: the `tokenCount` on its agent replies (cursorUsage). It records
19
+ * no cache split, so every input token is priced uncached: an estimate,
20
+ * and an upper bound. Replies on Auto ("default") have no list price and
21
+ * are counted, not priced.
22
+ *
23
+ * Priced at pricing.ts's list prices (usageCost), as every report here is.
24
+ * Claude Code, Codex and Gemini CLI are read through the shared scan
25
+ * (scan.ts), so a second run reads only what was appended since; Cursor's
26
+ * replies are kept per chat until the chat changes.
27
+ *
28
+ * `savings` bills a narrower slice of the same Claude Code requests: the main
29
+ * conversation's input (cache writes and reads included, output not), in
30
+ * sessions with 10+ requests. `spend` counts every request, its output and
31
+ * subagents too; on the requests both count, the dollars are the same.
32
+ */
33
+ import { type Extractor } from "./scan.js";
34
+ export type Tool = "claude" | "codex" | "gemini" | "cursor";
35
+ export declare const TOOLS: Tool[];
36
+ export declare const TOOL_NAME: Record<Tool, string>;
37
+ /** One request (a Cursor reply), priced. */
38
+ export interface SpendItem {
39
+ tool: Tool;
40
+ ts: number;
41
+ project: string;
42
+ /** The session it belongs to: its transcript's name, or Cursor's chat id. */
43
+ session: string;
44
+ model?: string;
45
+ input: number;
46
+ read: number;
47
+ write: number;
48
+ output: number;
49
+ /** At list price; 0 when the model has no price on file (`priced` false). */
50
+ usd: number;
51
+ inputUsd: number;
52
+ writeUsd: number;
53
+ readUsd: number;
54
+ outputUsd: number;
55
+ priced: boolean;
56
+ /** Claude Code: run by a subagent. */
57
+ subagent?: boolean;
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
+ key?: string;
60
+ }
61
+ /** A project's name as `savings` shows it: the folder's path with "-" for separators, less "-Users-<you>-". */
62
+ export declare function projectName(folder: string): string;
63
+ /**
64
+ * Claude Code's requests between `since` and `until`, main threads and
65
+ * subagents, over `tops` (default: every transcript written since `since`).
66
+ */
67
+ export declare function claudeSpend(since: number, until?: number, tops?: string[], onProgress?: (done: number, total: number) => void): SpendItem[];
68
+ /**
69
+ * What `spend` takes from a Codex rollout: its folder, each model change,
70
+ * and every token_count event's last request and running total.
71
+ */
72
+ export declare const CODEX_SPEND_ROWS: Extractor<null>;
73
+ /** The requests of one Codex rollout since `since`. Throws when it cannot be read. */
74
+ export declare function codexFileSpend(file: string, since: number, until?: number): SpendItem[];
75
+ /** Codex rollouts written since `since`: the live ones and the archived. */
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. */
78
+ export declare function codexSpend(since: number, until?: number, home?: string): SpendItem[];
79
+ /**
80
+ * What `spend` takes from a Gemini CLI chat (JSONL): each `gemini` message's
81
+ * id, time, model and token counts. A message without a time of its own
82
+ * takes the last time met before it.
83
+ */
84
+ export declare const GEMINI_SPEND_ROWS: Extractor<{
85
+ ts: string;
86
+ }>;
87
+ /** The billed messages of one Gemini CLI chat since `since`. Throws when it cannot be read. */
88
+ export declare function geminiFileSpend(file: string, since: number, until?: number): SpendItem[];
89
+ export declare function geminiFiles(since: number, home?: string): string[];
90
+ export declare function geminiSpend(since: number, until?: number, home?: string): SpendItem[];
91
+ export declare function cursorSpend(since: number, until?: number): SpendItem[];
92
+ export interface ToolSpend {
93
+ tool: Tool;
94
+ name: string;
95
+ usd: number;
96
+ requests: number;
97
+ tokens: {
98
+ input: number;
99
+ read: number;
100
+ write: number;
101
+ output: number;
102
+ };
103
+ /** Claude Code: what its subagents cost, inside `usd`. */
104
+ subagentUsd?: number;
105
+ /** Cursor: priced without a cache split, an upper bound. */
106
+ estimate?: boolean;
107
+ /** Requests whose model has no list price, counted but not in `usd`. */
108
+ unpriced: number;
109
+ unpricedTokens: number;
110
+ unpricedModels: string[];
111
+ }
112
+ export interface SpendRow {
113
+ usd: number;
114
+ requests: number;
115
+ byTool: Partial<Record<Tool, number>>;
116
+ }
117
+ export interface SpendReport {
118
+ days: number;
119
+ since: number;
120
+ until: number;
121
+ usd: number;
122
+ requests: number;
123
+ tools: ToolSpend[];
124
+ projects: Array<SpendRow & {
125
+ project: string;
126
+ }>;
127
+ models: Array<SpendRow & {
128
+ model: string;
129
+ }>;
130
+ /** Every local day of the window, oldest first. */
131
+ daily: Array<SpendRow & {
132
+ day: string;
133
+ }>;
134
+ /** The bill by what it paid for. */
135
+ parts: {
136
+ inputUsd: number;
137
+ writeUsd: number;
138
+ readUsd: number;
139
+ outputUsd: number;
140
+ };
141
+ sessions: Array<{
142
+ tool: Tool;
143
+ project: string;
144
+ session: string;
145
+ model?: string;
146
+ usd: number;
147
+ requests: number;
148
+ first: number;
149
+ last: number;
150
+ }>;
151
+ /** A tool that could not be read (Cursor without SQLite), and why. */
152
+ skipped: Array<{
153
+ tool: Tool;
154
+ reason: string;
155
+ }>;
156
+ }
157
+ /** The local calendar day of `ts`, "YYYY-MM-DD". */
158
+ export declare function localDay(ts: number): string;
159
+ /** Add up priced requests into the report. */
160
+ export declare function summarizeSpend(items: SpendItem[], days: number, since: number, until: number, skipped?: SpendReport["skipped"]): SpendReport;
161
+ export interface SpendOptions {
162
+ home?: string;
163
+ /** Claude Code transcripts to read instead of every one written in the window (tests). */
164
+ claudePaths?: string[];
165
+ onProgress?: (done: number, total: number) => void;
166
+ now?: number;
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;
174
+ /** The last `days` days, every tool on this machine. A tool with nothing on disk is just absent. */
175
+ export declare function spendReport(days?: number, opts?: SpendOptions): SpendReport;
176
+ export declare const usd: (n: number) => string;
177
+ /** The full report, kept within 80 columns. `top`: rows per list. */
178
+ export declare function renderSpend(r: SpendReport, top?: number): string;
179
+ /**
180
+ * `spend --share`: totals only. No project names, paths or session ids, so
181
+ * sharing it leaks nothing.
182
+ */
183
+ export declare function renderSpendShare(r: SpendReport): string;