context-doctor 0.48.0 → 0.49.1

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 (77) hide show
  1. package/README.md +16 -14
  2. package/dist/abclaude.js +1 -1
  3. package/dist/budget.d.ts +5 -2
  4. package/dist/budget.js +21 -7
  5. package/dist/cache.js +3 -3
  6. package/dist/cachemisses.d.ts +3 -0
  7. package/dist/cachemisses.js +8 -0
  8. package/dist/cachettl.js +6 -2
  9. package/dist/ccost.d.ts +195 -0
  10. package/dist/ccost.js +400 -0
  11. package/dist/cli.js +135 -32
  12. package/dist/cline.d.ts +41 -0
  13. package/dist/cline.js +174 -0
  14. package/dist/coldresume.d.ts +11 -0
  15. package/dist/coldresume.js +3 -3
  16. package/dist/coldreturns.d.ts +145 -0
  17. package/dist/coldreturns.js +282 -0
  18. package/dist/compactcost.d.ts +10 -4
  19. package/dist/compactcost.js +12 -7
  20. package/dist/compactwindow.js +2 -2
  21. package/dist/copilotusage.d.ts +78 -0
  22. package/dist/copilotusage.js +193 -0
  23. package/dist/doctor.d.ts +6 -0
  24. package/dist/doctor.js +17 -4
  25. package/dist/fix.d.ts +28 -2
  26. package/dist/fix.js +49 -5
  27. package/dist/install.js +1 -1
  28. package/dist/limits.d.ts +232 -14
  29. package/dist/limits.js +739 -33
  30. package/dist/mcp.js +19 -19
  31. package/dist/mcpdefer.d.ts +47 -0
  32. package/dist/mcpdefer.js +91 -0
  33. package/dist/mod/api.d.ts +72 -2
  34. package/dist/mod/api.js +5 -1
  35. package/dist/mod/logic.d.ts +289 -16
  36. package/dist/mod/logic.js +362 -38
  37. package/dist/mod/register.d.ts +37 -2
  38. package/dist/mod/register.js +290 -9
  39. package/dist/modmeasure.d.ts +6 -4
  40. package/dist/modmeasure.js +8 -4
  41. package/dist/opencode.d.ts +57 -0
  42. package/dist/opencode.js +234 -0
  43. package/dist/orgrates.d.ts +7 -0
  44. package/dist/orgrates.js +19 -0
  45. package/dist/overhead.d.ts +3 -0
  46. package/dist/overhead.js +5 -1
  47. package/dist/pricing.d.ts +59 -2
  48. package/dist/pricing.js +130 -10
  49. package/dist/proxy.d.ts +8 -1
  50. package/dist/proxy.js +13 -1
  51. package/dist/savings.d.ts +5 -1
  52. package/dist/savings.js +11 -5
  53. package/dist/scan.d.ts +3 -1
  54. package/dist/scan.js +8 -1
  55. package/dist/sessionprice.d.ts +5 -0
  56. package/dist/sessionprice.js +5 -1
  57. package/dist/sidecost.d.ts +65 -0
  58. package/dist/sidecost.js +117 -0
  59. package/dist/spend.d.ts +94 -3
  60. package/dist/spend.js +251 -23
  61. package/dist/spendplace.d.ts +40 -0
  62. package/dist/spendplace.js +93 -0
  63. package/dist/spendteam.d.ts +160 -0
  64. package/dist/spendteam.js +286 -0
  65. package/dist/starts.d.ts +106 -0
  66. package/dist/starts.js +406 -0
  67. package/dist/statusline.d.ts +2 -2
  68. package/dist/statusline.js +2 -2
  69. package/dist/subagentmodel.js +9 -7
  70. package/dist/subagentpay.d.ts +31 -2
  71. package/dist/subagentpay.js +232 -68
  72. package/dist/subagents.js +3 -3
  73. package/dist/tasks.js +3 -2
  74. package/dist/tooloutput.js +5 -5
  75. package/dist/usagepane.d.ts +77 -0
  76. package/dist/usagepane.js +287 -0
  77. package/package.json +1 -1
package/dist/savings.js CHANGED
@@ -16,7 +16,7 @@ import { AutoClearer } from "./autoclear.js";
16
16
  import { coldResumeEvents } from "./coldresume.js";
17
17
  import { listSessions, isClaudeSession } from "./session.js";
18
18
  import { rowsOf } from "./scan.js";
19
- import { CACHE_WRITE_1H, CACHE_WRITE_5M, cacheWriteSplit, rateCard, ratesAt, requestCost, writeMultiplier } from "./pricing.js";
19
+ import { billedCost, CACHE_WRITE_1H, CACHE_WRITE_5M, cacheWriteSplit, rateCard, ratesAt, writeMultiplier } from "./pricing.js";
20
20
  import { priceBasis } from "./orgrates.js";
21
21
  import { estimateTokens, formatTokens, realModel } from "./tokens.js";
22
22
  import { withInvocation } from "./invocation.js";
@@ -143,7 +143,8 @@ function replayExtractor(id, options, makeClearer, replay) {
143
143
  k: "r", now, cold,
144
144
  bw: fresh + read * 0.1 + ttl.fiveMinute * CACHE_WRITE_5M + ttl.oneHour * CACHE_WRITE_1H,
145
145
  // No time of its own (now is 0 then): priced as of now, as requestCost prices one.
146
- usd: requestCost(pm, u, now || undefined)?.promptUsd ?? 0,
146
+ // With the iterations its usage leaves out (billedCost): an advisor's call, a declined attempt.
147
+ usd: billedCost(pm, u, now || undefined)?.promptUsd ?? 0,
147
148
  raw: fresh + read + write,
148
149
  };
149
150
  // Only what is set: a record read back from the cache must equal this one.
@@ -197,8 +198,8 @@ function replayExtractor(id, options, makeClearer, replay) {
197
198
  load: (v) => ({ ...v, ids: new Set(v.ids), base: loadArm(v.base, options), auto: loadArm(v.auto, options) }),
198
199
  };
199
200
  }
200
- const REPLAY = replayExtractor("replay.4", {}, undefined, true);
201
- const BILL = replayExtractor("bill.4", {}, undefined, false);
201
+ const REPLAY = replayExtractor("replay.5", {}, undefined, true);
202
+ const BILL = replayExtractor("bill.5", {}, undefined, false);
202
203
  /** What `estimateSavings` reads from each transcript, with or without autopilot's replay (for `prescan`). */
203
204
  export const savingsRows = (replay = true) => (replay ? REPLAY : BILL);
204
205
  /**
@@ -353,7 +354,7 @@ export function estimateSavings(days = 30, options = {}, paths, onProgress, repl
353
354
  }
354
355
  const tokens = (n) => (n >= 1e9 ? `${(n / 1e9).toFixed(1)}B` : formatTokens(n));
355
356
  const usd = (n) => (n >= 100 ? `$${Math.round(n).toLocaleString("en-US")}` : `$${n.toFixed(2)}`);
356
- export function renderSavings(r, autopilotOn = false, cw, missLines, limitLines, lensLines) {
357
+ export function renderSavings(r, autopilotOn = false, cw, missLines, limitLines, lensLines, keepWarm) {
357
358
  const lines = [];
358
359
  if (r.sessions.length === 0) {
359
360
  lines.push(`No Claude Code sessions with 10+ requests in the last ${r.days} days to replay.`);
@@ -375,6 +376,11 @@ export function renderSavings(r, autopilotOn = false, cw, missLines, limitLines,
375
376
  lines.push(" expired. Running /compact then, net of the compaction itself, would");
376
377
  lines.push(" have saved this. The every-prompt hook points these moments out, in");
377
378
  lines.push(" every Claude Code surface, the desktop app included.");
379
+ if (keepWarm && keepWarm.netUsd >= 1) {
380
+ // Not a third column to add up: it replaces the re-write compaction cannot avoid.
381
+ lines.push(` Or keep the cache warm while away, up to ${keepWarm.hours} h: ${usd(keepWarm.netUsd)} net of`);
382
+ lines.push(` ${usd(keepWarm.pingUsd)} in pings (/context-doctor-keep-warm; each gap: cache-misses).`);
383
+ }
378
384
  lines.push("");
379
385
  if (allDesktop) {
380
386
  lines.push(`2. Autopilot ${"n/a".padStart(9)}`);
package/dist/scan.d.ts CHANGED
@@ -109,4 +109,6 @@ export declare function pick(o: any, keys: readonly string[]): any;
109
109
  * records `speed`, `inference_geo` and `server_tool_use`; kept on each, they
110
110
  * would grow every record for nothing.
111
111
  */
112
- export declare const slimUsage: (u: any) => unknown;
112
+ export declare const slimUsage: (u: any, opts?: {
113
+ iterations?: boolean;
114
+ }) => unknown;
package/dist/scan.js CHANGED
@@ -43,6 +43,7 @@ import { createHash, randomBytes } from "node:crypto";
43
43
  import { homedir } from "node:os";
44
44
  import { isAbsolute, join } from "node:path";
45
45
  import { PROXY_VERSION } from "./proxy.js";
46
+ import { extraIterations } from "./pricing.js";
46
47
  /** Bumped when the entry layout below changes. */
47
48
  const SCHEMA = 1;
48
49
  const DAY = 86_400_000;
@@ -507,7 +508,7 @@ const USAGE_KEYS = ["input_tokens", "cache_creation_input_tokens", "cache_read_i
507
508
  * records `speed`, `inference_geo` and `server_tool_use`; kept on each, they
508
509
  * would grow every record for nothing.
509
510
  */
510
- export const slimUsage = (u) => {
511
+ export const slimUsage = (u, opts = {}) => {
511
512
  const out = pick(u, USAGE_KEYS);
512
513
  if (!out || typeof out !== "object" || Array.isArray(out))
513
514
  return out;
@@ -518,5 +519,11 @@ export const slimUsage = (u) => {
518
519
  const searches = u.server_tool_use?.web_search_requests;
519
520
  if (typeof searches === "number" && searches > 0)
520
521
  out.server_tool_use = { web_search_requests: searches };
522
+ // The request's iterations, only where some bill beyond its top-level usage (an advisor's, a
523
+ // declined attempt's: extraIterations); every request has one, the request itself, kept for nothing.
524
+ if (opts.iterations && extraIterations(u).length)
525
+ out.iterations = u.iterations.map((t) => pick(t, ITERATION_KEYS));
521
526
  return out;
522
527
  };
528
+ /** What an iteration is priced from (extraIterations). */
529
+ const ITERATION_KEYS = ["type", "model", "input_tokens", "cache_creation_input_tokens", "cache_read_input_tokens", "output_tokens", "cache_creation"];
@@ -84,6 +84,11 @@ export interface SessionTotal {
84
84
  estimatedUsd: number;
85
85
  /** Bytes read to bring the entries up to date. */
86
86
  read: number;
87
+ /** Each file's own dollars and requests (the main transcript, each subagent's), as counted in `usd`: the usage pane's per-subagent cost. */
88
+ byFile: Record<string, {
89
+ usd: number;
90
+ requests: number;
91
+ }>;
87
92
  /** Keeps the entries, so the next look reads only what was appended. */
88
93
  save: () => void;
89
94
  }
@@ -202,10 +202,12 @@ export function sessionTotal(input, now = Date.now()) {
202
202
  // Each reply once: a fork's copy shares its key with the reply it copied.
203
203
  const seen = new Set();
204
204
  let usd = 0, subagentUsd = 0, workflowUsd = 0, unpriced = 0, estimatedUsd = 0;
205
+ const byFile = {};
205
206
  for (const [file, whose] of files) {
206
207
  const e = kept[file];
207
208
  if (!e)
208
209
  continue;
210
+ const mine = (byFile[file] = { usd: 0, requests: 0 });
209
211
  const x = new Set((e.x ?? []).map(([i]) => i)), y = new Set((e.y ?? []).map(([i]) => i));
210
212
  e.k.forEach((key, i) => {
211
213
  if (key) {
@@ -214,6 +216,8 @@ export function sessionTotal(input, now = Date.now()) {
214
216
  seen.add(key);
215
217
  }
216
218
  usd += e.d[i];
219
+ mine.usd += e.d[i];
220
+ mine.requests++;
217
221
  if (whose === "sub")
218
222
  subagentUsd += e.d[i];
219
223
  if (whose === "workflow")
@@ -240,7 +244,7 @@ export function sessionTotal(input, now = Date.now()) {
240
244
  }
241
245
  catch { /* read again next time */ }
242
246
  };
243
- return { app, usd, subagentUsd, workflowUsd, unpriced, estimatedUsd, read, save };
247
+ return { app, usd, subagentUsd, workflowUsd, unpriced, estimatedUsd, read, byFile, save };
244
248
  }
245
249
  /** Keeps a look's entries once it read enough to be worth it, as the threshold check does. */
246
250
  export function saveIfWorthIt(t) {
@@ -0,0 +1,65 @@
1
+ /**
2
+ * Two Claude Code costs no transcript row records the usage of (ROADMAP F1,
3
+ * the gap to Claude Code's own `cost-state`): one estimated from what the
4
+ * rows do record and counted, one only named in the gap.
5
+ *
6
+ * Prompt suggestions. When a main-thread turn ends, Claude Code asks the
7
+ * session's model for the grey "what you might type next" line: a one-turn
8
+ * fork of the conversation (`querySource: "prompt_suggestion"`, made with
9
+ * `skipTranscript`), so it is billed and counted in Claude Code's cost, and
10
+ * no row has it. Read from the 2.1.325 binary: it sends the conversation as
11
+ * the turn's last request did plus that reply and a ~500-token instruction,
12
+ * and skips the turn when that last reply wrote more than about 10,000 tokens
13
+ * with its input and output (`cache_cold`), as well as in plan mode, at a
14
+ * rate limit, after an API error, and early in a conversation. Measured on
15
+ * the author's machine, on the stretches between two of Claude Code's
16
+ * cost-state records that hold one turn: each added exactly the last
17
+ * request's prompt read from the cache, its reply's output written to it
18
+ * (at the main thread's cache lifetime), 506 input tokens and 12-17 output
19
+ * tokens. On one 199-turn session the input Claude Code counted beyond ours
20
+ * was 198 times 506 tokens. `claude -p` and other SDK hosts get none unless
21
+ * they ask (their entrypoint starts "sdk"). Not counted in any total: on the
22
+ * author's last 30 days whole Desktop sessions sent none (every turn typed by
23
+ * a person), so whether one was sent is in no file; ccost.ts names them in
24
+ * the gap, as many as Claude Code's input beyond ours has room for.
25
+ *
26
+ * Unsettled subagent output. Claude Code 2.1.284 to 2.1.299 wrote a
27
+ * subagent's reply rows as it streamed and never wrote the last one: no row
28
+ * of the reply has a `stop_reason`, and `output_tokens` stays at the first
29
+ * few tokens (20,082 of 23,262 subagent replies on 2.1.295 on the author's
30
+ * machine). Counted, wherever usage is read.
31
+ * The reply's content is all there: its output is estimated from it, the
32
+ * text and tool calls by their length and the thinking (redacted to a
33
+ * signature) by the signature's length, a fit on the author's 23,000 settled
34
+ * replies (Opus 5.5, Opus 4.8, Fable 5.2: within 3% in total, 8 replies in
35
+ * 10 within -15% to +28%). On the session that showed it, the estimate came to
36
+ * 1.14M output tokens where Claude Code counted 1.12M beyond ours.
37
+ */
38
+ import { type RecordedUsage } from "./pricing.js";
39
+ /** A suggestion's own instruction, in input tokens (measured: 506). */
40
+ export declare const SUGGESTION_PROMPT_TOKENS = 506;
41
+ /** A suggestion's output (measured: 12-17). */
42
+ export declare const SUGGESTION_OUTPUT_TOKENS = 15;
43
+ /** Claude Code skips a suggestion after a reply whose input, output and cache write come to more than this (2.1.325's `cache_cold`). */
44
+ export declare const SUGGESTION_MAX_LAST_TOKENS = 10000;
45
+ /**
46
+ * The prompt suggestion a reply row's turn ended with, as the usage Claude
47
+ * Code was billed for it; undefined when the row ends no main-thread turn or
48
+ * Claude Code would have skipped it.
49
+ */
50
+ export declare function suggestionUsage(e: any): RecordedUsage | undefined;
51
+ /** A reply row's suggestion priced at its model and time; undefined as suggestionUsage, or when its model has no price. */
52
+ export declare function suggestionCost(e: any): {
53
+ usage: RecordedUsage;
54
+ cost: import("./pricing.js").RequestCost;
55
+ } | undefined;
56
+ /** The Claude Code versions that left subagent replies unsettled (seen on the author's machine: 2.1.284 to 2.1.299; 2.1.308 settles them). */
57
+ export declare const UNSETTLED_FROM = "2.1.284";
58
+ export declare const UNSETTLED_UNTIL = "2.1.299";
59
+ /** Whether a row's Claude Code version is one that left replies unsettled. */
60
+ export declare function unsettledVersion(v: unknown): boolean;
61
+ /** Output tokens per character of text and tool input, and per character of a redacted thinking block's signature (the fit above). */
62
+ export declare const OUTPUT_PER_CHAR = 0.4;
63
+ export declare const OUTPUT_PER_SIGNATURE_CHAR = 0.26;
64
+ /** One reply row's content, as the output tokens it took to write (the fit above); 0 for none. */
65
+ export declare function contentOutputTokens(content: unknown): number;
@@ -0,0 +1,117 @@
1
+ /**
2
+ * Two Claude Code costs no transcript row records the usage of (ROADMAP F1,
3
+ * the gap to Claude Code's own `cost-state`): one estimated from what the
4
+ * rows do record and counted, one only named in the gap.
5
+ *
6
+ * Prompt suggestions. When a main-thread turn ends, Claude Code asks the
7
+ * session's model for the grey "what you might type next" line: a one-turn
8
+ * fork of the conversation (`querySource: "prompt_suggestion"`, made with
9
+ * `skipTranscript`), so it is billed and counted in Claude Code's cost, and
10
+ * no row has it. Read from the 2.1.325 binary: it sends the conversation as
11
+ * the turn's last request did plus that reply and a ~500-token instruction,
12
+ * and skips the turn when that last reply wrote more than about 10,000 tokens
13
+ * with its input and output (`cache_cold`), as well as in plan mode, at a
14
+ * rate limit, after an API error, and early in a conversation. Measured on
15
+ * the author's machine, on the stretches between two of Claude Code's
16
+ * cost-state records that hold one turn: each added exactly the last
17
+ * request's prompt read from the cache, its reply's output written to it
18
+ * (at the main thread's cache lifetime), 506 input tokens and 12-17 output
19
+ * tokens. On one 199-turn session the input Claude Code counted beyond ours
20
+ * was 198 times 506 tokens. `claude -p` and other SDK hosts get none unless
21
+ * they ask (their entrypoint starts "sdk"). Not counted in any total: on the
22
+ * author's last 30 days whole Desktop sessions sent none (every turn typed by
23
+ * a person), so whether one was sent is in no file; ccost.ts names them in
24
+ * the gap, as many as Claude Code's input beyond ours has room for.
25
+ *
26
+ * Unsettled subagent output. Claude Code 2.1.284 to 2.1.299 wrote a
27
+ * subagent's reply rows as it streamed and never wrote the last one: no row
28
+ * of the reply has a `stop_reason`, and `output_tokens` stays at the first
29
+ * few tokens (20,082 of 23,262 subagent replies on 2.1.295 on the author's
30
+ * machine). Counted, wherever usage is read.
31
+ * The reply's content is all there: its output is estimated from it, the
32
+ * text and tool calls by their length and the thinking (redacted to a
33
+ * signature) by the signature's length, a fit on the author's 23,000 settled
34
+ * replies (Opus 5.5, Opus 4.8, Fable 5.2: within 3% in total, 8 replies in
35
+ * 10 within -15% to +28%). On the session that showed it, the estimate came to
36
+ * 1.14M output tokens where Claude Code counted 1.12M beyond ours.
37
+ */
38
+ import { isUnbilledModel, requestCost } from "./pricing.js";
39
+ import { realModel } from "./tokens.js";
40
+ /** A suggestion's own instruction, in input tokens (measured: 506). */
41
+ export const SUGGESTION_PROMPT_TOKENS = 506;
42
+ /** A suggestion's output (measured: 12-17). */
43
+ export const SUGGESTION_OUTPUT_TOKENS = 15;
44
+ /** Claude Code skips a suggestion after a reply whose input, output and cache write come to more than this (2.1.325's `cache_cold`). */
45
+ export const SUGGESTION_MAX_LAST_TOKENS = 10_000;
46
+ const n = (v) => (typeof v === "number" && Number.isFinite(v) && v > 0 ? v : 0);
47
+ /**
48
+ * The prompt suggestion a reply row's turn ended with, as the usage Claude
49
+ * Code was billed for it; undefined when the row ends no main-thread turn or
50
+ * Claude Code would have skipped it.
51
+ */
52
+ export function suggestionUsage(e) {
53
+ const m = e?.message;
54
+ if (e?.type !== "assistant" || e.isSidechain === true || m?.stop_reason !== "end_turn" || !m.usage || isUnbilledModel(m.model))
55
+ return undefined;
56
+ if (typeof e.entrypoint === "string" && e.entrypoint.startsWith("sdk"))
57
+ return undefined;
58
+ const u = m.usage;
59
+ const input = n(u.input_tokens), read = n(u.cache_read_input_tokens), write = n(u.cache_creation_input_tokens), output = n(u.output_tokens);
60
+ if (input + output + write > SUGGESTION_MAX_LAST_TOKENS || input + read + write === 0)
61
+ return undefined;
62
+ // Its reply written at the lifetime the turn's own writes used (the main thread's: an hour, unless they were all 5-minute).
63
+ const fiveMin = n(u.cache_creation?.ephemeral_5m_input_tokens) > 0 && n(u.cache_creation?.ephemeral_1h_input_tokens) === 0;
64
+ return {
65
+ input_tokens: SUGGESTION_PROMPT_TOKENS, cache_read_input_tokens: input + read + write, cache_creation_input_tokens: output,
66
+ cache_creation: fiveMin ? { ephemeral_5m_input_tokens: output, ephemeral_1h_input_tokens: 0 } : { ephemeral_1h_input_tokens: output, ephemeral_5m_input_tokens: 0 },
67
+ output_tokens: SUGGESTION_OUTPUT_TOKENS,
68
+ ...(u.speed === "fast" ? { speed: "fast" } : {}), ...(u.inference_geo === "us" ? { inference_geo: "us" } : {}),
69
+ };
70
+ }
71
+ /** A reply row's suggestion priced at its model and time; undefined as suggestionUsage, or when its model has no price. */
72
+ export function suggestionCost(e) {
73
+ const u = suggestionUsage(e);
74
+ if (!u)
75
+ return undefined;
76
+ const c = requestCost(realModel(e.message.model), u, Date.parse(String(e.timestamp ?? "")));
77
+ return c ? { usage: u, cost: c } : undefined;
78
+ }
79
+ /** The Claude Code versions that left subagent replies unsettled (seen on the author's machine: 2.1.284 to 2.1.299; 2.1.308 settles them). */
80
+ export const UNSETTLED_FROM = "2.1.284";
81
+ export const UNSETTLED_UNTIL = "2.1.299";
82
+ /** Whether a row's Claude Code version is one that left replies unsettled. */
83
+ export function unsettledVersion(v) {
84
+ if (typeof v !== "string")
85
+ return false;
86
+ const x = v.split(/[.-]/).map((n) => parseInt(n, 10) || 0);
87
+ const cmp = (b) => {
88
+ const y = b.split(".").map(Number);
89
+ for (let i = 0; i < 3; i++)
90
+ if ((x[i] ?? 0) !== y[i])
91
+ return (x[i] ?? 0) - y[i];
92
+ return 0;
93
+ };
94
+ return cmp(UNSETTLED_FROM) >= 0 && cmp(UNSETTLED_UNTIL) <= 0;
95
+ }
96
+ /** Output tokens per character of text and tool input, and per character of a redacted thinking block's signature (the fit above). */
97
+ export const OUTPUT_PER_CHAR = 0.4;
98
+ export const OUTPUT_PER_SIGNATURE_CHAR = 0.26;
99
+ /** One reply row's content, as the output tokens it took to write (the fit above); 0 for none. */
100
+ export function contentOutputTokens(content) {
101
+ if (!Array.isArray(content))
102
+ return 0;
103
+ let chars = 0, sig = 0;
104
+ for (const c of content) {
105
+ if (!c || typeof c !== "object")
106
+ continue;
107
+ if (c.type === "text" && typeof c.text === "string")
108
+ chars += c.text.length;
109
+ else if (c.type === "tool_use")
110
+ chars += JSON.stringify(c.input ?? {}).length + String(c.name ?? "").length;
111
+ else if (c.type === "thinking") {
112
+ chars += typeof c.thinking === "string" ? c.thinking.length : 0;
113
+ sig += typeof c.signature === "string" ? c.signature.length : 0;
114
+ }
115
+ }
116
+ return Math.round(chars * OUTPUT_PER_CHAR + sig * OUTPUT_PER_SIGNATURE_CHAR);
117
+ }
package/dist/spend.d.ts CHANGED
@@ -41,8 +41,15 @@
41
41
  */
42
42
  import { type ProgressOptions } from "./progresssummaries.js";
43
43
  import { type Modifiers } from "./pricing.js";
44
+ import { type SessionGap } from "./ccost.js";
45
+ /**
46
+ * What spend's dollars are: each request as it was billed (its tier, fast mode,
47
+ * US-only, web searches) at list rates, or at the organization's rates.
48
+ * "At list prices" was true before those were priced; it no longer is.
49
+ */
50
+ export declare const spendBasis: () => string;
44
51
  import { type Extractor } from "./scan.js";
45
- export type Tool = "claude" | "codex" | "gemini" | "cursor";
52
+ export type Tool = "claude" | "codex" | "gemini" | "cursor" | "copilot" | "opencode" | "cline";
46
53
  export declare const TOOLS: Tool[];
47
54
  export declare const TOOL_NAME: Record<Tool, string>;
48
55
  /** One request (a Cursor reply), priced. */
@@ -78,6 +85,25 @@ export interface SpendItem {
78
85
  key?: string;
79
86
  /** Claude Code: a compaction's own request, which no row records usage for: estimated from the context it read and its summary (compactcost.ts). */
80
87
  compaction?: boolean;
88
+ /** Claude Code: output tokens estimated from the reply's content, inside `output` and `usd`, where its rows never settled it (sidecost.ts). */
89
+ unsettled?: number;
90
+ /** Copilot CLI: the AI credits it used (one is $0.01), as Copilot recorded them; not in `usd`. */
91
+ credits?: number;
92
+ /** Copilot CLI: the premium requests it counted (its multiplier); not in `usd`. */
93
+ premium?: number;
94
+ /** The folder it ran in, and its git root and branch where the tool recorded them (spendplace.ts). Read for `--by repo` and `--by branch` only; never exported. */
95
+ cwd?: string;
96
+ root?: string;
97
+ branch?: string;
98
+ /** Its repository's name (spendplace.ts repoName), set when the report groups by repository or branch. */
99
+ repo?: string;
100
+ /**
101
+ * Claude Code: an iteration of a request that its top-level usage leaves
102
+ * out, billed on top at its own model (pricing.ts extraIterations): its
103
+ * type, "advisor_message" (the advisor tool's call) or the attempt a
104
+ * fallback replaced ("message"). Not a request of its own: not in the counts.
105
+ */
106
+ iteration?: string;
81
107
  }
82
108
  /**
83
109
  * A project folder's name (its path with "-" for separators, as Claude Code
@@ -95,7 +121,7 @@ export declare const anyModifier: (m: Modifiers | undefined) => m is Modifiers;
95
121
  * Claude Code's requests between `since` and `until`, main threads and
96
122
  * subagents, over `tops` (default: every transcript written since `since`).
97
123
  */
98
- export declare function claudeSpend(since: number, until?: number, tops?: string[], onProgress?: (done: number, total: number) => void): SpendItem[];
124
+ export declare function claudeSpend(since: number, until?: number, tops?: string[], onProgress?: (done: number, total: number) => void, place?: boolean): SpendItem[];
99
125
  /**
100
126
  * What `spend` takes from a Codex rollout: its folder, its own id and the
101
127
  * thread that spawned it (the first session_meta), each model change, and
@@ -150,6 +176,16 @@ export declare function geminiFileSpend(file: string, since: number, until?: num
150
176
  export declare function geminiFiles(since: number, home?: string): string[];
151
177
  export declare function geminiSpend(since: number, until?: number, home?: string): SpendItem[];
152
178
  export declare function cursorSpend(since: number, until?: number): SpendItem[];
179
+ /**
180
+ * Copilot CLI's model calls (copilotusage.ts), each priced at its model's
181
+ * list price where the table has one, else counted. What Copilot bills is
182
+ * its AI credits and premium requests, kept beside the price, not in it.
183
+ */
184
+ export declare function copilotSpend(since: number, until?: number, home?: string): SpendItem[];
185
+ /** OpenCode's model calls (opencode.ts), each at its model's list price. Throws SqliteUnavailableError when its database cannot be read here. */
186
+ export declare function opencodeSpend(since: number, until?: number, home?: string): SpendItem[];
187
+ /** Cline's requests (cline.ts), each at its model's list price; one with no model is counted, not priced. */
188
+ export declare function clineSpend(since: number, until?: number, home?: string): SpendItem[];
153
189
  export interface ToolSpend {
154
190
  tool: Tool;
155
191
  name: string;
@@ -168,6 +204,9 @@ export interface ToolSpend {
168
204
  workflowRuns?: number;
169
205
  /** Cursor: priced without a cache split, an upper bound. */
170
206
  estimate?: boolean;
207
+ /** Copilot CLI: the AI credits and premium requests it recorded, beside `usd` (which is the tokens at list price). */
208
+ credits?: number;
209
+ premium?: number;
171
210
  /** Requests whose model has no list price, counted but not in `usd`. */
172
211
  unpriced: number;
173
212
  unpricedTokens: number;
@@ -194,6 +233,15 @@ export interface SpendReport {
194
233
  projects: Array<SpendRow & {
195
234
  project: string;
196
235
  }>;
236
+ /** By repository (`--by repo` or `--by branch`): a folder's git repository, else the project. Absent otherwise. */
237
+ repos?: Array<SpendRow & {
238
+ repo: string;
239
+ }>;
240
+ /** By repository and branch (`--by branch`); a request whose tool records no branch has none. Absent otherwise. */
241
+ branches?: Array<SpendRow & {
242
+ repo: string;
243
+ branch?: string;
244
+ }>;
197
245
  models: Array<SpendRow & {
198
246
  model: string;
199
247
  }>;
@@ -223,6 +271,27 @@ export interface SpendReport {
223
271
  requests: number;
224
272
  usd: number;
225
273
  };
274
+ /** Claude Code subagent replies whose rows never settled their output (2.1.284-2.1.299): the output estimated from their content, inside `usd`; absent when none. */
275
+ unsettled?: {
276
+ replies: number;
277
+ tokens: number;
278
+ usd: number;
279
+ };
280
+ /** Claude Code: iterations billed beyond their request's top-level usage (the advisor's calls, attempts a fallback replaced), by type: inside `usd`; absent when none. */
281
+ iterations?: Record<string, {
282
+ calls: number;
283
+ usd: number;
284
+ models: string[];
285
+ }>;
286
+ /**
287
+ * Claude Code's own figure (its `cost-state` records) beside ours, per
288
+ * session wholly in the window that has one (ccost.ts); absent when none.
289
+ */
290
+ claudeCode?: {
291
+ ccUsd: number;
292
+ ourUsd: number;
293
+ sessions: SessionGap[];
294
+ };
226
295
  /**
227
296
  * Claude Code's subagent progress summaries, estimated (no transcript records them): NOT in `usd`.
228
297
  * `notesUsd` as short notes (served since November 2026), `forkUsd` as the whole context (before).
@@ -259,6 +328,8 @@ export declare function localDay(ts: number): string;
259
328
  export declare function summarizeSpend(items: SpendItem[], days: number, since: number, until: number, skipped?: SpendReport["skipped"]): SpendReport;
260
329
  export interface SpendOptions {
261
330
  home?: string;
331
+ /** Group by repository, or by repository and branch, besides project: reads where each request ran (spendplace.ts). */
332
+ by?: "project" | "repo" | "branch";
262
333
  /** Claude Code transcripts to read instead of every one written in the window (tests). */
263
334
  claudePaths?: string[];
264
335
  onProgress?: (done: number, total: number) => void;
@@ -277,12 +348,32 @@ export interface SpendOptions {
277
348
  * --json died on a string too long), and 1e9 days fell off the calendar.
278
349
  */
279
350
  export declare const MAX_SPEND_DAYS = 3650;
351
+ /**
352
+ * One Claude Code session's comparison with Claude Code's own figure (ccost.ts):
353
+ * its transcript and its subagents', to its last `cost-state`. Undefined when
354
+ * it has none, or cannot be read.
355
+ */
356
+ export declare function claudeCodeSession(top: string): SessionGap | undefined;
357
+ /**
358
+ * A session's requests priced past the day their model's price ended or
359
+ * changed, said as `spend` says it: which price, and the one used instead.
360
+ * Undefined when none (or the transcript cannot be read).
361
+ */
362
+ export declare function sessionPriceEnded(top: string): string | undefined;
363
+ /** Every request of the last `days` days, every tool on this machine, and what could not be read. */
364
+ export declare function collectSpend(days?: number, opts?: SpendOptions): {
365
+ items: SpendItem[];
366
+ days: number;
367
+ since: number;
368
+ until: number;
369
+ skipped: SpendReport["skipped"];
370
+ };
280
371
  /** The last `days` days, every tool on this machine. A tool with nothing on disk is just absent. */
281
372
  export declare function spendReport(days?: number, opts?: SpendOptions): SpendReport;
282
373
  export declare const usd: (n: number) => string;
283
374
  /** "fast mode +$4.10, US-only +$0.93, web searches $0.12 (12), long-prompt tier +$0.40": what each billing modifier added, the ones that added anything. */
284
375
  export declare function modifiersText(m: Modifiers): string;
285
- /** The full report, kept within 80 columns. `top`: rows per list. */
376
+ /** The full report, kept within 80 columns. `top`: rows per list. Grouped by repository or branch instead of project when the report has them (`--by`). */
286
377
  export declare function renderSpend(r: SpendReport, top?: number): string;
287
378
  /**
288
379
  * `spend --share`: totals only. No project names, paths or session ids, so