@agentguard-run/burn 0.3.24 → 0.3.26

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.
@@ -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);
@@ -569,6 +581,13 @@ function readInsightSession(filename, options = {}, read = {}) {
569
581
  }
570
582
  const calls = { ...parent.state.observedCalls };
571
583
  const turns = [...parent.turns];
584
+ const ids = [], outcomes = { completed: new Set(), ended: new Set(), resumed: new Set() };
585
+ const addOutcomes = (state) => {
586
+ for (const signal of ['completed', 'ended', 'resumed'])
587
+ for (const id of Object.keys(state.subagentSignals?.[signal] ?? {}))
588
+ outcomes[signal].add(id);
589
+ };
590
+ addOutcomes(parent.state);
572
591
  for (const name of files) {
573
592
  const child = readInsightTranscript((0, node_path_1.join)(childDirectory, name), { host: options.host, spawnedSession: true }, read);
574
593
  const known = new Set(turns.map(turn => turn.id));
@@ -581,12 +600,19 @@ function readInsightSession(filename, options = {}, read = {}) {
581
600
  Object.assign(calls, child.state.observedCalls);
582
601
  for (const key of ['lines', 'malformedLines', 'duplicateUsageRecords', 'unsupportedUsageRecords'])
583
602
  parent.diagnostics[key] += child.diagnostics[key];
603
+ // A sub-agent's own sub-agents report how they ended in its transcript.
604
+ addOutcomes(child.state);
605
+ const id = subagent_signals_1.SUBAGENT_FILE.exec(name)?.[1];
606
+ if (id)
607
+ ids.push(id);
584
608
  }
585
609
  // State remains the parent's cursor state; recursive session reads are for
586
610
  // reporting. Incremental hooks call parseInsightTranscript on one file.
587
611
  parent.turns = deduplicateTurns(turns);
588
612
  parent.updatedTurns = parent.turns;
589
613
  parent.observations = observations(calls);
614
+ if (ids.length)
615
+ parent.subagents = { ids, completed: [...outcomes.completed], ended: [...outcomes.ended], resumed: [...outcomes.resumed] };
590
616
  return parent;
591
617
  }
592
618
  /** 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.24",
3
+ "version": "0.3.26",
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",