@agentguard-run/burn 0.3.25 → 0.3.27

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/CHANGELOG.md CHANGED
@@ -1,5 +1,20 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.3.27 (2026-10-02)
4
+
5
+ - `why` and every other command that reads one session no longer stop on a session file over about 512 MB. A transcript over 256 MB is now read in 16 MB pieces cut at line ends, the way `calendar` reads every file, so no single string has to hold the whole file, and the report equals a whole-file read. One long-running Claude Code session had reached 568 MB, and `why` on it stopped with "Cannot create a string longer than 0x1fffffe8 characters"; it now reports in about 9 seconds. Files up to 256 MB are read exactly as before.
6
+ - Tests: 537 (536 pass, 1 skipped).
7
+
8
+ ## 0.3.26 (2026-10-02)
9
+
10
+ - Sub-agents that started, used tokens and ended without finishing now show up in `why`, `calendar` and the STOP line. A sub-agent counts only on terminal evidence: Claude Code recorded the status of its task notification as `failed`, `killed` or `stopped`, and never recorded it as `completed` or resumed (a SendMessage result that started it again). One launched in the background with no end recorded may still be running, so it never counts. A launch refused before it started (a hook, a permission rule, your no) has no transcript and used no tokens, so it is not counted either. Burn has no rule for a session being over, so it relies on these records alone. It knows whether a sub-agent finished, never whether its work was right, so every line says "ended without finishing", never "failed".
11
+ - `why` adds one line after the observed calls when at least one did: `Sub-agents that ended without finishing: 2 of 5, 275,000 tokens (58.9% of session tokens, $0.75 API list equivalent).` The count is out of every sub-agent transcript in the session's `subagents` folder, the tokens are their own responses counted once as everywhere in `why`, and the dollars are left out when a model is unpriced. A sub-agent's own sub-agents count by what its transcript records.
12
+ - `calendar` adds the same totals across every session, on one more summary line: `2 of 5 sub-agents ended without finishing (275,000 tokens, 58.9% of tokens, $0.75 at API prices)`. Each sub-agent counts once, on its first day with tokens, with all of its tokens, so the count and the tokens describe the same sub-agents. The daily count keeps them after the transcripts are deleted. Days an earlier Burn counted carry no sub-agent counts, so their sub-agents are in neither number. `calendar json` gains `subagents`, `unfinishedSubagents`, `unfinishedTokens` and `unfinishedUsd` in `totals`.
13
+ - The STOP line about finished sub-agents gains a sentence when the session's transcripts record any that ended without finishing: `The 15 sub-agents that finished in this session averaged 10.0M tokens each ($4.99 at API prices, not a bill). 2 more ended without finishing and used 3.1M tokens in total. This one could differ.` It still needs three finished sub-agents, and the hook still reads no transcript for it: the ids come from the reading it already does and are saved beside the completed ids, as `ended` and `resumed` in the saved cursor. A cursor saved by an earlier Burn loads with neither, so a sub-agent whose end it had already read is not counted.
14
+ - Spanish and Portuguese say the same, in the same tone: "quedaron sin terminar", "pararam sem terminar".
15
+ - Internals: one function, `subagentSignals` in `src/history/subagent-signals.ts`, reads these records for the hook, `why` and `calendar`, so the three can't disagree. It reads a notification's ids and status only from its header, before the summary and the sub-agent's own result, so a result that quotes a notification can never become an id or a status. A notification that lists several tasks applies its status to each; the finished line reads completions the same way. `why json` gains `subagents` (the ids it counted from) and, on a transcript that records any, `state.subagentSignals`; a session with neither prints the same json as 0.3.25. The calendar's cache is rebuilt once (schema 4).
16
+ - Tests: 536 (535 pass, 1 skipped), up from 517.
17
+
3
18
  ## 0.3.25 (2026-10-01)
4
19
 
5
20
  - `card` draws the calendar's totals as one 1200 by 675 PNG to post: tokens with the Claude Code and Codex split, dollars at API list price (not a bill), the sub-agent share, the busiest day, the launches AgentGuard held, and one bar per day in whole weeks. `--weeks N` (1 to 53, default 4) and `--out file.png` (default `agentguard-burn-card.png`). It is drawn locally from the figures `calendar` prints; no project, prompt or file name appears on it, and nothing is uploaded.
package/README.md CHANGED
@@ -213,6 +213,8 @@ The setup and the re-read conversation split each call's cached reads at the siz
213
213
 
214
214
  After a `/compact`, an automatic compaction, a model switch, or a `/clear` that the transcript records, `why` adds one measured line before the tip, for example `Measured change: after /compact on 2026-09-27 at 14:02 UTC, Claude read a median of 85K tokens per message, down from 660K in the 20 messages before.` It compares the median tokens per message of the main conversation in the N messages after the latest such event with the N before it: N is 20, fewer when the session or the next or previous event leaves fewer, and with fewer than 5 on either side that event says nothing. It states a measurement next to an event, never a saving or a cause, and prints whether or not tips are on.
215
215
 
216
+ When the session's transcripts record sub-agents that ended without finishing, `why` adds one line after the observed calls, for example `Sub-agents that ended without finishing: 2 of 5, 275,000 tokens (58.9% of session tokens, $0.75 API list equivalent).` A sub-agent counts only when Claude Code recorded its status as `failed`, `killed` or `stopped`, and never as `completed` or resumed. One launched in the background with no end recorded may still be running, so it never counts. The count is out of every sub-agent transcript in the session's `subagents` folder, the tokens are their own responses counted once, and the dollars are left out when a model is unpriced. Burn knows whether a sub-agent finished, never whether its work was right. `why json` lists the ids it counted from under `subagents`.
217
+
216
218
  `why` prints in Latin American Spanish or Brazilian Portuguese when your machine is set to that language, and `--lang es`, `--lang pt` or `--lang en` picks one explicitly. The order is `--lang`, then `AGENTGUARD_LANG`, then `LC_ALL`, `LC_MESSAGES` and `LANG` (the first one set decides, as POSIX says, so `LC_ALL=C` means English), then the locale Node resolves. Every other language is English. Figures keep their en-US formatting in every language (`1,234,567`, `$1335.37`, `12.3%`), so a translated report matches screenshots digit for digit. `why`, `compare` and `calendar` are translated. Their `json` output is the same in every language, and every other command stays English.
217
219
 
218
220
  Later cache reads up to the baseline go to instruction stack + system. Reads above it go to history re-sent. Fresh input plus cache creation is the measured arriving increment. Burn subtracts the previous response's output before assigning that increment to intervening tool results and user messages. Result byte sizes only split that measured total; bytes are never converted into tokens. A result for a previously read Read path goes to re-read files. Mixed user and tool intervals are marked shared and counted in the footer.
@@ -287,7 +289,7 @@ agentguard-burn calendar json
287
289
 
288
290
  Every Claude Code and Codex session on this machine on one heatmap, sub-agents included: a column per week, a row per weekday, darker for more tokens. Each response's tokens and API price come from the parser and prices `why` uses, counted on the local calendar day the response was recorded. A response recorded in two files (a sub-agent's copy of its parent's last reply, a project that moved, a forked session) counts once, merged the way `why` merges a session. A forked Codex session whose copied history has no verifiable boundary is left out and named in a note, as `why` reports it unavailable.
289
291
 
290
- The summary is three short lines, however wide the terminal: the total tokens and the dollars at API prices (not a bill; from $1,000 in whole dollars, such as `$28,252 to $28,254 at API prices, not a bill`, and one number when both ends round to the same dollar); the busiest day and the share of tokens sub-agents used (every token of their responses); and, only when there were any, how many sub-agent launches AgentGuard held: refused by an enforced STOP, or held for your yes, as the decisions ledger records them. On a narrow terminal a line's two items take a line each. A day is amber when sub-agents used more than half of its tokens, and carries a red mark when AgentGuard held a launch that day. The five shades run from Less to More: a day's level is the quarter of the shown days with tokens that it reaches, so the busiest day shown is always the darkest. Tokens on a model without a verified rate are counted but left out of the dollars, and a note names the model.
292
+ The summary is at most four short lines, however wide the terminal: the total tokens and the dollars at API prices (not a bill; from $1,000 in whole dollars, such as `$28,252 to $28,254 at API prices, not a bill`, and one number when both ends round to the same dollar); the busiest day and the share of tokens sub-agents used (every token of their responses); only when there were any, how many sub-agents ended without finishing, out of all of them, with their tokens, share and dollars, by the rule `why` uses (each sub-agent counts once, on its first day with tokens, with all of its tokens, and days an earlier Burn counted carry no sub-agent counts); and, only when there were any, how many sub-agent launches AgentGuard held: refused by an enforced STOP, or held for your yes, as the decisions ledger records them. On a narrow terminal a line's two items take a line each. A day is amber when sub-agents used more than half of its tokens, and carries a red mark when AgentGuard held a launch that day. The five shades run from Less to More: a day's level is the quarter of the shown days with tokens that it reaches, so the busiest day shown is always the darkest. Tokens on a model without a verified rate are counted but left out of the dollars, and a note names the model.
291
293
 
292
294
  With no flag the calendar starts at the oldest recorded day, capped to the weeks that fit the terminal (its width on a terminal, 80 columns when piped, as when Claude Code runs `! npx agentguard-burn calendar`); `--weeks N` shows exactly N weeks, 1 to 53, ending with this week.
293
295
 
@@ -473,7 +475,11 @@ The third line appears once at least three of the session's sub-agents have
473
475
  finished: what they averaged, measured from their own transcripts as the hook
474
476
  reads them anyway (never a second pass), and never a forecast. With fewer, the
475
477
  prompt is the other three lines. The box of a refused launch carries the same
476
- line.
478
+ line. When the transcripts also record sub-agents that ended without finishing
479
+ (status `failed`, `killed` or `stopped`, and never `completed` or resumed), the
480
+ line adds how many and the tokens they used, for example `2 more ended without
481
+ finishing and used 3.1M tokens in total.` A sub-agent that may still be running
482
+ never counts.
477
483
 
478
484
  You answer with one keypress. Claude never sees that text, and auto mode
479
485
  cannot approve it silently (Claude Code 2.1.211 and later), so the answer is
@@ -41,6 +41,10 @@ export interface ReaderCursor {
41
41
  usage?: Map<string, ChildUsage>;
42
42
  /** Sub-agent ids the transcripts record as completed; the parent's set, shared with its children. */
43
43
  completed?: Set<string>;
44
+ /** Sub-agent ids the transcripts record as failed, killed or stopped; shared the same way. Optional, so older cursors still load. */
45
+ ended?: Set<string>;
46
+ /** Sub-agent ids the transcripts record as resumed, so possibly running again; shared the same way. */
47
+ resumed?: Set<string>;
44
48
  }
45
49
  export declare function newCursor(): ReaderCursor;
46
50
  interface RawLine {
@@ -86,9 +90,10 @@ export declare function readSessionIncremental(path: string, cursor: ReaderCurso
86
90
  /**
87
91
  * A reader cursor in a form JSON can hold: the byte offset and size reached in
88
92
  * the session transcript and in each sub-agent transcript, the usage already
89
- * counted per response, each sub-agent's own usage, and the ids of completed
90
- * sub-agents. Burn's Claude Code hook stores exactly this between calls; any
91
- * other hook that stores it the same way reads each byte once, as Burn does.
93
+ * counted per response, each sub-agent's own usage, and the ids of sub-agents
94
+ * recorded as completed, ended without finishing, or resumed. Burn's Claude
95
+ * Code hook stores exactly this between calls; any other hook that stores it the
96
+ * same way reads each byte once, as Burn does.
92
97
  */
93
98
  export interface PersistedReaderCursor {
94
99
  offset: number;
@@ -103,15 +108,21 @@ export interface PersistedReaderCursor {
103
108
  usage?: [string, ChildUsage][];
104
109
  /** The session transcript's cursor only: sub-agent ids the transcripts record as completed. */
105
110
  completed?: string[];
111
+ /** The same: sub-agent ids recorded as failed, killed or stopped. A cursor saved before Burn kept them loads with none. */
112
+ ended?: string[];
113
+ /** The same: sub-agent ids recorded as resumed. */
114
+ resumed?: string[];
106
115
  }
107
116
  /** A session cursor, sub-agent cursors included, as JSON can store it. Pair with restoreReaderCursor. */
108
117
  export declare function saveReaderCursor(cursor: ReaderCursor): PersistedReaderCursor;
109
118
  /**
110
119
  * The cursor saveReaderCursor stored. Its sub-agent cursors share the session's
111
- * de-duplication map and completed ids, as they do while reading. A cursor saved
112
- * from readIncremental alone (no sub-agent cursors) resumes the session
120
+ * de-duplication map and sub-agent outcomes, as they do while reading. A cursor
121
+ * saved from readIncremental alone (no sub-agent cursors) resumes the session
113
122
  * transcript where it stopped and reads each sub-agent transcript from its first
114
- * byte on the next readSessionIncremental.
123
+ * byte on the next readSessionIncremental. A cursor saved before Burn kept the
124
+ * ended and resumed ids loads with none, so a sub-agent whose end was read
125
+ * before then is never counted as ended: absent evidence stays absent.
115
126
  */
116
127
  export declare function restoreReaderCursor(saved: PersistedReaderCursor): ReaderCursor;
117
128
  /**
@@ -24,6 +24,7 @@ exports.readAll = readAll;
24
24
  const node_fs_1 = require("node:fs");
25
25
  const node_path_1 = require("node:path");
26
26
  const transcript_1 = require("../insights/transcript");
27
+ const subagent_signals_1 = require("./subagent-signals");
27
28
  const CHUNK = 64 * 1024;
28
29
  const MAX_LINE = 4 * 1024 * 1024;
29
30
  const SPAWN_TOOLS = new Set(['Agent', 'Task']);
@@ -41,7 +42,6 @@ function nonNegative(value) {
41
42
  return typeof value === 'number' && Number.isFinite(value) && value > 0 ? value : 0;
42
43
  }
43
44
  const MODEL_ID = /^[A-Za-z0-9_.:/-]{1,128}$/;
44
- const AGENT_ID = /^[A-Za-z0-9_-]{1,64}$/;
45
45
  /**
46
46
  * Add one response's newly observed usage to its child's running total. The
47
47
  * five-minute and one-hour parts of a cache write follow the record's own split;
@@ -58,28 +58,16 @@ function addChildUsage(usage, raw, [input, output, write, read]) {
58
58
  usage.set(model, [row[0] + input, row[1] + output, row[2] + write, row[3] + read, row[4] + five, row[5] + hour]);
59
59
  }
60
60
  /**
61
- * Note the sub-agents the host records as completed. Claude Code writes a
62
- * synchronous sub-agent's result with status "completed", and announces the end
63
- * of a background one with a <task-notification> in a queued message (a queue
64
- * operation, a queued-command attachment, or the user message it becomes). Only
65
- * the id of a completed sub-agent is kept; nothing else of the message is.
61
+ * Note how the host records sub-agents ending: completed, ended without
62
+ * finishing (failed, killed or stopped), or resumed (see subagent-signals.ts).
63
+ * Only the ids are kept; nothing else of the message is.
66
64
  */
67
- function observeCompleted(raw, completed) {
68
- const result = raw.toolUseResult;
69
- if (result && typeof result === 'object' && !Array.isArray(result)) {
70
- const { status, agentId } = result;
71
- if (status === 'completed' && typeof agentId === 'string' && AGENT_ID.test(agentId))
72
- completed.add(agentId);
73
- }
74
- const text = raw.type === 'queue-operation' ? raw.content
75
- : raw.type === 'user' ? raw.message?.content
76
- : raw.type === 'attachment' && raw.attachment?.type === 'queued_command' ? raw.attachment.prompt : undefined;
77
- if (typeof text !== 'string' || !text.startsWith('<task-notification>'))
78
- return;
79
- for (const [, body] of text.matchAll(/<task-notification>([\s\S]*?)<\/task-notification>/g)) {
80
- const id = /<task-id>([A-Za-z0-9_-]{1,64})<\/task-id>/.exec(body)?.[1];
81
- if (id && /<status>completed<\/status>/.test(body))
65
+ function observeSubagents(raw, cursor, completed) {
66
+ for (const [signal, id] of (0, subagent_signals_1.subagentSignals)(raw)) {
67
+ if (signal === 'completed')
82
68
  completed.add(id);
69
+ else
70
+ (signal === 'ended' ? cursor.ended ??= new Set() : cursor.resumed ??= new Set()).add(id);
83
71
  }
84
72
  }
85
73
  /** Turn one parsed line into an event, or null if it carries nothing we track. */
@@ -197,7 +185,7 @@ function readIncremental(path, cursor, options = {}) {
197
185
  try {
198
186
  const parsed = JSON.parse(lineBytes.toString('utf8'));
199
187
  if (cursor.completed)
200
- observeCompleted(parsed, cursor.completed);
188
+ observeSubagents(parsed, cursor, cursor.completed);
201
189
  const event = normaliseLine(parsed, cursor);
202
190
  if (event)
203
191
  events.push(event);
@@ -240,6 +228,8 @@ function readSessionIncremental(path, cursor, options = {}) {
240
228
  cursor.usageByMessage ??= new Map();
241
229
  cursor.children ??= new Map();
242
230
  cursor.completed ??= new Set();
231
+ cursor.ended ??= new Set();
232
+ cursor.resumed ??= new Set();
243
233
  const events = readIncremental(path, cursor, options);
244
234
  const directory = (0, node_path_1.join)(path.replace(/\.jsonl$/, ''), 'subagents');
245
235
  let names;
@@ -254,8 +244,10 @@ function readSessionIncremental(path, cursor, options = {}) {
254
244
  for (const name of names) {
255
245
  const child = cursor.children.get(name) ?? newCursor();
256
246
  child.usageByMessage = cursor.usageByMessage;
257
- // A sub-agent's own sub-agents report their completion in its transcript.
247
+ // A sub-agent's own sub-agents report how they ended in its transcript.
258
248
  child.completed = cursor.completed;
249
+ child.ended = cursor.ended;
250
+ child.resumed = cursor.resumed;
259
251
  // Measured from its first byte, as it is read anyway: no second pass over any child.
260
252
  if (!child.usage && child.offset === 0)
261
253
  child.usage = new Map();
@@ -275,6 +267,8 @@ function persist(cursor, child) {
275
267
  usageVersion: cursor.usageVersion,
276
268
  ...(!child ? { usageByMessage: [...(cursor.usageByMessage ?? [])] } : {}),
277
269
  ...(!child && cursor.completed?.size ? { completed: [...cursor.completed] } : {}),
270
+ ...(!child && cursor.ended?.size ? { ended: [...cursor.ended] } : {}),
271
+ ...(!child && cursor.resumed?.size ? { resumed: [...cursor.resumed] } : {}),
278
272
  ...(child && cursor.usage ? { usage: [...cursor.usage] } : {}),
279
273
  ...(cursor.children?.size ? { children: [...cursor.children].map(([name, value]) => [name, persist(value, true)]) } : {}) };
280
274
  }
@@ -284,18 +278,20 @@ function saveReaderCursor(cursor) {
284
278
  }
285
279
  /**
286
280
  * The cursor saveReaderCursor stored. Its sub-agent cursors share the session's
287
- * de-duplication map and completed ids, as they do while reading. A cursor saved
288
- * from readIncremental alone (no sub-agent cursors) resumes the session
281
+ * de-duplication map and sub-agent outcomes, as they do while reading. A cursor
282
+ * saved from readIncremental alone (no sub-agent cursors) resumes the session
289
283
  * transcript where it stopped and reads each sub-agent transcript from its first
290
- * byte on the next readSessionIncremental.
284
+ * byte on the next readSessionIncremental. A cursor saved before Burn kept the
285
+ * ended and resumed ids loads with none, so a sub-agent whose end was read
286
+ * before then is never counted as ended: absent evidence stays absent.
291
287
  */
292
288
  function restoreReaderCursor(saved) {
293
- const restore = (raw, usageByMessage, completed) => ({
289
+ const restore = (raw, usageByMessage, outcomes) => ({
294
290
  offset: raw.offset, size: raw.size, malformedLines: raw.malformedLines, depthByUuid: new Map(raw.depthByUuid),
295
- usageVersion: raw.usageVersion, usageByMessage, completed, ...(raw.usage ? { usage: new Map(raw.usage) } : {}),
296
- children: new Map((raw.children ?? []).map(([name, child]) => [name, restore(child, usageByMessage, completed)]))
291
+ usageVersion: raw.usageVersion, usageByMessage, ...outcomes, ...(raw.usage ? { usage: new Map(raw.usage) } : {}),
292
+ children: new Map((raw.children ?? []).map(([name, child]) => [name, restore(child, usageByMessage, outcomes)]))
297
293
  });
298
- return restore(saved, new Map(saved.usageByMessage ?? []), new Set(saved.completed ?? []));
294
+ return restore(saved, new Map(saved.usageByMessage ?? []), { completed: new Set(saved.completed ?? []), ended: new Set(saved.ended ?? []), resumed: new Set(saved.resumed ?? []) });
299
295
  }
300
296
  /**
301
297
  * An independent copy of a session cursor, sub-agent cursors included, to read
@@ -303,10 +299,11 @@ function restoreReaderCursor(saved) {
303
299
  * a step that fails reads the same bytes again instead of losing them.
304
300
  */
305
301
  function cloneReaderCursor(cursor) {
306
- const usageByMessage = new Map(cursor.usageByMessage ?? []), completed = new Set(cursor.completed ?? []);
302
+ const usageByMessage = new Map(cursor.usageByMessage ?? []);
303
+ const outcomes = { completed: new Set(cursor.completed ?? []), ended: new Set(cursor.ended ?? []), resumed: new Set(cursor.resumed ?? []) };
307
304
  const copy = (item) => ({
308
305
  offset: item.offset, size: item.size, malformedLines: item.malformedLines, depthByUuid: new Map(item.depthByUuid),
309
- usageVersion: item.usageVersion, usageByMessage, completed, ...(item.usage ? { usage: new Map(item.usage) } : {}),
306
+ usageVersion: item.usageVersion, usageByMessage, ...outcomes, ...(item.usage ? { usage: new Map(item.usage) } : {}),
310
307
  ...(item.children ? { children: new Map([...item.children].map(([name, child]) => [name, copy(child)])) } : {})
311
308
  });
312
309
  return copy(cursor);
@@ -0,0 +1,56 @@
1
+ /**
2
+ * How a Claude Code sub-agent ended, as one transcript record states it. The
3
+ * hook's reader (claude-transcript.ts) and the report parser
4
+ * (insights/transcript.ts) both call this, so the STOP line, `why` and
5
+ * `calendar` read every sub-agent by the same signals. Only sub-agent ids and
6
+ * statuses are read; nothing else of a record is kept.
7
+ *
8
+ * The shapes, as Claude Code writes them (checked against real transcripts on
9
+ * 2026-10-02):
10
+ *
11
+ * - completed: a synchronous sub-agent's tool result, `toolUseResult` with
12
+ * `status: "completed"` and its `agentId`; or, for a background one, a
13
+ * `<task-notification>` with `<status>completed</status>`.
14
+ * - ended without finishing: a `<task-notification>` with
15
+ * `<status>failed</status>`, `killed` or `stopped`.
16
+ * - resumed: a SendMessage result that started a sub-agent again,
17
+ * `toolUseResult.resumedAgentId`. A resumed sub-agent may be running, so an
18
+ * earlier end no longer says how it ended.
19
+ *
20
+ * A notification reaches the transcript in a queued message: a queue operation,
21
+ * a queued-command attachment, or the user message it becomes, always one
22
+ * notification at the start of the text. It names its task with `<task-id>` (a
23
+ * sub-agent's id is its `agent-<id>.jsonl`), and one notification can list
24
+ * several tasks under one status, which applies to each. Ids and status are read
25
+ * only from the header, where Claude Code writes them before the summary and the
26
+ * sub-agent's own result, so words inside a result, even a quoted notification,
27
+ * can never become an id or a status.
28
+ *
29
+ * Not signals: a launch result (`status: "async_launched"`) says the sub-agent
30
+ * is running; a notification with no status reports an event, not an end; and
31
+ * an error result to an Agent call (a hook's or a person's refusal, a rejected
32
+ * permission) answers a launch that never started, so it has no transcript and
33
+ * used no tokens.
34
+ */
35
+ export type SubagentSignal = 'completed' | 'ended' | 'resumed';
36
+ /** A sub-agent's transcript in its session's `subagents` folder, and the sub-agent id the name carries. */
37
+ export declare const SUBAGENT_FILE: RegExp;
38
+ /** Notification statuses that end a sub-agent without it finishing. */
39
+ export declare const UNFINISHED_STATUSES: ReadonlySet<string>;
40
+ /**
41
+ * The sub-agent signals one parsed transcript record carries, as
42
+ * `[signal, sub-agent id]` pairs; almost every record carries none.
43
+ */
44
+ export declare function subagentSignals(raw: unknown): ReadonlyArray<readonly [SubagentSignal, string]>;
45
+ /**
46
+ * A sub-agent that ended without finishing: recorded as failed, killed or
47
+ * stopped, and never as completed or resumed. A resumed one may be running
48
+ * again, and Burn does not order records across a session's files, so it is
49
+ * left out unless it completes. Anything else may have finished or may still be
50
+ * running, and is never counted.
51
+ */
52
+ export declare function endedWithoutFinishing(id: string, signals: {
53
+ completed?: ReadonlySet<string>;
54
+ ended?: ReadonlySet<string>;
55
+ resumed?: ReadonlySet<string>;
56
+ }): boolean;
@@ -0,0 +1,65 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.UNFINISHED_STATUSES = exports.SUBAGENT_FILE = void 0;
4
+ exports.subagentSignals = subagentSignals;
5
+ exports.endedWithoutFinishing = endedWithoutFinishing;
6
+ /** A sub-agent's transcript in its session's `subagents` folder, and the sub-agent id the name carries. */
7
+ exports.SUBAGENT_FILE = /^agent-([A-Za-z0-9][A-Za-z0-9_-]{0,63})\.jsonl$/;
8
+ /** Notification statuses that end a sub-agent without it finishing. */
9
+ exports.UNFINISHED_STATUSES = new Set(['failed', 'killed', 'stopped']);
10
+ /** A sub-agent or task id: Claude Code's are letters and digits. One never starts with `_`, so no id can be `__proto__`. */
11
+ const AGENT_ID = /^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/;
12
+ const NONE = Object.freeze([]);
13
+ const OPEN = '<task-notification>';
14
+ /** The text of a queued message: a queue operation, a queued-command attachment, or the user message it becomes. */
15
+ function queuedText(record) {
16
+ if (record.type === 'queue-operation')
17
+ return record.content;
18
+ if (record.type === 'user')
19
+ return record.message?.content;
20
+ return record.type === 'attachment' && record.attachment?.type === 'queued_command' ? record.attachment.prompt : undefined;
21
+ }
22
+ /**
23
+ * The sub-agent signals one parsed transcript record carries, as
24
+ * `[signal, sub-agent id]` pairs; almost every record carries none.
25
+ */
26
+ function subagentSignals(raw) {
27
+ if (!raw || typeof raw !== 'object')
28
+ return NONE;
29
+ const record = raw;
30
+ let found;
31
+ const result = record.toolUseResult;
32
+ if (result && typeof result === 'object' && !Array.isArray(result)) {
33
+ const { status, agentId, resumedAgentId } = result;
34
+ if (status === 'completed' && typeof agentId === 'string' && AGENT_ID.test(agentId))
35
+ (found ??= []).push(['completed', agentId]);
36
+ if (typeof resumedAgentId === 'string' && AGENT_ID.test(resumedAgentId))
37
+ (found ??= []).push(['resumed', resumedAgentId]);
38
+ }
39
+ const text = queuedText(record);
40
+ if (typeof text !== 'string' || !text.startsWith(OPEN))
41
+ return found ?? NONE;
42
+ // One notification leads the queued text. Only its header is read: the task
43
+ // ids, then the status, before any summary, note or result.
44
+ const at = text.indexOf('<status>');
45
+ const head = at < 0 ? '' : text.slice(OPEN.length, at);
46
+ if (at < 0 || /<\/?(?:task-notification|summary|note|result|usage|event)>/.test(head))
47
+ return found ?? NONE;
48
+ const status = /^<status>([a-z_]{1,32})<\/status>/.exec(text.slice(at, at + 64))?.[1];
49
+ const signal = status === 'completed' ? 'completed' : status !== undefined && exports.UNFINISHED_STATUSES.has(status) ? 'ended' : null;
50
+ if (!signal)
51
+ return found ?? NONE;
52
+ for (const [, id] of head.matchAll(/<task-id>([A-Za-z0-9][A-Za-z0-9_-]{0,63})<\/task-id>/g))
53
+ (found ??= []).push([signal, id]);
54
+ return found ?? NONE;
55
+ }
56
+ /**
57
+ * A sub-agent that ended without finishing: recorded as failed, killed or
58
+ * stopped, and never as completed or resumed. A resumed one may be running
59
+ * again, and Burn does not order records across a session's files, so it is
60
+ * left out unless it completes. Anything else may have finished or may still be
61
+ * running, and is never counted.
62
+ */
63
+ function endedWithoutFinishing(id, signals) {
64
+ return Boolean(signals.ended?.has(id)) && !signals.completed?.has(id) && !signals.resumed?.has(id);
65
+ }
@@ -150,13 +150,16 @@ function calendarLines(report, lang, columns, skin) {
150
150
  return lines;
151
151
  }
152
152
  // The summary in short lines: tokens and dollars; the busiest day and the
153
- // sub-agent share; the launches AgentGuard held, when there were any. Two items
154
- // share a line only when both fit the width; no line takes an item from another.
153
+ // sub-agent share; the sub-agents that ended without finishing and the launches
154
+ // AgentGuard held, each when there were any. Two items share a line only when
155
+ // both fit the width; no line takes an item from another.
155
156
  const totals = report.totals, spansYears = report.from.slice(0, 4) !== report.to.slice(0, 4);
157
+ const unfinished = totals.unfinishedSubagents ?? 0, unfinishedTokens = totals.unfinishedTokens ?? 0, unfinishedUsd = totals.unfinishedUsd ?? null;
156
158
  const summary = [
157
159
  [text.tokens((0, render_1.count)(totals.tokens)), text.dollars(totals.usd === null ? null : calendarDollars(totals.usd, words))],
158
160
  [...(report.busiest ? [text.busiest(text.date(dateOf(report.busiest.date, text), spansYears), (0, render_1.count)(report.busiest.tokens))] : []),
159
161
  text.subagents((0, render_1.share)(totals.subagentTokens, totals.tokens))],
162
+ unfinished > 0 ? [text.unfinished(unfinished, Math.max(unfinished, totals.subagents ?? 0), (0, render_1.count)(unfinishedTokens), (0, render_1.share)(unfinishedTokens, totals.tokens), unfinishedUsd === null ? null : calendarDollars(unfinishedUsd, words))] : [],
160
163
  totals.heldLaunches > 0 ? [text.held(totals.heldLaunches)] : [],
161
164
  ];
162
165
  for (const items of summary)
@@ -24,6 +24,21 @@ export interface CalendarFigures {
24
24
  unpricedTokens: number;
25
25
  /** Those models; null is a response without a model id. */
26
26
  unpricedModels: Array<string | null>;
27
+ /**
28
+ * On a stored sub-agent's first day with tokens, the sub-agent itself: 1.
29
+ * Absent on every other day, and on the days an older Burn counted, whose
30
+ * sub-agents are in neither count.
31
+ */
32
+ subagents?: number;
33
+ /**
34
+ * On that same day, a sub-agent that ended without finishing (recorded as
35
+ * failed, killed or stopped, never as completed or resumed): 1, with all
36
+ * of its tokens, their priced dollars and its tokens on unpriced models.
37
+ */
38
+ unfinishedSubagents?: number;
39
+ unfinishedTokens?: number;
40
+ unfinishedUsd?: DollarRange;
41
+ unfinishedUnpricedTokens?: number;
27
42
  }
28
43
  export interface CalendarDayData extends CalendarFigures {
29
44
  claudeTokens: number;
@@ -102,6 +117,18 @@ export interface CalendarTotals {
102
117
  heldLaunches: number;
103
118
  claudeTokens: number;
104
119
  codexTokens: number;
120
+ /**
121
+ * Stored sub-agents whose first day with tokens is shown, as this Burn counts
122
+ * them. calendarReport always sets these four; a report an older Burn recorded
123
+ * has none.
124
+ */
125
+ subagents?: number;
126
+ /** Those of them that ended without finishing: recorded as failed, killed or stopped, and never as completed or resumed. */
127
+ unfinishedSubagents?: number;
128
+ /** All of their tokens. */
129
+ unfinishedTokens?: number;
130
+ /** Those tokens at API list price; null when any of them is on a model without a known price. */
131
+ unfinishedUsd?: DollarRange | null;
105
132
  }
106
133
  export interface CalendarReport {
107
134
  /** The Sunday that starts the first week shown. */
@@ -24,6 +24,7 @@ exports.calendarReport = calendarReport;
24
24
  const node_crypto_1 = require("node:crypto");
25
25
  const node_fs_1 = require("node:fs");
26
26
  const node_path_1 = require("node:path");
27
+ const subagent_signals_1 = require("../history/subagent-signals");
27
28
  const history_1 = require("./history");
28
29
  const pricing_1 = require("./pricing");
29
30
  const render_1 = require("./render");
@@ -39,7 +40,8 @@ exports.CALENDAR_MAX_WEEKS = 53;
39
40
  exports.CALENDAR_GRID_PREFIX = Math.max(...Object.values(i18n_1.CALENDAR_TEXT).flatMap(text => text.weekdays.map(label => label.length))) + 1;
40
41
  /** Transcripts larger than this are parsed in pieces (see InsightReadOptions), which bounds memory on a machine of 400 MB sessions. */
41
42
  const CHUNK_BYTES = 16 * 1024 * 1024;
42
- const CACHE_SCHEMA = 3, ROLLUP_SCHEMA = 1;
43
+ /** 4: each transcript's cached counts carry the sub-agent outcomes it records. */
44
+ const CACHE_SCHEMA = 4, ROLLUP_SCHEMA = 1;
43
45
  const sha256 = (text) => (0, node_crypto_1.createHash)('sha256').update(text).digest('hex');
44
46
  const pad = (n) => String(n).padStart(2, '0');
45
47
  /** The local calendar day of an instant, YYYY-MM-DD, in this process's time zone. */
@@ -76,6 +78,8 @@ function transcriptUnits(locations) {
76
78
  }
77
79
  return units.sort((a, b) => a.path < b.path ? -1 : a.path > b.path ? 1 : 0);
78
80
  }
81
+ /** A stored sub-agent's key, `<session>/agent-<id>`: its session and its sub-agent id. */
82
+ const SUBAGENT_KEY = /^([^/]+)\/agent-([A-Za-z0-9][A-Za-z0-9_-]{0,63})$/;
79
83
  /** Parser ids are SHA-256 digests; 64 bits of one tell a machine's responses apart. */
80
84
  const turnKey = (id) => /^[0-9a-f]{64}$/.test(id) ? id.slice(0, 16) : sha256(id).slice(0, 16);
81
85
  const rowTokens = (row) => row[5] + row[6] + row[7] + row[8];
@@ -98,7 +102,9 @@ function readUnit(unit, rates) {
98
102
  turn.inputTokens, turn.cacheWriteTokens, turn.cacheReadTokens, turn.outputTokens,
99
103
  split ? turn.cacheWrite5mTokens : null, split ? turn.cacheWrite1hTokens : null, turn.cacheTtlSeconds ?? null, turn.subagent ? 1 : 0];
100
104
  });
101
- return { host: unit.host, key: unit.key, models, rows, forkUnknown: false };
105
+ const signals = transcript.state.subagentSignals;
106
+ return { host: unit.host, key: unit.key, models, rows, forkUnknown: false,
107
+ ...(signals ? { agents: [Object.keys(signals.completed ?? {}), Object.keys(signals.ended ?? {}), Object.keys(signals.resumed ?? {})] } : {}) };
102
108
  }
103
109
  /**
104
110
  * A cached response as a turn again, for the rare response recorded in more
@@ -142,8 +148,13 @@ const DAY = /^\d{4}-\d{2}-\d{2}$/;
142
148
  function figuresOf(value) {
143
149
  const raw = record(value), usd = record(raw.usd);
144
150
  const models = Array.isArray(raw.unpricedModels) ? raw.unpricedModels.filter((model) => model === null || typeof model === 'string') : [];
151
+ const unfinishedUsd = record(raw.unfinishedUsd);
145
152
  return { tokens: count(raw.tokens), subagentTokens: count(raw.subagentTokens), usd: { min: count(usd.min), max: count(usd.max) },
146
- unpricedTokens: count(raw.unpricedTokens), unpricedModels: models };
153
+ unpricedTokens: count(raw.unpricedTokens), unpricedModels: models,
154
+ // Kept only where a sub-agent's first day carries them; a day an older Burn counted has none.
155
+ ...(raw.subagents !== undefined ? { subagents: count(raw.subagents) } : {}),
156
+ ...(raw.unfinishedSubagents !== undefined ? { unfinishedSubagents: count(raw.unfinishedSubagents), unfinishedTokens: count(raw.unfinishedTokens),
157
+ unfinishedUsd: { min: count(unfinishedUsd.min), max: count(unfinishedUsd.max) }, unfinishedUnpricedTokens: count(raw.unfinishedUnpricedTokens) } : {}) };
147
158
  }
148
159
  /** The daily count on disk. An unreadable file is moved aside, never overwritten, so it can still be recovered. */
149
160
  function readRollup(home) {
@@ -203,7 +214,9 @@ function cacheSignature(rates) {
203
214
  function cachedUnit(value, file) {
204
215
  const unit = record(value);
205
216
  const same = Array.isArray(unit.file) && unit.file.length === 3 && unit.file.every((part, i) => part === file[i]);
206
- return same && typeof unit.key === 'string' && Array.isArray(unit.models) && Array.isArray(unit.rows)
217
+ const agents = unit.agents === undefined || (Array.isArray(unit.agents) && unit.agents.length === 3
218
+ && unit.agents.every(ids => Array.isArray(ids) && ids.every(id => typeof id === 'string')));
219
+ return same && agents && typeof unit.key === 'string' && Array.isArray(unit.models) && Array.isArray(unit.rows)
207
220
  && (unit.host === 'claude' || unit.host === 'codex') && typeof unit.forkUnknown === 'boolean' ? unit : undefined;
208
221
  }
209
222
  /* ----------------------------------------------------------------- ledger */
@@ -317,6 +330,40 @@ function collectCalendar(options) {
317
330
  shared[id] = merged.sessionId;
318
331
  add(merged.sessionId, merged.at ?? null, merged.inputTokens + merged.cacheWriteTokens + merged.cacheReadTokens + merged.outputTokens, merged.subagent === true, (0, pricing_1.priceTurn)(merged, rates).usd, merged.model ?? null);
319
332
  }
333
+ // Each stored sub-agent counts once, on its first day with tokens. Whether it
334
+ // ended without finishing is what its session's transcripts record: the
335
+ // parent's, and those of sub-agents that launched others. One that may still
336
+ // be running, or whose end no transcript records, is never counted as ended.
337
+ const outcomes = new Map();
338
+ for (const entry of loaded) {
339
+ if (!entry.agents)
340
+ continue;
341
+ const session = entry.key.split('/', 1)[0];
342
+ const sets = outcomes.get(session) ?? { completed: new Set(), ended: new Set(), resumed: new Set() };
343
+ const [completed, ended, resumed] = entry.agents;
344
+ for (const id of completed)
345
+ sets.completed.add(id);
346
+ for (const id of ended)
347
+ sets.ended.add(id);
348
+ for (const id of resumed)
349
+ sets.resumed.add(id);
350
+ outcomes.set(session, sets);
351
+ }
352
+ for (const [key, own] of fresh) {
353
+ const match = SUBAGENT_KEY.exec(key), firstDay = Object.keys(own).sort()[0];
354
+ if (!match || firstDay === undefined)
355
+ continue;
356
+ const target = own[firstDay];
357
+ target.subagents = 1;
358
+ const sets = outcomes.get(match[1]);
359
+ if (!sets || !(0, subagent_signals_1.endedWithoutFinishing)(match[2], sets))
360
+ continue;
361
+ const used = Object.values(own);
362
+ target.unfinishedSubagents = 1;
363
+ target.unfinishedTokens = used.reduce((sum, figures) => sum + figures.tokens, 0);
364
+ target.unfinishedUsd = used.reduce((sum, figures) => ({ min: sum.min + figures.usd.min, max: sum.max + figures.usd.max }), { min: 0, max: 0 });
365
+ target.unfinishedUnpricedTokens = used.reduce((sum, figures) => sum + figures.unpricedTokens, 0);
366
+ }
320
367
  // Files on disk replace their own days; files that are gone keep theirs.
321
368
  const files = {};
322
369
  let rollupFiles = 0;
@@ -368,6 +415,14 @@ function collectCalendar(options) {
368
415
  total.claudeTokens += figures.tokens;
369
416
  else
370
417
  total.codexTokens += figures.tokens;
418
+ if (figures.subagents)
419
+ total.subagents = (total.subagents ?? 0) + figures.subagents;
420
+ if (figures.unfinishedSubagents) {
421
+ total.unfinishedSubagents = (total.unfinishedSubagents ?? 0) + figures.unfinishedSubagents;
422
+ total.unfinishedTokens = (total.unfinishedTokens ?? 0) + (figures.unfinishedTokens ?? 0);
423
+ total.unfinishedUsd = { min: (total.unfinishedUsd?.min ?? 0) + (figures.unfinishedUsd?.min ?? 0), max: (total.unfinishedUsd?.max ?? 0) + (figures.unfinishedUsd?.max ?? 0) };
424
+ total.unfinishedUnpricedTokens = (total.unfinishedUnpricedTokens ?? 0) + (figures.unfinishedUnpricedTokens ?? 0);
425
+ }
371
426
  days.set(day, total);
372
427
  }
373
428
  }
@@ -420,10 +475,24 @@ function calendarReport(data, options = {}) {
420
475
  .sort((a, b) => a === b ? 0 : a === null ? 1 : b === null ? -1 : a < b ? -1 : 1);
421
476
  const usd = tokens > 0 && unpricedTokens === tokens ? null : days.reduce((total, day) => ({ min: total.min + day.usd.min, max: total.max + day.usd.max }), { min: 0, max: 0 });
422
477
  const busiest = days.reduce((best, day) => day.tokens > (best?.tokens ?? 0) ? day : best, null);
478
+ // A sub-agent is in the span when its first day is: its count and all of its tokens together.
479
+ const stored = { subagents: 0, unfinishedSubagents: 0, unfinishedTokens: 0, unfinishedUnpricedTokens: 0, unfinishedUsd: { min: 0, max: 0 } };
480
+ for (const day of days) {
481
+ const figures = data.days.get(day.date);
482
+ if (!figures)
483
+ continue;
484
+ stored.subagents += figures.subagents ?? 0;
485
+ stored.unfinishedSubagents += figures.unfinishedSubagents ?? 0;
486
+ stored.unfinishedTokens += figures.unfinishedTokens ?? 0;
487
+ stored.unfinishedUnpricedTokens += figures.unfinishedUnpricedTokens ?? 0;
488
+ stored.unfinishedUsd = { min: stored.unfinishedUsd.min + (figures.unfinishedUsd?.min ?? 0), max: stored.unfinishedUsd.max + (figures.unfinishedUsd?.max ?? 0) };
489
+ }
423
490
  return {
424
491
  from, to: today, weeks, firstRecordedDay: oldest, days,
425
492
  totals: { tokens, subagentTokens, subagentShare: tokens ? subagentTokens / tokens : null, usd, unpricedTokens, unpricedModels,
426
- heldLaunches: sum('heldLaunches'), claudeTokens: sum('claudeTokens'), codexTokens: sum('codexTokens') },
493
+ heldLaunches: sum('heldLaunches'), claudeTokens: sum('claudeTokens'), codexTokens: sum('codexTokens'),
494
+ subagents: stored.subagents, unfinishedSubagents: stored.unfinishedSubagents, unfinishedTokens: stored.unfinishedTokens,
495
+ unfinishedUsd: stored.unfinishedUnpricedTokens > 0 ? null : stored.unfinishedUsd },
427
496
  busiest: busiest ? { date: busiest.date, tokens: busiest.tokens } : null,
428
497
  historyShort: data.claudeSeen && oldest !== null && history < span,
429
498
  sources: data.sources, subagentsIncluded: true, basis: 'estimated_api_list_price',
@@ -51,6 +51,14 @@ export interface WhyText {
51
51
  shares: string;
52
52
  increments: (shared: number, rebaselines: number, priorOutput: string) => string;
53
53
  observed: (calls: InsightObservations) => string;
54
+ /**
55
+ * Sub-agents that ended without finishing (recorded as failed, killed or
56
+ * stopped, never as completed or resumed), out of every sub-agent with a
57
+ * transcript; their tokens, those tokens' share of the session's, and their
58
+ * API list equivalent, null when a model is unpriced. Printed only from 1.
59
+ * Burn knows whether a sub-agent finished, never whether its work was right.
60
+ */
61
+ unfinished: (count: number, total: number, tokens: string, share: string, usd: string | null) => string;
54
62
  methodTitle: string;
55
63
  explicit: string;
56
64
  unpricedModels: (models: string) => string;
@@ -96,12 +104,17 @@ export declare const WHY_TEXT: Readonly<Record<WhyLang, WhyText>>;
96
104
  * The cost of one more sub-agent, for the STOP prompt and box: what this
97
105
  * session's finished sub-agents averaged, a measurement of what already ran and
98
106
  * never a forecast. `count` is at least three; `usd` is null when any of them ran
99
- * on an unpriced model. Every other line of the STOP text is English on every
100
- * host, so the hook asks for English; the Spanish and Portuguese lines are here
101
- * for when the STOP text is translated.
107
+ * on an unpriced model. `unfinished`, when the transcripts record sub-agents
108
+ * that ended without finishing, adds how many and the tokens they used in all;
109
+ * Burn knows they did not finish, never whether any work was right. Every other
110
+ * line of the STOP text is English on every host, so the hook asks for English;
111
+ * the Spanish and Portuguese lines are here for when the STOP text is translated.
102
112
  */
103
113
  export interface DecisionText {
104
- finished: (count: number, tokens: string, usd: string | null) => string;
114
+ finished: (count: number, tokens: string, usd: string | null, unfinished?: {
115
+ count: number;
116
+ tokens: string;
117
+ } | null) => string;
105
118
  }
106
119
  export declare const DECISION_TEXT: Readonly<Record<WhyLang, DecisionText>>;
107
120
  /**
@@ -165,6 +178,12 @@ export interface CalendarText {
165
178
  dollars: (usd: string | null) => string;
166
179
  busiest: (date: string, count: string) => string;
167
180
  subagents: (share: string) => string;
181
+ /**
182
+ * Sub-agents that ended without finishing, out of every sub-agent counted:
183
+ * their tokens, those tokens' share of all tokens, and dollars at API prices,
184
+ * null when a model is unpriced. Printed only from 1.
185
+ */
186
+ unfinished: (count: number, total: number, tokens: string, share: string, usd: string | null) => string;
168
187
  /** Sub-agent launches AgentGuard held (refused, or held for the person's yes); printed only above zero. */
169
188
  held: (launches: number) => string;
170
189
  less: string;
@@ -60,6 +60,7 @@ const en = {
60
60
  shares: 'Token shares partition recorded usage; byte sizes only split measured token increments and are never converted into tokens.',
61
61
  increments: (shared, rebaselines, priorOutput) => `Shared event increments: ${shared}. Prefix rebaselines: ${rebaselines}. Prior output retained in unattributed input: ${priorOutput} tokens.`,
62
62
  observed: calls => `Observed calls: ${calls.readCalls} reads of ${calls.uniqueReadFiles} paths, ${calls.repeatedReadCalls} repeated reads, ${calls.spawnCalls} spawns, ${calls.toolResultRecords} tool results.`,
63
+ unfinished: (count, total, tokens, share, usd) => `Sub-agents that ended without finishing: ${count} of ${total}, ${tokens} tokens (${share} of session tokens${usd === null ? '' : `, ${usd} API list equivalent`}).`,
63
64
  methodTitle: 'Method',
64
65
  explicit: 'Explicit host token attribution takes precedence over the delta method for responses that provide it.',
65
66
  unpricedModels: models => `Tokens only for unpriced models: ${models}. No verified exact model rate is available for at least one token category.`,
@@ -110,6 +111,7 @@ const es = {
110
111
  shares: 'Los porcentajes de tokens reparten el uso registrado; los tamaños en bytes solo dividen incrementos medidos de tokens y nunca se convierten en tokens.',
111
112
  increments: (shared, rebaselines, priorOutput) => `Incrementos compartidos entre eventos: ${shared}. Nuevas líneas base del prefijo: ${rebaselines}. Tokens de salida previa retenidos en la entrada sin atribuir: ${priorOutput}.`,
112
113
  observed: calls => `Llamadas observadas: ${plural(calls.readCalls, 'lectura', 'lecturas')} de ${plural(calls.uniqueReadFiles, 'ruta', 'rutas')}, ${plural(calls.repeatedReadCalls, 'lectura repetida', 'lecturas repetidas')}, ${plural(calls.spawnCalls, 'subagente lanzado', 'subagentes lanzados')}, ${plural(calls.toolResultRecords, 'resultado de herramienta', 'resultados de herramientas')}.`,
114
+ unfinished: (count, total, tokens, share, usd) => `Subagentes que quedaron sin terminar: ${count} de ${total}, ${tokens} tokens (el ${share} de los tokens de la sesión${usd === null ? '' : `, ${usd} equivalente a precio de lista de la API`}).`,
113
115
  methodTitle: 'Método',
114
116
  explicit: 'La atribución explícita de tokens que informa el host tiene prioridad sobre el método de deltas en las respuestas que la incluyen.',
115
117
  unpricedModels: models => `Modelos sin precio (solo tokens): ${models}. No hay una tarifa exacta verificada para al menos una categoría de tokens.`,
@@ -160,6 +162,7 @@ const pt = {
160
162
  shares: 'As porcentagens de tokens repartem o uso registrado; os tamanhos em bytes apenas dividem incrementos medidos de tokens e nunca são convertidos em tokens.',
161
163
  increments: (shared, rebaselines, priorOutput) => `Incrementos compartilhados entre eventos: ${shared}. Novas linhas de base do prefixo: ${rebaselines}. Tokens de saída anterior retidos na entrada não atribuída: ${priorOutput}.`,
162
164
  observed: calls => `Chamadas observadas: ${plural(calls.readCalls, 'leitura', 'leituras')} de ${plural(calls.uniqueReadFiles, 'caminho', 'caminhos')}, ${plural(calls.repeatedReadCalls, 'leitura repetida', 'leituras repetidas')}, ${plural(calls.spawnCalls, 'subagente iniciado', 'subagentes iniciados')}, ${plural(calls.toolResultRecords, 'resultado de ferramenta', 'resultados de ferramentas')}.`,
165
+ unfinished: (count, total, tokens, share, usd) => `Subagentes que pararam sem terminar: ${count} de ${total}, ${tokens} tokens (${share} dos tokens da sessão${usd === null ? '' : `, ${usd} equivalente ao preço de tabela da API`}).`,
163
166
  methodTitle: 'Método',
164
167
  explicit: 'A atribuição explícita de tokens informada pelo host tem prioridade sobre o método de deltas nas respostas que a incluem.',
165
168
  unpricedModels: models => `Modelos sem preço (apenas tokens): ${models}. Não há tarifa exata verificada para pelo menos uma categoria de tokens.`,
@@ -184,9 +187,9 @@ const pt = {
184
187
  };
185
188
  exports.WHY_TEXT = { en, es, pt };
186
189
  exports.DECISION_TEXT = {
187
- en: { finished: (count, tokens, usd) => `The ${count} sub-agents that finished in this session averaged ${tokens} tokens each${usd ? ` (${usd} at API prices, not a bill)` : ''}. This one could differ.` },
188
- es: { finished: (count, tokens, usd) => `Los ${count} subagentes que terminaron en esta sesión promediaron ${tokens} tokens cada uno${usd ? ` (${usd} a precios de la API, no una factura)` : ''}. Este podría ser distinto.` },
189
- pt: { finished: (count, tokens, usd) => `Os ${count} subagentes que terminaram nesta sessão usaram em média ${tokens} tokens cada${usd ? ` (${usd} a preços da API, não uma fatura)` : ''}. Este pode ser diferente.` },
190
+ en: { finished: (count, tokens, usd, unfinished) => `The ${count} sub-agents that finished in this session averaged ${tokens} tokens each${usd ? ` (${usd} at API prices, not a bill)` : ''}.${!unfinished ? '' : unfinished.count === 1 ? ` 1 more ended without finishing and used ${unfinished.tokens} tokens.` : ` ${unfinished.count} more ended without finishing and used ${unfinished.tokens} tokens in total.`} This one could differ.` },
191
+ es: { finished: (count, tokens, usd, unfinished) => `Los ${count} subagentes que terminaron en esta sesión promediaron ${tokens} tokens cada uno${usd ? ` (${usd} a precios de la API, no una factura)` : ''}.${!unfinished ? '' : unfinished.count === 1 ? ` Otro quedó sin terminar y usó ${unfinished.tokens} tokens.` : ` Otros ${unfinished.count} quedaron sin terminar y usaron ${unfinished.tokens} tokens en total.`} Este podría ser distinto.` },
192
+ pt: { finished: (count, tokens, usd, unfinished) => `Os ${count} subagentes que terminaram nesta sessão usaram em média ${tokens} tokens cada${usd ? ` (${usd} a preços da API, não uma fatura)` : ''}.${!unfinished ? '' : unfinished.count === 1 ? ` Outro parou sem terminar e usou ${unfinished.tokens} tokens.` : ` Outros ${unfinished.count} pararam sem terminar e usaram ${unfinished.tokens} tokens no total.`} Este pode ser diferente.` },
190
193
  };
191
194
  const TWO_IDS = 'agentguard-burn compare SESSION_A SESSION_B';
192
195
  const compareEn = {
@@ -274,6 +277,7 @@ const calendarEn = {
274
277
  dollars: usd => usd === null ? 'no dollar total: no known API price for these models' : `${usd} at API prices, not a bill`,
275
278
  busiest: (date, count) => `busiest day: ${date} (${count} ${count === '1' ? 'token' : 'tokens'})`,
276
279
  subagents: share => `sub-agents used ${share} of tokens`,
280
+ unfinished: (count, total, tokens, share, usd) => `${count} of ${total} ${total === 1 ? 'sub-agent' : 'sub-agents'} ended without finishing (${tokens} ${tokens === '1' ? 'token' : 'tokens'}, ${share} of tokens${usd === null ? '' : `, ${usd} at API prices`})`,
277
281
  held: launches => `AgentGuard held ${launches} ${launches === 1 ? 'launch' : 'launches'}`,
278
282
  less: 'Less',
279
283
  more: 'More',
@@ -305,6 +309,7 @@ const calendarEs = {
305
309
  dollars: usd => usd === null ? 'sin total en dólares: no se conoce el precio de la API de estos modelos' : `${usd} a precios de la API, no es una factura`,
306
310
  busiest: (date, count) => `día con más tokens: ${date} (${count})`,
307
311
  subagents: share => `los subagentes usaron el ${share} de los tokens`,
312
+ unfinished: (count, total, tokens, share, usd) => `${count} de ${total} ${total === 1 ? 'subagente' : 'subagentes'} ${count === 1 ? 'quedó' : 'quedaron'} sin terminar (${tokens} ${tokens === '1' ? 'token' : 'tokens'}, el ${share} de los tokens${usd === null ? '' : `, ${usd} a precios de la API`})`,
308
313
  held: launches => launches === 1 ? 'AgentGuard retuvo 1 lanzamiento' : `AgentGuard retuvo ${launches} lanzamientos`,
309
314
  less: 'Menos',
310
315
  more: 'Más',
@@ -335,6 +340,7 @@ const calendarPt = {
335
340
  dollars: usd => usd === null ? 'sem total em dólares: o preço da API destes modelos não é conhecido' : `${usd} a preços da API, não é uma fatura`,
336
341
  busiest: (date, count) => `dia com mais tokens: ${date} (${count})`,
337
342
  subagents: share => `os subagentes usaram ${share} dos tokens`,
343
+ unfinished: (count, total, tokens, share, usd) => `${count} de ${total} ${total === 1 ? 'subagente' : 'subagentes'} ${count === 1 ? 'parou' : 'pararam'} sem terminar (${tokens} ${tokens === '1' ? 'token' : 'tokens'}, ${share} dos tokens${usd === null ? '' : `, ${usd} a preços da API`})`,
338
344
  held: launches => launches === 1 ? 'o AgentGuard reteve 1 lançamento' : `o AgentGuard reteve ${launches} lançamentos`,
339
345
  less: 'Menos',
340
346
  more: 'Mais',
@@ -99,6 +99,25 @@ export declare function whyTipInput(figures: Pick<SessionFigures, 'turns' | 'att
99
99
  * caller decides whether to show it.
100
100
  */
101
101
  export declare function whyTipLine(transcript: InsightTranscript, rates?: PricingTable, lang?: WhyLang, context?: TipContext): string | null;
102
+ /** The sub-agents of one session that ended without finishing, and what they used. */
103
+ export interface UnfinishedSubagents {
104
+ count: number;
105
+ /** Every sub-agent with a transcript in the session's `subagents` folder. */
106
+ total: number;
107
+ /** Their responses' tokens, counted once as everywhere in `why`. */
108
+ tokens: number;
109
+ /** Those tokens' API list equivalent; null when any of them is on an unpriced model. */
110
+ usd: DollarRange | null;
111
+ }
112
+ /**
113
+ * The session's sub-agents that ended without finishing: recorded as failed,
114
+ * killed or stopped, and never as completed or resumed. One that may still be
115
+ * running, or whose end no transcript records, is never counted. Their tokens
116
+ * are their own transcripts' responses after the same de-duplication the table
117
+ * uses. Null when there are none, and for a transcript read without its
118
+ * sub-agents.
119
+ */
120
+ export declare function unfinishedSubagents(transcript: Pick<InsightTranscript, 'subagents'>, figures: Pick<SessionFigures, 'turns' | 'prices'>): UnfinishedSubagents | null;
102
121
  /** Messages on each side of an event the measured change compares, at most and at least. */
103
122
  export declare const PROOF_WINDOW = 20;
104
123
  export declare const PROOF_MINIMUM = 5;
@@ -9,12 +9,14 @@ exports.modelLabel = modelLabel;
9
9
  exports.whyTip = whyTip;
10
10
  exports.whyTipInput = whyTipInput;
11
11
  exports.whyTipLine = whyTipLine;
12
+ exports.unfinishedSubagents = unfinishedSubagents;
12
13
  exports.proofLine = proofLine;
13
14
  exports.renderWhy = renderWhy;
14
15
  exports.rewriteReport = rewriteReport;
15
16
  exports.rewriteReportJson = rewriteReportJson;
16
17
  exports.renderRewrites = renderRewrites;
17
18
  exports.renderPricing = renderPricing;
19
+ const subagent_signals_1 = require("../history/subagent-signals");
18
20
  const attribution_1 = require("./attribution");
19
21
  const pricing_1 = require("./pricing");
20
22
  const live_1 = require("./live");
@@ -218,6 +220,32 @@ const figuresTip = (figures, rates, lang, context = 'why') => whyTip(whyTipInput
218
220
  function whyTipLine(transcript, rates = {}, lang = 'en', context = 'why') {
219
221
  return transcript.state.forkHistoryBoundaryUnknown ? null : figuresTip(sessionFigures(transcript, rates), rates, lang, context);
220
222
  }
223
+ /**
224
+ * The session's sub-agents that ended without finishing: recorded as failed,
225
+ * killed or stopped, and never as completed or resumed. One that may still be
226
+ * running, or whose end no transcript records, is never counted. Their tokens
227
+ * are their own transcripts' responses after the same de-duplication the table
228
+ * uses. Null when there are none, and for a transcript read without its
229
+ * sub-agents.
230
+ */
231
+ function unfinishedSubagents(transcript, figures) {
232
+ const outcome = transcript.subagents;
233
+ if (!outcome?.ended.length)
234
+ return null;
235
+ const sets = { completed: new Set(outcome.completed), ended: new Set(outcome.ended), resumed: new Set(outcome.resumed) };
236
+ const unfinished = new Set(outcome.ids.filter(id => (0, subagent_signals_1.endedWithoutFinishing)(id, sets)).map(id => `agent-${id}`));
237
+ if (!unfinished.size)
238
+ return null;
239
+ let tokens = 0;
240
+ const prices = [];
241
+ figures.turns.forEach((turn, i) => {
242
+ if (!turn.subagent || !unfinished.has(turn.sessionId))
243
+ return;
244
+ tokens += totalTokens(turn);
245
+ prices.push(figures.prices[i].usd);
246
+ });
247
+ return { count: unfinished.size, total: outcome.ids.length, tokens, usd: sumPrices(prices) };
248
+ }
221
249
  /** Messages on each side of an event the measured change compares, at most and at least. */
222
250
  exports.PROOF_WINDOW = 20;
223
251
  exports.PROOF_MINIMUM = 5;
@@ -281,8 +309,9 @@ function renderWhy(transcript, rates = {}, options = {}) {
281
309
  });
282
310
  const unknownModels = [...new Set(prices.filter(price => price.usd === null).map(price => price.model ?? text.missingModel))];
283
311
  const tip = options.tips ? figuresTip(figures, rates, lang) : null;
284
- // A measurement, not a tip: it prints whether or not tips are on.
312
+ // Measurements, not tips: they print whether or not tips are on.
285
313
  const proof = proofLine(turns, lang);
314
+ const unfinished = unfinishedSubagents(transcript, figures);
286
315
  return [
287
316
  `AgentGuard why: ${transcript.sessionId}`,
288
317
  text.summary(turns.length, (0, exports.count)(attribution.totalTokens), totalUsd === null ? null : money(totalUsd)),
@@ -291,6 +320,7 @@ function renderWhy(transcript, rates = {}, options = {}) {
291
320
  text.shares,
292
321
  text.increments(attribution.sharedTurns, attribution.prefixRebaselines, (0, exports.count)(attribution.previousOutputTokensReserved)),
293
322
  text.observed(transcript.observations),
323
+ ...(unfinished ? [text.unfinished(unfinished.count, unfinished.total, (0, exports.count)(unfinished.tokens), (0, exports.share)(unfinished.tokens, attribution.totalTokens), unfinished.usd === null ? null : money(unfinished.usd))] : []),
294
324
  '', text.methodTitle,
295
325
  ...types_1.INSIGHT_BUCKETS.map(bucket => `${text.labels[bucket]}: ${text.method[bucket]}`),
296
326
  ...(turns.some(turn => turn.explicitAttribution.length > 0) ? [text.explicit] : []),
@@ -14,10 +14,20 @@ export interface InsightReadOptions {
14
14
  * parsed with the parser state the previous piece returned, so no single string
15
15
  * holds the whole file (V8 cannot hold a string past about 512 MB). The turns,
16
16
  * observations and summed diagnostics equal a whole-file parse. Unset reads the
17
- * whole file at once, as `why` does.
17
+ * whole file at once, as `why` does, unless the file is over
18
+ * WHOLE_FILE_MAX_BYTES: then it is read in pieces all the same.
18
19
  */
19
20
  chunkBytes?: number;
21
+ /** Tests only: the size above which a read with no chunkBytes still goes in pieces. */
22
+ wholeFileMaxBytes?: number;
20
23
  }
24
+ /**
25
+ * Above this size a whole-file read could pass V8's string limit, so the file is
26
+ * read in pieces even when no chunk size was asked for. Such a session is rare
27
+ * but real: one long-running Claude Code session reached 568 MB, and `why` on
28
+ * it stopped with "Cannot create a string longer than 0x1fffffe8 characters".
29
+ */
30
+ export declare const WHOLE_FILE_MAX_BYTES: number;
21
31
  export declare function readInsightTranscript(filename: string, options?: InsightParseOptions, read?: InsightReadOptions): InsightTranscript;
22
32
  /** Read one Claude session plus its explicitly stored child transcripts. */
23
33
  export declare function readInsightSession(filename: string, options?: InsightParseOptions, read?: InsightReadOptions): InsightTranscript;
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.providerResponseIdentity = void 0;
3
+ exports.WHOLE_FILE_MAX_BYTES = exports.providerResponseIdentity = void 0;
4
4
  exports.parseInsightTranscript = parseInsightTranscript;
5
5
  exports.readInsightTranscript = readInsightTranscript;
6
6
  exports.readInsightSession = readInsightSession;
@@ -8,6 +8,7 @@ exports.deduplicateTurns = deduplicateTurns;
8
8
  const node_crypto_1 = require("node:crypto");
9
9
  const node_fs_1 = require("node:fs");
10
10
  const node_path_1 = require("node:path");
11
+ const subagent_signals_1 = require("../history/subagent-signals");
11
12
  const object = (value) => value !== null && typeof value === 'object' && !Array.isArray(value) ? value : {};
12
13
  const count = (value) => typeof value === 'number' && Number.isSafeInteger(value) && value >= 0 ? value : 0;
13
14
  const hasCount = (value) => typeof value === 'number' && Number.isSafeInteger(value) && value >= 0;
@@ -160,6 +161,16 @@ function observeImageBlocks(raw, state) {
160
161
  state.imagesDroppedPending = (state.imagesDroppedPending ?? 0) + (previous - current);
161
162
  state.imageBlocksByMessage[key] = current;
162
163
  }
164
+ /**
165
+ * How sub-agents ended, as this record states it: completed, ended without
166
+ * finishing, or resumed (subagentSignals, the reader the hook uses too). Only
167
+ * ids are kept, and the state gains the field at the first such record, so a
168
+ * transcript without one parses to the same state as before.
169
+ */
170
+ function observeSubagentSignals(raw, state) {
171
+ for (const [signal, id] of (0, subagent_signals_1.subagentSignals)(raw))
172
+ ((state.subagentSignals ??= {})[signal] ??= {})[id] = true;
173
+ }
163
174
  /** A /clear that Claude Code wrote into this transcript as a command record. Only the command name is matched; nothing of the message is kept. */
164
175
  function isClearCommand(content) {
165
176
  const texts = typeof content === 'string' ? [content]
@@ -360,6 +371,7 @@ function parseInsightTranscript(text, options = {}) {
360
371
  observeTools(raw, state);
361
372
  observeInputEvents(raw, state);
362
373
  observeImageBlocks(raw, state);
374
+ observeSubagentSignals(raw, state);
363
375
  if (identifier(raw.version) && /^\d+\.\d+/.test(String(raw.version)))
364
376
  state.hostVersion = identifier(raw.version);
365
377
  const host = detectHost(raw, usage, state.host);
@@ -516,11 +528,23 @@ function parseInsightTranscript(text, options = {}) {
516
528
  return { host: state.host, sessionId: state.sessionId, turns: Object.values(state.seen), updatedTurns: [...updated.values()], diagnostics, state,
517
529
  observations: observations(state.observedCalls ?? {}), acceptedQuotaLineNumbers };
518
530
  }
531
+ /**
532
+ * Above this size a whole-file read could pass V8's string limit, so the file is
533
+ * read in pieces even when no chunk size was asked for. Such a session is rare
534
+ * but real: one long-running Claude Code session reached 568 MB, and `why` on
535
+ * it stopped with "Cannot create a string longer than 0x1fffffe8 characters".
536
+ */
537
+ exports.WHOLE_FILE_MAX_BYTES = 256 * 1024 * 1024;
538
+ const LARGE_FILE_CHUNK_BYTES = 16 * 1024 * 1024;
519
539
  const DIAGNOSTIC_KEYS = ['lines', 'malformedLines', 'duplicateUsageRecords', 'unsupportedUsageRecords', 'inheritedUsageRecords'];
520
540
  function parseFile(filename, options, read) {
521
- const limit = read.chunkBytes;
522
- if (!limit || !(limit > 0))
523
- return parseInsightTranscript((0, node_fs_1.readFileSync)(filename, 'utf8'), options);
541
+ let limit = read.chunkBytes;
542
+ if (!limit || !(limit > 0)) {
543
+ const max = read.wholeFileMaxBytes ?? exports.WHOLE_FILE_MAX_BYTES;
544
+ if ((0, node_fs_1.statSync)(filename).size <= max)
545
+ return parseInsightTranscript((0, node_fs_1.readFileSync)(filename, 'utf8'), options);
546
+ limit = Math.min(LARGE_FILE_CHUNK_BYTES, max);
547
+ }
524
548
  const fd = (0, node_fs_1.openSync)(filename, 'r');
525
549
  try {
526
550
  if ((0, node_fs_1.fstatSync)(fd).size <= limit)
@@ -569,6 +593,13 @@ function readInsightSession(filename, options = {}, read = {}) {
569
593
  }
570
594
  const calls = { ...parent.state.observedCalls };
571
595
  const turns = [...parent.turns];
596
+ const ids = [], outcomes = { completed: new Set(), ended: new Set(), resumed: new Set() };
597
+ const addOutcomes = (state) => {
598
+ for (const signal of ['completed', 'ended', 'resumed'])
599
+ for (const id of Object.keys(state.subagentSignals?.[signal] ?? {}))
600
+ outcomes[signal].add(id);
601
+ };
602
+ addOutcomes(parent.state);
572
603
  for (const name of files) {
573
604
  const child = readInsightTranscript((0, node_path_1.join)(childDirectory, name), { host: options.host, spawnedSession: true }, read);
574
605
  const known = new Set(turns.map(turn => turn.id));
@@ -581,12 +612,19 @@ function readInsightSession(filename, options = {}, read = {}) {
581
612
  Object.assign(calls, child.state.observedCalls);
582
613
  for (const key of ['lines', 'malformedLines', 'duplicateUsageRecords', 'unsupportedUsageRecords'])
583
614
  parent.diagnostics[key] += child.diagnostics[key];
615
+ // A sub-agent's own sub-agents report how they ended in its transcript.
616
+ addOutcomes(child.state);
617
+ const id = subagent_signals_1.SUBAGENT_FILE.exec(name)?.[1];
618
+ if (id)
619
+ ids.push(id);
584
620
  }
585
621
  // State remains the parent's cursor state; recursive session reads are for
586
622
  // reporting. Incremental hooks call parseInsightTranscript on one file.
587
623
  parent.turns = deduplicateTurns(turns);
588
624
  parent.updatedTurns = parent.turns;
589
625
  parent.observations = observations(calls);
626
+ if (ids.length)
627
+ parent.subagents = { ids, completed: [...outcomes.completed], ended: [...outcomes.ended], resumed: [...outcomes.resumed] };
590
628
  return parent;
591
629
  }
592
630
  /** Forked transcript copies can repeat provider response ids across files. */
@@ -132,6 +132,24 @@ export interface InsightParserState {
132
132
  imagesDroppedPending?: number;
133
133
  /** A compaction or /clear seen since the last usage turn, handed to the next one. */
134
134
  pendingReset?: InsightReset;
135
+ /**
136
+ * Sub-agent ids this transcript records as completed, as ended without
137
+ * finishing (failed, killed or stopped) or as resumed (subagentSignals);
138
+ * absent until the first such record. Ids only.
139
+ */
140
+ subagentSignals?: Partial<Record<'completed' | 'ended' | 'resumed', Record<string, true>>>;
141
+ }
142
+ /**
143
+ * A Claude Code session read with its `subagents` folder: the id of each
144
+ * sub-agent with a transcript there (`agent-<id>.jsonl`), and every id the
145
+ * session's transcripts (the parent's and each sub-agent's) record as completed,
146
+ * ended without finishing or resumed. Ids only.
147
+ */
148
+ export interface InsightSubagents {
149
+ ids: string[];
150
+ completed: string[];
151
+ ended: string[];
152
+ resumed: string[];
135
153
  }
136
154
  export interface InsightObservations {
137
155
  readCalls: number;
@@ -151,6 +169,8 @@ export interface InsightTranscript {
151
169
  observations: InsightObservations;
152
170
  /** Zero-based line indexes in this parsed chunk, after fork ownership checks. */
153
171
  acceptedQuotaLineNumbers?: number[];
172
+ /** Set by readInsightSession when the session has sub-agent transcripts. */
173
+ subagents?: InsightSubagents;
154
174
  }
155
175
  export interface InsightParseOptions {
156
176
  host?: InsightHost;
@@ -1,12 +1,14 @@
1
1
  /**
2
2
  * The cost of one more sub-agent, at the decision: what this session's own
3
- * finished sub-agents averaged, for the STOP prompt and box.
3
+ * finished sub-agents averaged, and what the ones that ended without finishing
4
+ * used, for the STOP prompt and box.
4
5
  *
5
6
  * Everything comes from state the Claude Code hook already keeps. While the hook
6
7
  * reads each child transcript's new bytes (as it always has, for the session
7
- * totals) it adds that child's usage up by model, and while it reads the parent
8
- * transcript it notes which sub-agents Claude Code records as completed. Nothing
9
- * here opens a transcript, so the line costs the hook no extra read.
8
+ * totals) it adds that child's usage up by model, and while it reads the
9
+ * transcripts it notes which sub-agents Claude Code records as completed, as
10
+ * ended without finishing, or as resumed. Nothing here opens a transcript, so
11
+ * the line costs the hook no extra read.
10
12
  */
11
13
  import type { ReaderCursor } from './history/claude-transcript';
12
14
  import { type WhyLang } from './insights/i18n';
@@ -21,20 +23,35 @@ export interface FinishedSubagents {
21
23
  meanTokens: number;
22
24
  /** Mean API list-price equivalent per finished sub-agent; null when any of them has an unpriced model. */
23
25
  meanUsd: DollarRange | null;
26
+ /**
27
+ * Sub-agents that ended without finishing, measured the same way, and the
28
+ * tokens they used in all: recorded as failed, killed or stopped, and never as
29
+ * completed or resumed. Absent when there are none: a sub-agent that may still
30
+ * be running is never counted.
31
+ */
32
+ unfinished?: {
33
+ count: number;
34
+ tokens: number;
35
+ };
24
36
  }
37
+ /** The cursor fields the summary reads; the outcome sets are optional, so a cursor saved by an older Burn still works. */
38
+ export type SubagentCursor = Pick<ReaderCursor, 'children' | 'completed' | 'ended' | 'resumed'>;
25
39
  /**
26
40
  * The sub-agents a session's transcripts record as completed (Claude Code's
27
41
  * `agent-<id>.jsonl` children), each measured from its first byte; null when
28
42
  * fewer than three qualify. A child an older Burn had already read part of has
29
43
  * no measurement and is left out rather than undercounted. `priced` false
30
- * leaves the dollars out.
44
+ * leaves the dollars out. With the summary come the sub-agents that ended
45
+ * without finishing, measured the same way, when there are any.
31
46
  */
32
- export declare function finishedSubagents(cursor: Pick<ReaderCursor, 'children' | 'completed'>, rates?: PricingTable, priced?: boolean): FinishedSubagents | null;
47
+ export declare function finishedSubagents(cursor: SubagentCursor, rates?: PricingTable, priced?: boolean): FinishedSubagents | null;
33
48
  /**
34
49
  * "The 15 sub-agents that finished in this session averaged 10.0M tokens each
35
- * ($4.99 at API prices, not a bill). This one could differ." A measured average
36
- * of what already ran, never a forecast; null without a summary. The STOP text
37
- * is English on every host, so the hook passes 'en'.
50
+ * ($4.99 at API prices, not a bill). 2 more ended without finishing and used
51
+ * 3.1M tokens in total. This one could differ." A measurement of what already
52
+ * ran, never a forecast; the middle sentence only when the transcripts record a
53
+ * sub-agent ending without finishing. Null without a summary. The STOP text is
54
+ * English on every host, so the hook passes 'en'.
38
55
  */
39
56
  export declare function subagentCostLine(summary: FinishedSubagents | null, lang?: WhyLang): string | null;
40
57
  /**
@@ -46,4 +63,4 @@ export declare function subagentCostLine(summary: FinishedSubagents | null, lang
46
63
  * dollars, and nothing here throws, so it can never turn a prompt into a
47
64
  * failed-closed refusal.
48
65
  */
49
- export declare function decisionCostLine(cursor: Pick<ReaderCursor, 'children' | 'completed'>, home: string, policy?: Policy): string | null;
66
+ export declare function decisionCostLine(cursor: SubagentCursor, home: string, policy?: Policy): string | null;
@@ -4,6 +4,7 @@ exports.MIN_FINISHED_SUBAGENTS = void 0;
4
4
  exports.finishedSubagents = finishedSubagents;
5
5
  exports.subagentCostLine = subagentCostLine;
6
6
  exports.decisionCostLine = decisionCostLine;
7
+ const subagent_signals_1 = require("./history/subagent-signals");
7
8
  const i18n_1 = require("./insights/i18n");
8
9
  const live_1 = require("./insights/live");
9
10
  const pricing_1 = require("./insights/pricing");
@@ -29,21 +30,29 @@ function childUsd(usage, rates) {
29
30
  * `agent-<id>.jsonl` children), each measured from its first byte; null when
30
31
  * fewer than three qualify. A child an older Burn had already read part of has
31
32
  * no measurement and is left out rather than undercounted. `priced` false
32
- * leaves the dollars out.
33
+ * leaves the dollars out. With the summary come the sub-agents that ended
34
+ * without finishing, measured the same way, when there are any.
33
35
  */
34
36
  function finishedSubagents(cursor, rates = {}, priced = true) {
35
37
  if (!cursor.completed?.size || !cursor.children?.size)
36
38
  return null;
37
39
  const rows = [];
40
+ const unfinished = { count: 0, tokens: 0 };
38
41
  for (const [name, child] of cursor.children) {
39
- const id = /^agent-([A-Za-z0-9_-]{1,64})\.jsonl$/.exec(name)?.[1];
40
- if (!id || !cursor.completed.has(id) || !child.usage)
42
+ const id = subagent_signals_1.SUBAGENT_FILE.exec(name)?.[1];
43
+ if (!id || !child.usage)
41
44
  continue;
42
45
  let tokens = 0;
43
46
  for (const [input, output, write, read] of child.usage.values())
44
47
  tokens += input + output + write + read;
45
- if (tokens > 0)
46
- rows.push({ tokens, usd: priced ? childUsd(child.usage, rates) : null });
48
+ if (cursor.completed.has(id)) {
49
+ if (tokens > 0)
50
+ rows.push({ tokens, usd: priced ? childUsd(child.usage, rates) : null });
51
+ }
52
+ else if ((0, subagent_signals_1.endedWithoutFinishing)(id, cursor)) {
53
+ unfinished.count++;
54
+ unfinished.tokens += tokens;
55
+ }
47
56
  }
48
57
  if (rows.length < exports.MIN_FINISHED_SUBAGENTS)
49
58
  return null;
@@ -51,18 +60,20 @@ function finishedSubagents(cursor, rates = {}, priced = true) {
51
60
  const meanUsd = rows.every(row => row.usd !== null)
52
61
  ? { min: rows.reduce((sum, row) => sum + row.usd.min, 0) / count, max: rows.reduce((sum, row) => sum + row.usd.max, 0) / count }
53
62
  : null;
54
- return { count, meanTokens: rows.reduce((sum, row) => sum + row.tokens, 0) / count, meanUsd };
63
+ return { count, meanTokens: rows.reduce((sum, row) => sum + row.tokens, 0) / count, meanUsd, ...(unfinished.count ? { unfinished } : {}) };
55
64
  }
56
65
  /**
57
66
  * "The 15 sub-agents that finished in this session averaged 10.0M tokens each
58
- * ($4.99 at API prices, not a bill). This one could differ." A measured average
59
- * of what already ran, never a forecast; null without a summary. The STOP text
60
- * is English on every host, so the hook passes 'en'.
67
+ * ($4.99 at API prices, not a bill). 2 more ended without finishing and used
68
+ * 3.1M tokens in total. This one could differ." A measurement of what already
69
+ * ran, never a forecast; the middle sentence only when the transcripts record a
70
+ * sub-agent ending without finishing. Null without a summary. The STOP text is
71
+ * English on every host, so the hook passes 'en'.
61
72
  */
62
73
  function subagentCostLine(summary, lang = 'en') {
63
74
  if (!summary)
64
75
  return null;
65
- return i18n_1.DECISION_TEXT[lang].finished(summary.count, (0, stop_text_1.shortTokens)(summary.meanTokens), summary.meanUsd ? (0, live_1.dollars)(summary.meanUsd, i18n_1.WHY_TEXT[lang]) : null);
76
+ return i18n_1.DECISION_TEXT[lang].finished(summary.count, (0, stop_text_1.shortTokens)(summary.meanTokens), summary.meanUsd ? (0, live_1.dollars)(summary.meanUsd, i18n_1.WHY_TEXT[lang]) : null, summary.unfinished?.count ? { count: summary.unfinished.count, tokens: (0, stop_text_1.shortTokens)(summary.unfinished.tokens) } : null);
66
77
  }
67
78
  /**
68
79
  * The line a STOP prints, exactly as Burn's own Claude Code hook prints it: the
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@agentguard-run/burn",
3
- "version": "0.3.25",
3
+ "version": "0.3.27",
4
4
  "description": "Local session usage and runaway-agent circuit breaker. Explain tokens, cache rewrites and API list cost, track pace, warn on heavy turns, and gate agent fan-out with signed receipts. Developer command ranking requires explicit --rank.",
5
5
  "license": "SEE LICENSE IN LICENSE",
6
6
  "homepage": "https://agentguard.run/burn",