@agentguard-run/burn 0.3.19 → 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 +41 -0
- package/README.md +63 -2
- package/dist/src/canvas.d.ts +7 -1
- package/dist/src/canvas.js +10 -1
- package/dist/src/cli.js +70 -6
- package/dist/src/frames.d.ts +10 -0
- package/dist/src/frames.js +5 -0
- package/dist/src/gateway.js +11 -7
- package/dist/src/history/claude-transcript.d.ts +63 -1
- package/dist/src/history/claude-transcript.js +105 -2
- package/dist/src/hook/pre-tool-use.d.ts +2 -10
- package/dist/src/hook/pre-tool-use.js +9 -18
- package/dist/src/index.d.ts +4 -1
- package/dist/src/index.js +18 -2
- package/dist/src/insights/calendar-render.d.ts +71 -0
- package/dist/src/insights/calendar-render.js +251 -0
- package/dist/src/insights/calendar.d.ts +138 -0
- package/dist/src/insights/calendar.js +431 -0
- package/dist/src/insights/i18n.d.ts +103 -6
- package/dist/src/insights/i18n.js +123 -7
- package/dist/src/insights/render.d.ts +85 -12
- package/dist/src/insights/render.js +207 -17
- 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/insights/transcript.d.ts +13 -2
- package/dist/src/insights/transcript.js +61 -6
- package/dist/src/insights/types.d.ts +14 -0
- package/dist/src/policy.d.ts +25 -0
- package/dist/src/policy.js +82 -9
- package/dist/src/recording.js +5 -1
- package/dist/src/replay/render.d.ts +2 -0
- package/dist/src/replay/render.js +4 -0
- package/dist/src/stop-text.d.ts +11 -2
- package/dist/src/stop-text.js +23 -3
- package/dist/src/subagent-cost.d.ts +49 -0
- package/dist/src/subagent-cost.js +90 -0
- package/package.json +5 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,46 @@
|
|
|
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
|
+
|
|
22
|
+
## 0.3.20 (2026-09-27)
|
|
23
|
+
|
|
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`.
|
|
25
|
+
- The calendar's summary gives the total tokens, the dollars at API prices ("not a bill"), the busiest day, the share of tokens sub-agents used and, when there were any, how many sub-agent launches AgentGuard held: refused by an enforced STOP, or held for your yes. A total of $1,000 or more (at API prices, not a bill) prints in whole dollars with thousands separators, for example "$28,252 to $28,254 at API prices, not a bill", and as one number when both ends round to the same dollar. A day is amber when sub-agents used more than half of its tokens and carries a red mark when AgentGuard held a launch; piped or without colour those days are the letters `s` and `H`. Nothing in the calendar compares you with anyone else.
|
|
26
|
+
- The calendar counts each response once, on the local day it was recorded, with the parser and prices `why` uses. A response stored in two files (a sub-agent's copy of its parent's reply, a project that moved, a forked session) counts once. Checked against `why` on 574 real sessions, every day matched except one session stored in two project directories, which the calendar counts once across both. A forked Codex session whose copied history has no verifiable boundary is left out, with a note.
|
|
27
|
+
- Claude Code deletes transcripts after 30 days by default, so each `calendar` run keeps a daily count per transcript in `calendar/daily.json` under the Burn home: tokens, sub-agent tokens and dollars per day, with no paths and no content, readable only by you. A transcript still on disk is always counted from the transcript, a deleted one's days come from the daily count, and no day is counted twice. `calendar/cache.json` lets a later run read again only the transcripts that changed. A very large transcript is read in 16 MB pieces, so it never has to fit in memory as one string.
|
|
28
|
+
- `why` now ends with the one action that matters most for the session, from the session's own numbers and Anthropic's published guidance (code.claude.com/docs/en/costs, /prompt-caching and /sub-agents). A cause stands out at the 0.3.16 thresholds (sub-agents at 20% of session tokens, full-prefix rewrites at 15% of the API list total) or, for two new causes, at 30% of session tokens: the conversation Claude reads again on every message, and the setup it reads before every message. The cause that is largest at API list price wins, or the largest in tokens when a model has no known price. The actions:
|
|
29
|
+
- Sub-agents that ran on the main conversation's model: "Next: 38 sub-agents ran on Opus 5.5. 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."
|
|
30
|
+
- Any other sub-agent use, reworded because a STOP now asks first: "Next: sub-agents used 48.9% of this session's tokens. AgentGuard's free plugin asks you before the next sub-agent past your limit starts: agentguard.run/try". 0.3.19 said spawn limits refuse that launch. In interactive Claude Code the next launch past a limit waits for your yes; it is refused only where no prompt can show. Spanish and Portuguese say the same.
|
|
31
|
+
- Reloads after a pause longer than the cache lasts: how many, the longest pause, and "Run /compact before a break, so the reload after it is smaller." Reloads caused by switching models: how many, and "Pick your model when you start, or switch at a break, right after /compact." Any other reload cause: the 0.3.16 tip with its dollars and `rewrites`, unchanged.
|
|
32
|
+
- The conversation read again on every message: its median per message, and "/compact at a natural break, or /clear between unrelated tasks". This replaces the 0.3.16 history tip.
|
|
33
|
+
- The setup read before every message (CLAUDE.md, tools, MCP servers and your first message): its median per message, a short CLAUDE.md, and turning off MCP servers you are not using (/mcp).
|
|
34
|
+
No tip claims a saving, and no new tip prints a dollar figure. `quiet on` still hides the tip.
|
|
35
|
+
- `why` adds one measured line when the transcript records a `/compact`, an automatic compaction, a model switch or a `/clear`, for example "Measured change: after /compact on 2026-09-27 at 14:02 UTC, Claude read a median of 85K tokens per message, down from 660K in the 20 messages before." It compares the median tokens per message in up to 20 messages after the latest such event with as many before it, main conversation only; with fewer than 5 on either side it tries an earlier event. It is a measurement next to an event, never a saving and never a cause, and it prints whether tips are on or off.
|
|
36
|
+
- A STOP now shows what the session's finished sub-agents averaged. When an enforced STOP holds a sub-agent launch in Claude Code and at least three of the session's sub-agents have finished, the permission prompt gains one line: "The 15 sub-agents that finished in this session averaged 10.0M tokens each ($4.99 at API prices, not a bill). This one could differ." The box of a refused launch carries the same line. A sub-agent counts as finished when Claude Code records it as completed; failed, killed and stopped ones do not. The figures come from the finished sub-agents' own transcripts, added up while the hook reads them as it already did, so the hook never reads a transcript twice; on the author's machine its time stayed within run-to-run noise. A model with no known price leaves the dollars out. With fewer than three finished, the prompt and the box are as in 0.3.19. Codex, Cursor, the proxy and the middleware print their STOP text unchanged.
|
|
37
|
+
- `--version` and `-v` print the version and exit 0. They used to print the whole help and exit 64.
|
|
38
|
+
- `help`, `--help` and `-h` print the help and exit 0. An unknown command still prints it and exits 64.
|
|
39
|
+
- Piped output is no longer cut short. The CLI now exits only after stdout and stderr have flushed; on macOS a pipe could stop at 64 KB (`calendar --weeks 53 json` stopped mid-string, and a large `why json` could too).
|
|
40
|
+
- The calendar, the tips and the measured line print in Latin American Spanish and Brazilian Portuguese as `why` does, figures in en-US digits. The STOP line is English, as all STOP text is.
|
|
41
|
+
- What changes in output: in English, `why` is byte-identical to 0.3.19 except the tip line, wherever the chosen tip or its wording changed, and the measured line, wherever an event qualifies. `why json` gains `signals.reset` (`{kind, trigger, at}`) on the first response after a compaction or a recorded `/clear`, and `state.pendingReset` when a transcript ends on one; a session with neither prints the same json as 0.3.19. The help lists `calendar`. The STOP prompt and box change only as described above. `compare` and every other command print what they did in 0.3.19.
|
|
42
|
+
- Internals: `readInsightTranscript` and `readInsightSession` take an optional `{ chunkBytes }`. `whyTip` takes a `WhyTipInput` that `whyTipInput` builds from `sessionFigures`. New `calendarDollars`, `proofLine`, `modelLabel`, `shortTokens`, `finishedSubagents`, `subagentCostLine`, `CALENDAR_TEXT` and `DECISION_TEXT`; `askReason` and `renderStop` take an optional cost line. Recordings accept `calendar` frames. Tests: 489 (488 pass, 1 skipped), up from 443 in 0.3.19.
|
|
43
|
+
|
|
3
44
|
## 0.3.19 (2026-09-27)
|
|
4
45
|
|
|
5
46
|
- Every command Burn prints now uses the short, unscoped name `npx agentguard-burn` (the `agentguard-burn` launcher on npm runs the latest Burn): the override line in the STOP box, the `why` tips in English, Spanish and Portuguese, and the `quiet` messages. The name has no "@", so X no longer turns a quoted command into a link to someone else's account. `why` output is otherwise byte-identical to 0.3.16 in English.
|
package/README.md
CHANGED
|
@@ -14,6 +14,8 @@ agentguard-burn why
|
|
|
14
14
|
|
|
15
15
|
The two init commands print hook configuration for review. Merge the relevant snippet into your host configuration. They do not write it. For Codex, review and trust the hook through `/hooks`. Upgrading an existing hook requires the new snippet: it matches every tool so pace can update on ordinary tool calls, while admission still gates spawns.
|
|
16
16
|
|
|
17
|
+
`agentguard-burn --version` (or `-v`) prints the installed version.
|
|
18
|
+
|
|
17
19
|
For Claude Code, configure its `statusLine` command as `agentguard-burn statusline`. It receives the host JSON on stdin. Codex 0.154.0 has no external status command slot. Use `agentguard-burn statusline SESSION_ID` in a companion terminal and the native Codex limit indicators. See [host fields and setup](docs/USAGE_AND_PRICING.md#what-the-hosts-expose).
|
|
18
20
|
|
|
19
21
|
## Import a DisciplineBench run
|
|
@@ -200,9 +202,18 @@ A session argument can also be a transcript path. Without one, Burn uses the ses
|
|
|
200
202
|
|
|
201
203
|
The table covers instruction stack + system, history re-sent, repeated file reads, subagent fan-out, tool output, conversation, full-prefix rewrites, output and unattributed usage. The fixed-prefix baseline is the first assistant response's measured context. It includes the initial user message, so the label is an operational baseline rather than a direct measurement of instruction files. A rewrite classified as prefix change resets that baseline and is counted in the footer; the new baseline can include history already present at that point.
|
|
202
204
|
|
|
203
|
-
The report ends with at most one tip
|
|
205
|
+
The report ends with at most one tip: the one action that matters most for this session, from its own numbers. A cause stands out at these shares: sub-agents at 20% or more of session tokens, full-prefix rewrites at 15% or more of the session's API list equivalent (skipped when a model is unpriced), and the conversation Claude re-reads, or the setup it reads before every message, at 30% or more of session tokens. Among the causes that stand out, the largest at API list price wins (the largest in tokens when a model is unpriced), and the tip names one action from Anthropic's own guidance ([costs](https://code.claude.com/docs/en/costs), [prompt caching](https://code.claude.com/docs/en/prompt-caching), [sub-agents](https://code.claude.com/docs/en/sub-agents)):
|
|
206
|
+
|
|
207
|
+
- Sub-agents that ran on the main model: `38 sub-agents ran on Opus 5.5.` and a smaller model for searching and reading logs (`CLAUDE_CODE_SUBAGENT_MODEL=haiku`, or `model: haiku` in the sub-agent's definition). Otherwise the sub-agent share, and AgentGuard's free plugin, which asks you before the next sub-agent past your limit starts.
|
|
208
|
+
- Reloads after a pause outlasted the cache: how many, the longest pause, and `/compact` before a break. Reloads from switching models: how many, and switching at a break right after `/compact`. Any other reload cause: the dollars and `agentguard-burn rewrites`.
|
|
209
|
+
- The conversation re-read on every message: its median per message, and `/compact` at a natural break or `/clear` between unrelated tasks.
|
|
210
|
+
- The setup read before every message (CLAUDE.md, tools, MCP servers and the first message): its median per message, a short CLAUDE.md and turning off unused MCP servers (`/mcp`).
|
|
211
|
+
|
|
212
|
+
The setup and the re-read conversation split each call's cached reads at the size of the session's first call, so a rewrite that resets the table's baseline never turns re-read conversation into setup. Tips never claim a saving and print no dollar figure except the rewrite dollars the table prints. When nothing stands out there is no tip. `agentguard-burn quiet on` hides it, `quiet off` shows it again and `quiet` says which. `why json` never contains it.
|
|
204
213
|
|
|
205
|
-
`why`
|
|
214
|
+
After a `/compact`, an automatic compaction, a model switch, or a `/clear` that the transcript records, `why` adds one measured line before the tip, for example `Measured change: after /compact on 2026-09-27 at 14:02 UTC, Claude read a median of 85K tokens per message, down from 660K in the 20 messages before.` It compares the median tokens per message of the main conversation in the N messages after the latest such event with the N before it: N is 20, fewer when the session or the next or previous event leaves fewer, and with fewer than 5 on either side that event says nothing. It states a measurement next to an event, never a saving or a cause, and prints whether or not tips are on.
|
|
215
|
+
|
|
216
|
+
`why` prints in Latin American Spanish or Brazilian Portuguese when your machine is set to that language, and `--lang es`, `--lang pt` or `--lang en` picks one explicitly. The order is `--lang`, then `AGENTGUARD_LANG`, then `LC_ALL`, `LC_MESSAGES` and `LANG` (the first one set decides, as POSIX says, so `LC_ALL=C` means English), then the locale Node resolves. Every other language is English. Figures keep their en-US formatting in every language (`1,234,567`, `$1335.37`, `12.3%`), so a translated report matches screenshots digit for digit. `why`, `compare` and `calendar` are translated. Their `json` output is the same in every language, and every other command stays English.
|
|
206
217
|
|
|
207
218
|
Later cache reads up to the baseline go to instruction stack + system. Reads above it go to history re-sent. Fresh input plus cache creation is the measured arriving increment. Burn subtracts the previous response's output before assigning that increment to intervening tool results and user messages. Result byte sizes only split that measured total; bytes are never converted into tokens. A result for a previously read Read path goes to re-read files. Mixed user and tool intervals are marked shared and counted in the footer.
|
|
208
219
|
|
|
@@ -266,6 +277,49 @@ AgentGuard cannot tell whether these sessions did the same task. Compare runs of
|
|
|
266
277
|
|
|
267
278
|
`compare` measures and does not rank models. `--lang es|pt` and your locale choose the language exactly as for `why`. `compare json` is never translated: both sessions with ids, paths, project, models and every metric, and each change as an unrounded fraction of A.
|
|
268
279
|
|
|
280
|
+
## Tokens per day
|
|
281
|
+
|
|
282
|
+
```sh
|
|
283
|
+
agentguard-burn calendar
|
|
284
|
+
agentguard-burn calendar --weeks 12
|
|
285
|
+
agentguard-burn calendar json
|
|
286
|
+
```
|
|
287
|
+
|
|
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
|
+
|
|
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
|
+
|
|
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:
|
|
295
|
+
|
|
296
|
+
```text
|
|
297
|
+
AgentGuard calendar: tokens per day, Aug 30 to Sep 26, 2026
|
|
298
|
+
696,040 tokens · $7.29 at API prices, not a bill
|
|
299
|
+
busiest day: Sep 24 (511,040 tokens) · sub-agents used 7.3% of tokens
|
|
300
|
+
AgentGuard held 2 launches
|
|
301
|
+
|
|
302
|
+
Sep
|
|
303
|
+
Su ·· ·· ··
|
|
304
|
+
Mo ·· ▓s ··
|
|
305
|
+
Tu ░░ ·· ·· ··
|
|
306
|
+
We ·· ▒▒ █H ··
|
|
307
|
+
Th ·· ·· ·· ██
|
|
308
|
+
Fr ·· ·· ·· ··
|
|
309
|
+
Sa ·· ·· ·· ▒▒
|
|
310
|
+
|
|
311
|
+
Less ·· ░░ ▒▒ ▓▓ ██ More
|
|
312
|
+
Days marked s: sub-agents used more than half of that day's tokens.
|
|
313
|
+
Days marked H: AgentGuard held a launch that day.
|
|
314
|
+
From Claude Code and Codex sessions on this machine, sub-agents included.
|
|
315
|
+
Claude Code deletes sessions older than 30 days by default.
|
|
316
|
+
Burn keeps each day's count whenever you run this, so the calendar grows.
|
|
317
|
+
```
|
|
318
|
+
|
|
319
|
+
Claude Code deletes transcripts after 30 days by default (`cleanupPeriodDays`), so each run keeps a daily count per transcript file in `calendar/daily.json` under the Burn home (`AGENTGUARD_HOME`, default `~/.agentguard`): tokens, sub-agent tokens and dollars per day, with no paths and no content, owner-only and written atomically. A transcript still on disk is always counted from the transcript; a deleted transcript's days come from the daily count; no file-day is counted from both. Run `calendar` at least once within Claude Code's retention period to keep every day. `calendar/cache.json` keeps each response's counts, keyed by the transcript's path digest, size and modification time, so a later run re-reads only the transcripts that changed; a new Burn version or a pricing override recounts everything once.
|
|
320
|
+
|
|
321
|
+
`calendar json` is never translated: every day of the span with its figures and level, the totals, the busiest day and where the figures came from. `--lang es|pt` and your locale choose the language exactly as for `why`. Nothing in the calendar compares you with anyone else.
|
|
322
|
+
|
|
269
323
|
## Two safety planes
|
|
270
324
|
|
|
271
325
|
Structural limits use active time rather than the age of the session. The
|
|
@@ -398,9 +452,16 @@ prompt. The prompt names the one limit that fired, for example:
|
|
|
398
452
|
```
|
|
399
453
|
AgentGuard: 15 sub-agents in the last 15 active minutes. Limit: 15.
|
|
400
454
|
Session so far: 15 sub-agents, 154.0M tokens.
|
|
455
|
+
The 12 sub-agents that finished in this session averaged 10.0M tokens each ($4.99 at API prices, not a bill). This one could differ.
|
|
401
456
|
Allow this one launch? If you say no, nothing starts.
|
|
402
457
|
```
|
|
403
458
|
|
|
459
|
+
The third line appears once at least three of the session's sub-agents have
|
|
460
|
+
finished: what they averaged, measured from their own transcripts as the hook
|
|
461
|
+
reads them anyway (never a second pass), and never a forecast. With fewer, the
|
|
462
|
+
prompt is the other three lines. The box of a refused launch carries the same
|
|
463
|
+
line.
|
|
464
|
+
|
|
404
465
|
You answer with one keypress. Claude never sees that text, and auto mode
|
|
405
466
|
cannot approve it silently (Claude Code 2.1.211 and later), so the answer is
|
|
406
467
|
yours. Where no prompt can appear (print mode, `bypassPermissions`, `dontAsk`,
|
package/dist/src/canvas.d.ts
CHANGED
|
@@ -1,4 +1,10 @@
|
|
|
1
|
-
|
|
1
|
+
/**
|
|
2
|
+
* Heat ramps for calendar cells: `shade0` is a day with no tokens; `teal1` to
|
|
3
|
+
* `teal4` and `amber1` to `amber4` are the four token levels, mixed from the
|
|
4
|
+
* canvas background toward mint and amber, so the top level is the brand colour.
|
|
5
|
+
*/
|
|
6
|
+
export type CanvasHeatColor = 'shade0' | 'teal1' | 'teal2' | 'teal3' | 'teal4' | 'amber1' | 'amber2' | 'amber3' | 'amber4';
|
|
7
|
+
export type CanvasColor = 'mint' | 'slate' | 'amber' | 'red' | 'white' | 'none' | CanvasHeatColor;
|
|
2
8
|
export type CanvasColorMode = 'truecolor' | '256' | 'none';
|
|
3
9
|
export interface CanvasCell {
|
|
4
10
|
char: string;
|
package/dist/src/canvas.js
CHANGED
|
@@ -9,6 +9,15 @@ exports.CANVAS_PALETTE = {
|
|
|
9
9
|
amber: { hex: '#F59E0B', rgb: [245, 158, 11], ansi256: 208 },
|
|
10
10
|
red: { hex: '#EF4444', rgb: [239, 68, 68], ansi256: 203 },
|
|
11
11
|
white: { hex: '#E2E8F0', rgb: [226, 232, 240], ansi256: 254 },
|
|
12
|
+
shade0: { hex: '#333E4B', rgb: [51, 62, 75], ansi256: 238 },
|
|
13
|
+
teal1: { hex: '#164E4E', rgb: [22, 78, 78], ansi256: 23 },
|
|
14
|
+
teal2: { hex: '#1C6F6D', rgb: [28, 111, 109], ansi256: 30 },
|
|
15
|
+
teal3: { hex: '#239692', rgb: [35, 150, 146], ansi256: 37 },
|
|
16
|
+
teal4: { hex: '#2ABCB4', rgb: [42, 188, 180], ansi256: 44 },
|
|
17
|
+
amber1: { hex: '#5D4213', rgb: [93, 66, 19], ansi256: 94 },
|
|
18
|
+
amber2: { hex: '#8C5F10', rgb: [140, 95, 16], ansi256: 136 },
|
|
19
|
+
amber3: { hex: '#C27F0E', rgb: [194, 127, 14], ansi256: 172 },
|
|
20
|
+
amber4: { hex: '#F59E0B', rgb: [245, 158, 11], ansi256: 214 },
|
|
12
21
|
};
|
|
13
22
|
const GLYPHS = {
|
|
14
23
|
'0': ['█▀█', '█ █', '█▄█'], '1': [' ▀█', ' █', ' █'],
|
|
@@ -31,7 +40,7 @@ const BIG_GLYPHS = {
|
|
|
31
40
|
'9': [' ### ', '# #', '# #', ' ####', ' #', ' #', ' ### '],
|
|
32
41
|
'-': [' ', ' ', ' ', '#####', ' ', ' ', ' '],
|
|
33
42
|
};
|
|
34
|
-
const colors = new Set(['mint', 'slate', 'amber', 'red', 'white', 'none']);
|
|
43
|
+
const colors = new Set(['mint', 'slate', 'amber', 'red', 'white', 'none', 'shade0', 'teal1', 'teal2', 'teal3', 'teal4', 'amber1', 'amber2', 'amber3', 'amber4']);
|
|
35
44
|
function dimension(value, fallback, limit) {
|
|
36
45
|
return Math.max(1, Math.min(limit, Math.floor(typeof value === 'number' && Number.isFinite(value) ? value : fallback)));
|
|
37
46
|
}
|
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");
|
|
@@ -141,6 +142,11 @@ async function main(argv) {
|
|
|
141
142
|
};
|
|
142
143
|
const has = (name) => rawRest.includes(name);
|
|
143
144
|
switch (command) {
|
|
145
|
+
case '--version':
|
|
146
|
+
case '-v':
|
|
147
|
+
// The version of this install, from the package that ships it, and nothing else.
|
|
148
|
+
process.stdout.write(`${require('../../package.json').version}\n`);
|
|
149
|
+
return 0;
|
|
144
150
|
case 'live': {
|
|
145
151
|
const { runLivePanel } = await Promise.resolve().then(() => __importStar(require('./live-panel')));
|
|
146
152
|
return runLivePanel(HOME, rawRest);
|
|
@@ -263,6 +269,48 @@ async function main(argv) {
|
|
|
263
269
|
show({ kind: 'command', command, values: { ...report } }, json ? JSON.stringify(report, null, 2) + '\n' : renderCompare(report, language) + '\n', json);
|
|
264
270
|
return 0;
|
|
265
271
|
}
|
|
272
|
+
case 'calendar': {
|
|
273
|
+
// `--weeks N` (1 to 53, also --weeks=N), `json`, and `--lang` exactly as `why` takes it.
|
|
274
|
+
const args = [];
|
|
275
|
+
let lang, langGiven = false, weeksText, weeksGiven = false;
|
|
276
|
+
for (let i = 0; i < rest.length; i++) {
|
|
277
|
+
if (rest[i] === '--lang') {
|
|
278
|
+
langGiven = true;
|
|
279
|
+
lang = rest[++i];
|
|
280
|
+
}
|
|
281
|
+
else if (rest[i].startsWith('--lang=')) {
|
|
282
|
+
langGiven = true;
|
|
283
|
+
lang = rest[i].slice('--lang='.length);
|
|
284
|
+
}
|
|
285
|
+
else if (rest[i] === '--weeks') {
|
|
286
|
+
weeksGiven = true;
|
|
287
|
+
weeksText = rest[++i];
|
|
288
|
+
}
|
|
289
|
+
else if (rest[i].startsWith('--weeks=')) {
|
|
290
|
+
weeksGiven = true;
|
|
291
|
+
weeksText = rest[i].slice('--weeks='.length);
|
|
292
|
+
}
|
|
293
|
+
else
|
|
294
|
+
args.push(rest[i]);
|
|
295
|
+
}
|
|
296
|
+
const json = args.includes('json') || args.includes('--json');
|
|
297
|
+
const weeks = weeksGiven && /^\d{1,2}$/.test(weeksText ?? '') ? Number(weeksText) : undefined;
|
|
298
|
+
if ((langGiven && (0, i18n_1.whyLangOf)(lang) === null) || (weeksGiven && !(weeks >= 1 && weeks <= 53)) || args.some(value => value !== 'json' && value !== '--json')) {
|
|
299
|
+
process.stderr.write('Usage: agentguard-burn calendar [--weeks N] [json] [--lang en|es|pt]\n');
|
|
300
|
+
return 64;
|
|
301
|
+
}
|
|
302
|
+
const language = (0, i18n_1.detectWhyLang)({ flag: lang, env: process.env, intlLocale: intlLocale() });
|
|
303
|
+
const { calendarReport, collectCalendar } = await Promise.resolve().then(() => __importStar(require('./insights/calendar')));
|
|
304
|
+
const { renderCalendar } = await Promise.resolve().then(() => __importStar(require('./insights/calendar-render')));
|
|
305
|
+
// The span fits the terminal: its columns on a TTY, 80 when piped.
|
|
306
|
+
const columns = process.stdout.isTTY && (process.stdout.columns ?? 0) > 0 ? process.stdout.columns : 80;
|
|
307
|
+
const data = collectCalendar({ home: HOME, rates: (0, live_1.readPricing)(HOME, (0, pre_tool_use_1.loadPolicy)(HOME)) });
|
|
308
|
+
if (!data.saved)
|
|
309
|
+
process.stderr.write(i18n_1.CALENDAR_TEXT[language].saveFailed + '\n');
|
|
310
|
+
const report = calendarReport(data, { now: Date.now(), columns, ...(weeks ? { weeks } : {}) });
|
|
311
|
+
show({ kind: 'calendar', report, lang: language, columns }, json ? JSON.stringify(report, null, 2) + '\n' : renderCalendar(report, language, columns) + '\n', json);
|
|
312
|
+
return 0;
|
|
313
|
+
}
|
|
266
314
|
case 'quiet': {
|
|
267
315
|
const [state, ...extra] = rest;
|
|
268
316
|
if (extra.length || (state !== undefined && state !== 'on' && state !== 'off')) {
|
|
@@ -273,7 +321,7 @@ async function main(argv) {
|
|
|
273
321
|
(0, upgrade_moments_1.setQuiet)(HOME, state === 'on');
|
|
274
322
|
const quiet = quietOn();
|
|
275
323
|
show({ kind: 'command', command, values: { tips: quiet ? 'off' : 'on', quiet: quiet ? 'on' : 'off', file: (0, upgrade_moments_1.quietFile)(HOME) } }, quiet
|
|
276
|
-
? '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'
|
|
277
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');
|
|
278
326
|
return 0;
|
|
279
327
|
}
|
|
@@ -374,11 +422,14 @@ async function main(argv) {
|
|
|
374
422
|
case 'status': {
|
|
375
423
|
const monthly = (0, upgrade_moments_1.monthlySummary)(HOME);
|
|
376
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);
|
|
377
427
|
const e = shadowEligibility();
|
|
378
428
|
const gateway = new gateway_1.Gateway(HOME, { sign: false });
|
|
379
429
|
const lc = policy.thresholds.localCompute;
|
|
380
430
|
const override = (0, override_1.readOverride)(HOME);
|
|
381
|
-
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, ''] : []),
|
|
382
433
|
`mode: ${policy.mode}${policy.mode === 'enforce' ? ' (the next STOP blocks)' : ' (recording only; nothing is blocked)'}`,
|
|
383
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}`,
|
|
384
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'}`,
|
|
@@ -526,7 +577,7 @@ async function main(argv) {
|
|
|
526
577
|
return 0;
|
|
527
578
|
}
|
|
528
579
|
default:
|
|
529
|
-
show({ kind: 'command', command: 'help', values: { commands: ['ps', 'reap', 'live', 'record', 'render', 'blocks', 'limits', 'price-shadow', 'why', 'compare', 'rewrites', 'ttl', 'pace', 'statusline', 'pricing', 'replay', 'calibrate', 'status', 'init', 'enforce', 'shadow', 'resume', 'quiet', 'proxy', 'conformance'] } }, 'agentguard-burn <ps|reap|live|record|render|blocks|limits|price-shadow|why|compare|rewrites|ttl|pace|statusline|pricing|replay|calibrate|status|init|enforce|shadow|resume|quiet|proxy|conformance>\n' +
|
|
580
|
+
show({ kind: 'command', command: 'help', values: { commands: ['ps', 'reap', 'live', 'record', 'render', 'blocks', 'limits', 'price-shadow', 'calendar', 'why', 'compare', 'rewrites', 'ttl', 'pace', 'statusline', 'pricing', 'replay', 'calibrate', 'status', 'init', 'enforce', 'shadow', 'resume', 'quiet', 'proxy', 'conformance'] } }, 'agentguard-burn <ps|reap|live|record|render|blocks|limits|price-shadow|calendar|why|compare|rewrites|ttl|pace|statusline|pricing|replay|calibrate|status|init|enforce|shadow|resume|quiet|proxy|conformance>\n' +
|
|
530
581
|
' ps [--json] local agent processes, held memory and workspace disk\n' +
|
|
531
582
|
' render <run.jsonl> --mp4 <out.mp4> [--gif <out.gif>] [--phone] local recorded-run export\n' +
|
|
532
583
|
' render <run.jsonl> --mp4 <out.mp4> --dashboard [--wide] [--economics <blocks.json>] dashboard export\n' +
|
|
@@ -540,6 +591,7 @@ async function main(argv) {
|
|
|
540
591
|
' why [session] token attribution and API list-price equivalents\n' +
|
|
541
592
|
' --lang es|pt the why report in Latin American Spanish or Brazilian Portuguese; your locale picks it by default\n' +
|
|
542
593
|
' compare [sessionA] [sessionB] two sessions side by side: tokens, cache, sub-agents, rewrites, list USD; json and --lang as for why\n' +
|
|
594
|
+
' calendar [--weeks N] tokens per day, Claude Code and Codex together: sub-agent days, launches AgentGuard held, dollars at API prices; json and --lang as for why\n' +
|
|
543
595
|
' rewrites [session|all] every full-prefix cache write with its cause, idle gap and list price\n' +
|
|
544
596
|
' ttl [session|all] one-hour cache lifetime counterfactual from your own idle gaps\n' +
|
|
545
597
|
' pace [session] ten-minute pace and next-hour projection\n' +
|
|
@@ -561,7 +613,7 @@ async function main(argv) {
|
|
|
561
613
|
'Developer review commands (never installed as hooks):\n' +
|
|
562
614
|
' guard-candidates [--ledger <local.ndjson>] [--out <name.review.json>] [--rank]\n' +
|
|
563
615
|
' deduplicate recorded shell text; --rank explicitly permits jsort provider requests\n');
|
|
564
|
-
return command ?
|
|
616
|
+
return !command || command === 'help' || command === '--help' || command === '-h' ? 0 : 64;
|
|
565
617
|
}
|
|
566
618
|
}
|
|
567
619
|
async function run() {
|
|
@@ -607,7 +659,19 @@ async function run() {
|
|
|
607
659
|
throw error;
|
|
608
660
|
}
|
|
609
661
|
}
|
|
610
|
-
|
|
662
|
+
/**
|
|
663
|
+
* Exit once stdout and stderr have handed everything to the OS. A pipe is
|
|
664
|
+
* asynchronous on macOS, and exiting at once cut piped output at 64 KB
|
|
665
|
+
* (`calendar --weeks 53 json` stopped mid-string).
|
|
666
|
+
*/
|
|
667
|
+
function exit(code) {
|
|
668
|
+
let pending = 2;
|
|
669
|
+
const done = () => { if (--pending === 0)
|
|
670
|
+
process.exit(code); };
|
|
671
|
+
process.stdout.write('', done);
|
|
672
|
+
process.stderr.write('', done);
|
|
673
|
+
}
|
|
674
|
+
run().then((code) => exit(code), (error) => {
|
|
611
675
|
process.stderr.write(`${error instanceof Error ? error.message : String(error)}\n`);
|
|
612
|
-
|
|
676
|
+
exit(4);
|
|
613
677
|
});
|
package/dist/src/frames.d.ts
CHANGED
|
@@ -6,6 +6,8 @@ import type { AuditReport, AuditRow } from './idle/types';
|
|
|
6
6
|
import type { BurnReport } from './types';
|
|
7
7
|
import { type StopHost } from './stop-text';
|
|
8
8
|
import type { ReplaySummary } from './replay/simulate';
|
|
9
|
+
import type { CalendarReport } from './insights/calendar';
|
|
10
|
+
import type { WhyLang } from './insights/i18n';
|
|
9
11
|
export type AuditFrameReport = Omit<AuditReport, 'processes' | 'rows'> & {
|
|
10
12
|
rows: Array<Omit<AuditRow, 'processes'>>;
|
|
11
13
|
};
|
|
@@ -35,6 +37,14 @@ export type BurnFrame = {
|
|
|
35
37
|
command: string;
|
|
36
38
|
values: Record<string, unknown>;
|
|
37
39
|
page?: number;
|
|
40
|
+
}
|
|
41
|
+
/** A calendar is one block sized to its weeks, drawn whole and never paged; `columns` is the width its text wrapped at. */
|
|
42
|
+
| {
|
|
43
|
+
kind: 'calendar';
|
|
44
|
+
report: CalendarReport;
|
|
45
|
+
lang: WhyLang;
|
|
46
|
+
columns: number;
|
|
47
|
+
page?: number;
|
|
38
48
|
};
|
|
39
49
|
export interface FrameOptions {
|
|
40
50
|
recorded?: boolean;
|
package/dist/src/frames.js
CHANGED
|
@@ -35,6 +35,11 @@ function valueRows(values, prefix = '', depth = 0) {
|
|
|
35
35
|
});
|
|
36
36
|
}
|
|
37
37
|
function renderFrame(data, options = {}) {
|
|
38
|
+
if (data.kind === 'calendar') {
|
|
39
|
+
// Loaded only when a calendar is drawn, so hooks and other commands never load it.
|
|
40
|
+
const { drawCalendar } = require('./insights/calendar-render');
|
|
41
|
+
return drawCalendar(data.report, data.lang, data.columns, options.colour);
|
|
42
|
+
}
|
|
38
43
|
if (data.kind === 'bench')
|
|
39
44
|
return (0, bench_panel_1.renderBenchPanel)(data.snapshot, options);
|
|
40
45
|
if (data.kind === 'live')
|
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
|
|
@@ -14,6 +14,12 @@
|
|
|
14
14
|
import type { BurnEvent } from '../types';
|
|
15
15
|
/** Component maxima for one provider response, never transcript contents. */
|
|
16
16
|
export type UsageSnapshot = [input: number, output: number, cacheCreation: number, cacheRead: number];
|
|
17
|
+
/**
|
|
18
|
+
* Usage one child transcript added under one model, deduplicated exactly as the
|
|
19
|
+
* session totals are. Cache writes are split into their five-minute and one-hour
|
|
20
|
+
* parts when the record says; a write with no recorded lifetime is in neither.
|
|
21
|
+
*/
|
|
22
|
+
export type ChildUsage = [input: number, output: number, cacheWrite: number, cacheRead: number, cacheWrite5m: number, cacheWrite1h: number];
|
|
17
23
|
export interface ReaderCursor {
|
|
18
24
|
/** Byte just after the last complete newline we processed. */
|
|
19
25
|
offset: number;
|
|
@@ -27,18 +33,37 @@ export interface ReaderCursor {
|
|
|
27
33
|
usageByMessage?: Map<string, UsageSnapshot>;
|
|
28
34
|
/** Child file cursors share usageByMessage with their parent. */
|
|
29
35
|
children?: Map<string, ReaderCursor>;
|
|
36
|
+
/**
|
|
37
|
+
* On a child cursor read from its first byte: the usage that child added, by
|
|
38
|
+
* model id ('' when none is recorded). A child an older Burn had already read
|
|
39
|
+
* part of has none, and stays unmeasured rather than undercounted.
|
|
40
|
+
*/
|
|
41
|
+
usage?: Map<string, ChildUsage>;
|
|
42
|
+
/** Sub-agent ids the transcripts record as completed; the parent's set, shared with its children. */
|
|
43
|
+
completed?: Set<string>;
|
|
30
44
|
}
|
|
31
45
|
export declare function newCursor(): ReaderCursor;
|
|
32
46
|
interface RawLine {
|
|
47
|
+
type?: unknown;
|
|
33
48
|
timestamp?: string;
|
|
34
49
|
uuid?: string;
|
|
35
50
|
parentUuid?: string;
|
|
36
51
|
isSidechain?: boolean;
|
|
37
52
|
message?: {
|
|
38
53
|
id?: unknown;
|
|
39
|
-
|
|
54
|
+
model?: unknown;
|
|
55
|
+
usage?: Record<string, unknown>;
|
|
40
56
|
content?: unknown;
|
|
41
57
|
};
|
|
58
|
+
/** A queued message (queue-operation records). */
|
|
59
|
+
content?: unknown;
|
|
60
|
+
/** A queued command (attachment records). */
|
|
61
|
+
attachment?: {
|
|
62
|
+
type?: unknown;
|
|
63
|
+
prompt?: unknown;
|
|
64
|
+
};
|
|
65
|
+
/** A tool's recorded result; a synchronous sub-agent's carries its id and status. */
|
|
66
|
+
toolUseResult?: unknown;
|
|
42
67
|
}
|
|
43
68
|
/** Turn one parsed line into an event, or null if it carries nothing we track. */
|
|
44
69
|
export declare function normaliseLine(raw: RawLine, cursor: ReaderCursor): BurnEvent | null;
|
|
@@ -58,6 +83,43 @@ export declare function readIncremental(path: string, cursor: ReaderCursor, opti
|
|
|
58
83
|
* usage deltas contribute here. The parent's observed spawn count stays intact.
|
|
59
84
|
*/
|
|
60
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;
|
|
61
123
|
/** Convenience for replay and tests: read a session and its own stored children. */
|
|
62
124
|
export declare function readAll(path: string): {
|
|
63
125
|
events: BurnEvent[];
|