@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.
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.CALENDAR_MARKERS = exports.CALENDAR_SHADES = void 0;
3
+ exports.calendarCells = exports.calendarGridWidth = exports.CALENDAR_MARKERS = exports.CALENDAR_SHADES = void 0;
4
4
  exports.calendarDollars = calendarDollars;
5
5
  exports.wrap = wrap;
6
6
  exports.calendarLines = calendarLines;
@@ -8,11 +8,21 @@ exports.renderCalendar = renderCalendar;
8
8
  exports.drawCalendar = drawCalendar;
9
9
  /**
10
10
  * The calendar's two faces from one layout. On a colour terminal each day is a
11
- * coloured square on the canvas palette (teal by tokens, amber when sub-agents
11
+ * coloured block on the canvas palette (teal by tokens, amber when sub-agents
12
12
  * used more than half of the day's tokens, a red diamond on a day AgentGuard
13
13
  * held a launch), drawn through the presentation path. Piped, with --no-color or
14
- * NO_COLOR, each day is a shade character and the two kinds of marked day are
14
+ * NO_COLOR, each day is shade characters and the two kinds of marked day are
15
15
  * letters, so nothing depends on colour.
16
+ *
17
+ * Two cell sizes. Big, whenever the span fits the width that way: two
18
+ * characters a day (▇▇ in colour, the shade pair such as ▓▓ in plain text) and
19
+ * one space between weeks, which reads as roughly square. Compact otherwise: one
20
+ * character a day and one space, as 0.3.20 drew every calendar. The span is
21
+ * chosen first (calendarReport) and never shrinks to make the cells bigger.
22
+ *
23
+ * A colour day is the lower seven-eighths block, not the full block: terminals
24
+ * draw █ to the full height of the line, so a week of full blocks joins into one
25
+ * bar, while ▇ leaves a thin gap above each day and the grid reads as squares.
16
26
  */
17
27
  const canvas_1 = require("../canvas");
18
28
  const calendar_1 = require("./calendar");
@@ -23,22 +33,57 @@ const render_1 = require("./render");
23
33
  exports.CALENDAR_SHADES = ['·', '░', '▒', '▓', '█'];
24
34
  /** The plain-text day letters, the same in every language: sub-agents used most of the day, and AgentGuard held a launch. */
25
35
  exports.CALENDAR_MARKERS = { subagents: 's', held: 'H' };
26
- const SQUARE = '■', DIAMOND = '◆';
36
+ /** A compact colour day; half of a big colour day (see above); a held day's mark. */
37
+ const SQUARE = '■', BLOCK = '▇', DIAMOND = '◆';
27
38
  const TEAL = ['shade0', 'teal1', 'teal2', 'teal3', 'teal4'];
28
39
  const AMBER = ['shade0', 'amber1', 'amber2', 'amber3', 'amber4'];
40
+ /** Columns per week: the day's characters and one space. */
41
+ const WEEK_COLUMNS = { big: 3, compact: 2 };
42
+ /**
43
+ * The grid's width at a cell size: the weekday labels and the week columns,
44
+ * without the last space. The labels count at their widest language, so a width
45
+ * picks the same cell size in every language.
46
+ */
47
+ const calendarGridWidth = (weeks, cells) => calendar_1.CALENDAR_GRID_PREFIX + WEEK_COLUMNS[cells] * weeks - 1;
48
+ exports.calendarGridWidth = calendarGridWidth;
49
+ /** "Less ·· ░░ ▒▒ ▓▓ ██ More" in the widest language: five two-character swatches and six spaces. */
50
+ const BIG_SCALE_WIDTH = Math.max(...Object.values(i18n_1.CALENDAR_TEXT).map(text => text.less.length + text.more.length + 16));
51
+ /**
52
+ * Big cells whenever the span's weeks, and the Less to More scale under them,
53
+ * fit `columns` at two characters a day; compact otherwise, a `--weeks` span
54
+ * wider than the terminal included.
55
+ */
56
+ const calendarCells = (weeks, columns) => Math.max((0, exports.calendarGridWidth)(weeks, 'big'), BIG_SCALE_WIDTH) <= columns ? 'big' : 'compact';
57
+ exports.calendarCells = calendarCells;
29
58
  const segment = (text, color = 'none') => ({ text, color });
30
59
  const dateOf = (day, text) => ({ month: text.months[Number(day.slice(5, 7)) - 1], day: Number(day.slice(8, 10)), year: Number(day.slice(0, 4)) });
31
- /** One day's cell. The held mark wins over amber; a day before the first record, or after today, is blank. */
32
- function cell(day, skin) {
33
- if (!day)
34
- return { segment: segment(' '), mark: null };
35
- if (day.heldLaunches > 0)
36
- return { segment: skin === 'plain' ? segment(exports.CALENDAR_MARKERS.held) : segment(DIAMOND, 'red'), mark: 'held' };
37
- if (day.level === null)
38
- return { segment: segment(' '), mark: null };
39
- if (day.subagentsOverHalf)
40
- return { segment: skin === 'plain' ? segment(exports.CALENDAR_MARKERS.subagents) : segment(SQUARE, AMBER[day.level]), mark: 'subagents' };
41
- return { segment: skin === 'plain' ? segment(exports.CALENDAR_SHADES[day.level]) : segment(SQUARE, TEAL[day.level]), mark: null };
60
+ /**
61
+ * One day's cell and the marks it shows. Compact: the level's shade or square,
62
+ * or on a marked day the mark alone, the held mark winning over amber. Big: the
63
+ * left half always shows the level (amber on a sub-agent day, in colour), and
64
+ * the right half repeats it or carries the day's mark (`s` or `H` in plain text,
65
+ * the red diamond in colour), so a marked day keeps its shade. A day before the
66
+ * first record, or after today, is blank unless AgentGuard held a launch on it.
67
+ */
68
+ function cell(day, skin, cells) {
69
+ const level = day?.level ?? null, held = (day?.heldLaunches ?? 0) > 0, amber = level !== null && day.subagentsOverHalf;
70
+ if (level === null && !held)
71
+ return { parts: [segment(cells === 'big' ? ' ' : ' ')], marks: [] };
72
+ const heldMark = skin === 'plain' ? segment(exports.CALENDAR_MARKERS.held) : segment(DIAMOND, 'red');
73
+ const colours = amber ? AMBER : TEAL, marks = held ? ['held'] : amber ? ['subagents'] : [];
74
+ if (cells === 'compact') {
75
+ if (held)
76
+ return { parts: [heldMark], marks };
77
+ return { parts: [skin === 'plain' ? segment(amber ? exports.CALENDAR_MARKERS.subagents : exports.CALENDAR_SHADES[level]) : segment(SQUARE, colours[level])], marks };
78
+ }
79
+ if (skin === 'plain') {
80
+ const shade = level === null ? ' ' : exports.CALENDAR_SHADES[level];
81
+ return { parts: [segment(shade + (held ? exports.CALENDAR_MARKERS.held : amber ? exports.CALENDAR_MARKERS.subagents : shade))], marks };
82
+ }
83
+ if (!held)
84
+ return { parts: [segment(BLOCK + BLOCK, colours[level])], marks };
85
+ // A held day in colour: its level's block, then the red diamond. An amber left half shows amber too.
86
+ return { parts: [level === null ? segment(' ') : segment(BLOCK, colours[level]), heldMark], marks: amber ? ['subagents', 'held'] : marks };
42
87
  }
43
88
  /**
44
89
  * The calendar's dollar total. Under $1,000 it prints as `why` prints dollars
@@ -90,9 +135,8 @@ function joinItems(items, width) {
90
135
  return lines.flatMap(value => wrap(value, width));
91
136
  }
92
137
  /**
93
- * The report line by line. `columns` wraps the text lines; the grid's width is
94
- * its weeks (two columns each, beside the weekday labels), which the span was
95
- * already chosen to fit.
138
+ * The report line by line. `columns` wraps the text lines and picks the cell
139
+ * size (calendarCells); the span was already chosen to fit it.
96
140
  */
97
141
  function calendarLines(report, lang, columns, skin) {
98
142
  const text = i18n_1.CALENDAR_TEXT[lang], words = i18n_1.WHY_TEXT[lang], width = Math.max(20, Math.floor(columns));
@@ -104,31 +148,38 @@ function calendarLines(report, lang, columns, skin) {
104
148
  paragraph(text.noData, 'white');
105
149
  return lines;
106
150
  }
151
+ // The summary in short lines: tokens and dollars; the busiest day and the
152
+ // sub-agent share; the launches AgentGuard held, when there were any. Two items
153
+ // share a line only when both fit the width; no line takes an item from another.
107
154
  const totals = report.totals, spansYears = report.from.slice(0, 4) !== report.to.slice(0, 4);
108
- const items = [
109
- text.tokens((0, render_1.count)(totals.tokens)),
110
- text.dollars(totals.usd === null ? null : calendarDollars(totals.usd, words)),
111
- ...(report.busiest ? [text.busiest(text.date(dateOf(report.busiest.date, text), spansYears), (0, render_1.count)(report.busiest.tokens))] : []),
112
- text.subagents((0, render_1.share)(totals.subagentTokens, totals.tokens)),
113
- ...(totals.heldLaunches > 0 ? [text.held(totals.heldLaunches)] : []),
155
+ const summary = [
156
+ [text.tokens((0, render_1.count)(totals.tokens)), text.dollars(totals.usd === null ? null : calendarDollars(totals.usd, words))],
157
+ [...(report.busiest ? [text.busiest(text.date(dateOf(report.busiest.date, text), spansYears), (0, render_1.count)(report.busiest.tokens))] : []),
158
+ text.subagents((0, render_1.share)(totals.subagentTokens, totals.tokens))],
159
+ totals.heldLaunches > 0 ? [text.held(totals.heldLaunches)] : [],
114
160
  ];
115
- for (const line of joinItems(items, width))
116
- lines.push([segment(line, 'white')]);
161
+ for (const items of summary)
162
+ for (const line of joinItems(items, width))
163
+ lines.push([segment(line, 'white')]);
117
164
  lines.push([]);
118
- // Month names above the first week whose Sunday falls in that month. The first
119
- // column is named too unless the next name starts before it ends.
165
+ const cells = (0, exports.calendarCells)(report.weeks, columns), step = WEEK_COLUMNS[cells];
120
166
  const labelWidth = Math.max(...text.weekdays.map(label => label.length)) + 1;
167
+ // Month names above the first week whose Sunday falls in that month. The first
168
+ // column is named too unless the next name starts before it ends. A name that
169
+ // would run past the width (or past the grid, when a --weeks grid is wider) is
170
+ // left out: it would wrap the whole row.
171
+ const limit = Math.max(width, labelWidth + step * report.weeks - 1);
121
172
  const months = [];
122
173
  for (let week = 0; week < report.weeks; week++) {
123
174
  const sunday = (0, calendar_1.addDays)(report.from, 7 * week);
124
175
  if (week === 0 || sunday.slice(0, 7) !== (0, calendar_1.addDays)(sunday, -7).slice(0, 7))
125
- months.push({ x: labelWidth + 2 * week, name: text.months[Number(sunday.slice(5, 7)) - 1] });
176
+ months.push({ x: labelWidth + step * week, name: text.months[Number(sunday.slice(5, 7)) - 1] });
126
177
  }
127
178
  if (months.length > 1 && months[1].x < months[0].x + months[0].name.length + 1)
128
179
  months.shift();
129
180
  const monthRow = [];
130
181
  let x = 0;
131
- for (const month of months) {
182
+ for (const month of months.filter(label => label.x + label.name.length <= limit)) {
132
183
  monthRow.push(segment(' '.repeat(month.x - x)), segment(month.name, 'slate'));
133
184
  x = month.x + month.name.length;
134
185
  }
@@ -137,18 +188,21 @@ function calendarLines(report, lang, columns, skin) {
137
188
  for (let weekday = 0; weekday < 7; weekday++) {
138
189
  const row = [segment(text.weekdays[weekday].padEnd(labelWidth), 'slate')];
139
190
  for (let week = 0; week < report.weeks; week++) {
140
- const drawn = cell(report.days[7 * week + weekday], skin);
141
- if (drawn.mark)
142
- marked.add(drawn.mark);
143
- row.push(drawn.segment, segment(' '));
191
+ const drawn = cell(report.days[7 * week + weekday], skin, cells);
192
+ for (const mark of drawn.marks)
193
+ marked.add(mark);
194
+ row.push(...drawn.parts, segment(' '));
144
195
  }
145
196
  lines.push(row);
146
197
  }
147
198
  lines.push([]);
199
+ // The Less to More scale in the cells the grid uses.
200
+ const swatch = cells === 'big' ? BLOCK + BLOCK : SQUARE;
148
201
  lines.push(skin === 'plain'
149
- ? [segment(`${text.less} ${exports.CALENDAR_SHADES.join(' ')} ${text.more}`)]
150
- : [segment(text.less, 'slate'), ...TEAL.flatMap(color => [segment(' '), segment(SQUARE, color)]), segment(' '), segment(text.more, 'slate')]);
151
- // A colour screen shows the mark beside its sentence; plain text names the letter in the sentence.
202
+ ? [segment(`${text.less} ${exports.CALENDAR_SHADES.map(shade => cells === 'big' ? shade + shade : shade).join(' ')} ${text.more}`)]
203
+ : [segment(text.less, 'slate'), ...TEAL.flatMap(color => [segment(' '), segment(swatch, color)]), segment(' '), segment(text.more, 'slate')]);
204
+ // A colour screen shows the mark beside its sentence, where it sits in a day
205
+ // (the diamond is a big day's right half); plain text names the letter.
152
206
  const legend = (mark, glyph, sentences) => {
153
207
  if (!marked.has(mark))
154
208
  return;
@@ -156,13 +210,14 @@ function calendarLines(report, lang, columns, skin) {
156
210
  paragraph(sentences.plain(exports.CALENDAR_MARKERS[mark]), 'none');
157
211
  return;
158
212
  }
159
- const [head = '', ...rest] = wrap(sentences.colour, width - 2);
160
- lines.push([glyph, segment(` ${head}`, 'slate')]);
213
+ const indent = ' '.repeat(glyph.reduce((sum, part) => sum + part.text.length, 0) + 1);
214
+ const [head = '', ...rest] = wrap(sentences.colour, width - indent.length);
215
+ lines.push([...glyph, segment(` ${head}`, 'slate')]);
161
216
  for (const line of rest)
162
- lines.push([segment(` ${line}`, 'slate')]);
217
+ lines.push([segment(`${indent}${line}`, 'slate')]);
163
218
  };
164
- legend('subagents', segment(SQUARE, 'amber4'), text.subagentDays);
165
- legend('held', segment(DIAMOND, 'red'), text.heldDays);
219
+ legend('subagents', [segment(swatch, 'amber4')], text.subagentDays);
220
+ legend('held', cells === 'big' ? [segment(' '), segment(DIAMOND, 'red')] : [segment(DIAMOND, 'red')], text.heldDays);
166
221
  if (totals.claudeTokens > 0 || totals.codexTokens > 0)
167
222
  paragraph(text.sources(totals.claudeTokens > 0, totals.codexTokens > 0), 'slate');
168
223
  if (totals.unpricedTokens > 0)
@@ -60,6 +60,8 @@ export interface WhyText {
60
60
  diagnostics: (duplicates: number, malformed: number) => string;
61
61
  /** The sub-agent share, with AgentGuard's plugin that asks before the next sub-agent past a limit starts; and the 0.3.16 reload dollars, with the `rewrites` command. */
62
62
  tipFanout: (share: string) => string;
63
+ /** The same share for someone already running the plugin: the STOP box's action for too many sub-agents takes the place of the plugin. */
64
+ tipFanoutPlugin: (share: string) => string;
63
65
  tipRewrites: (rewrites: string, total: string) => string;
64
66
  /** Sub-agents that ran on the main conversation's model, by its display name (Opus 5.5). */
65
67
  tipSubagentModel: (count: number, model: string) => string;
@@ -68,6 +68,7 @@ const en = {
68
68
  mixedRanges: 'Some bucket cache-write costs are ranges because mixed cache lifetimes are not attributed to individual buckets. Range endpoints are not additive across buckets.',
69
69
  diagnostics: (duplicates, malformed) => `Usage records de-duplicated: ${duplicates}. Malformed lines skipped: ${malformed}.`,
70
70
  tipFanout: share => `Next: sub-agents used ${share} of this session's tokens. AgentGuard's free plugin asks you before the next sub-agent past your limit starts: agentguard.run/try`,
71
+ tipFanoutPlugin: share => `Next: sub-agents used ${share} of this session's tokens. Give related work to one sub-agent instead of several.`,
71
72
  tipRewrites: (rewrites, total) => `Next: full-prefix rewrites are ${rewrites} of ${total} API list equivalent here. See the cause of each one: npx agentguard-burn rewrites`,
72
73
  tipSubagentModel: (count, model) => `Next: ${count} ${count === 1 ? 'sub-agent' : 'sub-agents'} ran on ${model}. For searching and reading logs, a smaller model does the job: set CLAUDE_CODE_SUBAGENT_MODEL=haiku, or put model: haiku in the sub-agent's definition.`,
73
74
  tipIdleReloads: (count, longest) => `Next: Claude had to reload the whole conversation ${times(count)} after a pause longer than its cache lasts (longest pause: ${longest}). Run /compact before a break, so the reload after it is smaller.`,
@@ -117,6 +118,7 @@ const es = {
117
118
  mixedRanges: 'Algunos costos de escritura en caché por categoría son rangos, porque las duraciones de caché mixtas no se atribuyen a categorías individuales. Los extremos de los rangos no se suman entre categorías.',
118
119
  diagnostics: (duplicates, malformed) => `Registros de uso deduplicados: ${duplicates}. Líneas mal formadas omitidas: ${malformed}.`,
119
120
  tipFanout: share => `Próximo paso: los subagentes usaron el ${share} de los tokens de esta sesión. El plugin gratuito de AgentGuard te pregunta antes de que empiece el siguiente subagente por encima de tu límite: agentguard.run/try`,
121
+ tipFanoutPlugin: share => `Próximo paso: los subagentes usaron el ${share} de los tokens de esta sesión. Da el trabajo relacionado a un solo subagente en lugar de a varios.`,
120
122
  tipRewrites: (rewrites, total) => `Próximo paso: las reescrituras de prefijo completo suman ${rewrites} de ${total} (equivalente a precio de lista de la API) en esta sesión. Mira la causa de cada una: npx agentguard-burn rewrites`,
121
123
  tipSubagentModel: (count, model) => `Próximo paso: ${plural(count, 'subagente usó', 'subagentes usaron')} ${model}. Para buscar y leer logs, un modelo más pequeño basta: define CLAUDE_CODE_SUBAGENT_MODEL=haiku, o pon model: haiku en la definición del subagente.`,
122
124
  tipIdleReloads: (count, longest) => `Próximo paso: Claude tuvo que recargar toda la conversación ${veces(count)} después de una pausa más larga de lo que dura su caché (pausa más larga: ${longest}). Usa /compact antes de un descanso, así la recarga que viene después es más pequeña.`,
@@ -166,6 +168,7 @@ const pt = {
166
168
  mixedRanges: 'Alguns custos de gravação em cache por categoria aparecem como faixas, porque durações de cache mistas não são atribuídas a categorias individuais. Os extremos das faixas não se somam entre categorias.',
167
169
  diagnostics: (duplicates, malformed) => `Registros de uso deduplicados: ${duplicates}. Linhas malformadas ignoradas: ${malformed}.`,
168
170
  tipFanout: share => `Próximo passo: os subagentes usaram ${share} dos tokens desta sessão. O plugin gratuito do AgentGuard pergunta a você antes que o próximo subagente acima do seu limite comece: agentguard.run/try`,
171
+ tipFanoutPlugin: share => `Próximo passo: os subagentes usaram ${share} dos tokens desta sessão. Dê o trabalho relacionado a um único subagente em vez de vários.`,
169
172
  tipRewrites: (rewrites, total) => `Próximo passo: as reescritas de prefixo completo somam ${rewrites} de ${total} (equivalente ao preço de tabela da API) nesta sessão. Veja a causa de cada uma: npx agentguard-burn rewrites`,
170
173
  tipSubagentModel: (count, model) => `Próximo passo: ${plural(count, 'subagente usou', 'subagentes usaram')} o ${model}. Para buscar e ler logs, um modelo menor dá conta: defina CLAUDE_CODE_SUBAGENT_MODEL=haiku, ou coloque model: haiku na definição do subagente.`,
171
174
  tipIdleReloads: (count, longest) => `Próximo passo: o Claude teve que recarregar a conversa inteira ${vezes(count)} depois de uma pausa mais longa que a duração do cache (pausa mais longa: ${longest}). Use /compact antes de um intervalo, assim a recarga depois dele fica menor.`,
@@ -33,6 +33,8 @@ exports.MODEL_PRICING = Object.freeze({
33
33
  'claude-opus-5-5': Object.freeze({ ...rates(4, 0.2, 5, 8, 20), verifiedAt: '2026-09-22' }),
34
34
  'claude-opus-5': rates(5, 0.5, 6.25, 10, 25),
35
35
  'claude-opus-4-8': rates(5, 0.5, 6.25, 10, 25),
36
+ // Verified 2026-09-29: Sonnet 5.5 (released 2026-09-28) lists the same rates as Sonnet 5.
37
+ 'claude-sonnet-5-5': Object.freeze({ ...rates(2, 0.2, 2.5, 4, 10), verifiedAt: '2026-09-29' }),
36
38
  'claude-sonnet-5': rates(2, 0.2, 2.5, 4, 10),
37
39
  'claude-haiku-4-5-20251001': rates(1, 0.1, 1.25, 2, 5),
38
40
  'gpt-6-astra': openaiRates(10, 1, 12.5, 50, 'https://developers.openai.com/api/docs/pricing'),
@@ -63,6 +63,12 @@ export interface WhyTipInput {
63
63
  medianPerCall: number;
64
64
  };
65
65
  }
66
+ /**
67
+ * Where the tip is shown: `why` itself, or the AgentGuard plugin. The fan-out
68
+ * tip points `why` readers to the plugin; someone the plugin shows it to already
69
+ * runs it, so there it ends with the STOP box's action for too many sub-agents.
70
+ */
71
+ export type TipContext = 'why' | 'plugin';
66
72
  /**
67
73
  * The coach: one next step, for the largest cause that stands out in this
68
74
  * session; null when none does, never a generic line. A cause stands out at the
@@ -74,8 +80,9 @@ export interface WhyTipInput {
74
80
  * for its cause (code.claude.com/docs/en/costs, /prompt-caching, /sub-agents),
75
81
  * and every figure is this session's own. Where the cause has no sharper action,
76
82
  * the share tip prints for sub-agents and the 0.3.16 dollars tip for rewrites.
83
+ * In the plugin context only the share tip's second sentence changes.
77
84
  */
78
- export declare function whyTip(input: WhyTipInput, lang?: WhyLang): string | null;
85
+ export declare function whyTip(input: WhyTipInput, lang?: WhyLang, context?: TipContext): string | null;
79
86
  /**
80
87
  * What `whyTip` weighs, from the figures `why` prints. The sub-agent and rewrite
81
88
  * rows are the table's own. The setup and the re-read conversation split each
@@ -84,6 +91,14 @@ export declare function whyTip(input: WhyTipInput, lang?: WhyLang): string | nul
84
91
  * conversation into setup; they are measured, like every row, from recorded usage.
85
92
  */
86
93
  export declare function whyTipInput(figures: Pick<SessionFigures, 'turns' | 'attribution' | 'totalUsd'>, rates?: PricingTable, bucketUsd?: (bucket: InsightBucket) => DollarRange | null): WhyTipInput;
94
+ /**
95
+ * The tip line `why` ends with for this transcript, in the same words and with
96
+ * the same figures: null when nothing stands out, and for the unknown
97
+ * fork-history report, which prints no tip. The plugin context changes only
98
+ * the fan-out tip's second sentence. It does not read the quiet flag; the
99
+ * caller decides whether to show it.
100
+ */
101
+ export declare function whyTipLine(transcript: InsightTranscript, rates?: PricingTable, lang?: WhyLang, context?: TipContext): string | null;
87
102
  /** Messages on each side of an event the measured change compares, at most and at least. */
88
103
  export declare const PROOF_WINDOW = 20;
89
104
  export declare const PROOF_MINIMUM = 5;
@@ -8,6 +8,7 @@ exports.table = table;
8
8
  exports.modelLabel = modelLabel;
9
9
  exports.whyTip = whyTip;
10
10
  exports.whyTipInput = whyTipInput;
11
+ exports.whyTipLine = whyTipLine;
11
12
  exports.proofLine = proofLine;
12
13
  exports.renderWhy = renderWhy;
13
14
  exports.rewriteReport = rewriteReport;
@@ -94,8 +95,9 @@ const HAS_SMALLER_MODEL = /^claude-(?:opus|fable|sonnet)-/;
94
95
  * for its cause (code.claude.com/docs/en/costs, /prompt-caching, /sub-agents),
95
96
  * and every figure is this session's own. Where the cause has no sharper action,
96
97
  * the share tip prints for sub-agents and the 0.3.16 dollars tip for rewrites.
98
+ * In the plugin context only the share tip's second sentence changes.
97
99
  */
98
- function whyTip(input, lang = 'en') {
100
+ function whyTip(input, lang = 'en', context = 'why') {
99
101
  const { totalTokens, totalUsd } = input, text = i18n_1.WHY_TEXT[lang];
100
102
  const priced = totalUsd !== null && midpoint(totalUsd) > 0;
101
103
  const tokenShare = (tokens) => totalTokens > 0 ? tokens / totalTokens : 0;
@@ -117,7 +119,7 @@ function whyTip(input, lang = 'en') {
117
119
  const { mainModel, onMainModel = 0, onMainModelShare = 0 } = input.subagents;
118
120
  return mainModel && onMainModel > 0 && onMainModelShare >= 0.5 && HAS_SMALLER_MODEL.test(mainModel)
119
121
  ? text.tipSubagentModel(onMainModel, modelLabel(mainModel))
120
- : text.tipFanout((0, exports.share)(input.subagents.tokens, totalTokens));
122
+ : (context === 'plugin' ? text.tipFanoutPlugin : text.tipFanout)((0, exports.share)(input.subagents.tokens, totalTokens));
121
123
  }
122
124
  case 'reloads': {
123
125
  const { cause, count = 0, longestIdleMs = null } = input.reloads;
@@ -204,6 +206,18 @@ function whyTipInput(figures, rates = {}, bucketUsd) {
204
206
  conversation: { tokens: conversation.tokens, usd: conversation.usd, medianPerCall: median(conversation.perCall) },
205
207
  setup: { tokens: setup.tokens, usd: setup.usd, medianPerCall: median(setup.perCall) } };
206
208
  }
209
+ /** The one path from a session's figures to its tip: `renderWhy` prints this line and `whyTipLine` returns it. */
210
+ const figuresTip = (figures, rates, lang, context = 'why') => whyTip(whyTipInput(figures, rates), lang, context);
211
+ /**
212
+ * The tip line `why` ends with for this transcript, in the same words and with
213
+ * the same figures: null when nothing stands out, and for the unknown
214
+ * fork-history report, which prints no tip. The plugin context changes only
215
+ * the fan-out tip's second sentence. It does not read the quiet flag; the
216
+ * caller decides whether to show it.
217
+ */
218
+ function whyTipLine(transcript, rates = {}, lang = 'en', context = 'why') {
219
+ return transcript.state.forkHistoryBoundaryUnknown ? null : figuresTip(sessionFigures(transcript, rates), rates, lang, context);
220
+ }
207
221
  /** Messages on each side of an event the measured change compares, at most and at least. */
208
222
  exports.PROOF_WINDOW = 20;
209
223
  exports.PROOF_MINIMUM = 5;
@@ -253,7 +267,8 @@ function renderWhy(transcript, rates = {}, options = {}) {
253
267
  text.forkUnavailable,
254
268
  table(text.headers, types_1.INSIGHT_BUCKETS.map(bucket => [text.labels[bucket], text.unattributed, text.unattributed, text.unattributed, text.unattributed])),
255
269
  ].join('\n');
256
- const { turns, attribution, prices, totals, totalUsd } = sessionFigures(transcript, rates);
270
+ const figures = sessionFigures(transcript, rates);
271
+ const { turns, attribution, prices, totals, totalUsd } = figures;
257
272
  const lastAttribution = attribution.turnAttributions.at(-1);
258
273
  const byTurn = new Map(attribution.turnAttributions.map(turn => [turn.turnId, turn]));
259
274
  const mixedWriteAllocation = turns.some(turn => (turn.cacheWrite5mTokens ?? 0) > 0 && (turn.cacheWrite1hTokens ?? 0) > 0
@@ -265,7 +280,7 @@ function renderWhy(transcript, rates = {}, options = {}) {
265
280
  return [text.labels[bucket], (0, exports.count)(tokens), money(bucketUsd(bucket)), (0, exports.share)(tokens, attribution.totalTokens), (0, exports.share)(lastTokens, lastAttribution?.totalTokens ?? 0)];
266
281
  });
267
282
  const unknownModels = [...new Set(prices.filter(price => price.usd === null).map(price => price.model ?? text.missingModel))];
268
- const tip = options.tips ? whyTip(whyTipInput({ turns, attribution, totalUsd }, rates, bucketUsd), lang) : null;
283
+ const tip = options.tips ? figuresTip(figures, rates, lang) : null;
269
284
  // A measurement, not a tip: it prints whether or not tips are on.
270
285
  const proof = proofLine(turns, lang);
271
286
  return [
@@ -0,0 +1,33 @@
1
+ import type { WhyLang } from './i18n';
2
+ import type { PricingTable } from './pricing';
3
+ import { type TipContext } from './render';
4
+ export type { TipContext };
5
+ export interface SessionTipOptions {
6
+ /** The AgentGuard home whose pricing overrides `why` uses: AGENTGUARD_HOME, else ~/.agentguard. */
7
+ home?: string;
8
+ /** Rates to price with instead of the home's. */
9
+ rates?: PricingTable;
10
+ /** The language, as `why --lang` takes it. English when not given. */
11
+ lang?: WhyLang;
12
+ /** Read files larger than this many bytes in pieces of this size (16 MB). The tip is the same; only memory changes. */
13
+ chunkBytes?: number;
14
+ /**
15
+ * Where the line is shown. 'why' (the default) is `why`'s own line. 'plugin'
16
+ * is for the AgentGuard plugin, whose users already run it: the fan-out tip
17
+ * ends with "Give related work to one sub-agent instead of several." instead
18
+ * of pointing to the plugin. Every other tip is the same in both.
19
+ */
20
+ context?: TipContext;
21
+ }
22
+ /**
23
+ * The "Next: ..." line `why <transcriptPath>` ends with, or null when nothing
24
+ * stands out. The transcript is read as `why` reads it: Codex when the path is
25
+ * a rollout, Claude Code otherwise, with every sub-agent transcript in the
26
+ * session's `subagents` folder, priced with the home's overrides. The words and
27
+ * figures come from the function `why` prints the tip with, so the two cannot
28
+ * differ. A long transcript is read in pieces cut at line ends, which gives the
29
+ * same turns as reading it whole and keeps it out of memory as one string. It
30
+ * ignores the quiet flag (the caller decides whether to show the line), writes
31
+ * nothing, and throws when the path is not a transcript file.
32
+ */
33
+ export declare function sessionTip(transcriptPath: string, options?: SessionTipOptions): string | null;
@@ -0,0 +1,32 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.sessionTip = sessionTip;
4
+ const node_os_1 = require("node:os");
5
+ const node_path_1 = require("node:path");
6
+ const policy_1 = require("../policy");
7
+ const live_1 = require("./live");
8
+ const render_1 = require("./render");
9
+ const sessions_1 = require("./sessions");
10
+ const transcript_1 = require("./transcript");
11
+ /** A transcript larger than this is read in pieces of this size, as `calendar` reads it. */
12
+ const CHUNK_BYTES = 16 * 1024 * 1024;
13
+ /**
14
+ * The "Next: ..." line `why <transcriptPath>` ends with, or null when nothing
15
+ * stands out. The transcript is read as `why` reads it: Codex when the path is
16
+ * a rollout, Claude Code otherwise, with every sub-agent transcript in the
17
+ * session's `subagents` folder, priced with the home's overrides. The words and
18
+ * figures come from the function `why` prints the tip with, so the two cannot
19
+ * differ. A long transcript is read in pieces cut at line ends, which gives the
20
+ * same turns as reading it whole and keeps it out of memory as one string. It
21
+ * ignores the quiet flag (the caller decides whether to show the line), writes
22
+ * nothing, and throws when the path is not a transcript file.
23
+ */
24
+ function sessionTip(transcriptPath, options = {}) {
25
+ const location = (0, sessions_1.transcriptFileLocation)(transcriptPath);
26
+ if (!location)
27
+ throw new Error('Session transcript not found. Pass its local JSONL path.');
28
+ const home = options.home ?? process.env.AGENTGUARD_HOME ?? (0, node_path_1.join)((0, node_os_1.homedir)(), '.agentguard');
29
+ const rates = options.rates ?? (0, live_1.readPricing)(home, (0, policy_1.loadPolicy)(home, { notice: false }));
30
+ const transcript = (0, transcript_1.readInsightSession)(location.path, { host: location.host, sessionId: location.sessionId }, { chunkBytes: options.chunkBytes ?? CHUNK_BYTES });
31
+ return (0, render_1.whyTipLine)(transcript, rates, options.lang ?? 'en', options.context === 'plugin' ? 'plugin' : 'why');
32
+ }
@@ -14,6 +14,12 @@ export declare function discoverInsightTranscripts(roots?: {
14
14
  claude: string;
15
15
  codex: string;
16
16
  }): TranscriptLocation[];
17
+ /**
18
+ * A transcript named by its path, as `why <path>` reads it: Codex when the path
19
+ * is a rollout or sits under `.codex`, Claude Code otherwise, and the session id
20
+ * from the file name. Null when the path is not a file.
21
+ */
22
+ export declare function transcriptFileLocation(file: string): TranscriptLocation | null;
17
23
  export declare function selectInsightTranscript(session?: string, locations?: TranscriptLocation[]): TranscriptLocation;
18
24
  /**
19
25
  * A file Claude Code keeps inside a session's own directory, such as
@@ -2,6 +2,7 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.transcriptRoots = transcriptRoots;
4
4
  exports.discoverInsightTranscripts = discoverInsightTranscripts;
5
+ exports.transcriptFileLocation = transcriptFileLocation;
5
6
  exports.selectInsightTranscript = selectInsightTranscript;
6
7
  exports.isSessionSidecar = isSessionSidecar;
7
8
  exports.isSubagentTranscript = isSubagentTranscript;
@@ -43,12 +44,22 @@ function discoverInsightTranscripts(roots = transcriptRoots()) {
43
44
  visit(roots.codex, 'codex', 0);
44
45
  return found.sort((a, b) => b.modifiedAt - a.modifiedAt || a.path.localeCompare(b.path));
45
46
  }
47
+ /**
48
+ * A transcript named by its path, as `why <path>` reads it: Codex when the path
49
+ * is a rollout or sits under `.codex`, Claude Code otherwise, and the session id
50
+ * from the file name. Null when the path is not a file.
51
+ */
52
+ function transcriptFileLocation(file) {
53
+ if (!file || !(0, node_fs_1.existsSync)(file) || !(0, node_fs_1.statSync)(file).isFile())
54
+ return null;
55
+ const path = (0, node_path_1.resolve)(file);
56
+ return { path, host: /(?:rollout-|[\\/]\.codex[\\/])/.test(path) ? 'codex' : 'claude', sessionId: (0, node_path_1.basename)(path, '.jsonl'), modifiedAt: (0, node_fs_1.statSync)(path).mtimeMs };
57
+ }
46
58
  function selectInsightTranscript(session, locations) {
47
59
  const requested = session || process.env.AGENTGUARD_SESSION_ID || process.env.CLAUDE_SESSION_ID || process.env.CODEX_THREAD_ID;
48
- if (requested && (0, node_fs_1.existsSync)(requested) && (0, node_fs_1.statSync)(requested).isFile()) {
49
- const path = (0, node_path_1.resolve)(requested);
50
- return { path, host: /(?:rollout-|[\\/]\.codex[\\/])/.test(path) ? 'codex' : 'claude', sessionId: (0, node_path_1.basename)(path, '.jsonl'), modifiedAt: (0, node_fs_1.statSync)(path).mtimeMs };
51
- }
60
+ const file = requested ? transcriptFileLocation(requested) : null;
61
+ if (file)
62
+ return file;
52
63
  const candidates = locations ?? discoverInsightTranscripts();
53
64
  // With nothing requested, the newest top-level session wins. A subagent's own
54
65
  // transcript (Claude Code keeps them under <session>/subagents/agent-*.jsonl) is
@@ -1,6 +1,31 @@
1
1
  import type { Policy } from './types';
2
2
  /** Normalize before evaluating or hashing so receipts bind the actual policy. */
3
3
  export declare function normalizePolicy(policy: Policy): Policy;
4
+ /** Why a burn-policy.json that exists was not used. */
5
+ export type PolicyFileProblem = 'unreadable' | 'invalid_json' | 'not_object' | 'missing_mode' | 'invalid_mode' | 'missing_thresholds';
6
+ /**
7
+ * The policy file at a home: missing (the defaults apply, as intended), loaded,
8
+ * or present but ignored, with every reason and one plain line that says so.
9
+ */
10
+ export type PolicyFileCheck = {
11
+ status: 'missing';
12
+ file: string;
13
+ } | {
14
+ status: 'loaded';
15
+ file: string;
16
+ } | {
17
+ status: 'ignored';
18
+ file: string;
19
+ problems: PolicyFileProblem[];
20
+ line: string;
21
+ };
22
+ /**
23
+ * Whether the home's burn-policy.json is missing, loaded or ignored, decided
24
+ * exactly as loadPolicy decides. An ignored file leaves the defaults in place,
25
+ * which only watch, so a hand-edited file with a mistake would otherwise turn
26
+ * enforcement off without a word. Reads the file; writes nothing.
27
+ */
28
+ export declare function checkPolicyFile(home: string): PolicyFileCheck;
4
29
  export declare function loadPolicy(home: string, options?: {
5
30
  notice?: boolean;
6
31
  }): Policy;
@@ -1,9 +1,11 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.normalizePolicy = normalizePolicy;
4
+ exports.checkPolicyFile = checkPolicyFile;
4
5
  exports.loadPolicy = loadPolicy;
5
6
  /** Load additive policy defaults without rewriting the operator's policy. */
6
7
  const node_fs_1 = require("node:fs");
8
+ const node_os_1 = require("node:os");
7
9
  const node_path_1 = require("node:path");
8
10
  const defaults_1 = require("./defaults");
9
11
  const noticed = new Set();
@@ -82,22 +84,93 @@ function noticeOnce(home, fields) {
82
84
  }
83
85
  process.stderr.write(`AgentGuard loaded missing policy fields from defaults: ${fields.join(', ')}; existing overrides are unchanged.\n`);
84
86
  }
85
- function loadPolicy(home, options = {}) {
87
+ const REASON = {
88
+ unreadable: "it can't be read",
89
+ invalid_json: 'it is not valid JSON',
90
+ not_object: 'it is not a JSON object',
91
+ missing_mode: 'it has no "mode"',
92
+ invalid_mode: 'its "mode" is not "enforce" or "shadow"',
93
+ missing_thresholds: 'it has no "thresholds"',
94
+ };
95
+ const FIX = {
96
+ unreadable: 'Make it readable',
97
+ invalid_json: 'Fix the JSON',
98
+ not_object: 'Write it as {"mode": "enforce", "thresholds": {}}',
99
+ missing_mode: 'Add "mode": "enforce"',
100
+ invalid_mode: 'Set "mode" to "enforce"',
101
+ missing_thresholds: 'Add "thresholds": {}',
102
+ };
103
+ /** The path as a person types it: ~ for their home directory. */
104
+ function shownPath(file) {
105
+ const home = (0, node_os_1.homedir)();
106
+ return home && file.startsWith(home + node_path_1.sep) ? `~${file.slice(home.length)}` : file;
107
+ }
108
+ function ignored(file, problems, mode) {
109
+ // A file whose mode already says "shadow" only watches anyway; the fix makes it count again.
110
+ const lost = mode === 'shadow' ? 'so AgentGuard uses it' : 'to turn limits back on';
111
+ const reason = problems.length === 2 && problems[1] === 'missing_thresholds'
112
+ ? problems[0] === 'missing_mode' ? 'it has no "mode" and no "thresholds"' : `${REASON[problems[0]]}, and it has no "thresholds"`
113
+ : REASON[problems[0]];
114
+ const fix = problems.length === 2 ? `${FIX[problems[0]]} and ${problems[0] === 'missing_mode' ? '' : 'add '}"thresholds": {}` : FIX[problems[0]];
115
+ return { status: 'ignored', file, problems,
116
+ line: `AgentGuard ignored ${shownPath(file)}: ${reason}. Using the defaults, which only watch. ${fix} ${lost}.` };
117
+ }
118
+ /** What loadPolicy reads: the check, and the parsed policy when the file is used. */
119
+ function readPolicyFile(home) {
120
+ const file = (0, node_path_1.join)(home, 'burn-policy.json');
121
+ let text;
122
+ try {
123
+ text = (0, node_fs_1.readFileSync)(file, 'utf8');
124
+ }
125
+ catch (error) {
126
+ const code = error.code;
127
+ return { check: code === 'ENOENT' || code === 'ENOTDIR' ? { status: 'missing', file } : ignored(file, ['unreadable']) };
128
+ }
129
+ let parsed;
86
130
  try {
87
- const parsed = JSON.parse((0, node_fs_1.readFileSync)((0, node_path_1.join)(home, 'burn-policy.json'), 'utf8'));
88
- if (parsed && (parsed.mode === 'shadow' || parsed.mode === 'enforce') && parsed.thresholds) {
131
+ parsed = JSON.parse(text);
132
+ }
133
+ catch {
134
+ return { check: ignored(file, ['invalid_json']) };
135
+ }
136
+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed))
137
+ return { check: ignored(file, ['not_object']) };
138
+ const { mode, thresholds } = parsed;
139
+ const problems = [];
140
+ if (mode === undefined)
141
+ problems.push('missing_mode');
142
+ else if (mode !== 'shadow' && mode !== 'enforce')
143
+ problems.push('invalid_mode');
144
+ if (!thresholds)
145
+ problems.push('missing_thresholds');
146
+ return problems.length ? { check: ignored(file, problems, mode) } : { check: { status: 'loaded', file }, policy: parsed };
147
+ }
148
+ /**
149
+ * Whether the home's burn-policy.json is missing, loaded or ignored, decided
150
+ * exactly as loadPolicy decides. An ignored file leaves the defaults in place,
151
+ * which only watch, so a hand-edited file with a mistake would otherwise turn
152
+ * enforcement off without a word. Reads the file; writes nothing.
153
+ */
154
+ function checkPolicyFile(home) {
155
+ return readPolicyFile(home).check;
156
+ }
157
+ function loadPolicy(home, options = {}) {
158
+ const { policy } = readPolicyFile(home);
159
+ if (policy) {
160
+ try {
89
161
  const missing = [];
90
- if (parsed.thresholds.fanout?.windowActiveMinutes === undefined)
162
+ if (policy.thresholds.fanout?.windowActiveMinutes === undefined)
91
163
  missing.push('fanout.windowActiveMinutes=120');
92
- if (parsed.thresholds.spawnRate?.enforce === undefined)
164
+ if (policy.thresholds.spawnRate?.enforce === undefined)
93
165
  missing.push('spawnRate.enforce=true');
94
166
  if (missing.length && options.notice !== false)
95
167
  noticeOnce(home, missing);
96
- return normalizePolicy(withTeamThresholds(home, parsed));
168
+ return normalizePolicy(withTeamThresholds(home, policy));
169
+ }
170
+ catch {
171
+ /* unusable after all: shadow defaults */
97
172
  }
98
173
  }
99
- catch {
100
- /* no policy yet: shadow defaults */
101
- }
174
+ // No policy yet, or one that is ignored (checkPolicyFile says why): shadow defaults.
102
175
  return normalizePolicy(defaults_1.DEFAULT_POLICY);
103
176
  }