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
@@ -24,12 +24,13 @@
24
24
  * window for a hard task) and what the parent would have spent on its own tool
25
25
  * calls, so "did not pay" means "did not pay in context", not "was a mistake".
26
26
  */
27
- import { existsSync, readdirSync, readFileSync } from "node:fs";
27
+ import { closeSync, existsSync, openSync, readdirSync, readFileSync, readSync } from "node:fs";
28
28
  import { basename, join } from "node:path";
29
- import { forEachLine, listSessions, outputSettler, replyCounter, isClaudeSession } from "./session.js";
29
+ import { listSessions, outputSettler, replyCounter, isClaudeSession } from "./session.js";
30
+ import { rowsOf, slimUsage } from "./scan.js";
30
31
  import { subagentFiles, workflowRunInfo } from "./subagents.js";
31
32
  import { estimateTokens, formatTokens, realModel } from "./tokens.js";
32
- import { cacheWriteSplit, formatUsd, rateCard, ratesAt, requestCost, writeMultiplier, writePerM } from "./pricing.js";
33
+ import { billedCost, cacheWriteSplit, formatUsd, rateCard, ratesAt, requestCost, writeMultiplier, writePerM } from "./pricing.js";
33
34
  import { priceBasis } from "./orgrates.js";
34
35
  /**
35
36
  * The model `fix` offers the subagents (subagentmodel.ts): the id the price
@@ -64,48 +65,223 @@ const cheaper = (a, b) => a.inputPerM < b.inputPerM || (a.inputPerM === b.inputP
64
65
  * bills it for less, else as billed.
65
66
  */
66
67
  function billed(model, u, at) {
67
- const own = requestCost(model, u, at);
68
+ // With the iterations its top-level usage leaves out (billedCost), which a move to Sonnet leaves as they were.
69
+ const own = billedCost(model, u, at);
68
70
  if (!own)
69
71
  return undefined;
70
72
  const sonnet = requestCost(SUBAGENT_CANDIDATE, u, at);
71
73
  const moved = cheaper(sonnet.rates, own.rates);
72
- return { usd: own.totalUsd, sonnetUsd: moved ? sonnet.totalUsd : own.totalUsd, rates: own.rates, sonnetRates: moved ? sonnet.rates : own.rates };
74
+ return { usd: own.totalUsd, sonnetUsd: moved ? sonnet.totalUsd + (own.extra?.usd ?? 0) : own.totalUsd, rates: own.rates, sonnetRates: moved ? sonnet.rates : own.rates };
73
75
  }
74
76
  /**
75
- * A subagent's bill (each request as billed, requestCost), steps, startup
76
- * context, start time, the tool output it read, and the rates its first
77
- * request billed at.
77
+ * What `subagents` takes from a subagent's transcript, through the shared
78
+ * scan (scan.ts), so a second run reads only what was appended: each reply's
79
+ * id, model, time and usage (every row, for the output a streamed reply
80
+ * settles on its last: a later row keeps only that), and the tool output
81
+ * each user row hands it, as tokens. The task is read from the transcript's
82
+ * head when needed (subagentTask): the cache keeps no message text.
78
83
  */
79
- export function scanSubagent(path) {
80
- const tokens = { input: 0, read: 0, write: 0, output: 0 };
81
- let costUsd = 0, atSonnetUsd = 0, readTokens = 0, task = "", model, firstRates;
82
- let steps = 0, startup = 0, start = Infinity, writes5m = 0, writes1h = 0;
83
- // The rates of the last reply, for the output its later rows settle.
84
- let last;
85
- const sighting = replyCounter();
86
- const settle = outputSettler();
87
- forEachLine(path, (line) => {
84
+ export const SUBAGENT_ROWS = {
85
+ id: "subagent.1",
86
+ init: () => ({ ids: {} }),
87
+ line(line, row, out, st) {
88
+ const result = line.includes('"tool_result"');
89
+ if (!result && !line.includes('"usage"'))
90
+ return;
88
91
  let e;
89
92
  try {
90
- e = JSON.parse(line);
93
+ e = row();
91
94
  }
92
95
  catch {
93
96
  return;
94
97
  }
95
98
  const content = e?.message?.content;
96
99
  if (e?.type === "user") {
97
- if (!task && typeof content === "string")
98
- task = content;
100
+ let n = 0;
99
101
  if (Array.isArray(content))
100
102
  for (const b of content)
101
103
  if (b?.type === "tool_result")
102
- readTokens += blockTokens(b.content);
104
+ n += blockTokens(b.content);
105
+ if (n)
106
+ out.push(["r", n]);
103
107
  return;
104
108
  }
105
109
  if (e?.type !== "assistant" || !e.message?.usage)
106
110
  return;
107
- if (typeof e.message.model === "string" && !realModel(e.message.model))
108
- return; // "<synthetic>": not a request
111
+ const m = e.message;
112
+ const model = typeof m.model === "string" ? m.model : null;
113
+ if (typeof m.id === "string") {
114
+ // A later row of a reply already met: read only for the output it settles on.
115
+ if (st.ids[m.id]) {
116
+ out.push(["o", m.id, model, tok(m.usage.output_tokens)]);
117
+ return;
118
+ }
119
+ st.ids[m.id] = 1;
120
+ }
121
+ const at = Date.parse(String(e.timestamp ?? ""));
122
+ out.push(["a", typeof m.id === "string" ? m.id : null, model, Number.isFinite(at) ? at : null, packUsage(m.usage)]);
123
+ },
124
+ };
125
+ const tok = (v) => (typeof v === "number" && Number.isFinite(v) && v > 0 ? v : 0);
126
+ /**
127
+ * A reply's usage as the subagent scans keep it, short (thousands of
128
+ * transcripts are read back on every run): input, cache reads, cache writes,
129
+ * of them at 1 hour, output, fast mode / US-only (1 / 2), web searches, and
130
+ * the iterations billed beyond it (extraIterations), when any.
131
+ */
132
+ function packUsage(u) {
133
+ const w = cacheWriteSplit(u);
134
+ const slim = slimUsage(u, { iterations: true });
135
+ const packed = [tok(u.input_tokens), tok(u.cache_read_input_tokens), w.fiveMinute + w.oneHour + w.twelveHour, w.oneHour, tok(u.output_tokens), (u.speed === "fast" ? 1 : 0) + (u.inference_geo === "us" ? 2 : 0), tok(u.server_tool_use?.web_search_requests)];
136
+ if (slim?.iterations)
137
+ packed.push(slim.iterations);
138
+ return packed;
139
+ }
140
+ /** packUsage's array as the usage requestCost reads. */
141
+ function unpackUsage(p) {
142
+ return {
143
+ input_tokens: p[0], cache_read_input_tokens: p[1], cache_creation_input_tokens: p[2], output_tokens: p[4],
144
+ cache_creation: { ephemeral_1h_input_tokens: p[3], ephemeral_5m_input_tokens: p[2] - p[3] },
145
+ ...(p[5] & 1 ? { speed: "fast" } : {}), ...(p[5] & 2 ? { inference_geo: "us" } : {}),
146
+ ...(p[6] ? { server_tool_use: { web_search_requests: p[6] } } : {}),
147
+ ...(p[7] ? { iterations: p[7] } : {}),
148
+ };
149
+ }
150
+ /**
151
+ * A subagent's task: the first user row with text, read from the
152
+ * transcript's head (16 KB at a time, at most 1 MB): only for a subagent
153
+ * whose meta file gives no description.
154
+ */
155
+ export function subagentTask(path) {
156
+ let fd;
157
+ try {
158
+ fd = openSync(path, "r");
159
+ }
160
+ catch {
161
+ return "";
162
+ }
163
+ try {
164
+ let head = "";
165
+ for (let pos = 0; pos < 1024 * 1024;) {
166
+ const buf = Buffer.alloc(16 * 1024);
167
+ const n = readSync(fd, buf, 0, buf.length, pos);
168
+ if (n <= 0)
169
+ break;
170
+ pos += n;
171
+ head += buf.subarray(0, n).toString("utf8");
172
+ const lines = head.split("\n");
173
+ head = lines.pop();
174
+ for (const line of lines) {
175
+ if (!line.includes('"user"'))
176
+ continue;
177
+ try {
178
+ const e = JSON.parse(line);
179
+ if (e?.type === "user" && typeof e.message?.content === "string")
180
+ return e.message.content.replace(/\s+/g, " ").slice(0, 90);
181
+ }
182
+ catch { /* not a row */ }
183
+ }
184
+ }
185
+ return "";
186
+ }
187
+ catch {
188
+ return "";
189
+ }
190
+ finally {
191
+ closeSync(fd);
192
+ }
193
+ }
194
+ /**
195
+ * What `subagents` takes from a parent transcript, through the shared scan:
196
+ * its main-thread replies (time, model, prompt size, what changes their
197
+ * rates, cache writes by lifetime), its compactions, and every row that
198
+ * mentions one of its subagents (the Agent tool's result for that call, a
199
+ * background agent's task notification), as tokens and the ids it names:
200
+ * the calls of the Agent tool it made (kept in the state), and the ids a
201
+ * notification names (`<task-id>`, `<tool-use-id>`, `agentId:`).
202
+ */
203
+ export const PARENT_ROWS = {
204
+ id: "subparent.1",
205
+ init: () => ({ calls: [] }),
206
+ line(line, row, out, st) {
207
+ const isUsage = line.includes('"usage"');
208
+ const isCompact = line.includes('"compact_boundary"');
209
+ const named = [...line.matchAll(MENTION)].map((m) => m[1] ?? m[2] ?? m[3] ?? m[4]);
210
+ // The Agent tool's results, by the call they answer (a set: one transcript makes hundreds of calls).
211
+ const calls = st.calls.length && line.includes('"tool_use_id"') ? [...line.matchAll(RESULT_OF)].map((m) => m[1]).filter((id) => callSet(st.calls).has(id)) : [];
212
+ if (!isUsage && !isCompact && !named.length && !calls.length && !line.includes('"name":"Agent"') && !line.includes('"name":"Task"'))
213
+ return;
214
+ let e;
215
+ try {
216
+ e = row();
217
+ }
218
+ catch {
219
+ return;
220
+ }
221
+ const at = Date.parse(String(e?.timestamp ?? ""));
222
+ if (isCompact && e?.subtype === "compact_boundary" && Number.isFinite(at))
223
+ out.push(["c", at]);
224
+ if (e?.type === "assistant") {
225
+ const m = e.message;
226
+ for (const b of Array.isArray(m?.content) ? m.content : []) {
227
+ if (b?.type === "tool_use" && (b.name === "Agent" || b.name === "Task") && typeof b.id === "string" && !st.calls.includes(b.id))
228
+ st.calls.push(b.id);
229
+ }
230
+ // Its time, prompt, writes by lifetime, fast mode / US-only (1 / 2): what the parent's side is priced from.
231
+ if (!e.isSidechain && m?.usage) {
232
+ const u = m.usage, w = cacheWriteSplit(u);
233
+ out.push(["a", typeof m.id === "string" ? m.id : null, typeof m.model === "string" ? m.model : null, Number.isFinite(at) ? at : null, tok(u.input_tokens) + tok(u.cache_creation_input_tokens) + tok(u.cache_read_input_tokens), w.fiveMinute, w.oneHour, (u.speed === "fast" ? 1 : 0) + (u.inference_geo === "us" ? 2 : 0)]);
234
+ }
235
+ return;
236
+ }
237
+ const ids = [...new Set([...calls, ...named])];
238
+ if (!ids.length || !Number.isFinite(at))
239
+ return;
240
+ // Background agents report through a task notification; foreground ones through the tool result.
241
+ const content = e?.message?.content ?? e?.content;
242
+ const n = blockTokens(Array.isArray(content) ? content.map((b) => (b?.type === "tool_result" ? { text: typeof b.content === "string" ? b.content : JSON.stringify(b.content) } : b)) : content);
243
+ out.push(["m", at, n, ids]);
244
+ },
245
+ };
246
+ /**
247
+ * The ids a row names its subagent by: a task notification's, the Agent
248
+ * tool's result's, and the hand-back that carries a background agent's final
249
+ * report (`<agent-message from="<id>">`, its quotes escaped in the row's JSON):
250
+ * on the author's machine that report, ~3k tokens, is what the parent read,
251
+ * where the notification is ~400.
252
+ */
253
+ const MENTION = /<task-id>([\w-]{1,80})<\/task-id>|<tool-use-id>([\w-]{1,80})<\/tool-use-id>|agentId: ([\w-]{1,80})|<agent-message from=\\"([\w-]{1,80})\\"/g;
254
+ /** `calls` as a set, made again only when the list changed (it only grows). */
255
+ let calledSet;
256
+ function callSet(calls) {
257
+ if (calledSet?.of !== calls || calledSet.n !== calls.length)
258
+ calledSet = { of: calls, n: calls.length, set: new Set(calls) };
259
+ return calledSet.set;
260
+ }
261
+ /** A tool result's call. */
262
+ const RESULT_OF = /"tool_use_id":"([\w-]{1,80})"/g;
263
+ /**
264
+ * A subagent's bill (each request as billed, requestCost), steps, startup
265
+ * context, start time, the tool output it read, and the rates its first
266
+ * request billed at. Read through the shared scan (SUBAGENT_ROWS).
267
+ */
268
+ export function scanSubagent(path) {
269
+ const tokens = { input: 0, read: 0, write: 0, output: 0 };
270
+ let costUsd = 0, atSonnetUsd = 0, readTokens = 0, model, firstRates;
271
+ let steps = 0, startup = 0, start = Infinity, writes5m = 0, writes1h = 0;
272
+ // The rates of the last reply, for the output its later rows settle.
273
+ let last;
274
+ const sighting = replyCounter();
275
+ const settle = outputSettler();
276
+ for (const r of rowsOf(path, SUBAGENT_ROWS)) {
277
+ if (r[0] === "r") {
278
+ readTokens += r[1];
279
+ continue;
280
+ }
281
+ if (typeof r[2] === "string" && !realModel(r[2]))
282
+ continue; // "<synthetic>": not a request
283
+ const repeat = r[0] === "o";
284
+ const e = { message: { id: r[1] ?? undefined, model: r[2] ?? undefined, usage: repeat ? { output_tokens: r[3] } : unpackUsage(r[4]) } };
109
285
  const seen = sighting(e);
110
286
  if (seen === "repeat") {
111
287
  // A later row of the same reply: only its final output count is new.
@@ -116,15 +292,15 @@ export function scanSubagent(path) {
116
292
  costUsd += (more * last.rates.outputPerM) / 1e6;
117
293
  atSonnetUsd += (more * last.sonnetRates.outputPerM) / 1e6;
118
294
  }
119
- return;
295
+ continue;
120
296
  }
121
297
  if (seen !== "new")
122
- return;
298
+ continue;
123
299
  settle(e, true);
124
300
  model = realModel(e.message.model) ?? model;
125
301
  const u = e.message.usage;
126
302
  const n = (k) => (typeof u[k] === "number" && u[k] > 0 ? u[k] : 0);
127
- const at = Date.parse(e.timestamp);
303
+ const at = typeof r[3] === "number" ? r[3] : NaN;
128
304
  if (Number.isFinite(at))
129
305
  start = Math.min(start, at);
130
306
  if (steps === 0)
@@ -140,59 +316,48 @@ export function scanSubagent(path) {
140
316
  const b = billed(model, u, Number.isFinite(at) ? at : undefined);
141
317
  last = b;
142
318
  if (!b)
143
- return;
319
+ continue;
144
320
  firstRates ??= b.rates;
145
321
  costUsd += b.usd;
146
322
  atSonnetUsd += b.sonnetUsd;
147
- });
148
- return { costUsd, atSonnetUsd, readTokens, task: task.replace(/\s+/g, " ").slice(0, 90), steps, startup, start, model, writeMult: writeMultiplier(writes5m, writes1h), ...(firstRates ? { rates: firstRates } : {}), tokens };
323
+ }
324
+ return { costUsd, atSonnetUsd, readTokens, steps, startup, start, model, writeMult: writeMultiplier(writes5m, writes1h), ...(firstRates ? { rates: firstRates } : {}), tokens };
149
325
  }
150
- function scanParent(path, ids) {
326
+ /** A parent transcript as `subagents` weighs its subagents against it, read through the shared scan (PARENT_ROWS). */
327
+ function scanParent(path) {
151
328
  const view = { requests: [], prompts: [], models: [], billing: [], compactions: [], writes5m: 0, writes1h: 0, returns: new Map() };
152
329
  let lastId;
153
- forEachLine(path, (line) => {
154
- const hits = [...ids].filter((id) => line.includes(id));
155
- const isUsage = line.includes('"usage"');
156
- const isCompact = line.includes('"compact_boundary"');
157
- if (!hits.length && !isUsage && !isCompact)
158
- return;
159
- let e;
160
- try {
161
- e = JSON.parse(line);
162
- }
163
- catch {
164
- return;
330
+ for (const r of rowsOf(path, PARENT_ROWS)) {
331
+ if (r[0] === "c") {
332
+ view.compactions.push(r[1]);
333
+ continue;
165
334
  }
166
- const at = Date.parse(e?.timestamp);
167
- if (isCompact && e?.subtype === "compact_boundary" && Number.isFinite(at))
168
- view.compactions.push(at);
169
335
  // Placeholder messages Claude Code writes itself ("<synthetic>") are not API requests.
170
- if (e?.type === "assistant" && !e.isSidechain && e.message?.usage && e.message.id !== lastId && realModel(e.message.model)) {
171
- lastId = e.message.id;
172
- view.model = realModel(e.message.model) ?? view.model;
173
- if (Number.isFinite(at)) {
174
- const u = e.message.usage;
336
+ if (r[0] === "a") {
337
+ const [, id, model, at, prompt, w5m, w1h, flags] = r;
338
+ if ((id ?? undefined) === lastId || !realModel(model ?? undefined))
339
+ continue;
340
+ lastId = id ?? undefined;
341
+ view.model = realModel(model) ?? view.model;
342
+ if (typeof at === "number") {
175
343
  view.requests.push(at);
176
- view.prompts.push((u.input_tokens ?? 0) + (u.cache_creation_input_tokens ?? 0) + (u.cache_read_input_tokens ?? 0));
177
- view.billing.push({ speed: u.speed, inference_geo: u.inference_geo });
344
+ view.prompts.push(prompt);
345
+ view.billing.push({ ...(flags & 1 ? { speed: "fast" } : {}), ...(flags & 2 ? { inference_geo: "us" } : {}) });
178
346
  view.models.push(view.model);
179
347
  }
180
- const w = cacheWriteSplit(e.message.usage);
181
- view.writes5m += w.fiveMinute;
182
- view.writes1h += w.oneHour;
183
- return;
348
+ view.writes5m += w5m;
349
+ view.writes1h += w1h;
350
+ continue;
184
351
  }
185
- if (!hits.length || !Number.isFinite(at) || e?.type === "assistant")
186
- return;
187
- // Background agents report through a task notification; foreground ones through the tool result.
188
- const content = e?.message?.content ?? e?.content;
189
- const tokens = blockTokens(Array.isArray(content) ? content.map((b) => (b?.type === "tool_result" ? { text: typeof b.content === "string" ? b.content : JSON.stringify(b.content) } : b)) : content);
190
- for (const id of hits) {
352
+ if (r[0] !== "m")
353
+ continue;
354
+ const [, at, n, ids] = r;
355
+ for (const id of ids) {
191
356
  const prev = view.returns.get(id);
192
- if (!prev || tokens > prev.tokens)
193
- view.returns.set(id, { tokens, at });
357
+ if (!prev || n > prev.tokens)
358
+ view.returns.set(id, { tokens: n, at });
194
359
  }
195
- });
360
+ }
196
361
  return view;
197
362
  }
198
363
  export function subagentPayback(days = 30, paths, onProgress) {
@@ -239,8 +404,7 @@ export function subagentPayback(days = 30, paths, onProgress) {
239
404
  catch { /* older Claude Code: no meta */ }
240
405
  return { id, file: join(dir, f), meta };
241
406
  });
242
- const ids = new Set(metas.flatMap((m) => [m.id, m.meta.toolUseId].filter((x) => Boolean(x))));
243
- const view = scanParent(parent, ids);
407
+ const view = scanParent(parent);
244
408
  // What the parent pays to write a token to its cache, from its own usage.
245
409
  const parentWrite = writeMultiplier(view.writes5m, view.writes1h);
246
410
  for (const m of metas) {
@@ -280,7 +444,7 @@ export function subagentPayback(days = 30, paths, onProgress) {
280
444
  out.push({
281
445
  id: m.id,
282
446
  type: m.meta.agentType ?? "unknown",
283
- task: m.meta.description ?? s.task,
447
+ task: m.meta.description ?? subagentTask(m.file),
284
448
  costUsd: s.costUsd,
285
449
  atSonnetUsd: s.atSonnetUsd,
286
450
  inParentUsd,
package/dist/subagents.js CHANGED
@@ -16,7 +16,7 @@
16
16
  import { readdirSync, readFileSync, statSync } from "node:fs";
17
17
  import { basename, join } from "node:path";
18
18
  import { formatTokens } from "./tokens.js";
19
- import { formatUsd, requestCost } from "./pricing.js";
19
+ import { billedCost, formatUsd } from "./pricing.js";
20
20
  import { orgRatesLine } from "./orgrates.js";
21
21
  import { forEachLine, outputSettler, replyCounter } from "./session.js";
22
22
  import { realModel } from "./tokens.js";
@@ -167,8 +167,8 @@ function summarize(path) {
167
167
  s.cacheReadTokens += read;
168
168
  s.outputTokens += out;
169
169
  // Subagents write at the 5-minute TTL (1.25x), the main thread mostly
170
- // at 1 hour (2x); the usage records which. As billed: requestCost.
171
- const c = requestCost(s.model, u, Number.isFinite(at) ? at : undefined);
170
+ // at 1 hour (2x); the usage records which. As billed, with the iterations its top-level usage leaves out: billedCost.
171
+ const c = billedCost(s.model, u, Number.isFinite(at) ? at : undefined);
172
172
  rates = c?.rates;
173
173
  if (c)
174
174
  cost += c.totalUsd;
package/dist/tasks.js CHANGED
@@ -21,7 +21,7 @@
21
21
  import { realModel } from "./tokens.js";
22
22
  import { basename } from "node:path";
23
23
  import { forEachLine, listSessions, outputSettler, replyCounter, isClaudeSession } from "./session.js";
24
- import { formatUsd, requestCost } from "./pricing.js";
24
+ import { billedCost, formatUsd } from "./pricing.js";
25
25
  /**
26
26
  * One session's bill, priced as the prompt cache bills it, from the usage the
27
27
  * transcript records. `since` counts only requests and commits from then on,
@@ -97,7 +97,8 @@ export function sessionCost(path, since = 0, counted = { rows: new Set(), commit
97
97
  }
98
98
  model = realModel(e.message.model) ?? model;
99
99
  // Each request at its own model's price, as billed: one session can switch models.
100
- const c = requestCost(model, e.message.usage, Number.isFinite(at) ? at : undefined);
100
+ // With the iterations its top-level usage leaves out (an advisor's call, a declined attempt): billedCost.
101
+ const c = billedCost(model, e.message.usage, Number.isFinite(at) ? at : undefined);
101
102
  if (!c)
102
103
  return;
103
104
  rates = c.rates;
@@ -38,7 +38,7 @@
38
38
  */
39
39
  import { listSessions, isClaudeSession, replyCounter } from "./session.js";
40
40
  import { pick, rowsOf, slimUsage } from "./scan.js";
41
- import { cacheWriteSplit, rateCard, ratesAt, requestCost, writeMultiplier } from "./pricing.js";
41
+ import { billedCost, cacheWriteSplit, rateCard, ratesAt, writeMultiplier } from "./pricing.js";
42
42
  import { isCodeLike, realModel, tokensForLength } from "./tokens.js";
43
43
  import { subagentTranscripts } from "./cachettl.js";
44
44
  /** The settings key the lever writes. */
@@ -90,7 +90,7 @@ function resultText(content) {
90
90
  return s;
91
91
  }
92
92
  export const TOOL_OUTPUT_ROWS = {
93
- id: "tool-output.2",
93
+ id: "tool-output.3",
94
94
  init: () => ({ ids: {}, calls: {} }),
95
95
  line(raw, row, out, st) {
96
96
  if (!raw.includes('"usage"') && !raw.includes('"tool_use"') && !raw.includes('"tool_result"') && !raw.includes("compact_boundary"))
@@ -117,10 +117,10 @@ export const TOOL_OUTPUT_ROWS = {
117
117
  // A reply is written one content block a row, each with its usage: one request, at its first row.
118
118
  if (m.usage && typeof m.id === "string" && !((st.ids[m.id] ?? 0) & (th + 1))) {
119
119
  st.ids[m.id] = (st.ids[m.id] ?? 0) | (th + 1);
120
- out.push({ t: "r", th, ...pick(e, ["timestamp", "uuid"]), id: m.id, model: m.model, u: slimUsage(m.usage) });
120
+ out.push({ t: "r", th, ...pick(e, ["timestamp", "uuid"]), id: m.id, model: m.model, u: slimUsage(m.usage, { iterations: true }) });
121
121
  }
122
122
  else if (m.usage && typeof m.id !== "string") {
123
- out.push({ t: "r", th, ...pick(e, ["timestamp", "uuid"]), model: m.model, u: slimUsage(m.usage) });
123
+ out.push({ t: "r", th, ...pick(e, ["timestamp", "uuid"]), model: m.model, u: slimUsage(m.usage, { iterations: true }) });
124
124
  }
125
125
  if (Array.isArray(m.content)) {
126
126
  for (const b of m.content) {
@@ -218,7 +218,7 @@ function timeline(path, since, until, runRows) {
218
218
  writePerM: (price?.inputPerM ?? 0) * writeMult,
219
219
  cold: num(u.cache_creation_input_tokens) > COLD_SHARE * prompt,
220
220
  counted: !!price && seen === "new" && at >= since && at < until,
221
- billedUsd: requestCost(m, u, at)?.promptUsd ?? 0,
221
+ billedUsd: billedCost(m, u, at)?.promptUsd ?? 0,
222
222
  ...(below && price ? { over: card.over, lower: below.inputPerM / price.inputPerM } : {}),
223
223
  });
224
224
  }
@@ -0,0 +1,77 @@
1
+ /**
2
+ * `context-doctor mod usage`: the figures behind the mod's usage pane
3
+ * (ROADMAP F5), printed as JSON for the mod to draw.
4
+ *
5
+ * Claude Code's Desktop app dropped its usage view (anthropics/claude-code
6
+ * #102264, #102098, #102130; #102094 the context ring) and 2.1.323 removed
7
+ * `subagentStatusLine` (#109446). The pane puts them back from what is on
8
+ * this machine:
9
+ *
10
+ * - tokens and list-price dollars by model for today, 7 and 30 days, from
11
+ * the requests `spend` reads (claudeSpend, through the shared scan
12
+ * cache), kept in a small file for HISTORY_TTL_MS so a pane left open
13
+ * does not scan every refresh (warm, the scan is ~150 ms on the author's
14
+ * 22,000 requests; cold, ~2.7 s);
15
+ * - the limit windows from the limits ledger (the 5-hour one only when the
16
+ * plan has it: Ultra has none), each with its pace, read on every refresh;
17
+ * and, with the history (it reads the transcripts over the readings'
18
+ * span), `limits`' per-reset figures (limitsByReset, ROADMAP F4): the
19
+ * list-price dollars per 1% of the current weekly window, or the last one
20
+ * that had a figure, and the latest move in that figure, dated;
21
+ * - each running subagent the mod names (from `$.agent.list()`): its
22
+ * model and context from its transcript's tail, its cost so far from the
23
+ * session's price entries, which the every-prompt hook and `mod measure`
24
+ * keep (sessionTotal: only what was appended since is read).
25
+ *
26
+ * The context ring itself is Claude Code's own figure (`session.measure`),
27
+ * drawn by the mod with no run of this command.
28
+ *
29
+ * Silent like the status line: anything unreadable is left out, and the
30
+ * command prints `{}` at worst and exits 0.
31
+ */
32
+ import { type SpendItem } from "./spend.js";
33
+ import { type LimitReading, type LimitsByReset } from "./limits.js";
34
+ import type { AgentUse, HistoryUse, LimitWindow, UsagePaneData } from "./mod/logic.js";
35
+ /** The history part is measured again at most this often, whoever asks (two sessions' panes share it). */
36
+ export declare const HISTORY_TTL_MS: number;
37
+ export type { AgentUse, HistoryUse, LimitWindow, ModelUse, PeriodUse, UsagePaneData } from "./mod/logic.js";
38
+ export interface UsagePaneInput {
39
+ sessionId?: string;
40
+ cwd?: string;
41
+ /** The running subagents' ids, as `$.agent.list()` gives them. */
42
+ agents?: unknown;
43
+ /** Leave the history out (a refresh for the subagents alone). */
44
+ history?: boolean;
45
+ /** Measure the history again even within HISTORY_TTL_MS (the pane's Refresh). */
46
+ fresh?: boolean;
47
+ }
48
+ /** Sum the requests into today, the last 7 and the last 30 days, each by model, the most dollars first. */
49
+ export declare function summarizeHistory(items: SpendItem[], now: number): HistoryUse;
50
+ /**
51
+ * What the pane takes of `limits`' per-reset view (F4): for each Claude
52
+ * window, dollars per 1% of the current window (or of the last one that had
53
+ * a figure: a new window has too few stretches), the latest move in that
54
+ * figure, and whether the plan has no 5-hour window (Ultra).
55
+ */
56
+ export declare function limitFitsOf(r: LimitsByReset): Pick<HistoryUse, "limitFits" | "limitMove" | "noFiveHour">;
57
+ /** The history part: from the cache while it is fresh, else measured (spend's scan, then the limit fits over the same requests). */
58
+ export declare function historyUse(now: number, fresh?: boolean): {
59
+ h: HistoryUse;
60
+ from: "cache" | "measured";
61
+ ms: number;
62
+ };
63
+ /**
64
+ * Each Claude window in the ledger, newest reading first, with its pace.
65
+ * A window with no reading in the last 8 days is not shown: a plan with no
66
+ * 5-hour window (Ultra) has only the weekly one.
67
+ */
68
+ export declare function limitWindows(now: number, fits?: HistoryUse["limitFits"], readings?: LimitReading[]): LimitWindow[];
69
+ /** A subagent's model and context, from the last request in its transcript's tail. */
70
+ export declare function agentTail(file: string): {
71
+ model?: string;
72
+ contextTokens?: number;
73
+ };
74
+ /** Each running subagent's model, context and cost so far. */
75
+ export declare function agentUse(sessionId: string | undefined, cwd: string | undefined, list: unknown, now: number): AgentUse[];
76
+ /** Everything the pane draws but the context ring. Never throws. */
77
+ export declare function usagePane(input: UsagePaneInput, now?: number): UsagePaneData;