@agentguard-run/burn 0.3.20 → 0.3.22
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 +23 -0
- package/README.md +13 -11
- package/dist/src/cli.js +6 -2
- package/dist/src/gateway.js +11 -7
- package/dist/src/history/claude-transcript.d.ts +37 -0
- package/dist/src/history/claude-transcript.js +47 -0
- package/dist/src/hook/pre-tool-use.d.ts +2 -14
- package/dist/src/hook/pre-tool-use.js +3 -39
- package/dist/src/index.d.ts +4 -1
- package/dist/src/index.js +18 -2
- package/dist/src/insights/calendar-render.d.ts +28 -5
- package/dist/src/insights/calendar-render.js +97 -42
- package/dist/src/insights/i18n.d.ts +2 -0
- package/dist/src/insights/i18n.js +3 -0
- package/dist/src/insights/pricing.js +2 -0
- package/dist/src/insights/render.d.ts +16 -1
- package/dist/src/insights/render.js +19 -4
- package/dist/src/insights/session-tip.d.ts +33 -0
- package/dist/src/insights/session-tip.js +32 -0
- package/dist/src/insights/sessions.d.ts +6 -0
- package/dist/src/insights/sessions.js +15 -4
- package/dist/src/policy.d.ts +25 -0
- package/dist/src/policy.js +82 -9
- package/dist/src/subagent-cost.d.ts +11 -0
- package/dist/src/subagent-cost.js +25 -0
- package/docs/USAGE_AND_PRICING.md +2 -2
- package/package.json +5 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,28 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 0.3.22 (2026-09-29)
|
|
4
|
+
|
|
5
|
+
- Prices Claude Sonnet 5.5 (`claude-sonnet-5-5`), released on September 28, 2026, at the rates on Anthropic's price list, checked on 2026-09-29: 2, 0.2, 2.5, 4 and 10 USD per million tokens for fresh input, cache read, five-minute write, one-hour write and output. Before this row its turns were unpriced, so a session that used Sonnet 5.5 showed no dollar total.
|
|
6
|
+
|
|
7
|
+
## 0.3.21 (2026-09-27)
|
|
8
|
+
|
|
9
|
+
- `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.
|
|
10
|
+
- 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.
|
|
11
|
+
- 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.
|
|
12
|
+
- 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.
|
|
13
|
+
- 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:
|
|
14
|
+
- `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.
|
|
15
|
+
- `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.
|
|
16
|
+
- `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.
|
|
17
|
+
- 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.
|
|
18
|
+
- 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.
|
|
19
|
+
- 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.
|
|
20
|
+
- `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.
|
|
21
|
+
- 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.
|
|
22
|
+
- npm now links the package to agentguard.run/burn and to the issue tracker (`homepage` and `bugs` in package.json).
|
|
23
|
+
- 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`.
|
|
24
|
+
- 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.
|
|
25
|
+
|
|
3
26
|
## 0.3.20 (2026-09-27)
|
|
4
27
|
|
|
5
28
|
- 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
|
|
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.
|
|
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
|
-
|
|
301
|
-
Su
|
|
302
|
-
Mo
|
|
303
|
-
Tu
|
|
304
|
-
We
|
|
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
|
|
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'}`,
|
package/dist/src/gateway.js
CHANGED
|
@@ -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 (
|
|
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 =
|
|
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
|
|
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
|
|
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:
|
|
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:
|
|
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
|
package/dist/src/index.d.ts
CHANGED
|
@@ -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.
|
|
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
|
|
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
|
|
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
|
|
41
|
-
*
|
|
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. */
|