@agentguard-run/burn 0.3.20 → 0.3.21

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,24 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.3.21 (2026-09-27)
4
+
5
+ - `calendar` draws big days whenever the span fits: two characters a day and one space between weeks, which reads as roughly square, instead of one small square. That takes the weekday labels plus three columns a week (25 weeks fit 80 columns, 39 fit 120, all 53 fit 162), measured against the terminal's width, or 80 columns when piped. A span that does not fit keeps the 0.3.20 one-character days, whether a long history at 80 columns or a `--weeks` span wider than the terminal; the span itself never shrinks to make the days bigger, so `calendar json` is unchanged. Month names sit over the wider columns, and the Less to More scale uses the same cells.
6
+ - In colour a big day is `▇▇`, the seven-eighths block, so the days of a week stay apart: terminals draw a full block to the full line height, which joined a week of `██` into one bar. Piped, with `--no-color` or `NO_COLOR`, a big day is a shade pair (`·· ░░ ▒▒ ▓▓ ██`). A marked big day keeps its shade in the left half and shows its mark in the right (`▓s`, `█H`, or the red diamond beside the day's colour), so the heat still reads on a day with sub-agents or a held launch.
7
+ - The summary is three short lines at any width: tokens and dollars; the busiest day and the sub-agent share; `AgentGuard held N launches` only when N is above zero. 0.3.20 joined the items while they fit, so a wide terminal got them all on one line of up to about 180 characters. On a narrow terminal a line's two items take a line each.
8
+ - A month name over the last week no longer runs past the terminal's width: it is left out when it would wrap the row. In 0.3.20 a Portuguese calendar of 38 weeks at 80 columns reached 81 columns whenever the current week began a month.
9
+ - Other Claude Code hooks, such as the AgentGuard plugin, can now count a session the way Burn's own hook does. The package exports what that hook uses:
10
+ - `readSessionIncremental(transcriptPath, cursor)` reads the session's transcript and every sub-agent transcript in its `subagents` folder, each from where it stopped last time, and returns the same events Burn's hook adds up, sub-agent usage included. A sub-agent's own launches and file reads are left out, as in Burn's hook.
11
+ - `saveReaderCursor`, `restoreReaderCursor` and `cloneReaderCursor` keep that cursor between calls as JSON, so a later call, or a restarted process, reads 0 bytes of files that did not change. Reading into a copy lets a hook keep the old cursor until it has stored what it read. A cursor saved from `readIncremental` alone picks up the session transcript where it stopped and reads each sub-agent transcript once, from the start.
12
+ - `decisionCostLine(cursor, home, policy)` returns the line a STOP prints about the session's finished sub-agents, word for word as Burn's hook prints it, next to `finishedSubagents`, `subagentCostLine` and `MIN_FINISHED_SUBAGENTS`. Burn's own hook now calls these same functions, so the two can't drift apart.
13
+ - A sub-agent's cursor no longer keeps the depth of each of its lines. Depth only places launches, and a sub-agent's launches are not counted, so the state Burn's hook saves for a session is smaller.
14
+ - The `Gateway` adds up a batch of observations in one pass. It used to copy its list of calls and check for repeats once per event, so a first read of a long session with its sub-agents (15,000 events) took 7.9 seconds; it now takes 20 ms, with the same totals.
15
+ - A hook can now show the tip `why` ends with, for example when the next session starts: `sessionTip(transcriptPath)` returns that "Next: ..." line for the session at that path, or null when nothing stands out. It reads the session as `why` does (Codex when the path is a rollout, Claude Code otherwise, with every sub-agent transcript in the session's `subagents` folder, priced with your pricing overrides), and the words and figures come from the same function `why` prints the tip with, so the two can't differ. It returns English unless given `lang`, ignores `quiet` (the caller decides whether to show the line) and writes nothing. It leaves out the measured-change line, which describes a moment inside the old session. With `context: 'plugin'`, for the AgentGuard plugin, the fan-out tip's second sentence, which points to the plugin, becomes the action a STOP prints for too many sub-agents: "Next: sub-agents used 48.9% of this session's tokens. Give related work to one sub-agent instead of several." Spanish and Portuguese say the same. Every other tip, and `why` itself, are unchanged.
16
+ - `sessionTip` reads a long transcript in 16 MB pieces, as `calendar` does. On a 125 MB session with 199 sub-agents that takes 2.0 seconds and 360 MB of memory instead of 2.4 seconds and 860 MB, and on all 584 sessions on the machine it was checked on, the tip matched a whole-file read.
17
+ - A `burn-policy.json` that exists but can't be used (bad JSON, no "mode", a "mode" other than "enforce" or "shadow", no "thresholds", not a JSON object, or unreadable) used to be ignored without a word, so the defaults, which only watch, applied instead: a hand edit with a mistake turned enforcement off. `status` now starts with one line naming the file, the reason and the fix, for example: `AgentGuard ignored ~/.agentguard/burn-policy.json: it has no "mode". Using the defaults, which only watch. Add "mode": "enforce" to turn limits back on.` The new `checkPolicyFile(home)` tells a missing file (the defaults, as intended) from a loaded one and an ignored one, with the reasons and that line. `loadPolicy` decides with the same checks, so the two always agree. What loads is unchanged: a file with a "mode" and only some thresholds still loads, with the rest from the defaults.
18
+ - npm now links the package to agentguard.run/burn and to the issue tracker (`homepage` and `bugs` in package.json).
19
+ - Known limits: Burn's own hook, used without the plugin, does not show the ignored-policy line when a session starts; `status` shows it. The tips are written for Claude Code, so on a Codex session a tip can say "Claude" or name `/compact` and `/clear`.
20
+ - Apart from the calendar above, the `status` line for an ignored policy file and the list of what `quiet on` hides, nothing changes in the output of any command.
21
+
3
22
  ## 0.3.20 (2026-09-27)
4
23
 
5
24
  - New `calendar`: tokens per day for every Claude Code and Codex session on this machine, sub-agents included, on one heatmap: a column per week, a row per weekday, five shades from Less to More. With no flag it starts at the oldest recorded day and fits the terminal (80 columns when piped); `calendar --weeks N` shows exactly N weeks, 1 to 53. `calendar json` prints every day and the totals and is never translated. `--lang es|pt` and your locale pick the language as they do for `why`.
package/README.md CHANGED
@@ -287,9 +287,11 @@ agentguard-burn calendar json
287
287
 
288
288
  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
289
 
290
- The summary gives the total tokens, 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, the share of tokens sub-agents used (every token of their responses) and, 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. 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.
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.
291
291
 
292
- With no flag the calendar starts at the oldest recorded day, capped to the weeks that fit the terminal (80 columns when piped); `--weeks N` shows exactly N weeks, 1 to 53, ending with this week. A colour terminal draws coloured squares; piped, with `--no-color` or with `NO_COLOR` set, each day is a shade character (`· ░ ▒ ▓ █`) and the two kinds of marked day are the letters `s` and `H`. The fixture in `tests/fixtures/calendar-fixtures.ts` prints:
292
+ 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
+
294
+ Days are big whenever the span fits: two characters a day and one space between weeks, which reads as roughly square. That takes the weekday labels plus three columns a week, so 25 weeks fit 80 columns, 39 fit 120 and all 53 fit 162. When the span does not fit (a long history at 80 columns, or a `--weeks` span wider than the terminal), each day is one character and one space, as 0.3.20 drew every calendar; the span never shrinks to make the days bigger. A colour terminal draws a big day as `▇▇` and a compact day as `■`. The seven-eighths block leaves a thin gap above each day, where full blocks would join a week's days into one bar. Piped, with `--no-color` or with `NO_COLOR` set, a big day is a shade pair (`·· ░░ ▒▒ ▓▓ ██`) and a compact day one shade character (`· ░ ▒ ▓ █`). The two kinds of marked day are the letters `s` and `H` (the red diamond in colour): a big day keeps its shade in the left half and shows the mark in the right (`▓s`, `█H`), while a compact day shows the mark alone. The fixture in `tests/fixtures/calendar-fixtures.ts` prints four weeks, in big days:
293
295
 
294
296
  ```text
295
297
  AgentGuard calendar: tokens per day, Aug 30 to Sep 26, 2026
@@ -297,16 +299,16 @@ AgentGuard calendar: tokens per day, Aug 30 to Sep 26, 2026
297
299
  busiest day: Sep 24 (511,040 tokens) · sub-agents used 7.3% of tokens
298
300
  AgentGuard held 2 launches
299
301
 
300
- Sep
301
- Su · · ·
302
- Mo · s ·
303
- Tu ░ · · ·
304
- We · ▒ H ·
305
- Th · · · █
306
- Fr · · · ·
307
- Sa · · · ▒
302
+ Sep
303
+ Su ·· ·· ··
304
+ Mo ·· ▓s ··
305
+ Tu ░░ ·· ·· ··
306
+ We ·· ▒▒ █H ··
307
+ Th ·· ·· ·· ██
308
+ Fr ·· ·· ·· ··
309
+ Sa ·· ·· ·· ▒▒
308
310
 
309
- Less · ░ ▒ ▓ █ More
311
+ Less ·· ░░ ▒▒ ▓▓ ██ More
310
312
  Days marked s: sub-agents used more than half of that day's tokens.
311
313
  Days marked H: AgentGuard held a launch that day.
312
314
  From Claude Code and Codex sessions on this machine, sub-agents included.
package/dist/src/cli.js CHANGED
@@ -65,6 +65,7 @@ const conformance_1 = require("./conformance");
65
65
  const defaults_1 = require("./defaults");
66
66
  const gateway_1 = require("./gateway");
67
67
  const pre_tool_use_1 = require("./hook/pre-tool-use");
68
+ const policy_1 = require("./policy");
68
69
  const install_1 = require("./install");
69
70
  const override_1 = require("./override");
70
71
  const server_1 = require("./proxy/server");
@@ -320,7 +321,7 @@ async function main(argv) {
320
321
  (0, upgrade_moments_1.setQuiet)(HOME, state === 'on');
321
322
  const quiet = quietOn();
322
323
  show({ kind: 'command', command, values: { tips: quiet ? 'off' : 'on', quiet: quiet ? 'on' : 'off', file: (0, upgrade_moments_1.quietFile)(HOME) } }, quiet
323
- ? 'Tips are off. Quiet is on: the why tip, the monthly summary in status and the AgentGuard plugin\'s upgrade, version and Score lines stay hidden on this machine.\nTurn them back on: npx agentguard-burn quiet off\n'
324
+ ? 'Tips are off. Quiet is on: the why tip, the monthly summary in status, and the AgentGuard plugin\'s upgrade, version and Score lines and its tip from your last session stay hidden on this machine.\nTurn them back on: npx agentguard-burn quiet off\n'
324
325
  : 'Tips are on. The why report ends with one tip when a share of the session stands out.\nHide tips: npx agentguard-burn quiet on\n');
325
326
  return 0;
326
327
  }
@@ -421,11 +422,14 @@ async function main(argv) {
421
422
  case 'status': {
422
423
  const monthly = (0, upgrade_moments_1.monthlySummary)(HOME);
423
424
  const policy = (0, pre_tool_use_1.loadPolicy)(HOME);
425
+ // A policy file with a mistake is ignored and the defaults only watch: say so first.
426
+ const policyFile = (0, policy_1.checkPolicyFile)(HOME);
424
427
  const e = shadowEligibility();
425
428
  const gateway = new gateway_1.Gateway(HOME, { sign: false });
426
429
  const lc = policy.thresholds.localCompute;
427
430
  const override = (0, override_1.readOverride)(HOME);
428
- show({ kind: 'command', command, values: { monthly, mode: policy.mode, thresholds: policy.thresholds, eligibility: e, override: override ? { active: true, once: override.once, until: override.until } : null, hosts: ['claude', 'cursor', 'codex'].map(h => { const { command: omitted, ...metadata } = (0, install_1.health)(h); return metadata; }), sessions: [...(0, status_1.readHookSessions)(HOME), ...gateway.sessions()].map(row => ({ sessionId: row.sessionId, hosts: row.hosts, tokens: row.state.totalTokens, spawns: row.state.spawnCount, liveSpawns: row.liveSpawns, capabilities: row.capabilities })) } }, [
431
+ show({ kind: 'command', command, values: { monthly, policyFile: { status: policyFile.status, problems: policyFile.status === 'ignored' ? policyFile.problems : [] }, mode: policy.mode, thresholds: policy.thresholds, eligibility: e, override: override ? { active: true, once: override.once, until: override.until } : null, hosts: ['claude', 'cursor', 'codex'].map(h => { const { command: omitted, ...metadata } = (0, install_1.health)(h); return metadata; }), sessions: [...(0, status_1.readHookSessions)(HOME), ...gateway.sessions()].map(row => ({ sessionId: row.sessionId, hosts: row.hosts, tokens: row.state.totalTokens, spawns: row.state.spawnCount, liveSpawns: row.liveSpawns, capabilities: row.capabilities })) } }, [
432
+ ...(policyFile.status === 'ignored' ? [policyFile.line, ''] : []),
429
433
  `mode: ${policy.mode}${policy.mode === 'enforce' ? ' (the next STOP blocks)' : ' (recording only; nothing is blocked)'}`,
430
434
  `thresholds: fan-out lifetime WARN ${policy.thresholds.fanout.warn}; STOP above ${policy.thresholds.fanout.stop} spawns in ${policy.thresholds.fanout.windowActiveMinutes ?? 120} active minutes; depth above ${policy.thresholds.fanout.maxDepth}`,
431
435
  `spawn-rate: WARN ${policy.thresholds.spawnRate?.warn ?? 8}; STOP ${policy.thresholds.spawnRate?.stop ?? 16} in ${policy.thresholds.spawnRate?.windowActiveMinutes ?? 15} active minutes; ${policy.thresholds.spawnRate?.enforce === false ? 'shadow only' : 'enforcing in enforce mode'}`,
@@ -131,18 +131,24 @@ class Gateway {
131
131
  for (const [sessionId, list] of bySession) {
132
132
  const first = list[0];
133
133
  const { state, meta } = this.load(sessionId, first.host, first.at);
134
+ // One lookup set and one copy of the call and spawn maps per session and
135
+ // batch, never per event: a first read of a long session, sub-agents
136
+ // included, folds thousands of events at once.
137
+ const batch = { seen: new Set(meta.seenEvents), calls: new Map(meta.calls), live: new Map(meta.liveSpawns) };
134
138
  for (const event of list)
135
- this.fold(event, state, meta, tx);
139
+ this.fold(event, state, meta, tx, batch);
140
+ meta.calls = [...batch.calls];
141
+ meta.liveSpawns = [...batch.live];
136
142
  this.save(meta, state);
137
143
  }
138
144
  });
139
145
  }
140
- fold(event, state, meta, tx) {
141
- if (meta.seenEvents.includes(event.eventId))
146
+ fold(event, state, meta, tx, batch) {
147
+ if (batch.seen.has(event.eventId))
142
148
  return;
149
+ batch.seen.add(event.eventId);
143
150
  meta.seenEvents.push(event.eventId);
144
- const calls = new Map(meta.calls);
145
- const live = new Map(meta.liveSpawns);
151
+ const { calls, live } = batch;
146
152
  switch (event.kind) {
147
153
  case 'session_opened':
148
154
  meta.closedAt = null;
@@ -176,8 +182,6 @@ class Gateway {
176
182
  // would count it without admitting it.
177
183
  break;
178
184
  }
179
- meta.calls = [...calls];
180
- meta.liveSpawns = [...live];
181
185
  }
182
186
  /**
183
187
  * Replace-not-add by call ID. An estimate reserved by middleware is
@@ -83,6 +83,43 @@ export declare function readIncremental(path: string, cursor: ReaderCursor, opti
83
83
  * usage deltas contribute here. The parent's observed spawn count stays intact.
84
84
  */
85
85
  export declare function readSessionIncremental(path: string, cursor: ReaderCursor, options?: ReadOptions): BurnEvent[];
86
+ /**
87
+ * A reader cursor in a form JSON can hold: the byte offset and size reached in
88
+ * 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.
92
+ */
93
+ export interface PersistedReaderCursor {
94
+ offset: number;
95
+ size: number;
96
+ malformedLines: number;
97
+ depthByUuid: [string, number][];
98
+ usageVersion?: 1;
99
+ /** The session transcript's cursor only: the de-duplication map every cursor of the session shares. */
100
+ usageByMessage?: [string, UsageSnapshot][];
101
+ children?: [string, PersistedReaderCursor][];
102
+ /** A sub-agent cursor measured from its first byte: the usage it added, by model. */
103
+ usage?: [string, ChildUsage][];
104
+ /** The session transcript's cursor only: sub-agent ids the transcripts record as completed. */
105
+ completed?: string[];
106
+ }
107
+ /** A session cursor, sub-agent cursors included, as JSON can store it. Pair with restoreReaderCursor. */
108
+ export declare function saveReaderCursor(cursor: ReaderCursor): PersistedReaderCursor;
109
+ /**
110
+ * 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
113
+ * transcript where it stopped and reads each sub-agent transcript from its first
114
+ * byte on the next readSessionIncremental.
115
+ */
116
+ export declare function restoreReaderCursor(saved: PersistedReaderCursor): ReaderCursor;
117
+ /**
118
+ * An independent copy of a session cursor, sub-agent cursors included, to read
119
+ * into. A caller keeps the cursor it has until what the copy read is stored, so
120
+ * a step that fails reads the same bytes again instead of losing them.
121
+ */
122
+ export declare function cloneReaderCursor(cursor: ReaderCursor): ReaderCursor;
86
123
  /** Convenience for replay and tests: read a session and its own stored children. */
87
124
  export declare function readAll(path: string): {
88
125
  events: BurnEvent[];
@@ -17,6 +17,9 @@ exports.newCursor = newCursor;
17
17
  exports.normaliseLine = normaliseLine;
18
18
  exports.readIncremental = readIncremental;
19
19
  exports.readSessionIncremental = readSessionIncremental;
20
+ exports.saveReaderCursor = saveReaderCursor;
21
+ exports.restoreReaderCursor = restoreReaderCursor;
22
+ exports.cloneReaderCursor = cloneReaderCursor;
20
23
  exports.readAll = readAll;
21
24
  const node_fs_1 = require("node:fs");
22
25
  const node_path_1 = require("node:path");
@@ -261,9 +264,53 @@ function readSessionIncremental(path, cursor, options = {}) {
261
264
  if (event.tokens > 0 || event.cacheRead > 0)
262
265
  events.push({ ...event, spawns: [], surfaces: [], sidechain: true });
263
266
  }
267
+ // Line depth only places spawns, and a sub-agent's spawns are dropped above,
268
+ // so a sub-agent cursor keeps no depth map: the saved cursor stays small.
269
+ child.depthByUuid.clear();
264
270
  }
265
271
  return events.sort((a, b) => a.at - b.at);
266
272
  }
273
+ function persist(cursor, child) {
274
+ return { offset: cursor.offset, size: cursor.size, malformedLines: cursor.malformedLines, depthByUuid: [...cursor.depthByUuid],
275
+ usageVersion: cursor.usageVersion,
276
+ ...(!child ? { usageByMessage: [...(cursor.usageByMessage ?? [])] } : {}),
277
+ ...(!child && cursor.completed?.size ? { completed: [...cursor.completed] } : {}),
278
+ ...(child && cursor.usage ? { usage: [...cursor.usage] } : {}),
279
+ ...(cursor.children?.size ? { children: [...cursor.children].map(([name, value]) => [name, persist(value, true)]) } : {}) };
280
+ }
281
+ /** A session cursor, sub-agent cursors included, as JSON can store it. Pair with restoreReaderCursor. */
282
+ function saveReaderCursor(cursor) {
283
+ return persist(cursor, false);
284
+ }
285
+ /**
286
+ * 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
289
+ * transcript where it stopped and reads each sub-agent transcript from its first
290
+ * byte on the next readSessionIncremental.
291
+ */
292
+ function restoreReaderCursor(saved) {
293
+ const restore = (raw, usageByMessage, completed) => ({
294
+ 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)]))
297
+ });
298
+ return restore(saved, new Map(saved.usageByMessage ?? []), new Set(saved.completed ?? []));
299
+ }
300
+ /**
301
+ * An independent copy of a session cursor, sub-agent cursors included, to read
302
+ * into. A caller keeps the cursor it has until what the copy read is stored, so
303
+ * a step that fails reads the same bytes again instead of losing them.
304
+ */
305
+ function cloneReaderCursor(cursor) {
306
+ const usageByMessage = new Map(cursor.usageByMessage ?? []), completed = new Set(cursor.completed ?? []);
307
+ const copy = (item) => ({
308
+ 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) } : {}),
310
+ ...(item.children ? { children: new Map([...item.children].map(([name, child]) => [name, copy(child)])) } : {})
311
+ });
312
+ return copy(cursor);
313
+ }
267
314
  /** Convenience for replay and tests: read a session and its own stored children. */
268
315
  function readAll(path) {
269
316
  const cursor = newCursor();
@@ -14,7 +14,7 @@
14
14
  * cannot fail closed if Claude Code times the hook out, so the hot path does
15
15
  * as little as possible.
16
16
  */
17
- import { type ChildUsage, type ReaderCursor, type UsageSnapshot } from '../history/claude-transcript';
17
+ import { type PersistedReaderCursor, type ReaderCursor } from '../history/claude-transcript';
18
18
  import type { BurnReport, Policy, SessionState } from '../types';
19
19
  export interface HookInput {
20
20
  hook_event_name?: string;
@@ -38,19 +38,7 @@ export interface HookOutput {
38
38
  permissionDecisionReason: string;
39
39
  };
40
40
  }
41
- export interface PersistedReaderCursor {
42
- offset: number;
43
- size: number;
44
- malformedLines: number;
45
- depthByUuid: [string, number][];
46
- usageVersion?: 1;
47
- usageByMessage?: [string, UsageSnapshot][];
48
- children?: [string, PersistedReaderCursor][];
49
- /** A child measured from its first byte: the usage it added, by model. */
50
- usage?: [string, ChildUsage][];
51
- /** The parent only: sub-agent ids the transcripts record as completed. */
52
- completed?: string[];
53
- }
41
+ export type { PersistedReaderCursor };
54
42
  export interface PersistedSession {
55
43
  cursor: PersistedReaderCursor;
56
44
  state: Omit<SessionState, 'tokensByActiveMinute' | 'spawnsByActiveMinute' | 'surfaceReaders'> & {
@@ -56,25 +56,10 @@ function inflateHookSession(raw) {
56
56
  surfaceReaders: new Map(raw.state.surfaceReaders.map(([k, v]) => [k, new Set(v)])),
57
57
  };
58
58
  }
59
- function inflateCursor(raw, shared, completed) {
60
- const usageByMessage = shared ?? new Map(raw.usageByMessage ?? []);
61
- const done = completed ?? new Set(raw.completed ?? []);
62
- return { offset: raw.offset, size: raw.size, malformedLines: raw.malformedLines, depthByUuid: new Map(raw.depthByUuid),
63
- usageVersion: raw.usageVersion, usageByMessage, completed: done, ...(raw.usage ? { usage: new Map(raw.usage) } : {}),
64
- children: new Map((raw.children ?? []).map(([name, child]) => [name, inflateCursor(child, usageByMessage, done)])) };
65
- }
66
- function persistCursor(cursor, child = false) {
67
- return { offset: cursor.offset, size: cursor.size, malformedLines: cursor.malformedLines, depthByUuid: [...cursor.depthByUuid],
68
- usageVersion: cursor.usageVersion,
69
- ...(!child ? { usageByMessage: [...(cursor.usageByMessage ?? [])] } : {}),
70
- ...(!child && cursor.completed?.size ? { completed: [...cursor.completed] } : {}),
71
- ...(child && cursor.usage ? { usage: [...cursor.usage] } : {}),
72
- ...(cursor.children?.size ? { children: [...cursor.children].map(([name, value]) => [name, persistCursor(value, true)]) } : {}) };
73
- }
74
59
  function loadSession(home, sessionId, firstEventAt) {
75
60
  try {
76
61
  const raw = JSON.parse((0, node_fs_1.readFileSync)(sessionFile(home, sessionId), 'utf8'));
77
- return { cursor: inflateCursor(raw.cursor), state: inflateHookSession(raw), notified: raw.notified ?? '', lastReceipt: raw.lastReceipt ?? null,
62
+ return { cursor: (0, claude_transcript_1.restoreReaderCursor)(raw.cursor), state: inflateHookSession(raw), notified: raw.notified ?? '', lastReceipt: raw.lastReceipt ?? null,
78
63
  fresh: false, needsRebuild: raw.cursor.usageVersion !== 1 || !Array.isArray(raw.cursor.usageByMessage) };
79
64
  }
80
65
  catch {
@@ -84,7 +69,7 @@ function loadSession(home, sessionId, firstEventAt) {
84
69
  function saveSession(home, cursor, state, notified, lastReceipt) {
85
70
  (0, node_fs_1.mkdirSync)((0, node_path_1.join)(home, 'sessions'), { recursive: true, mode: 0o700 });
86
71
  const persisted = {
87
- cursor: persistCursor(cursor),
72
+ cursor: (0, claude_transcript_1.saveReaderCursor)(cursor),
88
73
  state: {
89
74
  ...state,
90
75
  tokensByActiveMinute: [...state.tokensByActiveMinute],
@@ -249,7 +234,7 @@ function handleSpawnPreToolUse(input, home, now) {
249
234
  if (shouldDeny && policy.mode === 'enforce') {
250
235
  if (!override) {
251
236
  // The cost of one more sub-agent, at the decision: from the state just refreshed, never a transcript read.
252
- const costLine = decisionCostLine(refreshed.cursor, home, policy);
237
+ const costLine = (0, subagent_cost_1.decisionCostLine)(refreshed.cursor, home, policy);
253
238
  if (asked) {
254
239
  (0, recording_1.recordFrame)({ kind: 'report', report, outcome: 'asked', host: 'claude-code' });
255
240
  return ask((0, stop_text_1.askReason)(report, costLine));
@@ -287,27 +272,6 @@ function buildDenyReason(report, costLine) {
287
272
  // joiner preserves the blank first line, keeping that prefix off the frame.
288
273
  return '\u2060\n' + (0, render_1.renderStop)(report, { colour: false, host: 'claude-code', costLine });
289
274
  }
290
- /**
291
- * What this session's finished sub-agents averaged, in English like the rest of
292
- * the STOP text, or null below three. Best effort: a pricing file that cannot be
293
- * read costs the line its dollars, and nothing here can turn a prompt into a
294
- * failed-closed refusal.
295
- */
296
- function decisionCostLine(cursor, home, policy) {
297
- let rates;
298
- try {
299
- rates = (0, live_1.readPricing)(home, policy);
300
- }
301
- catch {
302
- rates = null;
303
- }
304
- try {
305
- return (0, subagent_cost_1.subagentCostLine)((0, subagent_cost_1.finishedSubagents)(cursor, rates ?? {}, rates !== null));
306
- }
307
- catch {
308
- return null;
309
- }
310
- }
311
275
  const ASK_MODES = new Set(['default', 'acceptEdits', 'auto', 'plan']);
312
276
  /**
313
277
  * Claude Code turns a hook's "ask" into a real permission prompt in these
@@ -2,7 +2,10 @@ export * from './types';
2
2
  export { DEFAULT_POLICY, DEFAULT_THRESHOLDS, DEFAULT_LOCAL_COMPUTE, CALL_RESERVATION_TTL_MS } from './defaults';
3
3
  export { evaluate, fmt } from './detectors/evaluate';
4
4
  export { evaluateLocalCompute } from './detectors/local-compute';
5
- export { readIncremental, readAll, newCursor, normaliseLine, type ReaderCursor } from './history/claude-transcript';
5
+ export { readIncremental, readAll, newCursor, normaliseLine, readSessionIncremental, saveReaderCursor, restoreReaderCursor, cloneReaderCursor, type ReaderCursor, type PersistedReaderCursor, type ChildUsage, type UsageSnapshot } from './history/claude-transcript';
6
+ export { finishedSubagents, subagentCostLine, decisionCostLine, MIN_FINISHED_SUBAGENTS, type FinishedSubagents } from './subagent-cost';
7
+ export { sessionTip, type SessionTipOptions, type TipContext } from './insights/session-tip';
8
+ export { checkPolicyFile, type PolicyFileCheck, type PolicyFileProblem } from './policy';
6
9
  export { applyEvent, applyCorrection, newSessionState, windowSum, medianCompletedMinute, cacheReadRatio } from './state/session';
7
10
  export { ReservationStore, Transaction, RESERVATION_TTL_MS, type Reservation, type CallReservation, type ComputeSnapshot } from './state/reservations';
8
11
  export { replayAll, replaySession, replayEvents, discoverTranscripts, type ReplaySummary, type SessionReplay } from './replay/simulate';
package/dist/src/index.js CHANGED
@@ -14,8 +14,8 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
14
  for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
15
  };
16
16
  Object.defineProperty(exports, "__esModule", { value: true });
17
- exports.BurnStopError = exports.createRawApiGuard = exports.sha256 = exports.canonical = exports.receiptDigest = exports.verifyReceipt = exports.ReceiptSigner = exports.mergeCapabilities = exports.Gateway = exports.AGENT_OVERRIDE_REASON = exports.agentOverrideAttempt = exports.asksPerson = exports.settingsSnippet = exports.loadPolicy = exports.refreshSession = exports.handlePreToolUse = exports.calibrate = exports.OVERRIDE_COMMAND = exports.stopSummary = exports.sessionSoFar = exports.primarySummary = exports.overriddenLine = exports.continueLines = exports.askReason = exports.renderStop = exports.renderReplay = exports.discoverTranscripts = exports.replayEvents = exports.replaySession = exports.replayAll = exports.RESERVATION_TTL_MS = exports.Transaction = exports.ReservationStore = exports.cacheReadRatio = exports.medianCompletedMinute = exports.windowSum = exports.newSessionState = exports.applyCorrection = exports.applyEvent = exports.normaliseLine = exports.newCursor = exports.readAll = exports.readIncremental = exports.evaluateLocalCompute = exports.fmt = exports.evaluate = exports.CALL_RESERVATION_TTL_MS = exports.DEFAULT_LOCAL_COMPUTE = exports.DEFAULT_THRESHOLDS = exports.DEFAULT_POLICY = void 0;
18
- exports.inflateHookSession = exports.findingSignature = exports.renderHostHealth = exports.readHookSessions = exports.configPath = exports.health = exports.install = exports.OVERRIDE_WINDOW_MS = exports.clearOverride = exports.consumeOverride = exports.readOverride = exports.writeOverride = exports.runConformance = exports.renderMachineStatus = exports.UsageObserver = exports.profileFor = exports.startProxy = exports.CODEX_FORBIDDEN_FIELDS = exports.readCodexTranscriptUsage = exports.parseCodexTranscript = exports.codexHooksSnippet = exports.handleCodexHook = exports.cursorHooksSnippet = exports.handleCursorHook = void 0;
17
+ exports.agentOverrideAttempt = exports.asksPerson = exports.settingsSnippet = exports.loadPolicy = exports.refreshSession = exports.handlePreToolUse = exports.calibrate = exports.OVERRIDE_COMMAND = exports.stopSummary = exports.sessionSoFar = exports.primarySummary = exports.overriddenLine = exports.continueLines = exports.askReason = exports.renderStop = exports.renderReplay = exports.discoverTranscripts = exports.replayEvents = exports.replaySession = exports.replayAll = exports.RESERVATION_TTL_MS = exports.Transaction = exports.ReservationStore = exports.cacheReadRatio = exports.medianCompletedMinute = exports.windowSum = exports.newSessionState = exports.applyCorrection = exports.applyEvent = exports.checkPolicyFile = exports.sessionTip = exports.MIN_FINISHED_SUBAGENTS = exports.decisionCostLine = exports.subagentCostLine = exports.finishedSubagents = exports.cloneReaderCursor = exports.restoreReaderCursor = exports.saveReaderCursor = exports.readSessionIncremental = exports.normaliseLine = exports.newCursor = exports.readAll = exports.readIncremental = exports.evaluateLocalCompute = exports.fmt = exports.evaluate = exports.CALL_RESERVATION_TTL_MS = exports.DEFAULT_LOCAL_COMPUTE = exports.DEFAULT_THRESHOLDS = exports.DEFAULT_POLICY = void 0;
18
+ exports.inflateHookSession = exports.findingSignature = exports.renderHostHealth = exports.readHookSessions = exports.configPath = exports.health = exports.install = exports.OVERRIDE_WINDOW_MS = exports.clearOverride = exports.consumeOverride = exports.readOverride = exports.writeOverride = exports.runConformance = exports.renderMachineStatus = exports.UsageObserver = exports.profileFor = exports.startProxy = exports.CODEX_FORBIDDEN_FIELDS = exports.readCodexTranscriptUsage = exports.parseCodexTranscript = exports.codexHooksSnippet = exports.handleCodexHook = exports.cursorHooksSnippet = exports.handleCursorHook = exports.BurnStopError = exports.createRawApiGuard = exports.sha256 = exports.canonical = exports.receiptDigest = exports.verifyReceipt = exports.ReceiptSigner = exports.mergeCapabilities = exports.Gateway = exports.AGENT_OVERRIDE_REASON = void 0;
19
19
  __exportStar(require("./types"), exports);
20
20
  var defaults_1 = require("./defaults");
21
21
  Object.defineProperty(exports, "DEFAULT_POLICY", { enumerable: true, get: function () { return defaults_1.DEFAULT_POLICY; } });
@@ -32,6 +32,22 @@ Object.defineProperty(exports, "readIncremental", { enumerable: true, get: funct
32
32
  Object.defineProperty(exports, "readAll", { enumerable: true, get: function () { return claude_transcript_1.readAll; } });
33
33
  Object.defineProperty(exports, "newCursor", { enumerable: true, get: function () { return claude_transcript_1.newCursor; } });
34
34
  Object.defineProperty(exports, "normaliseLine", { enumerable: true, get: function () { return claude_transcript_1.normaliseLine; } });
35
+ Object.defineProperty(exports, "readSessionIncremental", { enumerable: true, get: function () { return claude_transcript_1.readSessionIncremental; } });
36
+ Object.defineProperty(exports, "saveReaderCursor", { enumerable: true, get: function () { return claude_transcript_1.saveReaderCursor; } });
37
+ Object.defineProperty(exports, "restoreReaderCursor", { enumerable: true, get: function () { return claude_transcript_1.restoreReaderCursor; } });
38
+ Object.defineProperty(exports, "cloneReaderCursor", { enumerable: true, get: function () { return claude_transcript_1.cloneReaderCursor; } });
39
+ // What another Claude Code hook needs for the same session totals and STOP line as Burn's own hook (0.3.21).
40
+ var subagent_cost_1 = require("./subagent-cost");
41
+ Object.defineProperty(exports, "finishedSubagents", { enumerable: true, get: function () { return subagent_cost_1.finishedSubagents; } });
42
+ Object.defineProperty(exports, "subagentCostLine", { enumerable: true, get: function () { return subagent_cost_1.subagentCostLine; } });
43
+ Object.defineProperty(exports, "decisionCostLine", { enumerable: true, get: function () { return subagent_cost_1.decisionCostLine; } });
44
+ Object.defineProperty(exports, "MIN_FINISHED_SUBAGENTS", { enumerable: true, get: function () { return subagent_cost_1.MIN_FINISHED_SUBAGENTS; } });
45
+ // The tip `why` ends with, for a session's transcript path, so a hook can show it when the next session starts (0.3.21).
46
+ var session_tip_1 = require("./insights/session-tip");
47
+ Object.defineProperty(exports, "sessionTip", { enumerable: true, get: function () { return session_tip_1.sessionTip; } });
48
+ // Whether burn-policy.json is missing, loaded or ignored, and the line that says why it was ignored (0.3.21).
49
+ var policy_1 = require("./policy");
50
+ Object.defineProperty(exports, "checkPolicyFile", { enumerable: true, get: function () { return policy_1.checkPolicyFile; } });
35
51
  var session_1 = require("./state/session");
36
52
  Object.defineProperty(exports, "applyEvent", { enumerable: true, get: function () { return session_1.applyEvent; } });
37
53
  Object.defineProperty(exports, "applyCorrection", { enumerable: true, get: function () { return session_1.applyCorrection; } });
@@ -1,16 +1,28 @@
1
1
  /**
2
2
  * The calendar's two faces from one layout. On a colour terminal each day is a
3
- * coloured square on the canvas palette (teal by tokens, amber when sub-agents
3
+ * coloured block on the canvas palette (teal by tokens, amber when sub-agents
4
4
  * used more than half of the day's tokens, a red diamond on a day AgentGuard
5
5
  * held a launch), drawn through the presentation path. Piped, with --no-color or
6
- * NO_COLOR, each day is a shade character and the two kinds of marked day are
6
+ * NO_COLOR, each day is shade characters and the two kinds of marked day are
7
7
  * letters, so nothing depends on colour.
8
+ *
9
+ * Two cell sizes. Big, whenever the span fits the width that way: two
10
+ * characters a day (▇▇ in colour, the shade pair such as ▓▓ in plain text) and
11
+ * one space between weeks, which reads as roughly square. Compact otherwise: one
12
+ * character a day and one space, as 0.3.20 drew every calendar. The span is
13
+ * chosen first (calendarReport) and never shrinks to make the cells bigger.
14
+ *
15
+ * A colour day is the lower seven-eighths block, not the full block: terminals
16
+ * draw █ to the full height of the line, so a week of full blocks joins into one
17
+ * bar, while ▇ leaves a thin gap above each day and the grid reads as squares.
8
18
  */
9
19
  import { Canvas, type CanvasColor } from '../canvas';
10
20
  import { type CalendarReport } from './calendar';
11
21
  import { type WhyLang } from './i18n';
12
22
  import type { DollarRange } from './pricing';
13
23
  export type CalendarSkin = 'plain' | 'colour';
24
+ /** `big`: two characters a day; `compact`: one. Both put one space between weeks. */
25
+ export type CalendarCells = 'big' | 'compact';
14
26
  export interface CalendarSegment {
15
27
  text: string;
16
28
  color: CanvasColor;
@@ -23,6 +35,18 @@ export declare const CALENDAR_MARKERS: {
23
35
  readonly subagents: "s";
24
36
  readonly held: "H";
25
37
  };
38
+ /**
39
+ * The grid's width at a cell size: the weekday labels and the week columns,
40
+ * without the last space. The labels count at their widest language, so a width
41
+ * picks the same cell size in every language.
42
+ */
43
+ export declare const calendarGridWidth: (weeks: number, cells: CalendarCells) => number;
44
+ /**
45
+ * Big cells whenever the span's weeks, and the Less to More scale under them,
46
+ * fit `columns` at two characters a day; compact otherwise, a `--weeks` span
47
+ * wider than the terminal included.
48
+ */
49
+ export declare const calendarCells: (weeks: number, columns: number) => CalendarCells;
26
50
  /**
27
51
  * The calendar's dollar total. Under $1,000 it prints as `why` prints dollars
28
52
  * ($7.29, or $0.63 to $1.00). From $1,000, decided by the larger end, both ends
@@ -37,9 +61,8 @@ export declare function calendarDollars(value: DollarRange, words: {
37
61
  /** Greedy word wrap at `width`; a word is never split, and a word wider than the line stands alone. */
38
62
  export declare function wrap(text: string, width: number, indent?: string): string[];
39
63
  /**
40
- * The report line by line. `columns` wraps the text lines; the grid's width is
41
- * its weeks (two columns each, beside the weekday labels), which the span was
42
- * already chosen to fit.
64
+ * The report line by line. `columns` wraps the text lines and picks the cell
65
+ * size (calendarCells); the span was already chosen to fit it.
43
66
  */
44
67
  export declare function calendarLines(report: CalendarReport, lang: WhyLang, columns: number, skin: CalendarSkin): CalendarLine[];
45
68
  /** Plain text: shade characters and day letters, no control sequences, trailing spaces trimmed. */
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.CALENDAR_MARKERS = exports.CALENDAR_SHADES = void 0;
3
+ exports.calendarCells = exports.calendarGridWidth = exports.CALENDAR_MARKERS = exports.CALENDAR_SHADES = void 0;
4
4
  exports.calendarDollars = calendarDollars;
5
5
  exports.wrap = wrap;
6
6
  exports.calendarLines = calendarLines;
@@ -8,11 +8,21 @@ exports.renderCalendar = renderCalendar;
8
8
  exports.drawCalendar = drawCalendar;
9
9
  /**
10
10
  * The calendar's two faces from one layout. On a colour terminal each day is a
11
- * coloured square on the canvas palette (teal by tokens, amber when sub-agents
11
+ * coloured block on the canvas palette (teal by tokens, amber when sub-agents
12
12
  * used more than half of the day's tokens, a red diamond on a day AgentGuard
13
13
  * held a launch), drawn through the presentation path. Piped, with --no-color or
14
- * NO_COLOR, each day is a shade character and the two kinds of marked day are
14
+ * NO_COLOR, each day is shade characters and the two kinds of marked day are
15
15
  * letters, so nothing depends on colour.
16
+ *
17
+ * Two cell sizes. Big, whenever the span fits the width that way: two
18
+ * characters a day (▇▇ in colour, the shade pair such as ▓▓ in plain text) and
19
+ * one space between weeks, which reads as roughly square. Compact otherwise: one
20
+ * character a day and one space, as 0.3.20 drew every calendar. The span is
21
+ * chosen first (calendarReport) and never shrinks to make the cells bigger.
22
+ *
23
+ * A colour day is the lower seven-eighths block, not the full block: terminals
24
+ * draw █ to the full height of the line, so a week of full blocks joins into one
25
+ * bar, while ▇ leaves a thin gap above each day and the grid reads as squares.
16
26
  */
17
27
  const canvas_1 = require("../canvas");
18
28
  const calendar_1 = require("./calendar");
@@ -23,22 +33,57 @@ const render_1 = require("./render");
23
33
  exports.CALENDAR_SHADES = ['·', '░', '▒', '▓', '█'];
24
34
  /** The plain-text day letters, the same in every language: sub-agents used most of the day, and AgentGuard held a launch. */
25
35
  exports.CALENDAR_MARKERS = { subagents: 's', held: 'H' };
26
- const SQUARE = '■', DIAMOND = '◆';
36
+ /** A compact colour day; half of a big colour day (see above); a held day's mark. */
37
+ const SQUARE = '■', BLOCK = '▇', DIAMOND = '◆';
27
38
  const TEAL = ['shade0', 'teal1', 'teal2', 'teal3', 'teal4'];
28
39
  const AMBER = ['shade0', 'amber1', 'amber2', 'amber3', 'amber4'];
40
+ /** Columns per week: the day's characters and one space. */
41
+ const WEEK_COLUMNS = { big: 3, compact: 2 };
42
+ /**
43
+ * The grid's width at a cell size: the weekday labels and the week columns,
44
+ * without the last space. The labels count at their widest language, so a width
45
+ * picks the same cell size in every language.
46
+ */
47
+ const calendarGridWidth = (weeks, cells) => calendar_1.CALENDAR_GRID_PREFIX + WEEK_COLUMNS[cells] * weeks - 1;
48
+ exports.calendarGridWidth = calendarGridWidth;
49
+ /** "Less ·· ░░ ▒▒ ▓▓ ██ More" in the widest language: five two-character swatches and six spaces. */
50
+ const BIG_SCALE_WIDTH = Math.max(...Object.values(i18n_1.CALENDAR_TEXT).map(text => text.less.length + text.more.length + 16));
51
+ /**
52
+ * Big cells whenever the span's weeks, and the Less to More scale under them,
53
+ * fit `columns` at two characters a day; compact otherwise, a `--weeks` span
54
+ * wider than the terminal included.
55
+ */
56
+ const calendarCells = (weeks, columns) => Math.max((0, exports.calendarGridWidth)(weeks, 'big'), BIG_SCALE_WIDTH) <= columns ? 'big' : 'compact';
57
+ exports.calendarCells = calendarCells;
29
58
  const segment = (text, color = 'none') => ({ text, color });
30
59
  const dateOf = (day, text) => ({ month: text.months[Number(day.slice(5, 7)) - 1], day: Number(day.slice(8, 10)), year: Number(day.slice(0, 4)) });
31
- /** One day's cell. The held mark wins over amber; a day before the first record, or after today, is blank. */
32
- function cell(day, skin) {
33
- if (!day)
34
- return { segment: segment(' '), mark: null };
35
- if (day.heldLaunches > 0)
36
- return { segment: skin === 'plain' ? segment(exports.CALENDAR_MARKERS.held) : segment(DIAMOND, 'red'), mark: 'held' };
37
- if (day.level === null)
38
- return { segment: segment(' '), mark: null };
39
- if (day.subagentsOverHalf)
40
- return { segment: skin === 'plain' ? segment(exports.CALENDAR_MARKERS.subagents) : segment(SQUARE, AMBER[day.level]), mark: 'subagents' };
41
- return { segment: skin === 'plain' ? segment(exports.CALENDAR_SHADES[day.level]) : segment(SQUARE, TEAL[day.level]), mark: null };
60
+ /**
61
+ * One day's cell and the marks it shows. Compact: the level's shade or square,
62
+ * or on a marked day the mark alone, the held mark winning over amber. Big: the
63
+ * left half always shows the level (amber on a sub-agent day, in colour), and
64
+ * the right half repeats it or carries the day's mark (`s` or `H` in plain text,
65
+ * the red diamond in colour), so a marked day keeps its shade. A day before the
66
+ * first record, or after today, is blank unless AgentGuard held a launch on it.
67
+ */
68
+ function cell(day, skin, cells) {
69
+ const level = day?.level ?? null, held = (day?.heldLaunches ?? 0) > 0, amber = level !== null && day.subagentsOverHalf;
70
+ if (level === null && !held)
71
+ return { parts: [segment(cells === 'big' ? ' ' : ' ')], marks: [] };
72
+ const heldMark = skin === 'plain' ? segment(exports.CALENDAR_MARKERS.held) : segment(DIAMOND, 'red');
73
+ const colours = amber ? AMBER : TEAL, marks = held ? ['held'] : amber ? ['subagents'] : [];
74
+ if (cells === 'compact') {
75
+ if (held)
76
+ return { parts: [heldMark], marks };
77
+ return { parts: [skin === 'plain' ? segment(amber ? exports.CALENDAR_MARKERS.subagents : exports.CALENDAR_SHADES[level]) : segment(SQUARE, colours[level])], marks };
78
+ }
79
+ if (skin === 'plain') {
80
+ const shade = level === null ? ' ' : exports.CALENDAR_SHADES[level];
81
+ return { parts: [segment(shade + (held ? exports.CALENDAR_MARKERS.held : amber ? exports.CALENDAR_MARKERS.subagents : shade))], marks };
82
+ }
83
+ if (!held)
84
+ return { parts: [segment(BLOCK + BLOCK, colours[level])], marks };
85
+ // A held day in colour: its level's block, then the red diamond. An amber left half shows amber too.
86
+ return { parts: [level === null ? segment(' ') : segment(BLOCK, colours[level]), heldMark], marks: amber ? ['subagents', 'held'] : marks };
42
87
  }
43
88
  /**
44
89
  * The calendar's dollar total. Under $1,000 it prints as `why` prints dollars
@@ -90,9 +135,8 @@ function joinItems(items, width) {
90
135
  return lines.flatMap(value => wrap(value, width));
91
136
  }
92
137
  /**
93
- * The report line by line. `columns` wraps the text lines; the grid's width is
94
- * its weeks (two columns each, beside the weekday labels), which the span was
95
- * already chosen to fit.
138
+ * The report line by line. `columns` wraps the text lines and picks the cell
139
+ * size (calendarCells); the span was already chosen to fit it.
96
140
  */
97
141
  function calendarLines(report, lang, columns, skin) {
98
142
  const text = i18n_1.CALENDAR_TEXT[lang], words = i18n_1.WHY_TEXT[lang], width = Math.max(20, Math.floor(columns));
@@ -104,31 +148,38 @@ function calendarLines(report, lang, columns, skin) {
104
148
  paragraph(text.noData, 'white');
105
149
  return lines;
106
150
  }
151
+ // The summary in short lines: tokens and dollars; the busiest day and the
152
+ // sub-agent share; the launches AgentGuard held, when there were any. Two items
153
+ // share a line only when both fit the width; no line takes an item from another.
107
154
  const totals = report.totals, spansYears = report.from.slice(0, 4) !== report.to.slice(0, 4);
108
- const items = [
109
- text.tokens((0, render_1.count)(totals.tokens)),
110
- text.dollars(totals.usd === null ? null : calendarDollars(totals.usd, words)),
111
- ...(report.busiest ? [text.busiest(text.date(dateOf(report.busiest.date, text), spansYears), (0, render_1.count)(report.busiest.tokens))] : []),
112
- text.subagents((0, render_1.share)(totals.subagentTokens, totals.tokens)),
113
- ...(totals.heldLaunches > 0 ? [text.held(totals.heldLaunches)] : []),
155
+ const summary = [
156
+ [text.tokens((0, render_1.count)(totals.tokens)), text.dollars(totals.usd === null ? null : calendarDollars(totals.usd, words))],
157
+ [...(report.busiest ? [text.busiest(text.date(dateOf(report.busiest.date, text), spansYears), (0, render_1.count)(report.busiest.tokens))] : []),
158
+ text.subagents((0, render_1.share)(totals.subagentTokens, totals.tokens))],
159
+ totals.heldLaunches > 0 ? [text.held(totals.heldLaunches)] : [],
114
160
  ];
115
- for (const line of joinItems(items, width))
116
- lines.push([segment(line, 'white')]);
161
+ for (const items of summary)
162
+ for (const line of joinItems(items, width))
163
+ lines.push([segment(line, 'white')]);
117
164
  lines.push([]);
118
- // Month names above the first week whose Sunday falls in that month. The first
119
- // column is named too unless the next name starts before it ends.
165
+ const cells = (0, exports.calendarCells)(report.weeks, columns), step = WEEK_COLUMNS[cells];
120
166
  const labelWidth = Math.max(...text.weekdays.map(label => label.length)) + 1;
167
+ // Month names above the first week whose Sunday falls in that month. The first
168
+ // column is named too unless the next name starts before it ends. A name that
169
+ // would run past the width (or past the grid, when a --weeks grid is wider) is
170
+ // left out: it would wrap the whole row.
171
+ const limit = Math.max(width, labelWidth + step * report.weeks - 1);
121
172
  const months = [];
122
173
  for (let week = 0; week < report.weeks; week++) {
123
174
  const sunday = (0, calendar_1.addDays)(report.from, 7 * week);
124
175
  if (week === 0 || sunday.slice(0, 7) !== (0, calendar_1.addDays)(sunday, -7).slice(0, 7))
125
- months.push({ x: labelWidth + 2 * week, name: text.months[Number(sunday.slice(5, 7)) - 1] });
176
+ months.push({ x: labelWidth + step * week, name: text.months[Number(sunday.slice(5, 7)) - 1] });
126
177
  }
127
178
  if (months.length > 1 && months[1].x < months[0].x + months[0].name.length + 1)
128
179
  months.shift();
129
180
  const monthRow = [];
130
181
  let x = 0;
131
- for (const month of months) {
182
+ for (const month of months.filter(label => label.x + label.name.length <= limit)) {
132
183
  monthRow.push(segment(' '.repeat(month.x - x)), segment(month.name, 'slate'));
133
184
  x = month.x + month.name.length;
134
185
  }
@@ -137,18 +188,21 @@ function calendarLines(report, lang, columns, skin) {
137
188
  for (let weekday = 0; weekday < 7; weekday++) {
138
189
  const row = [segment(text.weekdays[weekday].padEnd(labelWidth), 'slate')];
139
190
  for (let week = 0; week < report.weeks; week++) {
140
- const drawn = cell(report.days[7 * week + weekday], skin);
141
- if (drawn.mark)
142
- marked.add(drawn.mark);
143
- row.push(drawn.segment, segment(' '));
191
+ const drawn = cell(report.days[7 * week + weekday], skin, cells);
192
+ for (const mark of drawn.marks)
193
+ marked.add(mark);
194
+ row.push(...drawn.parts, segment(' '));
144
195
  }
145
196
  lines.push(row);
146
197
  }
147
198
  lines.push([]);
199
+ // The Less to More scale in the cells the grid uses.
200
+ const swatch = cells === 'big' ? BLOCK + BLOCK : SQUARE;
148
201
  lines.push(skin === 'plain'
149
- ? [segment(`${text.less} ${exports.CALENDAR_SHADES.join(' ')} ${text.more}`)]
150
- : [segment(text.less, 'slate'), ...TEAL.flatMap(color => [segment(' '), segment(SQUARE, color)]), segment(' '), segment(text.more, 'slate')]);
151
- // A colour screen shows the mark beside its sentence; plain text names the letter in the sentence.
202
+ ? [segment(`${text.less} ${exports.CALENDAR_SHADES.map(shade => cells === 'big' ? shade + shade : shade).join(' ')} ${text.more}`)]
203
+ : [segment(text.less, 'slate'), ...TEAL.flatMap(color => [segment(' '), segment(swatch, color)]), segment(' '), segment(text.more, 'slate')]);
204
+ // A colour screen shows the mark beside its sentence, where it sits in a day
205
+ // (the diamond is a big day's right half); plain text names the letter.
152
206
  const legend = (mark, glyph, sentences) => {
153
207
  if (!marked.has(mark))
154
208
  return;
@@ -156,13 +210,14 @@ function calendarLines(report, lang, columns, skin) {
156
210
  paragraph(sentences.plain(exports.CALENDAR_MARKERS[mark]), 'none');
157
211
  return;
158
212
  }
159
- const [head = '', ...rest] = wrap(sentences.colour, width - 2);
160
- lines.push([glyph, segment(` ${head}`, 'slate')]);
213
+ const indent = ' '.repeat(glyph.reduce((sum, part) => sum + part.text.length, 0) + 1);
214
+ const [head = '', ...rest] = wrap(sentences.colour, width - indent.length);
215
+ lines.push([...glyph, segment(` ${head}`, 'slate')]);
161
216
  for (const line of rest)
162
- lines.push([segment(` ${line}`, 'slate')]);
217
+ lines.push([segment(`${indent}${line}`, 'slate')]);
163
218
  };
164
- legend('subagents', segment(SQUARE, 'amber4'), text.subagentDays);
165
- legend('held', segment(DIAMOND, 'red'), text.heldDays);
219
+ legend('subagents', [segment(swatch, 'amber4')], text.subagentDays);
220
+ legend('held', cells === 'big' ? [segment(' '), segment(DIAMOND, 'red')] : [segment(DIAMOND, 'red')], text.heldDays);
166
221
  if (totals.claudeTokens > 0 || totals.codexTokens > 0)
167
222
  paragraph(text.sources(totals.claudeTokens > 0, totals.codexTokens > 0), 'slate');
168
223
  if (totals.unpricedTokens > 0)
@@ -60,6 +60,8 @@ export interface WhyText {
60
60
  diagnostics: (duplicates: number, malformed: number) => string;
61
61
  /** The sub-agent share, with AgentGuard's plugin that asks before the next sub-agent past a limit starts; and the 0.3.16 reload dollars, with the `rewrites` command. */
62
62
  tipFanout: (share: string) => string;
63
+ /** The same share for someone already running the plugin: the STOP box's action for too many sub-agents takes the place of the plugin. */
64
+ tipFanoutPlugin: (share: string) => string;
63
65
  tipRewrites: (rewrites: string, total: string) => string;
64
66
  /** Sub-agents that ran on the main conversation's model, by its display name (Opus 5.5). */
65
67
  tipSubagentModel: (count: number, model: string) => string;
@@ -68,6 +68,7 @@ const en = {
68
68
  mixedRanges: 'Some bucket cache-write costs are ranges because mixed cache lifetimes are not attributed to individual buckets. Range endpoints are not additive across buckets.',
69
69
  diagnostics: (duplicates, malformed) => `Usage records de-duplicated: ${duplicates}. Malformed lines skipped: ${malformed}.`,
70
70
  tipFanout: share => `Next: sub-agents used ${share} of this session's tokens. AgentGuard's free plugin asks you before the next sub-agent past your limit starts: agentguard.run/try`,
71
+ tipFanoutPlugin: share => `Next: sub-agents used ${share} of this session's tokens. Give related work to one sub-agent instead of several.`,
71
72
  tipRewrites: (rewrites, total) => `Next: full-prefix rewrites are ${rewrites} of ${total} API list equivalent here. See the cause of each one: npx agentguard-burn rewrites`,
72
73
  tipSubagentModel: (count, model) => `Next: ${count} ${count === 1 ? 'sub-agent' : 'sub-agents'} ran on ${model}. For searching and reading logs, a smaller model does the job: set CLAUDE_CODE_SUBAGENT_MODEL=haiku, or put model: haiku in the sub-agent's definition.`,
73
74
  tipIdleReloads: (count, longest) => `Next: Claude had to reload the whole conversation ${times(count)} after a pause longer than its cache lasts (longest pause: ${longest}). Run /compact before a break, so the reload after it is smaller.`,
@@ -117,6 +118,7 @@ const es = {
117
118
  mixedRanges: 'Algunos costos de escritura en caché por categoría son rangos, porque las duraciones de caché mixtas no se atribuyen a categorías individuales. Los extremos de los rangos no se suman entre categorías.',
118
119
  diagnostics: (duplicates, malformed) => `Registros de uso deduplicados: ${duplicates}. Líneas mal formadas omitidas: ${malformed}.`,
119
120
  tipFanout: share => `Próximo paso: los subagentes usaron el ${share} de los tokens de esta sesión. El plugin gratuito de AgentGuard te pregunta antes de que empiece el siguiente subagente por encima de tu límite: agentguard.run/try`,
121
+ tipFanoutPlugin: share => `Próximo paso: los subagentes usaron el ${share} de los tokens de esta sesión. Da el trabajo relacionado a un solo subagente en lugar de a varios.`,
120
122
  tipRewrites: (rewrites, total) => `Próximo paso: las reescrituras de prefijo completo suman ${rewrites} de ${total} (equivalente a precio de lista de la API) en esta sesión. Mira la causa de cada una: npx agentguard-burn rewrites`,
121
123
  tipSubagentModel: (count, model) => `Próximo paso: ${plural(count, 'subagente usó', 'subagentes usaron')} ${model}. Para buscar y leer logs, un modelo más pequeño basta: define CLAUDE_CODE_SUBAGENT_MODEL=haiku, o pon model: haiku en la definición del subagente.`,
122
124
  tipIdleReloads: (count, longest) => `Próximo paso: Claude tuvo que recargar toda la conversación ${veces(count)} después de una pausa más larga de lo que dura su caché (pausa más larga: ${longest}). Usa /compact antes de un descanso, así la recarga que viene después es más pequeña.`,
@@ -166,6 +168,7 @@ const pt = {
166
168
  mixedRanges: 'Alguns custos de gravação em cache por categoria aparecem como faixas, porque durações de cache mistas não são atribuídas a categorias individuais. Os extremos das faixas não se somam entre categorias.',
167
169
  diagnostics: (duplicates, malformed) => `Registros de uso deduplicados: ${duplicates}. Linhas malformadas ignoradas: ${malformed}.`,
168
170
  tipFanout: share => `Próximo passo: os subagentes usaram ${share} dos tokens desta sessão. O plugin gratuito do AgentGuard pergunta a você antes que o próximo subagente acima do seu limite comece: agentguard.run/try`,
171
+ tipFanoutPlugin: share => `Próximo passo: os subagentes usaram ${share} dos tokens desta sessão. Dê o trabalho relacionado a um único subagente em vez de vários.`,
169
172
  tipRewrites: (rewrites, total) => `Próximo passo: as reescritas de prefixo completo somam ${rewrites} de ${total} (equivalente ao preço de tabela da API) nesta sessão. Veja a causa de cada uma: npx agentguard-burn rewrites`,
170
173
  tipSubagentModel: (count, model) => `Próximo passo: ${plural(count, 'subagente usou', 'subagentes usaram')} o ${model}. Para buscar e ler logs, um modelo menor dá conta: defina CLAUDE_CODE_SUBAGENT_MODEL=haiku, ou coloque model: haiku na definição do subagente.`,
171
174
  tipIdleReloads: (count, longest) => `Próximo passo: o Claude teve que recarregar a conversa inteira ${vezes(count)} depois de uma pausa mais longa que a duração do cache (pausa mais longa: ${longest}). Use /compact antes de um intervalo, assim a recarga depois dele fica menor.`,
@@ -63,6 +63,12 @@ export interface WhyTipInput {
63
63
  medianPerCall: number;
64
64
  };
65
65
  }
66
+ /**
67
+ * Where the tip is shown: `why` itself, or the AgentGuard plugin. The fan-out
68
+ * tip points `why` readers to the plugin; someone the plugin shows it to already
69
+ * runs it, so there it ends with the STOP box's action for too many sub-agents.
70
+ */
71
+ export type TipContext = 'why' | 'plugin';
66
72
  /**
67
73
  * The coach: one next step, for the largest cause that stands out in this
68
74
  * session; null when none does, never a generic line. A cause stands out at the
@@ -74,8 +80,9 @@ export interface WhyTipInput {
74
80
  * for its cause (code.claude.com/docs/en/costs, /prompt-caching, /sub-agents),
75
81
  * and every figure is this session's own. Where the cause has no sharper action,
76
82
  * the share tip prints for sub-agents and the 0.3.16 dollars tip for rewrites.
83
+ * In the plugin context only the share tip's second sentence changes.
77
84
  */
78
- export declare function whyTip(input: WhyTipInput, lang?: WhyLang): string | null;
85
+ export declare function whyTip(input: WhyTipInput, lang?: WhyLang, context?: TipContext): string | null;
79
86
  /**
80
87
  * What `whyTip` weighs, from the figures `why` prints. The sub-agent and rewrite
81
88
  * rows are the table's own. The setup and the re-read conversation split each
@@ -84,6 +91,14 @@ export declare function whyTip(input: WhyTipInput, lang?: WhyLang): string | nul
84
91
  * conversation into setup; they are measured, like every row, from recorded usage.
85
92
  */
86
93
  export declare function whyTipInput(figures: Pick<SessionFigures, 'turns' | 'attribution' | 'totalUsd'>, rates?: PricingTable, bucketUsd?: (bucket: InsightBucket) => DollarRange | null): WhyTipInput;
94
+ /**
95
+ * The tip line `why` ends with for this transcript, in the same words and with
96
+ * the same figures: null when nothing stands out, and for the unknown
97
+ * fork-history report, which prints no tip. The plugin context changes only
98
+ * the fan-out tip's second sentence. It does not read the quiet flag; the
99
+ * caller decides whether to show it.
100
+ */
101
+ export declare function whyTipLine(transcript: InsightTranscript, rates?: PricingTable, lang?: WhyLang, context?: TipContext): string | null;
87
102
  /** Messages on each side of an event the measured change compares, at most and at least. */
88
103
  export declare const PROOF_WINDOW = 20;
89
104
  export declare const PROOF_MINIMUM = 5;
@@ -8,6 +8,7 @@ exports.table = table;
8
8
  exports.modelLabel = modelLabel;
9
9
  exports.whyTip = whyTip;
10
10
  exports.whyTipInput = whyTipInput;
11
+ exports.whyTipLine = whyTipLine;
11
12
  exports.proofLine = proofLine;
12
13
  exports.renderWhy = renderWhy;
13
14
  exports.rewriteReport = rewriteReport;
@@ -94,8 +95,9 @@ const HAS_SMALLER_MODEL = /^claude-(?:opus|fable|sonnet)-/;
94
95
  * for its cause (code.claude.com/docs/en/costs, /prompt-caching, /sub-agents),
95
96
  * and every figure is this session's own. Where the cause has no sharper action,
96
97
  * the share tip prints for sub-agents and the 0.3.16 dollars tip for rewrites.
98
+ * In the plugin context only the share tip's second sentence changes.
97
99
  */
98
- function whyTip(input, lang = 'en') {
100
+ function whyTip(input, lang = 'en', context = 'why') {
99
101
  const { totalTokens, totalUsd } = input, text = i18n_1.WHY_TEXT[lang];
100
102
  const priced = totalUsd !== null && midpoint(totalUsd) > 0;
101
103
  const tokenShare = (tokens) => totalTokens > 0 ? tokens / totalTokens : 0;
@@ -117,7 +119,7 @@ function whyTip(input, lang = 'en') {
117
119
  const { mainModel, onMainModel = 0, onMainModelShare = 0 } = input.subagents;
118
120
  return mainModel && onMainModel > 0 && onMainModelShare >= 0.5 && HAS_SMALLER_MODEL.test(mainModel)
119
121
  ? text.tipSubagentModel(onMainModel, modelLabel(mainModel))
120
- : text.tipFanout((0, exports.share)(input.subagents.tokens, totalTokens));
122
+ : (context === 'plugin' ? text.tipFanoutPlugin : text.tipFanout)((0, exports.share)(input.subagents.tokens, totalTokens));
121
123
  }
122
124
  case 'reloads': {
123
125
  const { cause, count = 0, longestIdleMs = null } = input.reloads;
@@ -204,6 +206,18 @@ function whyTipInput(figures, rates = {}, bucketUsd) {
204
206
  conversation: { tokens: conversation.tokens, usd: conversation.usd, medianPerCall: median(conversation.perCall) },
205
207
  setup: { tokens: setup.tokens, usd: setup.usd, medianPerCall: median(setup.perCall) } };
206
208
  }
209
+ /** The one path from a session's figures to its tip: `renderWhy` prints this line and `whyTipLine` returns it. */
210
+ const figuresTip = (figures, rates, lang, context = 'why') => whyTip(whyTipInput(figures, rates), lang, context);
211
+ /**
212
+ * The tip line `why` ends with for this transcript, in the same words and with
213
+ * the same figures: null when nothing stands out, and for the unknown
214
+ * fork-history report, which prints no tip. The plugin context changes only
215
+ * the fan-out tip's second sentence. It does not read the quiet flag; the
216
+ * caller decides whether to show it.
217
+ */
218
+ function whyTipLine(transcript, rates = {}, lang = 'en', context = 'why') {
219
+ return transcript.state.forkHistoryBoundaryUnknown ? null : figuresTip(sessionFigures(transcript, rates), rates, lang, context);
220
+ }
207
221
  /** Messages on each side of an event the measured change compares, at most and at least. */
208
222
  exports.PROOF_WINDOW = 20;
209
223
  exports.PROOF_MINIMUM = 5;
@@ -253,7 +267,8 @@ function renderWhy(transcript, rates = {}, options = {}) {
253
267
  text.forkUnavailable,
254
268
  table(text.headers, types_1.INSIGHT_BUCKETS.map(bucket => [text.labels[bucket], text.unattributed, text.unattributed, text.unattributed, text.unattributed])),
255
269
  ].join('\n');
256
- const { turns, attribution, prices, totals, totalUsd } = sessionFigures(transcript, rates);
270
+ const figures = sessionFigures(transcript, rates);
271
+ const { turns, attribution, prices, totals, totalUsd } = figures;
257
272
  const lastAttribution = attribution.turnAttributions.at(-1);
258
273
  const byTurn = new Map(attribution.turnAttributions.map(turn => [turn.turnId, turn]));
259
274
  const mixedWriteAllocation = turns.some(turn => (turn.cacheWrite5mTokens ?? 0) > 0 && (turn.cacheWrite1hTokens ?? 0) > 0
@@ -265,7 +280,7 @@ function renderWhy(transcript, rates = {}, options = {}) {
265
280
  return [text.labels[bucket], (0, exports.count)(tokens), money(bucketUsd(bucket)), (0, exports.share)(tokens, attribution.totalTokens), (0, exports.share)(lastTokens, lastAttribution?.totalTokens ?? 0)];
266
281
  });
267
282
  const unknownModels = [...new Set(prices.filter(price => price.usd === null).map(price => price.model ?? text.missingModel))];
268
- const tip = options.tips ? whyTip(whyTipInput({ turns, attribution, totalUsd }, rates, bucketUsd), lang) : null;
283
+ const tip = options.tips ? figuresTip(figures, rates, lang) : null;
269
284
  // A measurement, not a tip: it prints whether or not tips are on.
270
285
  const proof = proofLine(turns, lang);
271
286
  return [
@@ -0,0 +1,33 @@
1
+ import type { WhyLang } from './i18n';
2
+ import type { PricingTable } from './pricing';
3
+ import { type TipContext } from './render';
4
+ export type { TipContext };
5
+ export interface SessionTipOptions {
6
+ /** The AgentGuard home whose pricing overrides `why` uses: AGENTGUARD_HOME, else ~/.agentguard. */
7
+ home?: string;
8
+ /** Rates to price with instead of the home's. */
9
+ rates?: PricingTable;
10
+ /** The language, as `why --lang` takes it. English when not given. */
11
+ lang?: WhyLang;
12
+ /** Read files larger than this many bytes in pieces of this size (16 MB). The tip is the same; only memory changes. */
13
+ chunkBytes?: number;
14
+ /**
15
+ * Where the line is shown. 'why' (the default) is `why`'s own line. 'plugin'
16
+ * is for the AgentGuard plugin, whose users already run it: the fan-out tip
17
+ * ends with "Give related work to one sub-agent instead of several." instead
18
+ * of pointing to the plugin. Every other tip is the same in both.
19
+ */
20
+ context?: TipContext;
21
+ }
22
+ /**
23
+ * The "Next: ..." line `why <transcriptPath>` ends with, or null when nothing
24
+ * stands out. The transcript is read as `why` reads it: Codex when the path is
25
+ * a rollout, Claude Code otherwise, with every sub-agent transcript in the
26
+ * session's `subagents` folder, priced with the home's overrides. The words and
27
+ * figures come from the function `why` prints the tip with, so the two cannot
28
+ * differ. A long transcript is read in pieces cut at line ends, which gives the
29
+ * same turns as reading it whole and keeps it out of memory as one string. It
30
+ * ignores the quiet flag (the caller decides whether to show the line), writes
31
+ * nothing, and throws when the path is not a transcript file.
32
+ */
33
+ export declare function sessionTip(transcriptPath: string, options?: SessionTipOptions): string | null;
@@ -0,0 +1,32 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.sessionTip = sessionTip;
4
+ const node_os_1 = require("node:os");
5
+ const node_path_1 = require("node:path");
6
+ const policy_1 = require("../policy");
7
+ const live_1 = require("./live");
8
+ const render_1 = require("./render");
9
+ const sessions_1 = require("./sessions");
10
+ const transcript_1 = require("./transcript");
11
+ /** A transcript larger than this is read in pieces of this size, as `calendar` reads it. */
12
+ const CHUNK_BYTES = 16 * 1024 * 1024;
13
+ /**
14
+ * The "Next: ..." line `why <transcriptPath>` ends with, or null when nothing
15
+ * stands out. The transcript is read as `why` reads it: Codex when the path is
16
+ * a rollout, Claude Code otherwise, with every sub-agent transcript in the
17
+ * session's `subagents` folder, priced with the home's overrides. The words and
18
+ * figures come from the function `why` prints the tip with, so the two cannot
19
+ * differ. A long transcript is read in pieces cut at line ends, which gives the
20
+ * same turns as reading it whole and keeps it out of memory as one string. It
21
+ * ignores the quiet flag (the caller decides whether to show the line), writes
22
+ * nothing, and throws when the path is not a transcript file.
23
+ */
24
+ function sessionTip(transcriptPath, options = {}) {
25
+ const location = (0, sessions_1.transcriptFileLocation)(transcriptPath);
26
+ if (!location)
27
+ throw new Error('Session transcript not found. Pass its local JSONL path.');
28
+ const home = options.home ?? process.env.AGENTGUARD_HOME ?? (0, node_path_1.join)((0, node_os_1.homedir)(), '.agentguard');
29
+ const rates = options.rates ?? (0, live_1.readPricing)(home, (0, policy_1.loadPolicy)(home, { notice: false }));
30
+ const transcript = (0, transcript_1.readInsightSession)(location.path, { host: location.host, sessionId: location.sessionId }, { chunkBytes: options.chunkBytes ?? CHUNK_BYTES });
31
+ return (0, render_1.whyTipLine)(transcript, rates, options.lang ?? 'en', options.context === 'plugin' ? 'plugin' : 'why');
32
+ }
@@ -14,6 +14,12 @@ export declare function discoverInsightTranscripts(roots?: {
14
14
  claude: string;
15
15
  codex: string;
16
16
  }): TranscriptLocation[];
17
+ /**
18
+ * A transcript named by its path, as `why <path>` reads it: Codex when the path
19
+ * is a rollout or sits under `.codex`, Claude Code otherwise, and the session id
20
+ * from the file name. Null when the path is not a file.
21
+ */
22
+ export declare function transcriptFileLocation(file: string): TranscriptLocation | null;
17
23
  export declare function selectInsightTranscript(session?: string, locations?: TranscriptLocation[]): TranscriptLocation;
18
24
  /**
19
25
  * A file Claude Code keeps inside a session's own directory, such as
@@ -2,6 +2,7 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.transcriptRoots = transcriptRoots;
4
4
  exports.discoverInsightTranscripts = discoverInsightTranscripts;
5
+ exports.transcriptFileLocation = transcriptFileLocation;
5
6
  exports.selectInsightTranscript = selectInsightTranscript;
6
7
  exports.isSessionSidecar = isSessionSidecar;
7
8
  exports.isSubagentTranscript = isSubagentTranscript;
@@ -43,12 +44,22 @@ function discoverInsightTranscripts(roots = transcriptRoots()) {
43
44
  visit(roots.codex, 'codex', 0);
44
45
  return found.sort((a, b) => b.modifiedAt - a.modifiedAt || a.path.localeCompare(b.path));
45
46
  }
47
+ /**
48
+ * A transcript named by its path, as `why <path>` reads it: Codex when the path
49
+ * is a rollout or sits under `.codex`, Claude Code otherwise, and the session id
50
+ * from the file name. Null when the path is not a file.
51
+ */
52
+ function transcriptFileLocation(file) {
53
+ if (!file || !(0, node_fs_1.existsSync)(file) || !(0, node_fs_1.statSync)(file).isFile())
54
+ return null;
55
+ const path = (0, node_path_1.resolve)(file);
56
+ return { path, host: /(?:rollout-|[\\/]\.codex[\\/])/.test(path) ? 'codex' : 'claude', sessionId: (0, node_path_1.basename)(path, '.jsonl'), modifiedAt: (0, node_fs_1.statSync)(path).mtimeMs };
57
+ }
46
58
  function selectInsightTranscript(session, locations) {
47
59
  const requested = session || process.env.AGENTGUARD_SESSION_ID || process.env.CLAUDE_SESSION_ID || process.env.CODEX_THREAD_ID;
48
- if (requested && (0, node_fs_1.existsSync)(requested) && (0, node_fs_1.statSync)(requested).isFile()) {
49
- const path = (0, node_path_1.resolve)(requested);
50
- return { path, host: /(?:rollout-|[\\/]\.codex[\\/])/.test(path) ? 'codex' : 'claude', sessionId: (0, node_path_1.basename)(path, '.jsonl'), modifiedAt: (0, node_fs_1.statSync)(path).mtimeMs };
51
- }
60
+ const file = requested ? transcriptFileLocation(requested) : null;
61
+ if (file)
62
+ return file;
52
63
  const candidates = locations ?? discoverInsightTranscripts();
53
64
  // With nothing requested, the newest top-level session wins. A subagent's own
54
65
  // transcript (Claude Code keeps them under <session>/subagents/agent-*.jsonl) is
@@ -1,6 +1,31 @@
1
1
  import type { Policy } from './types';
2
2
  /** Normalize before evaluating or hashing so receipts bind the actual policy. */
3
3
  export declare function normalizePolicy(policy: Policy): Policy;
4
+ /** Why a burn-policy.json that exists was not used. */
5
+ export type PolicyFileProblem = 'unreadable' | 'invalid_json' | 'not_object' | 'missing_mode' | 'invalid_mode' | 'missing_thresholds';
6
+ /**
7
+ * The policy file at a home: missing (the defaults apply, as intended), loaded,
8
+ * or present but ignored, with every reason and one plain line that says so.
9
+ */
10
+ export type PolicyFileCheck = {
11
+ status: 'missing';
12
+ file: string;
13
+ } | {
14
+ status: 'loaded';
15
+ file: string;
16
+ } | {
17
+ status: 'ignored';
18
+ file: string;
19
+ problems: PolicyFileProblem[];
20
+ line: string;
21
+ };
22
+ /**
23
+ * Whether the home's burn-policy.json is missing, loaded or ignored, decided
24
+ * exactly as loadPolicy decides. An ignored file leaves the defaults in place,
25
+ * which only watch, so a hand-edited file with a mistake would otherwise turn
26
+ * enforcement off without a word. Reads the file; writes nothing.
27
+ */
28
+ export declare function checkPolicyFile(home: string): PolicyFileCheck;
4
29
  export declare function loadPolicy(home: string, options?: {
5
30
  notice?: boolean;
6
31
  }): Policy;
@@ -1,9 +1,11 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.normalizePolicy = normalizePolicy;
4
+ exports.checkPolicyFile = checkPolicyFile;
4
5
  exports.loadPolicy = loadPolicy;
5
6
  /** Load additive policy defaults without rewriting the operator's policy. */
6
7
  const node_fs_1 = require("node:fs");
8
+ const node_os_1 = require("node:os");
7
9
  const node_path_1 = require("node:path");
8
10
  const defaults_1 = require("./defaults");
9
11
  const noticed = new Set();
@@ -82,22 +84,93 @@ function noticeOnce(home, fields) {
82
84
  }
83
85
  process.stderr.write(`AgentGuard loaded missing policy fields from defaults: ${fields.join(', ')}; existing overrides are unchanged.\n`);
84
86
  }
85
- function loadPolicy(home, options = {}) {
87
+ const REASON = {
88
+ unreadable: "it can't be read",
89
+ invalid_json: 'it is not valid JSON',
90
+ not_object: 'it is not a JSON object',
91
+ missing_mode: 'it has no "mode"',
92
+ invalid_mode: 'its "mode" is not "enforce" or "shadow"',
93
+ missing_thresholds: 'it has no "thresholds"',
94
+ };
95
+ const FIX = {
96
+ unreadable: 'Make it readable',
97
+ invalid_json: 'Fix the JSON',
98
+ not_object: 'Write it as {"mode": "enforce", "thresholds": {}}',
99
+ missing_mode: 'Add "mode": "enforce"',
100
+ invalid_mode: 'Set "mode" to "enforce"',
101
+ missing_thresholds: 'Add "thresholds": {}',
102
+ };
103
+ /** The path as a person types it: ~ for their home directory. */
104
+ function shownPath(file) {
105
+ const home = (0, node_os_1.homedir)();
106
+ return home && file.startsWith(home + node_path_1.sep) ? `~${file.slice(home.length)}` : file;
107
+ }
108
+ function ignored(file, problems, mode) {
109
+ // A file whose mode already says "shadow" only watches anyway; the fix makes it count again.
110
+ const lost = mode === 'shadow' ? 'so AgentGuard uses it' : 'to turn limits back on';
111
+ const reason = problems.length === 2 && problems[1] === 'missing_thresholds'
112
+ ? problems[0] === 'missing_mode' ? 'it has no "mode" and no "thresholds"' : `${REASON[problems[0]]}, and it has no "thresholds"`
113
+ : REASON[problems[0]];
114
+ const fix = problems.length === 2 ? `${FIX[problems[0]]} and ${problems[0] === 'missing_mode' ? '' : 'add '}"thresholds": {}` : FIX[problems[0]];
115
+ return { status: 'ignored', file, problems,
116
+ line: `AgentGuard ignored ${shownPath(file)}: ${reason}. Using the defaults, which only watch. ${fix} ${lost}.` };
117
+ }
118
+ /** What loadPolicy reads: the check, and the parsed policy when the file is used. */
119
+ function readPolicyFile(home) {
120
+ const file = (0, node_path_1.join)(home, 'burn-policy.json');
121
+ let text;
122
+ try {
123
+ text = (0, node_fs_1.readFileSync)(file, 'utf8');
124
+ }
125
+ catch (error) {
126
+ const code = error.code;
127
+ return { check: code === 'ENOENT' || code === 'ENOTDIR' ? { status: 'missing', file } : ignored(file, ['unreadable']) };
128
+ }
129
+ let parsed;
86
130
  try {
87
- const parsed = JSON.parse((0, node_fs_1.readFileSync)((0, node_path_1.join)(home, 'burn-policy.json'), 'utf8'));
88
- if (parsed && (parsed.mode === 'shadow' || parsed.mode === 'enforce') && parsed.thresholds) {
131
+ parsed = JSON.parse(text);
132
+ }
133
+ catch {
134
+ return { check: ignored(file, ['invalid_json']) };
135
+ }
136
+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed))
137
+ return { check: ignored(file, ['not_object']) };
138
+ const { mode, thresholds } = parsed;
139
+ const problems = [];
140
+ if (mode === undefined)
141
+ problems.push('missing_mode');
142
+ else if (mode !== 'shadow' && mode !== 'enforce')
143
+ problems.push('invalid_mode');
144
+ if (!thresholds)
145
+ problems.push('missing_thresholds');
146
+ return problems.length ? { check: ignored(file, problems, mode) } : { check: { status: 'loaded', file }, policy: parsed };
147
+ }
148
+ /**
149
+ * Whether the home's burn-policy.json is missing, loaded or ignored, decided
150
+ * exactly as loadPolicy decides. An ignored file leaves the defaults in place,
151
+ * which only watch, so a hand-edited file with a mistake would otherwise turn
152
+ * enforcement off without a word. Reads the file; writes nothing.
153
+ */
154
+ function checkPolicyFile(home) {
155
+ return readPolicyFile(home).check;
156
+ }
157
+ function loadPolicy(home, options = {}) {
158
+ const { policy } = readPolicyFile(home);
159
+ if (policy) {
160
+ try {
89
161
  const missing = [];
90
- if (parsed.thresholds.fanout?.windowActiveMinutes === undefined)
162
+ if (policy.thresholds.fanout?.windowActiveMinutes === undefined)
91
163
  missing.push('fanout.windowActiveMinutes=120');
92
- if (parsed.thresholds.spawnRate?.enforce === undefined)
164
+ if (policy.thresholds.spawnRate?.enforce === undefined)
93
165
  missing.push('spawnRate.enforce=true');
94
166
  if (missing.length && options.notice !== false)
95
167
  noticeOnce(home, missing);
96
- return normalizePolicy(withTeamThresholds(home, parsed));
168
+ return normalizePolicy(withTeamThresholds(home, policy));
169
+ }
170
+ catch {
171
+ /* unusable after all: shadow defaults */
97
172
  }
98
173
  }
99
- catch {
100
- /* no policy yet: shadow defaults */
101
- }
174
+ // No policy yet, or one that is ignored (checkPolicyFile says why): shadow defaults.
102
175
  return normalizePolicy(defaults_1.DEFAULT_POLICY);
103
176
  }
@@ -11,6 +11,7 @@
11
11
  import type { ReaderCursor } from './history/claude-transcript';
12
12
  import { type WhyLang } from './insights/i18n';
13
13
  import { type DollarRange, type PricingTable } from './insights/pricing';
14
+ import type { Policy } from './types';
14
15
  /** Fewer finished sub-agents than this say too little about the next one, so the line is left out. */
15
16
  export declare const MIN_FINISHED_SUBAGENTS = 3;
16
17
  export interface FinishedSubagents {
@@ -36,3 +37,13 @@ export declare function finishedSubagents(cursor: Pick<ReaderCursor, 'children'
36
37
  * is English on every host, so the hook passes 'en'.
37
38
  */
38
39
  export declare function subagentCostLine(summary: FinishedSubagents | null, lang?: WhyLang): string | null;
40
+ /**
41
+ * The line a STOP prints, exactly as Burn's own Claude Code hook prints it: the
42
+ * summary of a cursor that readSessionIncremental advanced, priced with the
43
+ * rates `why` uses (burn-pricing.json under `home`, or the policy's pricing
44
+ * file), in English like the rest of the STOP text. Null below three finished
45
+ * sub-agents. Best effort: a pricing file that cannot be read costs the line its
46
+ * dollars, and nothing here throws, so it can never turn a prompt into a
47
+ * failed-closed refusal.
48
+ */
49
+ export declare function decisionCostLine(cursor: Pick<ReaderCursor, 'children' | 'completed'>, home: string, policy?: Policy): string | null;
@@ -3,6 +3,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.MIN_FINISHED_SUBAGENTS = void 0;
4
4
  exports.finishedSubagents = finishedSubagents;
5
5
  exports.subagentCostLine = subagentCostLine;
6
+ exports.decisionCostLine = decisionCostLine;
6
7
  const i18n_1 = require("./insights/i18n");
7
8
  const live_1 = require("./insights/live");
8
9
  const pricing_1 = require("./insights/pricing");
@@ -63,3 +64,27 @@ function subagentCostLine(summary, lang = 'en') {
63
64
  return null;
64
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);
65
66
  }
67
+ /**
68
+ * The line a STOP prints, exactly as Burn's own Claude Code hook prints it: the
69
+ * summary of a cursor that readSessionIncremental advanced, priced with the
70
+ * rates `why` uses (burn-pricing.json under `home`, or the policy's pricing
71
+ * file), in English like the rest of the STOP text. Null below three finished
72
+ * sub-agents. Best effort: a pricing file that cannot be read costs the line its
73
+ * dollars, and nothing here throws, so it can never turn a prompt into a
74
+ * failed-closed refusal.
75
+ */
76
+ function decisionCostLine(cursor, home, policy) {
77
+ let rates;
78
+ try {
79
+ rates = (0, live_1.readPricing)(home, policy);
80
+ }
81
+ catch {
82
+ rates = null;
83
+ }
84
+ try {
85
+ return subagentCostLine(finishedSubagents(cursor, rates ?? {}, rates !== null));
86
+ }
87
+ catch {
88
+ return null;
89
+ }
90
+ }
package/package.json CHANGED
@@ -1,8 +1,12 @@
1
1
  {
2
2
  "name": "@agentguard-run/burn",
3
- "version": "0.3.20",
3
+ "version": "0.3.21",
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
+ "homepage": "https://agentguard.run/burn",
7
+ "bugs": {
8
+ "url": "https://github.com/MerchantGuard/agentguard-codex-plugin/issues"
9
+ },
6
10
  "type": "commonjs",
7
11
  "main": "dist/src/index.js",
8
12
  "types": "dist/src/index.d.ts",