@agentguard-run/burn 0.3.18 → 0.3.20

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.
Files changed (35) hide show
  1. package/CHANGELOG.md +33 -0
  2. package/README.md +105 -5
  3. package/dist/src/canvas.d.ts +7 -1
  4. package/dist/src/canvas.js +10 -1
  5. package/dist/src/cli.js +101 -7
  6. package/dist/src/frames.d.ts +10 -0
  7. package/dist/src/frames.js +5 -0
  8. package/dist/src/history/claude-transcript.d.ts +26 -1
  9. package/dist/src/history/claude-transcript.js +58 -2
  10. package/dist/src/hook/pre-tool-use.d.ts +6 -2
  11. package/dist/src/hook/pre-tool-use.js +35 -8
  12. package/dist/src/insights/calendar-render.d.ts +48 -0
  13. package/dist/src/insights/calendar-render.js +196 -0
  14. package/dist/src/insights/calendar.d.ts +138 -0
  15. package/dist/src/insights/calendar.js +431 -0
  16. package/dist/src/insights/compare.d.ts +104 -0
  17. package/dist/src/insights/compare.js +210 -0
  18. package/dist/src/insights/i18n.d.ts +134 -8
  19. package/dist/src/insights/i18n.js +200 -13
  20. package/dist/src/insights/render.d.ts +93 -13
  21. package/dist/src/insights/render.js +212 -28
  22. package/dist/src/insights/sessions.d.ts +25 -0
  23. package/dist/src/insights/sessions.js +72 -5
  24. package/dist/src/insights/transcript.d.ts +13 -2
  25. package/dist/src/insights/transcript.js +61 -6
  26. package/dist/src/insights/types.d.ts +17 -0
  27. package/dist/src/insights/types.js +3 -1
  28. package/dist/src/recording.js +5 -1
  29. package/dist/src/replay/render.d.ts +2 -0
  30. package/dist/src/replay/render.js +4 -0
  31. package/dist/src/stop-text.d.ts +16 -5
  32. package/dist/src/stop-text.js +28 -6
  33. package/dist/src/subagent-cost.d.ts +38 -0
  34. package/dist/src/subagent-cost.js +65 -0
  35. package/package.json +1 -1
@@ -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 ReaderCursor, type UsageSnapshot } from '../history/claude-transcript';
17
+ import { type ChildUsage, type ReaderCursor, type UsageSnapshot } from '../history/claude-transcript';
18
18
  import type { BurnReport, Policy, SessionState } from '../types';
19
19
  export interface HookInput {
20
20
  hook_event_name?: string;
@@ -46,6 +46,10 @@ export interface PersistedReaderCursor {
46
46
  usageVersion?: 1;
47
47
  usageByMessage?: [string, UsageSnapshot][];
48
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[];
49
53
  }
50
54
  export interface PersistedSession {
51
55
  cursor: PersistedReaderCursor;
@@ -84,7 +88,7 @@ export declare function handlePreToolUse(input: HookInput, home: string, now?: n
84
88
  */
85
89
  export declare function asksPerson(input: HookInput, policy: Pick<Policy, 'stopStyle'>): boolean;
86
90
  /** What Claude is told when it tries to override AgentGuard itself. */
87
- export declare const AGENT_OVERRIDE_REASON = "AgentGuard: overrides come from the person, not the agent. Ask them to type it themselves in Claude Code, with ! in front:\n! npx @agentguard-run/burn resume --once --reason \"...\"";
91
+ export declare const AGENT_OVERRIDE_REASON = "AgentGuard: overrides come from the person, not the agent. Ask them to type it themselves in Claude Code, with ! in front:\n! npx agentguard-burn resume --once --reason \"...\"";
88
92
  /**
89
93
  * An agent's own attempt to lift a STOP: running `resume`, `shadow` or
90
94
  * `calibrate` (which writes a shadow policy), or writing the override or
@@ -42,6 +42,7 @@ const stop_text_1 = require("../stop-text");
42
42
  const node_os_1 = require("node:os");
43
43
  const live_1 = require("../insights/live");
44
44
  const hook_1 = require("../idle/hook");
45
+ const subagent_cost_1 = require("../subagent-cost");
45
46
  const SPAWN_TOOLS = new Set(['Agent', 'Task']);
46
47
  function sessionFile(home, sessionId) {
47
48
  return (0, node_path_1.join)(home, 'sessions', `${sessionId.replace(/[^a-zA-Z0-9_-]/g, '_')}.json`);
@@ -55,15 +56,19 @@ function inflateHookSession(raw) {
55
56
  surfaceReaders: new Map(raw.state.surfaceReaders.map(([k, v]) => [k, new Set(v)])),
56
57
  };
57
58
  }
58
- function inflateCursor(raw, shared) {
59
+ function inflateCursor(raw, shared, completed) {
59
60
  const usageByMessage = shared ?? new Map(raw.usageByMessage ?? []);
60
- return { ...raw, depthByUuid: new Map(raw.depthByUuid), usageByMessage,
61
- children: new Map((raw.children ?? []).map(([name, child]) => [name, inflateCursor(child, 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)])) };
62
65
  }
63
66
  function persistCursor(cursor, child = false) {
64
67
  return { offset: cursor.offset, size: cursor.size, malformedLines: cursor.malformedLines, depthByUuid: [...cursor.depthByUuid],
65
68
  usageVersion: cursor.usageVersion,
66
69
  ...(!child ? { usageByMessage: [...(cursor.usageByMessage ?? [])] } : {}),
70
+ ...(!child && cursor.completed?.size ? { completed: [...cursor.completed] } : {}),
71
+ ...(child && cursor.usage ? { usage: [...cursor.usage] } : {}),
67
72
  ...(cursor.children?.size ? { children: [...cursor.children].map(([name, value]) => [name, persistCursor(value, true)]) } : {}) };
68
73
  }
69
74
  function loadSession(home, sessionId, firstEventAt) {
@@ -204,7 +209,6 @@ function handleSpawnPreToolUse(input, home, now) {
204
209
  const proposedDepth = input.agent_id ? 2 : 1;
205
210
  const { report, reservation, window } = (0, spawn_window_1.evaluateSpawnReservation)(tx, state, policy.thresholds, proposedDepth, input.tool_use_id ?? `${input.session_id}:${now}`, now, { sessions: (0, account_1.readAccountSessions)(home, state, now), now });
206
211
  const shouldDeny = report.verdict === 'STOP' || !reservation.allowed;
207
- const reason = shouldDeny ? buildDenyReason(report, reservation) : '';
208
212
  // The audited override: only consulted when a block is about to happen.
209
213
  const override = shouldDeny && policy.mode === 'enforce' ? (0, override_1.consumeOverride)(home, now) : null;
210
214
  const blocked = policy.mode === 'enforce' && shouldDeny && !override;
@@ -244,12 +248,14 @@ function handleSpawnPreToolUse(input, home, now) {
244
248
  });
245
249
  if (shouldDeny && policy.mode === 'enforce') {
246
250
  if (!override) {
251
+ // 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);
247
253
  if (asked) {
248
254
  (0, recording_1.recordFrame)({ kind: 'report', report, outcome: 'asked', host: 'claude-code' });
249
- return ask((0, stop_text_1.askReason)(report));
255
+ return ask((0, stop_text_1.askReason)(report, costLine));
250
256
  }
251
257
  (0, recording_1.recordFrame)({ kind: 'report', report, outcome: 'blocked', host: 'claude-code' });
252
- return deny(reason);
258
+ return deny(buildDenyReason(report, costLine));
253
259
  }
254
260
  (0, recording_1.recordFrame)({ kind: 'report', report, outcome: 'overridden', host: 'claude-code' });
255
261
  return { continue: true, systemMessage: (0, stop_text_1.overriddenLine)(report, override) };
@@ -274,12 +280,33 @@ function handleSpawnPreToolUse(input, home, now) {
274
280
  return policy.mode === 'enforce' ? deny(reason) : { continue: true, suppressOutput: true };
275
281
  }
276
282
  }
277
- function buildDenyReason(report, _reservation) {
283
+ function buildDenyReason(report, costLine) {
278
284
  // Claude Code shows this reason to the user. A box reads as an alarm; a
279
285
  // sentence reads as a log line. Colour is off: the host decides rendering.
280
286
  // Claude trims leading whitespace before adding Error:. A zero-width word
281
287
  // joiner preserves the blank first line, keeping that prefix off the frame.
282
- return '\u2060\n' + (0, render_1.renderStop)(report, { colour: false, host: 'claude-code' });
288
+ return '\u2060\n' + (0, render_1.renderStop)(report, { colour: false, host: 'claude-code', costLine });
289
+ }
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
+ }
283
310
  }
284
311
  const ASK_MODES = new Set(['default', 'acceptEdits', 'auto', 'plan']);
285
312
  /**
@@ -0,0 +1,48 @@
1
+ /**
2
+ * The calendar's two faces from one layout. On a colour terminal each day is a
3
+ * coloured square on the canvas palette (teal by tokens, amber when sub-agents
4
+ * used more than half of the day's tokens, a red diamond on a day AgentGuard
5
+ * held a launch), drawn through the presentation path. Piped, with --no-color or
6
+ * NO_COLOR, each day is a shade character and the two kinds of marked day are
7
+ * letters, so nothing depends on colour.
8
+ */
9
+ import { Canvas, type CanvasColor } from '../canvas';
10
+ import { type CalendarReport } from './calendar';
11
+ import { type WhyLang } from './i18n';
12
+ import type { DollarRange } from './pricing';
13
+ export type CalendarSkin = 'plain' | 'colour';
14
+ export interface CalendarSegment {
15
+ text: string;
16
+ color: CanvasColor;
17
+ }
18
+ export type CalendarLine = CalendarSegment[];
19
+ /** Levels 0 to 4, "Less" to "More". */
20
+ export declare const CALENDAR_SHADES: readonly ["·", "░", "▒", "▓", "█"];
21
+ /** The plain-text day letters, the same in every language: sub-agents used most of the day, and AgentGuard held a launch. */
22
+ export declare const CALENDAR_MARKERS: {
23
+ readonly subagents: "s";
24
+ readonly held: "H";
25
+ };
26
+ /**
27
+ * The calendar's dollar total. Under $1,000 it prints as `why` prints dollars
28
+ * ($7.29, or $0.63 to $1.00). From $1,000, decided by the larger end, both ends
29
+ * are whole dollars with thousands separators ($28,252 to $28,254), and one
30
+ * number when both round to the same dollar. The calendar only: `why` keeps its
31
+ * cents.
32
+ */
33
+ export declare function calendarDollars(value: DollarRange, words: {
34
+ unpriced: string;
35
+ to: string;
36
+ }): string;
37
+ /** Greedy word wrap at `width`; a word is never split, and a word wider than the line stands alone. */
38
+ export declare function wrap(text: string, width: number, indent?: string): string[];
39
+ /**
40
+ * The report line by line. `columns` wraps the text lines; the grid's width is
41
+ * its weeks (two columns each, beside the weekday labels), which the span was
42
+ * already chosen to fit.
43
+ */
44
+ export declare function calendarLines(report: CalendarReport, lang: WhyLang, columns: number, skin: CalendarSkin): CalendarLine[];
45
+ /** Plain text: shade characters and day letters, no control sequences, trailing spaces trimmed. */
46
+ export declare function renderCalendar(report: CalendarReport, lang?: WhyLang, columns?: number): string;
47
+ /** The colour face on a canvas sized to the report, never paged: a calendar is one block. */
48
+ export declare function drawCalendar(report: CalendarReport, lang?: WhyLang, columns?: number, colour?: boolean): Canvas;
@@ -0,0 +1,196 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.CALENDAR_MARKERS = exports.CALENDAR_SHADES = void 0;
4
+ exports.calendarDollars = calendarDollars;
5
+ exports.wrap = wrap;
6
+ exports.calendarLines = calendarLines;
7
+ exports.renderCalendar = renderCalendar;
8
+ exports.drawCalendar = drawCalendar;
9
+ /**
10
+ * The calendar's two faces from one layout. On a colour terminal each day is a
11
+ * coloured square on the canvas palette (teal by tokens, amber when sub-agents
12
+ * used more than half of the day's tokens, a red diamond on a day AgentGuard
13
+ * held a launch), drawn through the presentation path. Piped, with --no-color or
14
+ * NO_COLOR, each day is a shade character and the two kinds of marked day are
15
+ * letters, so nothing depends on colour.
16
+ */
17
+ const canvas_1 = require("../canvas");
18
+ const calendar_1 = require("./calendar");
19
+ const i18n_1 = require("./i18n");
20
+ const live_1 = require("./live");
21
+ const render_1 = require("./render");
22
+ /** Levels 0 to 4, "Less" to "More". */
23
+ exports.CALENDAR_SHADES = ['·', '░', '▒', '▓', '█'];
24
+ /** The plain-text day letters, the same in every language: sub-agents used most of the day, and AgentGuard held a launch. */
25
+ exports.CALENDAR_MARKERS = { subagents: 's', held: 'H' };
26
+ const SQUARE = '■', DIAMOND = '◆';
27
+ const TEAL = ['shade0', 'teal1', 'teal2', 'teal3', 'teal4'];
28
+ const AMBER = ['shade0', 'amber1', 'amber2', 'amber3', 'amber4'];
29
+ const segment = (text, color = 'none') => ({ text, color });
30
+ const dateOf = (day, text) => ({ month: text.months[Number(day.slice(5, 7)) - 1], day: Number(day.slice(8, 10)), year: Number(day.slice(0, 4)) });
31
+ /** One day's cell. The held mark wins over amber; a day before the first record, or after today, is blank. */
32
+ function cell(day, skin) {
33
+ if (!day)
34
+ return { segment: segment(' '), mark: null };
35
+ if (day.heldLaunches > 0)
36
+ return { segment: skin === 'plain' ? segment(exports.CALENDAR_MARKERS.held) : segment(DIAMOND, 'red'), mark: 'held' };
37
+ if (day.level === null)
38
+ return { segment: segment(' '), mark: null };
39
+ if (day.subagentsOverHalf)
40
+ return { segment: skin === 'plain' ? segment(exports.CALENDAR_MARKERS.subagents) : segment(SQUARE, AMBER[day.level]), mark: 'subagents' };
41
+ return { segment: skin === 'plain' ? segment(exports.CALENDAR_SHADES[day.level]) : segment(SQUARE, TEAL[day.level]), mark: null };
42
+ }
43
+ /**
44
+ * The calendar's dollar total. Under $1,000 it prints as `why` prints dollars
45
+ * ($7.29, or $0.63 to $1.00). From $1,000, decided by the larger end, both ends
46
+ * are whole dollars with thousands separators ($28,252 to $28,254), and one
47
+ * number when both round to the same dollar. The calendar only: `why` keeps its
48
+ * cents.
49
+ */
50
+ function calendarDollars(value, words) {
51
+ if (Math.round(Math.max(value.min, value.max) * 100) < 100_000)
52
+ return (0, live_1.dollars)(value, words);
53
+ const low = Math.round(value.min), high = Math.round(value.max);
54
+ return low === high ? `$${(0, render_1.count)(low)}` : `$${(0, render_1.count)(low)} ${words.to} $${(0, render_1.count)(high)}`;
55
+ }
56
+ /** Greedy word wrap at `width`; a word is never split, and a word wider than the line stands alone. */
57
+ function wrap(text, width, indent = '') {
58
+ const lines = [];
59
+ let line = '';
60
+ for (const word of text.split(' ')) {
61
+ if (!line)
62
+ line = word;
63
+ else if (line.length + 1 + word.length <= width)
64
+ line += ` ${word}`;
65
+ else {
66
+ lines.push(line);
67
+ line = indent + word;
68
+ }
69
+ }
70
+ if (line)
71
+ lines.push(line);
72
+ return lines;
73
+ }
74
+ /** Summary items joined with " · ", a new line before an item that would pass the width. */
75
+ function joinItems(items, width) {
76
+ const lines = [];
77
+ let line = '';
78
+ for (const item of items) {
79
+ if (!line)
80
+ line = item;
81
+ else if (line.length + 3 + item.length <= width)
82
+ line += ` · ${item}`;
83
+ else {
84
+ lines.push(line);
85
+ line = item;
86
+ }
87
+ }
88
+ if (line)
89
+ lines.push(line);
90
+ return lines.flatMap(value => wrap(value, width));
91
+ }
92
+ /**
93
+ * The report line by line. `columns` wraps the text lines; the grid's width is
94
+ * its weeks (two columns each, beside the weekday labels), which the span was
95
+ * already chosen to fit.
96
+ */
97
+ function calendarLines(report, lang, columns, skin) {
98
+ const text = i18n_1.CALENDAR_TEXT[lang], words = i18n_1.WHY_TEXT[lang], width = Math.max(20, Math.floor(columns));
99
+ const lines = [];
100
+ const paragraph = (value, color, indent = '') => { for (const line of wrap(value, width, indent))
101
+ lines.push([segment(line, color)]); };
102
+ paragraph(text.title(text.span(dateOf(report.from, text), dateOf(report.to, text))), 'mint');
103
+ if (report.firstRecordedDay === null) {
104
+ paragraph(text.noData, 'white');
105
+ return lines;
106
+ }
107
+ const totals = report.totals, spansYears = report.from.slice(0, 4) !== report.to.slice(0, 4);
108
+ const items = [
109
+ text.tokens((0, render_1.count)(totals.tokens)),
110
+ text.dollars(totals.usd === null ? null : calendarDollars(totals.usd, words)),
111
+ ...(report.busiest ? [text.busiest(text.date(dateOf(report.busiest.date, text), spansYears), (0, render_1.count)(report.busiest.tokens))] : []),
112
+ text.subagents((0, render_1.share)(totals.subagentTokens, totals.tokens)),
113
+ ...(totals.heldLaunches > 0 ? [text.held(totals.heldLaunches)] : []),
114
+ ];
115
+ for (const line of joinItems(items, width))
116
+ lines.push([segment(line, 'white')]);
117
+ lines.push([]);
118
+ // Month names above the first week whose Sunday falls in that month. The first
119
+ // column is named too unless the next name starts before it ends.
120
+ const labelWidth = Math.max(...text.weekdays.map(label => label.length)) + 1;
121
+ const months = [];
122
+ for (let week = 0; week < report.weeks; week++) {
123
+ const sunday = (0, calendar_1.addDays)(report.from, 7 * week);
124
+ if (week === 0 || sunday.slice(0, 7) !== (0, calendar_1.addDays)(sunday, -7).slice(0, 7))
125
+ months.push({ x: labelWidth + 2 * week, name: text.months[Number(sunday.slice(5, 7)) - 1] });
126
+ }
127
+ if (months.length > 1 && months[1].x < months[0].x + months[0].name.length + 1)
128
+ months.shift();
129
+ const monthRow = [];
130
+ let x = 0;
131
+ for (const month of months) {
132
+ monthRow.push(segment(' '.repeat(month.x - x)), segment(month.name, 'slate'));
133
+ x = month.x + month.name.length;
134
+ }
135
+ lines.push(monthRow);
136
+ const marked = new Set();
137
+ for (let weekday = 0; weekday < 7; weekday++) {
138
+ const row = [segment(text.weekdays[weekday].padEnd(labelWidth), 'slate')];
139
+ for (let week = 0; week < report.weeks; week++) {
140
+ const drawn = cell(report.days[7 * week + weekday], skin);
141
+ if (drawn.mark)
142
+ marked.add(drawn.mark);
143
+ row.push(drawn.segment, segment(' '));
144
+ }
145
+ lines.push(row);
146
+ }
147
+ lines.push([]);
148
+ lines.push(skin === 'plain'
149
+ ? [segment(`${text.less} ${exports.CALENDAR_SHADES.join(' ')} ${text.more}`)]
150
+ : [segment(text.less, 'slate'), ...TEAL.flatMap(color => [segment(' '), segment(SQUARE, color)]), segment(' '), segment(text.more, 'slate')]);
151
+ // A colour screen shows the mark beside its sentence; plain text names the letter in the sentence.
152
+ const legend = (mark, glyph, sentences) => {
153
+ if (!marked.has(mark))
154
+ return;
155
+ if (skin === 'plain') {
156
+ paragraph(sentences.plain(exports.CALENDAR_MARKERS[mark]), 'none');
157
+ return;
158
+ }
159
+ const [head = '', ...rest] = wrap(sentences.colour, width - 2);
160
+ lines.push([glyph, segment(` ${head}`, 'slate')]);
161
+ for (const line of rest)
162
+ lines.push([segment(` ${line}`, 'slate')]);
163
+ };
164
+ legend('subagents', segment(SQUARE, 'amber4'), text.subagentDays);
165
+ legend('held', segment(DIAMOND, 'red'), text.heldDays);
166
+ if (totals.claudeTokens > 0 || totals.codexTokens > 0)
167
+ paragraph(text.sources(totals.claudeTokens > 0, totals.codexTokens > 0), 'slate');
168
+ if (totals.unpricedTokens > 0)
169
+ paragraph(text.unpriced((0, render_1.count)(totals.unpricedTokens), totals.unpricedModels.map(model => model ?? words.missingModel).join(', ')), 'slate');
170
+ if (report.sources.forkBoundaryUnknown > 0)
171
+ paragraph(text.forkUnknown(report.sources.forkBoundaryUnknown), 'slate');
172
+ if (report.sources.unreadable > 0)
173
+ paragraph(text.unreadable(report.sources.unreadable), 'slate');
174
+ if (report.historyShort)
175
+ for (const sentence of text.shortHistory)
176
+ paragraph(sentence, 'slate');
177
+ return lines;
178
+ }
179
+ /** Plain text: shade characters and day letters, no control sequences, trailing spaces trimmed. */
180
+ function renderCalendar(report, lang = 'en', columns = 80) {
181
+ return calendarLines(report, lang, columns, 'plain').map(line => line.map(part => part.text).join('').trimEnd()).join('\n');
182
+ }
183
+ /** The colour face on a canvas sized to the report, never paged: a calendar is one block. */
184
+ function drawCalendar(report, lang = 'en', columns = 80, colour) {
185
+ const lines = calendarLines(report, lang, columns, 'colour');
186
+ const width = Math.max(1, ...lines.map(line => line.reduce((sum, part) => sum + part.text.length, 0)));
187
+ const canvas = new canvas_1.Canvas({ width, height: Math.max(1, lines.length), ...(colour === undefined ? {} : { colour }) });
188
+ lines.forEach((line, row) => {
189
+ let column = 0;
190
+ for (const part of line) {
191
+ canvas.put(row, column, part.text, part.color);
192
+ column += part.text.length;
193
+ }
194
+ });
195
+ return canvas;
196
+ }
@@ -0,0 +1,138 @@
1
+ import { type DollarRange, type PricingTable } from './pricing';
2
+ /** A span of at most 53 weeks: a year of Sundays plus the week in progress. */
3
+ export declare const CALENDAR_MAX_WEEKS = 53;
4
+ /**
5
+ * Weekday labels plus one space, in the widest language, so the span a width
6
+ * allows, and so `calendar json`, is the same in every language.
7
+ */
8
+ export declare const CALENDAR_GRID_PREFIX: number;
9
+ /** The local calendar day of an instant, YYYY-MM-DD, in this process's time zone. */
10
+ export declare function localDay(at: number): string;
11
+ /** Days since the epoch for a YYYY-MM-DD date: date arithmetic without clock time or daylight saving. */
12
+ export declare const dayNumber: (day: string) => number;
13
+ export declare const addDays: (day: string, days: number) => string;
14
+ /** 0 is Sunday. */
15
+ export declare const weekdayOf: (day: string) => number;
16
+ /** One file's measured figures for one day. */
17
+ export interface CalendarFigures {
18
+ tokens: number;
19
+ /** Every token of the responses sub-agents recorded (input, cache and output), sub-agent transcripts being what `why` reads as child transcripts. */
20
+ subagentTokens: number;
21
+ /** API list price of the tokens whose model has a verified rate. */
22
+ usd: DollarRange;
23
+ /** Tokens on models without a verified rate; not in `usd`. */
24
+ unpricedTokens: number;
25
+ /** Those models; null is a response without a model id. */
26
+ unpricedModels: Array<string | null>;
27
+ }
28
+ export interface CalendarDayData extends CalendarFigures {
29
+ claudeTokens: number;
30
+ codexTokens: number;
31
+ }
32
+ export interface CalendarSources {
33
+ /** Transcript files read this run, from the cache or from disk. */
34
+ transcripts: number;
35
+ /** Files whose transcript is gone and whose days come from the daily count. */
36
+ rollupFiles: number;
37
+ /** Codex forks whose inherited history has no verifiable boundary; `why` reports their usage unavailable, so none of it is counted. */
38
+ forkBoundaryUnknown: number;
39
+ /** Transcripts that could not be read this run; any earlier daily count of theirs is kept. */
40
+ unreadable: number;
41
+ /** Tokens on responses without a recorded time, which no day can hold. */
42
+ undatedTokens: number;
43
+ }
44
+ export interface CalendarData {
45
+ days: Map<string, CalendarDayData>;
46
+ /** Sub-agent launches AgentGuard held per day: refused by an enforced STOP, or held for the person's yes (`asked: true`). */
47
+ heldLaunches: Map<string, number>;
48
+ /** The oldest day with tokens, from transcripts or the daily count. */
49
+ firstDay: string | null;
50
+ claudeSeen: boolean;
51
+ sources: CalendarSources;
52
+ /** False when the daily count could not be written. */
53
+ saved: boolean;
54
+ }
55
+ export declare const calendarDirectory: (home: string) => string;
56
+ export declare const rollupPath: (home: string) => string;
57
+ export declare const cachePath: (home: string) => string;
58
+ export interface CalendarCollectOptions {
59
+ /** The Burn home (AGENTGUARD_HOME). */
60
+ home: string;
61
+ roots?: {
62
+ claude: string;
63
+ codex: string;
64
+ };
65
+ rates?: PricingTable;
66
+ }
67
+ /**
68
+ * Reads every local transcript (from the cache when unchanged), merges the daily
69
+ * count of files that are gone, writes both back, and reads the ledger.
70
+ */
71
+ export declare function collectCalendar(options: CalendarCollectOptions): CalendarData;
72
+ export type CalendarLevel = 0 | 1 | 2 | 3 | 4;
73
+ export interface CalendarDay {
74
+ /** YYYY-MM-DD, local time. */
75
+ date: string;
76
+ /** False before the first recorded day, where no transcript or daily count covers the day. */
77
+ recorded: boolean;
78
+ tokens: number;
79
+ /** Tokens of responses sub-agents recorded. */
80
+ subagentTokens: number;
81
+ /** API list price of the day's priced tokens. */
82
+ usd: DollarRange;
83
+ unpricedTokens: number;
84
+ claudeTokens: number;
85
+ codexTokens: number;
86
+ /** 0 without tokens; 1 to 4 by the quarter of the shown days with tokens this day reaches; null when not recorded. */
87
+ level: CalendarLevel | null;
88
+ /** Sub-agents recorded more than half of the day's tokens: drawn in amber. */
89
+ subagentsOverHalf: boolean;
90
+ /** Sub-agent launches AgentGuard held that day: drawn with the red mark. */
91
+ heldLaunches: number;
92
+ }
93
+ export interface CalendarTotals {
94
+ tokens: number;
95
+ subagentTokens: number;
96
+ /** Sub-agent tokens over all tokens, 0 to 1; null without tokens. */
97
+ subagentShare: number | null;
98
+ /** API list price of the priced tokens; null when there are tokens and none is priced. */
99
+ usd: DollarRange | null;
100
+ unpricedTokens: number;
101
+ unpricedModels: Array<string | null>;
102
+ heldLaunches: number;
103
+ claudeTokens: number;
104
+ codexTokens: number;
105
+ }
106
+ export interface CalendarReport {
107
+ /** The Sunday that starts the first week shown. */
108
+ from: string;
109
+ /** Today. */
110
+ to: string;
111
+ weeks: number;
112
+ firstRecordedDay: string | null;
113
+ /** Every day from `from` to `to`. */
114
+ days: CalendarDay[];
115
+ totals: CalendarTotals;
116
+ /** The shown day with the most tokens, the first of equal days. */
117
+ busiest: {
118
+ date: string;
119
+ tokens: number;
120
+ } | null;
121
+ /** The recorded history is shorter than the calendar could show, and Claude Code transcripts are in it. */
122
+ historyShort: boolean;
123
+ sources: CalendarSources;
124
+ subagentsIncluded: true;
125
+ basis: 'estimated_api_list_price';
126
+ }
127
+ export interface CalendarReportOptions {
128
+ now?: number;
129
+ /** An exact span, 1 to 53 weeks ending with the current week. */
130
+ weeks?: number;
131
+ /** Output width: without `weeks`, the span runs from the oldest recorded day, capped to the weeks that fit. */
132
+ columns?: number;
133
+ }
134
+ /** Weeks of two columns each that fit beside the weekday labels in `columns`, 1 to 53. */
135
+ export declare const weeksThatFit: (columns: number) => number;
136
+ /** A day's shade: the quarter of the shown days with tokens that it reaches, so the busiest shown day is always level 4. */
137
+ export declare function calendarLevels(values: number[]): (tokens: number) => CalendarLevel;
138
+ export declare function calendarReport(data: CalendarData, options?: CalendarReportOptions): CalendarReport;