@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
@@ -0,0 +1,210 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.shortId = void 0;
4
+ exports.compareSession = compareSession;
5
+ exports.compareReport = compareReport;
6
+ exports.pickCompareSessions = pickCompareSessions;
7
+ exports.comparePicked = comparePicked;
8
+ exports.signedChange = signedChange;
9
+ exports.signedPoints = signedPoints;
10
+ exports.renderCompare = renderCompare;
11
+ /**
12
+ * `compare`: two sessions side by side from local transcripts, for the advice to
13
+ * run the same task on each model and compare what /usage reports, which shows
14
+ * one session at a time. Every figure is the one `why` prints for that session
15
+ * (sessionFigures), child transcripts included the way `why` includes them.
16
+ * Measurement only: the report never judges which session or model did better.
17
+ */
18
+ const node_fs_1 = require("node:fs");
19
+ const node_path_1 = require("node:path");
20
+ const live_1 = require("./live");
21
+ const render_1 = require("./render");
22
+ const sessions_1 = require("./sessions");
23
+ const transcript_1 = require("./transcript");
24
+ const types_1 = require("./types");
25
+ const i18n_1 = require("./i18n");
26
+ /** The last dash-separated part of a session id, which `why` and `compare` accept back as an id suffix. */
27
+ const shortId = (sessionId) => sessionId.slice(sessionId.lastIndexOf('-') + 1) || sessionId;
28
+ exports.shortId = shortId;
29
+ const byName = (a, b) => a === b ? 0 : a === null ? 1 : b === null ? -1 : a < b ? -1 : 1;
30
+ const earliest = (times) => times.length ? times.reduce((low, value) => Math.min(low, value)) : undefined;
31
+ /** One session's figures. `origin` supplies the recorded working directory; without it a Claude session shows its project directory. */
32
+ function compareSession(location, transcript, rates = {}, origin = null) {
33
+ const figures = (0, render_1.sessionFigures)(transcript, rates), totals = figures.totals;
34
+ const available = !transcript.state.forkHistoryBoundaryUnknown;
35
+ const byModel = new Map();
36
+ for (const turn of figures.turns) {
37
+ const model = turn.model ?? null, row = byModel.get(model) ?? { model, responses: 0, outputTokens: 0, share: null };
38
+ row.responses++;
39
+ row.outputTokens += turn.outputTokens;
40
+ byModel.set(model, row);
41
+ }
42
+ const models = [...byModel.values()].map(row => ({ ...row, share: totals.output ? row.outputTokens / totals.output : null }))
43
+ .sort((a, b) => b.outputTokens - a.outputTokens || b.responses - a.responses || byName(a.model, b.model));
44
+ const timed = figures.turns.filter(turn => turn.at !== undefined && Number.isFinite(turn.at));
45
+ const started = earliest(timed.filter(turn => !turn.subagent).map(turn => turn.at)) ?? earliest(timed.map(turn => turn.at));
46
+ const input = totals.input + totals.write + totals.read;
47
+ const metrics = available
48
+ ? { assistantResponses: figures.turns.length, inputTokens: input, cacheReadTokens: totals.read, cacheWriteTokens: totals.write, freshInputTokens: totals.input,
49
+ cacheShare: input ? totals.read / input : 0, outputTokens: totals.output, subagentsLaunched: transcript.observations.spawnCalls,
50
+ fullPrefixRewrites: figures.attribution.rewrites.length, usd: figures.totalUsd }
51
+ : { assistantResponses: null, inputTokens: null, cacheReadTokens: null, cacheWriteTokens: null, freshInputTokens: null,
52
+ cacheShare: null, outputTokens: null, subagentsLaunched: null, fullPrefixRewrites: null, usd: null };
53
+ return {
54
+ sessionId: transcript.sessionId, shortId: (0, exports.shortId)(transcript.sessionId), host: location.host, path: location.path,
55
+ project: origin?.workingDirectory ?? (location.host === 'claude' ? (0, node_path_1.dirname)(location.path) : null),
56
+ startedAt: started === undefined ? null : new Date(started).toISOString(),
57
+ dominantModel: models[0]?.model ?? null, models, usageAvailable: available,
58
+ unpricedModels: available ? [...new Set(figures.prices.filter(price => price.usd === null).map(price => price.model))] : [],
59
+ metrics,
60
+ };
61
+ }
62
+ const midpoint = (value) => (value.min + value.max) / 2;
63
+ /** "A is not zero" as the table prints it: against $0.00 or 0.0% no change is computed. */
64
+ function printsAsZero(key, value) {
65
+ if (key === 'usd')
66
+ return Math.abs(value).toFixed(2) === '0.00';
67
+ if (key === 'cacheShare')
68
+ return (value * 100).toFixed(1) === '0.0';
69
+ return value === 0;
70
+ }
71
+ /**
72
+ * B against A. Counts and dollars change relatively (-65.3%); the cache share
73
+ * is already a percentage, so it changes by its difference in points (+2.6 pp),
74
+ * never by a percentage of a percentage.
75
+ */
76
+ function metricChange(key, before, after) {
77
+ const figure = (value) => value === null ? null : typeof value === 'number' ? value : midpoint(value);
78
+ const from = figure(before), to = figure(after);
79
+ if (from === null || to === null || printsAsZero(key, from))
80
+ return null;
81
+ return key === 'cacheShare' ? to - from : (to - from) / from;
82
+ }
83
+ function compareReport(a, b) {
84
+ const change = Object.fromEntries(types_1.COMPARE_METRICS.map(key => [key, metricChange(key, a.metrics[key], b.metrics[key])]));
85
+ return { a, b, change, subagentsIncluded: true, basis: 'estimated_api_list_price' };
86
+ }
87
+ /**
88
+ * A path given on the command line can name a discovered transcript through
89
+ * other text: a symlinked ~/.claude or ~/.codex, or a relative path resolved
90
+ * from the physical working directory. The discovered location is the one that
91
+ * groups with its siblings, and the one the newest-other search must skip.
92
+ */
93
+ function asDiscovered(location, locations) {
94
+ if (locations.some(item => item.path === location.path))
95
+ return location;
96
+ const real = (path) => { try {
97
+ return (0, node_fs_1.realpathSync)(path);
98
+ }
99
+ catch {
100
+ return null;
101
+ } };
102
+ const target = real(location.path);
103
+ return (target !== null && locations.find(item => (0, node_path_1.basename)(item.path) === (0, node_path_1.basename)(location.path) && real(item.path) === target)) || location;
104
+ }
105
+ /**
106
+ * Two selectors: those two sessions, in that order. One: that session and the
107
+ * newest other top-level session of its project. None: the two newest top-level
108
+ * sessions of the newest one's project. Selectors resolve exactly as `why`
109
+ * resolves one (id, id suffix or JSONL path). A top-level Claude Code session is
110
+ * a transcript directly inside its project directory, never a sub-agent file or
111
+ * any other file a session keeps beside it; a Codex rollout is top-level unless
112
+ * its first records mark a spawned sub-agent, and its project is the working
113
+ * directory it recorded. The session variables `why` falls back on are not read:
114
+ * with nothing given, recency decides.
115
+ */
116
+ function pickCompareSessions(selectors, options = {}) {
117
+ const roots = options.roots ?? (0, sessions_1.transcriptRoots)();
118
+ let discovered = options.locations;
119
+ const locations = () => discovered ??= (0, sessions_1.discoverInsightTranscripts)(roots);
120
+ if (selectors.length === 2)
121
+ return { ok: true, a: (0, sessions_1.selectInsightTranscript)(selectors[0], locations()), b: (0, sessions_1.selectInsightTranscript)(selectors[1], locations()), explicit: true };
122
+ const origins = new Map(), read = options.origin ?? sessions_1.transcriptOrigin;
123
+ const origin = (location) => {
124
+ let value = origins.get(location.path);
125
+ if (!value) {
126
+ value = read(location);
127
+ origins.set(location.path, value);
128
+ }
129
+ return value;
130
+ };
131
+ const topLevel = (location) => !(0, sessions_1.isSubagentTranscript)(location)
132
+ && (location.host === 'claude' ? (0, node_path_1.dirname)((0, node_path_1.dirname)(location.path)) === roots.claude : !origin(location).spawned);
133
+ const project = (location) => location.host === 'claude' ? (0, node_path_1.dirname)(location.path) : origin(location).workingDirectory;
134
+ const anchor = selectors.length ? asDiscovered((0, sessions_1.selectInsightTranscript)(selectors[0], locations()), locations()) : locations().find(topLevel);
135
+ if (!anchor)
136
+ return { ok: false, found: 0, project: null };
137
+ const key = project(anchor);
138
+ const other = key === null ? undefined
139
+ : locations().find(location => location.path !== anchor.path && location.host === anchor.host && project(location) === key && topLevel(location));
140
+ if (!other)
141
+ return { ok: false, found: 1, project: origin(anchor).workingDirectory ?? key };
142
+ return other.modifiedAt <= anchor.modifiedAt ? { ok: true, a: other, b: anchor, explicit: false } : { ok: true, a: anchor, b: other, explicit: false };
143
+ }
144
+ /** Reads each picked session the way `why` reads one. Unless the order was given, A is the session that started first. */
145
+ function comparePicked(pick, rates = {}, origin = sessions_1.transcriptOrigin) {
146
+ const read = (location) => compareSession(location, (0, transcript_1.readInsightSession)(location.path, { host: location.host, sessionId: location.sessionId }), rates, origin(location));
147
+ let a = read(pick.a), b = read(pick.b);
148
+ if (!pick.explicit && a.startedAt !== null && b.startedAt !== null && b.startedAt < a.startedAt)
149
+ [a, b] = [b, a];
150
+ return compareReport(a, b);
151
+ }
152
+ const INDENTED = new Set(['cacheReadTokens', 'cacheWriteTokens', 'freshInputTokens']);
153
+ const stamp = (iso) => `${iso.slice(0, 10)} ${iso.slice(11, 16)} UTC`;
154
+ const isRange = (value) => value !== null && Math.abs(value.max - value.min) >= 0.000001;
155
+ /** A signed percentage with one decimal, as `why` prints shares; a change that rounds to zero has no sign. */
156
+ function signedChange(change) {
157
+ if (change === null)
158
+ return '';
159
+ const digits = Math.abs(change * 100).toFixed(1);
160
+ return digits === '0.0' ? '0.0%' : `${change < 0 ? '-' : '+'}${digits}%`;
161
+ }
162
+ /** A difference in share, in percentage points: "+2.6 pp" reads the same in English, Spanish and Portuguese. */
163
+ function signedPoints(change) {
164
+ if (change === null)
165
+ return '';
166
+ const digits = Math.abs(change * 100).toFixed(1);
167
+ return digits === '0.0' ? '0.0 pp' : `${change < 0 ? '-' : '+'}${digits} pp`;
168
+ }
169
+ /** `lang` changes words only; every figure, id, model id, path and command prints as it does in English. */
170
+ function renderCompare(report, lang = 'en') {
171
+ const text = i18n_1.COMPARE_TEXT[lang], words = i18n_1.WHY_TEXT[lang];
172
+ const name = (model) => model ?? words.missingModel;
173
+ const modelLine = (session) => {
174
+ if (!session.models.length)
175
+ return text.noModel;
176
+ const output = session.models.reduce((sum, row) => sum + row.outputTokens, 0);
177
+ const listed = session.models.filter(row => row.share !== null && row.share >= 0.05);
178
+ return listed.length > 1 ? text.models(listed.map(row => `${name(row.model)} ${(0, render_1.share)(row.outputTokens, output)}`).join(', ')) : text.model(name(session.models[0].model));
179
+ };
180
+ const heading = (label, session) => [
181
+ `${label} ${session.shortId} ${session.startedAt === null ? text.startUnknown : text.started(stamp(session.startedAt))}`,
182
+ ` ${modelLine(session)}`,
183
+ ` ${text.project(session.project)}`,
184
+ ];
185
+ const cell = (session, key) => {
186
+ const metrics = session.metrics;
187
+ if (!session.usageAvailable)
188
+ return text.unavailable;
189
+ if (key === 'usd')
190
+ return (0, live_1.dollars)(metrics.usd, words);
191
+ if (key === 'cacheShare')
192
+ return (0, render_1.share)(metrics.cacheReadTokens, metrics.inputTokens);
193
+ return (0, render_1.count)(metrics[key]);
194
+ };
195
+ const rows = types_1.COMPARE_METRICS.map(key => [`${INDENTED.has(key) ? ' ' : ''}${text.labels[key]}`, cell(report.a, key), cell(report.b, key), key === 'cacheShare' ? signedPoints(report.change[key]) : signedChange(report.change[key])]);
196
+ const sessions = [['A', report.a], ['B', report.b]];
197
+ const unpriced = [...new Set(sessions.flatMap(([, session]) => session.unpricedModels.map(name)))];
198
+ const ranged = sessions.some(([, session]) => isRange(session.metrics.usd));
199
+ return [
200
+ text.title,
201
+ ...heading('A', report.a), ...heading('B', report.b),
202
+ '', (0, render_1.table)([...text.headers], rows), text.subagents,
203
+ '',
204
+ ...sessions.filter(([, session]) => !session.usageAvailable).map(([label]) => text.forkUnavailable(label)),
205
+ ...(unpriced.length ? [words.unpricedModels(unpriced.join(', '))] : []),
206
+ ...(ranged ? [words.missingTtl, ...(report.change.usd !== null ? [text.rangeMidpoint] : [])] : []),
207
+ text.listPrice,
208
+ text.sameTask,
209
+ ].join('\n');
210
+ }
@@ -1,14 +1,15 @@
1
1
  /**
2
- * Languages of the plain `why` report: English, Latin American Spanish and
3
- * Brazilian Portuguese. Only words change. Numbers keep their en-US formatting
4
- * (1,234,567, $1335.37, 12.3%) so figures match screenshots and the site, and
5
- * session ids, model ids, commands, URLs and product names print as they are.
6
- * `why json` is a machine format and is never translated.
2
+ * Languages of the plain `why`, `compare` and `calendar` reports: English, Latin
3
+ * American Spanish and Brazilian Portuguese. Only words change. Numbers keep their
4
+ * en-US formatting (1,234,567, $1335.37, 12.3%) so figures match screenshots and
5
+ * the site, and session ids, model ids, commands, URLs and product names print as
6
+ * they are. `why json`, `compare json` and `calendar json` are machine formats,
7
+ * never translated.
7
8
  *
8
9
  * Detection is pure: the CLI passes in the flag, the environment and the Intl
9
- * locale, and renderWhy receives the chosen language through its options.
10
+ * locale, and each renderer receives the chosen language as an argument.
10
11
  */
11
- import type { InsightBucket, InsightObservations } from './types';
12
+ import type { CompareMetric, InsightBucket, InsightObservations } from './types';
12
13
  export type WhyLang = 'en' | 'es' | 'pt';
13
14
  /**
14
15
  * The language of a flag value or locale: the part before '_', '-', '.' or '@',
@@ -57,9 +58,134 @@ export interface WhyText {
57
58
  missingTtl: string;
58
59
  mixedRanges: string;
59
60
  diagnostics: (duplicates: number, malformed: number) => string;
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. */
60
62
  tipFanout: (share: string) => string;
61
63
  tipRewrites: (rewrites: string, total: string) => string;
62
- tipHistory: (share: string) => string;
64
+ /** Sub-agents that ran on the main conversation's model, by its display name (Opus 5.5). */
65
+ tipSubagentModel: (count: number, model: string) => string;
66
+ /** Reloads after a pause outlasted the cache; `longest` is the longest such pause as `rewrites` prints it (47m, 2h 5m). */
67
+ tipIdleReloads: (count: number, longest: string) => string;
68
+ /** Reloads that a model switch caused. */
69
+ tipModelSwitch: (count: number) => string;
70
+ /** The conversation Claude re-read per message, a median. */
71
+ tipConversation: (tokens: string) => string;
72
+ /** The setup Claude read per message, a median. */
73
+ tipSetup: (tokens: string) => string;
74
+ /**
75
+ * One measured change around a compaction, /clear or model switch: the median
76
+ * tokens per message in the `messages` after it and in as many before it. The
77
+ * date and time are UTC. Measurement only, never a saving or a cause.
78
+ */
79
+ proof: (event: ProofEvent, when: {
80
+ date: string;
81
+ time: string;
82
+ }, after: string, before: string, messages: number, direction: 'down' | 'up' | 'same') => string;
63
83
  hide: string;
64
84
  }
85
+ /** What `why` measures a change around. `model` is a display name (Sonnet 5). */
86
+ export type ProofEvent = {
87
+ kind: 'compact' | 'auto' | 'compaction' | 'clear';
88
+ } | {
89
+ kind: 'model';
90
+ model: string;
91
+ };
65
92
  export declare const WHY_TEXT: Readonly<Record<WhyLang, WhyText>>;
93
+ /**
94
+ * The cost of one more sub-agent, for the STOP prompt and box: what this
95
+ * session's finished sub-agents averaged, a measurement of what already ran and
96
+ * never a forecast. `count` is at least three; `usd` is null when any of them ran
97
+ * on an unpriced model. Every other line of the STOP text is English on every
98
+ * host, so the hook asks for English; the Spanish and Portuguese lines are here
99
+ * for when the STOP text is translated.
100
+ */
101
+ export interface DecisionText {
102
+ finished: (count: number, tokens: string, usd: string | null) => string;
103
+ }
104
+ export declare const DECISION_TEXT: Readonly<Record<WhyLang, DecisionText>>;
105
+ /**
106
+ * Every line of the plain `compare` report, in the same three languages and under
107
+ * the same rules as `why`: words change, figures, ids, model ids, paths and
108
+ * commands do not. The rewrite label, the List USD header and the unpriced and
109
+ * missing-model wording are `why`'s own, so both reports use one vocabulary.
110
+ */
111
+ export interface CompareText {
112
+ title: string;
113
+ /** The session line after the short id; `stamp` is `YYYY-MM-DD HH:MM UTC`. */
114
+ started: (stamp: string) => string;
115
+ startUnknown: string;
116
+ /** The one model with at least 5% of output tokens, or the dominant one. */
117
+ model: (model: string) => string;
118
+ /** Two or more models with at least 5% of output tokens each, each with its share of the output tokens. */
119
+ models: (list: string) => string;
120
+ noModel: string;
121
+ project: (path: string | null) => string;
122
+ headers: [metric: string, a: string, b: string, change: string];
123
+ /** Table labels; the three input rows print indented under the input total. */
124
+ labels: Record<CompareMetric, string>;
125
+ /** Every cell of a session whose usage is unavailable. */
126
+ unavailable: string;
127
+ subagents: string;
128
+ forkUnavailable: (session: string) => string;
129
+ rangeMidpoint: string;
130
+ listPrice: string;
131
+ sameTask: string;
132
+ /** Stderr when fewer than two sessions are found; `project` is null when none is known. */
133
+ fewerThanTwo: (found: number, project: string | null) => string;
134
+ }
135
+ export declare const COMPARE_TEXT: Readonly<Record<WhyLang, CompareText>>;
136
+ /** A calendar date as the report names it: the month's short name, the day of the month and the year. */
137
+ export interface CalendarDate {
138
+ month: string;
139
+ day: number;
140
+ year: number;
141
+ }
142
+ /**
143
+ * Every line of the plain `calendar` report, in the same three languages and
144
+ * under the same rules as `why` and `compare`: words, weekday and month names
145
+ * change; figures, the shade characters, the plain-text day letters, AgentGuard,
146
+ * Burn, Claude Code and Codex do not. The command name in the title stays as
147
+ * typed, as `why` and `compare` keep theirs. Every line is written for a
148
+ * developer who has never heard of AgentGuard, in everyday words: "sub-agents" is
149
+ * Claude Code's own word, and a dollar figure is "at API prices, not a bill".
150
+ */
151
+ export interface CalendarText {
152
+ /** Row labels, Sunday first. */
153
+ weekdays: readonly [string, string, string, string, string, string, string];
154
+ /** January first, three letters each, so a label fits above two week columns. */
155
+ months: readonly [string, string, string, string, string, string, string, string, string, string, string, string];
156
+ /** A day in the summary, with its year only when the calendar spans two years. */
157
+ date: (date: CalendarDate, withYear: boolean) => string;
158
+ /** The span in the title, first day to last. */
159
+ span: (from: CalendarDate, to: CalendarDate) => string;
160
+ title: (span: string) => string;
161
+ tokens: (count: string) => string;
162
+ /** `usd` is null when no token shown has a known API price. */
163
+ dollars: (usd: string | null) => string;
164
+ busiest: (date: string, count: string) => string;
165
+ subagents: (share: string) => string;
166
+ /** Sub-agent launches AgentGuard held (refused, or held for the person's yes); printed only above zero. */
167
+ held: (launches: number) => string;
168
+ less: string;
169
+ more: string;
170
+ /** What an amber day means: `colour` beside an amber cell, `plain` names the day letter. */
171
+ subagentDays: {
172
+ colour: string;
173
+ plain: (letter: string) => string;
174
+ };
175
+ /** What a red mark means, the same way. */
176
+ heldDays: {
177
+ colour: string;
178
+ plain: (letter: string) => string;
179
+ };
180
+ /** Which hosts the shown days came from. */
181
+ sources: (claude: boolean, codex: boolean) => string;
182
+ unpriced: (tokens: string, models: string) => string;
183
+ forkUnknown: (forks: number) => string;
184
+ unreadable: (files: number) => string;
185
+ noData: string;
186
+ /** Printed while the recorded history is shorter than the calendar could show. */
187
+ shortHistory: readonly [string, string];
188
+ /** Stderr when the daily counts cannot be written. */
189
+ saveFailed: string;
190
+ }
191
+ export declare const CALENDAR_TEXT: Readonly<Record<WhyLang, CalendarText>>;
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.WHY_TEXT = void 0;
3
+ exports.CALENDAR_TEXT = exports.COMPARE_TEXT = exports.DECISION_TEXT = exports.WHY_TEXT = void 0;
4
4
  exports.whyLangOf = whyLangOf;
5
5
  exports.detectWhyLang = detectWhyLang;
6
6
  /**
@@ -30,6 +30,9 @@ function detectWhyLang(sources = {}) {
30
30
  }
31
31
  /** Spanish and Portuguese nouns agree with their count: 1 is singular, 0 and everything else plural. */
32
32
  const plural = (n, one, other) => `${n} ${n === 1 ? one : other}`;
33
+ const times = (n) => n === 1 ? 'once' : `${n} times`;
34
+ const veces = (n) => n === 1 ? 'una vez' : `${n} veces`;
35
+ const vezes = (n) => n === 1 ? 'uma vez' : `${n} vezes`;
33
36
  const en = {
34
37
  labels: {
35
38
  instruction_stack: 'Instruction stack + system', history_resent: 'History re-sent', reread_files: 'Re-read files',
@@ -64,10 +67,19 @@ const en = {
64
67
  missingTtl: 'Cache TTL is missing for some writes; their dollars span the verified five-minute and one-hour rates.',
65
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.',
66
69
  diagnostics: (duplicates, malformed) => `Usage records de-duplicated: ${duplicates}. Malformed lines skipped: ${malformed}.`,
67
- tipFanout: share => `Next: sub-agent fan-out is ${share} of this session's tokens. Spawn limits refuse the next sub-agent launch past your limit, free on one machine: agentguard.run/try`,
68
- tipRewrites: (rewrites, total) => `Next: full-prefix rewrites are ${rewrites} of ${total} API list equivalent here. See the cause of each one: npx @agentguard-run/burn rewrites`,
69
- tipHistory: share => `Next: history re-sent is ${share} of this session's tokens. A fresh session, or /compact, starts that history over.`,
70
- hide: 'Hide tips like this: npx @agentguard-run/burn quiet on',
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
+ 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
+ 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
+ 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.`,
74
+ tipModelSwitch: count => `Next: switching models made Claude reload the whole conversation ${times(count)}. Pick your model when you start, or switch at a break, right after /compact.`,
75
+ tipConversation: tokens => `Next: Claude re-reads the conversation on every message, a median of ${tokens} tokens each time. Run /compact at a natural break, or /clear between unrelated tasks.`,
76
+ tipSetup: tokens => `Next: Claude reads ${tokens} tokens of setup before every message (CLAUDE.md, tools, MCP servers and your first message). Keep CLAUDE.md short and turn off MCP servers you are not using (/mcp).`,
77
+ proof: (event, when, after, before, messages, direction) => {
78
+ const what = event.kind === 'model' ? `the switch to ${event.model}` : { compact: '/compact', auto: 'automatic compaction', compaction: 'compaction', clear: '/clear' }[event.kind];
79
+ const change = direction === 'same' ? `the same as in the ${messages} messages before` : `${direction} from ${before} in the ${messages} messages before`;
80
+ return `Measured change: after ${what} on ${when.date} at ${when.time} UTC, Claude read a median of ${after} tokens per message, ${change}.`;
81
+ },
82
+ hide: 'Hide tips like this: npx agentguard-burn quiet on',
71
83
  };
72
84
  /** Latin American Spanish: tú forms and vocabulary that reads the same from Mexico and Panama to Argentina. */
73
85
  const es = {
@@ -104,10 +116,19 @@ const es = {
104
116
  missingTtl: 'Algunas escrituras no tienen TTL de caché; su costo en dólares va de la tarifa verificada de cinco minutos a la de una hora.',
105
117
  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.',
106
118
  diagnostics: (duplicates, malformed) => `Registros de uso deduplicados: ${duplicates}. Líneas mal formadas omitidas: ${malformed}.`,
107
- tipFanout: share => `Próximo paso: el fan-out de subagentes representa el ${share} de los tokens de esta sesión. Los límites de subagentes rechazan nuevos subagentes cuando llegas a tu límite, gratis en una máquina: agentguard.run/try`,
108
- 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-run/burn rewrites`,
109
- tipHistory: share => `Próximo paso: el historial reenviado representa el ${share} de los tokens de esta sesión. Una sesión nueva, o /compact, reinicia ese historial.`,
110
- hide: 'Para ocultar consejos como este: npx @agentguard-run/burn quiet on',
119
+ 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`,
120
+ 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
+ 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
+ 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.`,
123
+ tipModelSwitch: count => `Próximo paso: cambiar de modelo hizo que Claude recargara toda la conversación ${veces(count)}. Elige tu modelo al empezar, o cambia en una pausa, justo después de /compact.`,
124
+ tipConversation: tokens => `Próximo paso: Claude vuelve a leer la conversación en cada mensaje, una mediana de ${tokens} tokens cada vez. Usa /compact en una pausa natural, o /clear entre tareas que no tienen relación.`,
125
+ tipSetup: tokens => `Próximo paso: Claude lee ${tokens} tokens de configuración antes de cada mensaje (CLAUDE.md, herramientas, servidores MCP y tu primer mensaje). Mantén CLAUDE.md corto y desactiva los servidores MCP que no uses (/mcp).`,
126
+ proof: (event, when, after, before, messages, direction) => {
127
+ const what = event.kind === 'model' ? `del cambio a ${event.model}` : { compact: 'de /compact', auto: 'de la compactación automática', compaction: 'de la compactación', clear: 'de /clear' }[event.kind];
128
+ const change = direction === 'same' ? `igual que en los ${messages} mensajes anteriores` : `${direction === 'down' ? 'por debajo' : 'por encima'} de los ${before} de los ${messages} mensajes anteriores`;
129
+ return `Cambio medido: después ${what} el ${when.date} a las ${when.time} UTC, Claude leyó una mediana de ${after} tokens por mensaje, ${change}.`;
130
+ },
131
+ hide: 'Para ocultar consejos como este: npx agentguard-burn quiet on',
111
132
  };
112
133
  /** Brazilian Portuguese: você forms. */
113
134
  const pt = {
@@ -144,9 +165,175 @@ const pt = {
144
165
  missingTtl: 'Algumas gravações não têm TTL de cache; o valor delas em dólares vai da tarifa verificada de cinco minutos à de uma hora.',
145
166
  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.',
146
167
  diagnostics: (duplicates, malformed) => `Registros de uso deduplicados: ${duplicates}. Linhas malformadas ignoradas: ${malformed}.`,
147
- tipFanout: share => `Próximo passo: o fan-out de subagentes representa ${share} dos tokens desta sessão. Os limites de subagentes recusam novos subagentes quando você chega ao seu limite, grátis em uma máquina: agentguard.run/try`,
148
- 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-run/burn rewrites`,
149
- tipHistory: share => `Próximo passo: o histórico reenviado representa ${share} dos tokens desta sessão. Uma sessão nova, ou /compact, reinicia esse histórico.`,
150
- hide: 'Para ocultar dicas como esta: npx @agentguard-run/burn quiet on',
168
+ 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`,
169
+ 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
+ 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
+ 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.`,
172
+ tipModelSwitch: count => `Próximo passo: trocar de modelo fez o Claude recarregar a conversa inteira ${vezes(count)}. Escolha o modelo ao começar, ou troque em uma pausa, logo depois do /compact.`,
173
+ tipConversation: tokens => `Próximo passo: o Claude relê a conversa a cada mensagem, uma mediana de ${tokens} tokens por vez. Use /compact em uma pausa natural, ou /clear entre tarefas sem relação.`,
174
+ tipSetup: tokens => `Próximo passo: o Claude lê ${tokens} tokens de configuração antes de cada mensagem (CLAUDE.md, ferramentas, servidores MCP e sua primeira mensagem). Mantenha o CLAUDE.md curto e desative os servidores MCP que você não usa (/mcp).`,
175
+ proof: (event, when, after, before, messages, direction) => {
176
+ const what = event.kind === 'model' ? `da troca para o ${event.model}` : { compact: 'do /compact', auto: 'da compactação automática', compaction: 'da compactação', clear: 'do /clear' }[event.kind];
177
+ const change = direction === 'same' ? `a mesma das ${messages} mensagens anteriores` : `${direction === 'down' ? 'abaixo' : 'acima'} dos ${before} das ${messages} mensagens anteriores`;
178
+ return `Mudança medida: depois ${what} em ${when.date} às ${when.time} UTC, o Claude leu uma mediana de ${after} tokens por mensagem, ${change}.`;
179
+ },
180
+ hide: 'Para ocultar dicas como esta: npx agentguard-burn quiet on',
151
181
  };
152
182
  exports.WHY_TEXT = { en, es, pt };
183
+ exports.DECISION_TEXT = {
184
+ en: { finished: (count, tokens, usd) => `The ${count} sub-agents that finished in this session averaged ${tokens} tokens each${usd ? ` (${usd} at API prices, not a bill)` : ''}. This one could differ.` },
185
+ es: { finished: (count, tokens, usd) => `Los ${count} subagentes que terminaron en esta sesión promediaron ${tokens} tokens cada uno${usd ? ` (${usd} a precios de la API, no una factura)` : ''}. Este podría ser distinto.` },
186
+ pt: { finished: (count, tokens, usd) => `Os ${count} subagentes que terminaram nesta sessão usaram em média ${tokens} tokens cada${usd ? ` (${usd} a preços da API, não uma fatura)` : ''}. Este pode ser diferente.` },
187
+ };
188
+ const TWO_IDS = 'agentguard-burn compare SESSION_A SESSION_B';
189
+ const compareEn = {
190
+ title: 'AgentGuard compare: B against A',
191
+ started: stamp => `started ${stamp}`,
192
+ startUnknown: 'start time not recorded',
193
+ model: model => `Model: ${model}`,
194
+ models: list => `Output by model: ${list}`,
195
+ noModel: 'Model: no assistant response recorded',
196
+ project: path => `Project: ${path ?? 'not recorded'}`,
197
+ headers: ['Metric', 'A', 'B', 'Change'],
198
+ labels: {
199
+ assistantResponses: 'Assistant responses', inputTokens: 'Input tokens', cacheReadTokens: 'read from cache', cacheWriteTokens: 'cache writes',
200
+ freshInputTokens: 'fresh input', cacheShare: 'Cache share', outputTokens: 'Output tokens', subagentsLaunched: 'Sub-agents launched',
201
+ fullPrefixRewrites: en.labels.full_prefix_rewrites, usd: en.headers[2],
202
+ },
203
+ unavailable: 'unavailable',
204
+ subagents: 'Totals include sub-agents.',
205
+ forkUnavailable: session => `${session}: inherited Codex history has no verifiable boundary, so its usage is unavailable. Copied usage is excluded, not counted as zero.`,
206
+ rangeMidpoint: 'A dollar range is compared at its midpoint.',
207
+ listPrice: 'Dollar figures are API list-price equivalents, not a bill.',
208
+ sameTask: 'AgentGuard cannot tell whether these sessions did the same task. Compare runs of the same task.',
209
+ fewerThanTwo: (found, project) => found === 0
210
+ ? `No local top-level session found, and compare needs two. Pass two ids: ${TWO_IDS}`
211
+ : `Only one top-level session found${project ? ` in ${project}` : ''}, and compare needs two. Pass two ids: ${TWO_IDS}`,
212
+ };
213
+ const compareEs = {
214
+ title: 'AgentGuard compare: B frente a A',
215
+ started: stamp => `inicio ${stamp}`,
216
+ startUnknown: 'hora de inicio no registrada',
217
+ model: model => `Modelo: ${model}`,
218
+ models: list => `Salida por modelo: ${list}`,
219
+ noModel: 'Modelo: no hay respuestas del asistente registradas',
220
+ project: path => `Proyecto: ${path ?? 'no registrado'}`,
221
+ headers: ['Métrica', 'A', 'B', 'Cambio'],
222
+ labels: {
223
+ assistantResponses: 'Respuestas del asistente', inputTokens: 'Tokens de entrada', cacheReadTokens: 'lectura de caché', cacheWriteTokens: 'escritura en caché',
224
+ freshInputTokens: 'entrada nueva', cacheShare: 'Proporción de caché', outputTokens: 'Tokens de salida', subagentsLaunched: 'Subagentes lanzados',
225
+ fullPrefixRewrites: es.labels.full_prefix_rewrites, usd: es.headers[2],
226
+ },
227
+ unavailable: 'no disponible',
228
+ subagents: 'Los totales incluyen los subagentes.',
229
+ forkUnavailable: session => `${session}: el historial heredado de Codex no tiene un punto de corte verificable, así que el uso de esta sesión no está disponible. El uso copiado queda excluido, no se cuenta como cero.`,
230
+ rangeMidpoint: 'Un rango en dólares se compara por su punto medio.',
231
+ listPrice: 'Las cifras en dólares son equivalentes a precio de lista de la API, no una factura.',
232
+ sameTask: 'AgentGuard no puede saber si estas sesiones hicieron la misma tarea. Compara ejecuciones de la misma tarea.',
233
+ fewerThanTwo: (found, project) => found === 0
234
+ ? `No se encontró ninguna sesión principal local, y compare necesita dos. Pasa dos ids: ${TWO_IDS}`
235
+ : `Solo se encontró una sesión principal${project ? ` en ${project}` : ''}, y compare necesita dos. Pasa dos ids: ${TWO_IDS}`,
236
+ };
237
+ const comparePt = {
238
+ title: 'AgentGuard compare: B em relação a A',
239
+ started: stamp => `início ${stamp}`,
240
+ startUnknown: 'horário de início não registrado',
241
+ model: model => `Modelo: ${model}`,
242
+ models: list => `Saída por modelo: ${list}`,
243
+ noModel: 'Modelo: nenhuma resposta do assistente registrada',
244
+ project: path => `Projeto: ${path ?? 'não registrado'}`,
245
+ headers: ['Métrica', 'A', 'B', 'Variação'],
246
+ labels: {
247
+ assistantResponses: 'Respostas do assistente', inputTokens: 'Tokens de entrada', cacheReadTokens: 'leitura de cache', cacheWriteTokens: 'gravação em cache',
248
+ freshInputTokens: 'entrada nova', cacheShare: 'Proporção de cache', outputTokens: 'Tokens de saída', subagentsLaunched: 'Subagentes iniciados',
249
+ fullPrefixRewrites: pt.labels.full_prefix_rewrites, usd: pt.headers[2],
250
+ },
251
+ unavailable: 'indisponível',
252
+ subagents: 'Os totais incluem os subagentes.',
253
+ forkUnavailable: session => `${session}: o histórico herdado do Codex não tem um ponto de corte verificável, então o uso desta sessão fica indisponível. O uso copiado fica de fora, não é contado como zero.`,
254
+ rangeMidpoint: 'Uma faixa em dólares é comparada pelo ponto médio.',
255
+ listPrice: 'Os valores em dólares são equivalentes ao preço de tabela da API, não uma fatura.',
256
+ sameTask: 'O AgentGuard não consegue saber se estas sessões fizeram a mesma tarefa. Compare execuções da mesma tarefa.',
257
+ fewerThanTwo: (found, project) => found === 0
258
+ ? `Nenhuma sessão principal local foi encontrada, e o compare precisa de duas. Passe dois ids: ${TWO_IDS}`
259
+ : `Só uma sessão principal foi encontrada${project ? ` em ${project}` : ''}, e o compare precisa de duas. Passe dois ids: ${TWO_IDS}`,
260
+ };
261
+ exports.COMPARE_TEXT = { en: compareEn, es: compareEs, pt: comparePt };
262
+ const hostList = (claude, codex, and, of = '') => [claude ? `${of}Claude Code` : '', codex ? `${of}Codex` : ''].filter(Boolean).join(` ${and} `);
263
+ const calendarEn = {
264
+ weekdays: ['Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa'],
265
+ months: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
266
+ date: (date, withYear) => `${date.month} ${date.day}${withYear ? `, ${date.year}` : ''}`,
267
+ span: (from, to) => from.year === to.year ? `${from.month} ${from.day} to ${to.month} ${to.day}, ${to.year}`
268
+ : `${from.month} ${from.day}, ${from.year} to ${to.month} ${to.day}, ${to.year}`,
269
+ title: span => `AgentGuard calendar: tokens per day, ${span}`,
270
+ tokens: count => `${count} ${count === '1' ? 'token' : 'tokens'}`,
271
+ dollars: usd => usd === null ? 'no dollar total: no known API price for these models' : `${usd} at API prices, not a bill`,
272
+ busiest: (date, count) => `busiest day: ${date} (${count} ${count === '1' ? 'token' : 'tokens'})`,
273
+ subagents: share => `sub-agents used ${share} of tokens`,
274
+ held: launches => `AgentGuard held ${launches} ${launches === 1 ? 'launch' : 'launches'}`,
275
+ less: 'Less',
276
+ more: 'More',
277
+ subagentDays: { colour: 'Days in amber: sub-agents used more than half of that day\'s tokens.', plain: letter => `Days marked ${letter}: sub-agents used more than half of that day's tokens.` },
278
+ heldDays: { colour: 'Red mark: AgentGuard held a launch that day.', plain: letter => `Days marked ${letter}: AgentGuard held a launch that day.` },
279
+ sources: (claude, codex) => `From ${hostList(claude, codex, 'and')} sessions on this machine, sub-agents included.`,
280
+ unpriced: (tokens, models) => `Unknown API price for ${models}: ${tokens} tokens not in the dollar total.`,
281
+ forkUnknown: forks => forks === 1 ? 'Not counted: 1 forked Codex session; its copied history cannot be split off.'
282
+ : `Not counted: ${forks} forked Codex sessions; their copied history cannot be split off.`,
283
+ unreadable: files => files === 1 ? 'Could not read 1 session file this time; its days show only what Burn counted before.'
284
+ : `Could not read ${files} session files this time; their days show only what Burn counted before.`,
285
+ noData: 'No Claude Code or Codex sessions found on this machine yet.',
286
+ shortHistory: ['Claude Code deletes sessions older than 30 days by default.', 'Burn keeps each day\'s count whenever you run this, so the calendar grows.'],
287
+ saveFailed: 'Burn could not store the counts from this run.',
288
+ };
289
+ const calendarEs = {
290
+ weekdays: ['Do', 'Lu', 'Ma', 'Mi', 'Ju', 'Vi', 'Sá'],
291
+ months: ['ene', 'feb', 'mar', 'abr', 'may', 'jun', 'jul', 'ago', 'sep', 'oct', 'nov', 'dic'],
292
+ date: (date, withYear) => `${date.day} ${date.month}${withYear ? ` de ${date.year}` : ''}`,
293
+ span: (from, to) => from.year === to.year ? `del ${from.day} ${from.month} al ${to.day} ${to.month} de ${to.year}`
294
+ : `del ${from.day} ${from.month} de ${from.year} al ${to.day} ${to.month} de ${to.year}`,
295
+ title: span => `AgentGuard calendar: tokens por día, ${span}`,
296
+ tokens: count => `${count} ${count === '1' ? 'token' : 'tokens'}`,
297
+ dollars: usd => usd === null ? 'sin total en dólares: no se conoce el precio de la API de estos modelos' : `${usd} a precios de la API, no es una factura`,
298
+ busiest: (date, count) => `día con más tokens: ${date} (${count})`,
299
+ subagents: share => `los subagentes usaron el ${share} de los tokens`,
300
+ held: launches => launches === 1 ? 'AgentGuard retuvo 1 lanzamiento' : `AgentGuard retuvo ${launches} lanzamientos`,
301
+ less: 'Menos',
302
+ more: 'Más',
303
+ subagentDays: { colour: 'Días en ámbar: los subagentes usaron más de la mitad de los tokens de ese día.', plain: letter => `Días con ${letter}: los subagentes usaron más de la mitad de los tokens de ese día.` },
304
+ heldDays: { colour: 'Marca roja: AgentGuard retuvo un lanzamiento ese día.', plain: letter => `Días con ${letter}: AgentGuard retuvo un lanzamiento ese día.` },
305
+ sources: (claude, codex) => `De las sesiones de ${hostList(claude, codex, 'y')} en esta máquina, subagentes incluidos.`,
306
+ unpriced: (tokens, models) => `Precio de la API desconocido para ${models}: ${tokens} tokens fuera del total en dólares.`,
307
+ forkUnknown: forks => `Sin contar: ${plural(forks, 'sesión bifurcada', 'sesiones bifurcadas')} de Codex; el historial copiado no se puede separar.`,
308
+ unreadable: files => files === 1 ? 'No se pudo leer 1 archivo de sesión esta vez; sus días muestran solo lo que Burn guardó antes.'
309
+ : `No se pudieron leer ${files} archivos de sesión esta vez; sus días muestran solo lo que Burn guardó antes.`,
310
+ noData: 'Todavía no hay sesiones de Claude Code ni de Codex en esta máquina.',
311
+ shortHistory: ['Claude Code borra las sesiones de más de 30 días de forma predeterminada.', 'Burn guarda el conteo diario cada vez que lo ejecutas, y el calendario crece.'],
312
+ saveFailed: 'Burn no pudo guardar los conteos de esta ejecución.',
313
+ };
314
+ const calendarPt = {
315
+ weekdays: ['Dom', 'Seg', 'Ter', 'Qua', 'Qui', 'Sex', 'Sáb'],
316
+ months: ['jan', 'fev', 'mar', 'abr', 'mai', 'jun', 'jul', 'ago', 'set', 'out', 'nov', 'dez'],
317
+ date: (date, withYear) => `${date.day} ${date.month}${withYear ? ` de ${date.year}` : ''}`,
318
+ span: (from, to) => from.year === to.year ? `de ${from.day} ${from.month} a ${to.day} ${to.month} de ${to.year}`
319
+ : `de ${from.day} ${from.month} de ${from.year} a ${to.day} ${to.month} de ${to.year}`,
320
+ title: span => `AgentGuard calendar: tokens por dia, ${span}`,
321
+ tokens: count => `${count} ${count === '1' ? 'token' : 'tokens'}`,
322
+ dollars: usd => usd === null ? 'sem total em dólares: o preço da API destes modelos não é conhecido' : `${usd} a preços da API, não é uma fatura`,
323
+ busiest: (date, count) => `dia com mais tokens: ${date} (${count})`,
324
+ subagents: share => `os subagentes usaram ${share} dos tokens`,
325
+ held: launches => launches === 1 ? 'o AgentGuard reteve 1 lançamento' : `o AgentGuard reteve ${launches} lançamentos`,
326
+ less: 'Menos',
327
+ more: 'Mais',
328
+ subagentDays: { colour: 'Dias em âmbar: os subagentes usaram mais da metade dos tokens daquele dia.', plain: letter => `Dias com ${letter}: os subagentes usaram mais da metade dos tokens daquele dia.` },
329
+ heldDays: { colour: 'Marca vermelha: o AgentGuard reteve um lançamento naquele dia.', plain: letter => `Dias com ${letter}: o AgentGuard reteve um lançamento naquele dia.` },
330
+ sources: (claude, codex) => `Das sessões ${hostList(claude, codex, 'e', 'do ')} nesta máquina, subagentes incluídos.`,
331
+ unpriced: (tokens, models) => `Preço da API desconhecido para ${models}: ${tokens} tokens fora do total em dólares.`,
332
+ forkUnknown: forks => `Fora da conta: ${plural(forks, 'sessão bifurcada', 'sessões bifurcadas')} do Codex; o histórico copiado não pode ser separado.`,
333
+ unreadable: files => files === 1 ? 'Não foi possível ler 1 arquivo de sessão desta vez; os dias dele mostram só o que o Burn salvou antes.'
334
+ : `Não foi possível ler ${files} arquivos de sessão desta vez; os dias deles mostram só o que o Burn salvou antes.`,
335
+ noData: 'Ainda não há sessões do Claude Code nem do Codex nesta máquina.',
336
+ shortHistory: ['O Claude Code apaga as sessões com mais de 30 dias por padrão.', 'O Burn salva a contagem diária a cada execução, então o calendário cresce.'],
337
+ saveFailed: 'O Burn não conseguiu salvar as contagens desta execução.',
338
+ };
339
+ exports.CALENDAR_TEXT = { en: calendarEn, es: calendarEs, pt: calendarPt };