@agentguard-run/burn 0.3.15 → 0.3.17

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,19 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.3.17 (2026-09-27)
4
+
5
+ - `why` prints in Latin American Spanish or Brazilian Portuguese when your machine is set to that language: the nine bucket labels, the table header, both header lines, the footnotes, every Method sentence, the conditional notes (explicit attribution, unpriced models, missing cache TTL, mixed-lifetime ranges), the diagnostics line, the unknown Codex fork-history message, the three tips and the hide line. The words `unpriced` and `to` inside dollar cells are translated as well (`sin precio`, `$0.63 a $1.00`).
6
+ - The language is chosen in this order, first match wins: `why --lang en|es|pt` (also `--lang=es`), the `AGENTGUARD_LANG` variable, then the POSIX message locale in its own precedence (`LC_ALL`, then `LC_MESSAGES`, then `LANG`, taking the part before `_` or `.`, so `es_MX.UTF-8` and `es_419` are Spanish and `pt_BR` and `pt_PT` are Portuguese), then the locale Node resolves through Intl (on Windows the only one). The first of these that is set decides, as it does for any POSIX program: `LC_ALL=C` over `LANG=es_PA.UTF-8` is English. `C`, `POSIX` and every other language are English. An unsupported or missing `--lang` value exits 64 with a usage line.
7
+ - Figures keep their en-US formatting in every language, deliberately: `1,234,567` tokens, `$1335.37`, `12.3%`, so a Spanish or Portuguese report matches screenshots and the site digit for digit. Session ids, model ids, commands (`npx @agentguard-run/burn rewrites`, `quiet on`), URLs, product names and the term fan-out stay as they are.
8
+ - What changes in output: only the plain `why` report, and only when the language resolves to Spanish or Portuguese. English output is byte-identical to 0.3.16 with tips on and off. `why json` is byte-identical to 0.3.16 in every language, and the frame `--record` writes for `why` is unchanged. Only `why` is translated in this release; every other command, the help and `quiet` print English as before. The help gains one line for `--lang`.
9
+ - Tests that spawn `why` and assert English now pin `AGENTGUARD_LANG=en`, so the suite passes on a machine whose locale is Spanish or Portuguese.
10
+
11
+ ## 0.3.16 (2026-09-27)
12
+
13
+ - `why` ends with at most one tip built from the session's own numbers, first match wins: sub-agent fan-out at 20% or more of session tokens names that share and points at spawn limits (free on one machine, agentguard.run/try); full-prefix rewrites at 15% or more of the session's API list equivalent name both dollar figures and point at `rewrites`, which gives the cause of each one (skipped when either figure is unpriced; a dollar range compares midpoints, as the `rewrites` share does); history re-sent at 30% or more of session tokens names that share and says a fresh session, or `/compact`, starts that history over. The share and dollars are the ones the table prints. When nothing reaches its threshold there is no line, and a Codex session whose inherited history has no verifiable boundary prints none.
14
+ - New `quiet on`, `quiet off` and `quiet`. `quiet on` creates `upgrade-moments/quiet` under `AGENTGUARD_HOME` (default `~/.agentguard`), the same file the AgentGuard plugin's `policy-cli.cjs quiet on` writes, so one switch hides the `why` tip, the monthly summary in `status` and the plugin's upgrade, version and Score lines. `quiet off` removes that one file and nothing else. `quiet` alone prints whether tips are on or off.
15
+ - What changes in output: only the plain `why` report, the same text on a terminal and through a pipe, and only while a tip applies and quiet is off. After the `Usage records de-duplicated` line it gains a blank line, the tip line (starting `Next:`) and `Hide tips like this: npx @agentguard-run/burn quiet on`. Every earlier line is unchanged from 0.3.15. `why json` and the frame `--record` writes for `why` are unchanged and never contain the tip; every other existing command prints what it did in 0.3.15, and the help lists `quiet`.
16
+
3
17
  ## 0.3.15 (2026-09-26)
4
18
 
5
19
  - `why`, `rewrites`, `ttl`, `pricing` and every other command whose values do not fit one screen now print their plain text on a colour terminal. 0.3.14 paged `why` at a person as 2,247 canvas screens of `prices.N...` rows and never printed its table; the table appeared only when piped or with `--no-color`. Small command frames (`status`, `enforce`) still draw the canvas.
package/README.md CHANGED
@@ -200,6 +200,10 @@ A session argument can also be a transcript path. Without one, Burn uses the ses
200
200
 
201
201
  The table covers instruction stack + system, history re-sent, repeated file reads, subagent fan-out, tool output, conversation, full-prefix rewrites, output and unattributed usage. The fixed-prefix baseline is the first assistant response's measured context. It includes the initial user message, so the label is an operational baseline rather than a direct measurement of instruction files. A rewrite classified as prefix change resets that baseline and is counted in the footer; the new baseline can include history already present at that point.
202
202
 
203
+ The report ends with at most one tip from the session's own numbers, first match wins: subagent fan-out at 20% or more of session tokens, full-prefix rewrites at 15% or more of the session's API list equivalent (skipped when a model is unpriced), history re-sent at 30% or more of session tokens. The tip quotes the share or dollars the table prints and names one next step. When nothing reaches its threshold there is no tip. `agentguard-burn quiet on` hides it, `quiet off` shows it again and `quiet` says which. `why json` never contains it.
204
+
205
+ `why` prints in Latin American Spanish or Brazilian Portuguese when your machine is set to that language, and `--lang es`, `--lang pt` or `--lang en` picks one explicitly. The order is `--lang`, then `AGENTGUARD_LANG`, then `LC_ALL`, `LC_MESSAGES` and `LANG` (the first one set decides, as POSIX says, so `LC_ALL=C` means English), then the locale Node resolves. Every other language is English. Figures keep their en-US formatting in every language (`1,234,567`, `$1335.37`, `12.3%`), so a translated report matches screenshots digit for digit. Only `why` is translated: `why json` is the same in every language, and every other command stays English.
206
+
203
207
  Later cache reads up to the baseline go to instruction stack + system. Reads above it go to history re-sent. Fresh input plus cache creation is the measured arriving increment. Burn subtracts the previous response's output before assigning that increment to intervening tool results and user messages. Result byte sizes only split that measured total; bytes are never converted into tokens. A result for a previously read Read path goes to re-read files. Mixed user and tool intervals are marked shared and counted in the footer.
204
208
 
205
209
  Rewrite tokens and child transcript usage keep their own buckets. Prior output deducted from an input increment remains in the unattributed residual so every recorded input and output token is counted exactly once. Missing event evidence also remains there. Integer allocation preserves every token, and the Method footer explains each row.
@@ -590,4 +594,4 @@ output or transcript content. See [the live panel and September 20 evidence](doc
590
594
 
591
595
  `agentguard-burn status` shows this UTC month’s recorded spawn stops and blocked shell commands. It reads Burn’s local ledger and plugin ledgers registered by either host, joins mirrored spawn receipts once, and excludes shadow decisions, approval holds and outcomes. Missing command history is unknown. Nothing is uploaded. Free installations see one Team line per UTC month. Counts update on later status calls without repeating that line.
592
596
 
593
- Run `node runtime/policy-cli.cjs quiet on` from the AgentGuard plugin directory to permanently dismiss the monthly summary, weekly STOP invitation and plugin version announcements on this machine. Both packages use `AGENTGUARD_HOME` or the default local AgentGuard home for this preference.
597
+ Run `agentguard-burn quiet on`, or `node runtime/policy-cli.cjs quiet on` from the AgentGuard plugin directory, to dismiss the monthly summary, the `why` tip, the weekly STOP invitation and plugin version announcements on this machine. Both write the same flag file, `upgrade-moments/quiet`, and use `AGENTGUARD_HOME` or the default local AgentGuard home for it. `agentguard-burn quiet off` removes that file.
package/dist/src/cli.js CHANGED
@@ -80,11 +80,23 @@ const attribution_1 = require("./insights/attribution");
80
80
  const pricing_1 = require("./insights/pricing");
81
81
  const transcript_2 = require("./insights/transcript");
82
82
  const render_2 = require("./insights/render");
83
+ const i18n_1 = require("./insights/i18n");
83
84
  const ttl_1 = require("./insights/ttl");
84
85
  const blocks_1 = require("./insights/blocks");
85
86
  const cli_1 = require("./idle/cli");
86
87
  const HOME = process.env.AGENTGUARD_HOME ?? (0, node_path_1.join)((0, node_os_1.homedir)(), '.agentguard');
87
88
  const PROXY_HOSTS = ['ollama', 'vllm', 'lm-studio', 'openai-compatible'];
89
+ /** The same flag file the AgentGuard plugin reads (runtime/upgrade-moments.cjs), so one switch silences both. */
90
+ const quietOn = () => (0, node_fs_1.existsSync)((0, upgrade_moments_1.quietFile)(HOME));
91
+ /** The locale Node resolved, the last fallback for the why report's language (on Windows it is the only one). */
92
+ const intlLocale = () => {
93
+ try {
94
+ return Intl.DateTimeFormat().resolvedOptions().locale;
95
+ }
96
+ catch {
97
+ return undefined;
98
+ }
99
+ };
88
100
  function readStdinJson() {
89
101
  try {
90
102
  return JSON.parse((0, node_fs_1.readFileSync)(0, 'utf8'));
@@ -193,9 +205,43 @@ async function main(argv) {
193
205
  return 0;
194
206
  }
195
207
  case 'why': {
196
- const location = (0, sessions_1.selectInsightTranscript)(rest.find(value => value !== 'json'));
208
+ // `--lang en|es|pt` (or --lang=es) picks the report's language and is never a session selector.
209
+ const args = [];
210
+ let lang, langGiven = false;
211
+ for (let i = 0; i < rest.length; i++) {
212
+ if (rest[i] === '--lang') {
213
+ langGiven = true;
214
+ lang = rest[++i];
215
+ }
216
+ else if (rest[i].startsWith('--lang=')) {
217
+ langGiven = true;
218
+ lang = rest[i].slice('--lang='.length);
219
+ }
220
+ else
221
+ args.push(rest[i]);
222
+ }
223
+ if (langGiven && (0, i18n_1.whyLangOf)(lang) === null) {
224
+ process.stderr.write('Usage: agentguard-burn why [session] [json] [--lang en|es|pt]\n');
225
+ return 64;
226
+ }
227
+ const location = (0, sessions_1.selectInsightTranscript)(args.find(value => value !== 'json'));
197
228
  const transcript = (0, transcript_1.readInsightSession)(location.path, { host: location.host, sessionId: location.sessionId });
198
- show({ kind: 'command', command, values: { session: transcript.sessionId, observations: transcript.observations, diagnostics: transcript.diagnostics, attribution: (0, attribution_1.attributeTurns)((0, transcript_2.deduplicateTurns)(transcript.turns)).buckets, prices: (0, transcript_2.deduplicateTurns)(transcript.turns).map(turn => (0, pricing_1.priceTurn)(turn, (0, live_1.readPricing)(HOME, (0, pre_tool_use_1.loadPolicy)(HOME)))) } }, rest.includes('json') ? JSON.stringify(transcript, null, 2) + '\n' : (0, render_2.renderWhy)(transcript, (0, live_1.readPricing)(HOME, (0, pre_tool_use_1.loadPolicy)(HOME))) + '\n', rest.includes('json'));
229
+ const json = args.includes('json');
230
+ show({ kind: 'command', command, values: { session: transcript.sessionId, observations: transcript.observations, diagnostics: transcript.diagnostics, attribution: (0, attribution_1.attributeTurns)((0, transcript_2.deduplicateTurns)(transcript.turns)).buckets, prices: (0, transcript_2.deduplicateTurns)(transcript.turns).map(turn => (0, pricing_1.priceTurn)(turn, (0, live_1.readPricing)(HOME, (0, pre_tool_use_1.loadPolicy)(HOME)))) } }, json ? JSON.stringify(transcript, null, 2) + '\n' : (0, render_2.renderWhy)(transcript, (0, live_1.readPricing)(HOME, (0, pre_tool_use_1.loadPolicy)(HOME)), { tips: !quietOn(), lang: (0, i18n_1.detectWhyLang)({ flag: lang, env: process.env, intlLocale: intlLocale() }) }) + '\n', json);
231
+ return 0;
232
+ }
233
+ case 'quiet': {
234
+ const [state, ...extra] = rest;
235
+ if (extra.length || (state !== undefined && state !== 'on' && state !== 'off')) {
236
+ process.stderr.write('Usage: agentguard-burn quiet [on|off]\n');
237
+ return 64;
238
+ }
239
+ if (state)
240
+ (0, upgrade_moments_1.setQuiet)(HOME, state === 'on');
241
+ const quiet = quietOn();
242
+ show({ kind: 'command', command, values: { tips: quiet ? 'off' : 'on', quiet: quiet ? 'on' : 'off', file: (0, upgrade_moments_1.quietFile)(HOME) } }, quiet
243
+ ? 'Tips are off. Quiet is on: the why tip, the monthly summary in status and the AgentGuard plugin\'s upgrade, version and Score lines stay hidden on this machine.\nTurn them back on: npx @agentguard-run/burn quiet off\n'
244
+ : 'Tips are on. The why report ends with one tip when a share of the session stands out.\nHide tips: npx @agentguard-run/burn quiet on\n');
199
245
  return 0;
200
246
  }
201
247
  case 'rewrites':
@@ -447,7 +493,7 @@ async function main(argv) {
447
493
  return 0;
448
494
  }
449
495
  default:
450
- show({ kind: 'command', command: 'help', values: { commands: ['ps', 'reap', 'live', 'record', 'render', 'blocks', 'limits', 'price-shadow', 'why', 'rewrites', 'ttl', 'pace', 'statusline', 'pricing', 'replay', 'calibrate', 'status', 'init', 'enforce', 'shadow', 'resume', 'proxy', 'conformance'] } }, 'agentguard-burn <ps|reap|live|record|render|blocks|limits|price-shadow|why|rewrites|ttl|pace|statusline|pricing|replay|calibrate|status|init|enforce|shadow|resume|proxy|conformance>\n' +
496
+ show({ kind: 'command', command: 'help', values: { commands: ['ps', 'reap', 'live', 'record', 'render', 'blocks', 'limits', 'price-shadow', 'why', 'rewrites', 'ttl', 'pace', 'statusline', 'pricing', 'replay', 'calibrate', 'status', 'init', 'enforce', 'shadow', 'resume', 'quiet', 'proxy', 'conformance'] } }, 'agentguard-burn <ps|reap|live|record|render|blocks|limits|price-shadow|why|rewrites|ttl|pace|statusline|pricing|replay|calibrate|status|init|enforce|shadow|resume|quiet|proxy|conformance>\n' +
451
497
  ' ps [--json] local agent processes, held memory and workspace disk\n' +
452
498
  ' render <run.jsonl> --mp4 <out.mp4> [--gif <out.gif>] [--phone] local recorded-run export\n' +
453
499
  ' render <run.jsonl> --mp4 <out.mp4> --dashboard [--wide] [--economics <blocks.json>] dashboard export\n' +
@@ -459,6 +505,7 @@ async function main(argv) {
459
505
  ' limits [session|all] local plan walls and prior Burn decisions\n' +
460
506
  ' price-shadow [session|all] local child list-price exposure and sensitivity\n' +
461
507
  ' why [session] token attribution and API list-price equivalents\n' +
508
+ ' --lang es|pt the why report in Latin American Spanish or Brazilian Portuguese; your locale picks it by default\n' +
462
509
  ' rewrites [session|all] every full-prefix cache write with its cause, idle gap and list price\n' +
463
510
  ' ttl [session|all] one-hour cache lifetime counterfactual from your own idle gaps\n' +
464
511
  ' pace [session] ten-minute pace and next-hour projection\n' +
@@ -474,6 +521,7 @@ async function main(argv) {
474
521
  ' shadow enforce -> shadow\n' +
475
522
  ' resume --once --reason "..." let the next STOP through, once, on any host\n' +
476
523
  ' resume --reason "..." let STOPs through for 15 minutes; --clear ends it\n' +
524
+ ' quiet [on|off] hide or show the why tip and the plugin upgrade lines; alone, says which\n' +
477
525
  ' proxy --upstream http://127.0.0.1:11434 --host ollama|vllm|lm-studio|openai-compatible [--listen 127.0.0.1:18080] [--session ID]\n' +
478
526
  ' conformance replay the storm and the grind through every adapter shape\n' +
479
527
  'Developer review commands (never installed as hooks):\n' +
@@ -0,0 +1,65 @@
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.
7
+ *
8
+ * 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
+ */
11
+ import type { InsightBucket, InsightObservations } from './types';
12
+ export type WhyLang = 'en' | 'es' | 'pt';
13
+ /**
14
+ * The language of a flag value or locale: the part before '_', '-', '.' or '@',
15
+ * in any case, so es_MX.UTF-8, es-419 and ES are Spanish and pt_BR and pt-PT are
16
+ * Portuguese. C and POSIX are English. Anything else is null.
17
+ */
18
+ export declare function whyLangOf(value: string | undefined): WhyLang | null;
19
+ export interface WhyLangSources {
20
+ /** The `--lang` value, already validated by the CLI. */
21
+ flag?: string;
22
+ env?: Readonly<Record<string, string | undefined>>;
23
+ /** Intl.DateTimeFormat().resolvedOptions().locale, the last fallback. */
24
+ intlLocale?: string;
25
+ }
26
+ /**
27
+ * First match wins: --lang, AGENTGUARD_LANG, then the POSIX message locale in
28
+ * its own precedence (LC_ALL, LC_MESSAGES, LANG), then the Intl locale. The
29
+ * first of these that is set decides, as it does for any POSIX program, so
30
+ * LC_ALL=C over LANG=es_MX.UTF-8 is English. A language without a translation
31
+ * is English.
32
+ */
33
+ export declare function detectWhyLang(sources?: WhyLangSources): WhyLang;
34
+ /** Every sentence and label of the `why` report. Figures arrive already formatted; counts arrive as numbers where a word agrees with them. */
35
+ export interface WhyText {
36
+ /** The table's first column, and the start of each Method line. */
37
+ labels: Record<InsightBucket, string>;
38
+ /** Each Method line after "<label>: ". */
39
+ method: Record<InsightBucket, string>;
40
+ headers: [bucket: string, tokens: string, usd: string, sessionShare: string, lastTurnShare: string];
41
+ /** Every cell of the unknown fork-history table. */
42
+ unattributed: string;
43
+ /** A dollar figure without a verified rate, and the word between the ends of a dollar range. */
44
+ unpriced: string;
45
+ to: string;
46
+ forkUnavailable: string;
47
+ /** `usd` is null when a model has no verified rate. */
48
+ summary: (responses: number, tokens: string, usd: string | null) => string;
49
+ usage: (input: string, cacheWrite: string, cacheRead: string, output: string) => string;
50
+ shares: string;
51
+ increments: (shared: number, rebaselines: number, priorOutput: string) => string;
52
+ observed: (calls: InsightObservations) => string;
53
+ methodTitle: string;
54
+ explicit: string;
55
+ unpricedModels: (models: string) => string;
56
+ missingModel: string;
57
+ missingTtl: string;
58
+ mixedRanges: string;
59
+ diagnostics: (duplicates: number, malformed: number) => string;
60
+ tipFanout: (share: string) => string;
61
+ tipRewrites: (rewrites: string, total: string) => string;
62
+ tipHistory: (share: string) => string;
63
+ hide: string;
64
+ }
65
+ export declare const WHY_TEXT: Readonly<Record<WhyLang, WhyText>>;
@@ -0,0 +1,152 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.WHY_TEXT = void 0;
4
+ exports.whyLangOf = whyLangOf;
5
+ exports.detectWhyLang = detectWhyLang;
6
+ /**
7
+ * The language of a flag value or locale: the part before '_', '-', '.' or '@',
8
+ * in any case, so es_MX.UTF-8, es-419 and ES are Spanish and pt_BR and pt-PT are
9
+ * Portuguese. C and POSIX are English. Anything else is null.
10
+ */
11
+ function whyLangOf(value) {
12
+ const code = (value ?? '').trim().split(/[_.@-]/, 1)[0].toLowerCase();
13
+ if (code === 'en' || code === 'es' || code === 'pt')
14
+ return code;
15
+ return code === 'c' || code === 'posix' ? 'en' : null;
16
+ }
17
+ /**
18
+ * First match wins: --lang, AGENTGUARD_LANG, then the POSIX message locale in
19
+ * its own precedence (LC_ALL, LC_MESSAGES, LANG), then the Intl locale. The
20
+ * first of these that is set decides, as it does for any POSIX program, so
21
+ * LC_ALL=C over LANG=es_MX.UTF-8 is English. A language without a translation
22
+ * is English.
23
+ */
24
+ function detectWhyLang(sources = {}) {
25
+ const env = sources.env ?? {};
26
+ for (const value of [sources.flag, env.AGENTGUARD_LANG, env.LC_ALL, env.LC_MESSAGES, env.LANG])
27
+ if (value !== undefined && value.trim() !== '')
28
+ return whyLangOf(value) ?? 'en';
29
+ return whyLangOf(sources.intlLocale) ?? 'en';
30
+ }
31
+ /** Spanish and Portuguese nouns agree with their count: 1 is singular, 0 and everything else plural. */
32
+ const plural = (n, one, other) => `${n} ${n === 1 ? one : other}`;
33
+ const en = {
34
+ labels: {
35
+ instruction_stack: 'Instruction stack + system', history_resent: 'History re-sent', reread_files: 'Re-read files',
36
+ subagent_fanout: 'Subagent fan-out', tool_output: 'Tool output', conversation: 'Conversation',
37
+ full_prefix_rewrites: 'Full-prefix rewrites', output: 'Output', unattributed: 'Unattributed',
38
+ },
39
+ method: {
40
+ instruction_stack: 'the first response context sets a fixed-prefix baseline including initial user content, later cached prefix is counted up to it, and prefix-change rewrites reset it with any history then present.',
41
+ history_resent: 'each response contributes cache-read tokens above its session fixed-prefix baseline, floored at zero.',
42
+ reread_files: 'the measured input and cache-creation increment after prior output subtraction is split by result bytes, with repeated Read paths assigned here.',
43
+ subagent_fanout: 'child transcripts contribute their measured input categories after rewrite allocation.',
44
+ tool_output: 'the same measured increment is split by result bytes among other tool results.',
45
+ conversation: 'user-message bytes receive their share of that measured increment, with mixed user and tool intervals marked shared.',
46
+ full_prefix_rewrites: 'qualifying turns contribute their measured cache-creation tokens and are excluded from event-increment allocation.',
47
+ output: 'every response contributes its recorded generated output tokens once.',
48
+ unattributed: 'residual measured usage includes prior output deducted from arriving-content increments and intervals without usable event evidence.',
49
+ },
50
+ headers: ['Bucket', 'Tokens', 'List USD', 'Session tokens', 'Last turn tokens'],
51
+ unattributed: 'unattributed',
52
+ unpriced: 'unpriced',
53
+ to: 'to',
54
+ forkUnavailable: 'Usage unavailable: inherited Codex history has no verifiable boundary. Copied usage is excluded, not counted as zero.',
55
+ summary: (responses, tokens, usd) => `${responses} assistant responses | ${tokens} tokens | ${usd ?? 'unpriced'} API list equivalent`,
56
+ usage: (input, cacheWrite, cacheRead, output) => `Usage: input ${input}, cache creation ${cacheWrite}, cache read ${cacheRead}, output ${output}.`,
57
+ shares: 'Token shares partition recorded usage; byte sizes only split measured token increments and are never converted into tokens.',
58
+ increments: (shared, rebaselines, priorOutput) => `Shared event increments: ${shared}. Prefix rebaselines: ${rebaselines}. Prior output retained in unattributed input: ${priorOutput} tokens.`,
59
+ observed: calls => `Observed calls: ${calls.readCalls} reads of ${calls.uniqueReadFiles} paths, ${calls.repeatedReadCalls} repeated reads, ${calls.spawnCalls} spawns, ${calls.toolResultRecords} tool results.`,
60
+ methodTitle: 'Method',
61
+ explicit: 'Explicit host token attribution takes precedence over the delta method for responses that provide it.',
62
+ unpricedModels: models => `Tokens only for unpriced models: ${models}. No verified exact model rate is available for at least one token category.`,
63
+ missingModel: 'missing model id',
64
+ missingTtl: 'Cache TTL is missing for some writes; their dollars span the verified five-minute and one-hour rates.',
65
+ 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
+ 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',
71
+ };
72
+ /** Latin American Spanish: tú forms and vocabulary that reads the same from Mexico and Panama to Argentina. */
73
+ const es = {
74
+ labels: {
75
+ instruction_stack: 'Pila de instrucciones + sistema', history_resent: 'Historial reenviado', reread_files: 'Archivos releídos',
76
+ subagent_fanout: 'Fan-out de subagentes', tool_output: 'Salida de herramientas', conversation: 'Conversación',
77
+ full_prefix_rewrites: 'Reescrituras de prefijo completo', output: 'Salida', unattributed: 'Sin atribuir',
78
+ },
79
+ method: {
80
+ instruction_stack: 'el contexto de la primera respuesta, incluido el contenido inicial del usuario, establece una línea base de prefijo fijo. El prefijo en caché posterior cuenta hasta esa línea base, y las reescrituras por cambio de prefijo la restablecen con el historial que haya en ese momento.',
81
+ history_resent: 'cada respuesta aporta los tokens de lectura de caché por encima de la línea base de prefijo fijo de su sesión, sin bajar de cero.',
82
+ reread_files: 'el incremento medido de entrada y escritura en caché, después de restar la salida previa, se reparte en proporción a los bytes de cada resultado, y las rutas que Read vuelve a leer se asignan aquí.',
83
+ subagent_fanout: 'las transcripciones de los subagentes aportan sus categorías de entrada medidas, después de asignar las reescrituras.',
84
+ tool_output: 'el mismo incremento medido se reparte entre los demás resultados de herramientas en proporción a sus bytes.',
85
+ conversation: 'los bytes de los mensajes del usuario reciben su parte de ese incremento medido, y los intervalos que mezclan usuario y herramientas se marcan como compartidos.',
86
+ full_prefix_rewrites: 'los turnos que cumplen el criterio aportan sus tokens medidos de escritura en caché y quedan fuera de la asignación de incrementos por evento.',
87
+ output: 'cada respuesta aporta una sola vez sus tokens de salida generados y registrados.',
88
+ unattributed: 'el uso medido residual incluye la salida previa que se descontó de los incrementos de contenido entrante, y también los intervalos sin evidencia utilizable de eventos.',
89
+ },
90
+ headers: ['Categoría', 'Tokens', 'USD de lista', '% de la sesión', '% del último turno'],
91
+ unattributed: 'sin atribuir',
92
+ unpriced: 'sin precio',
93
+ to: 'a',
94
+ forkUnavailable: 'Uso no disponible: el historial heredado de Codex no tiene un punto de corte verificable. El uso copiado queda excluido, no se cuenta como cero.',
95
+ summary: (responses, tokens, usd) => `${plural(responses, 'respuesta', 'respuestas')} del asistente | ${tokens} tokens | ${usd === null ? 'sin equivalente' : `${usd} equivalente`} a precio de lista de la API`,
96
+ usage: (input, cacheWrite, cacheRead, output) => `Uso: entrada ${input}, escritura en caché ${cacheWrite}, lectura de caché ${cacheRead}, salida ${output}.`,
97
+ shares: 'Los porcentajes de tokens reparten el uso registrado; los tamaños en bytes solo dividen incrementos medidos de tokens y nunca se convierten en tokens.',
98
+ increments: (shared, rebaselines, priorOutput) => `Incrementos compartidos entre eventos: ${shared}. Nuevas líneas base del prefijo: ${rebaselines}. Tokens de salida previa retenidos en la entrada sin atribuir: ${priorOutput}.`,
99
+ observed: calls => `Llamadas observadas: ${plural(calls.readCalls, 'lectura', 'lecturas')} de ${plural(calls.uniqueReadFiles, 'ruta', 'rutas')}, ${plural(calls.repeatedReadCalls, 'lectura repetida', 'lecturas repetidas')}, ${plural(calls.spawnCalls, 'subagente lanzado', 'subagentes lanzados')}, ${plural(calls.toolResultRecords, 'resultado de herramienta', 'resultados de herramientas')}.`,
100
+ methodTitle: 'Método',
101
+ explicit: 'La atribución explícita de tokens que informa el host tiene prioridad sobre el método de deltas en las respuestas que la incluyen.',
102
+ unpricedModels: models => `Modelos sin precio (solo tokens): ${models}. No hay una tarifa exacta verificada para al menos una categoría de tokens.`,
103
+ missingModel: 'sin id de modelo',
104
+ 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
+ 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
+ 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',
111
+ };
112
+ /** Brazilian Portuguese: você forms. */
113
+ const pt = {
114
+ labels: {
115
+ instruction_stack: 'Pilha de instruções + sistema', history_resent: 'Histórico reenviado', reread_files: 'Arquivos relidos',
116
+ subagent_fanout: 'Fan-out de subagentes', tool_output: 'Saída de ferramentas', conversation: 'Conversa',
117
+ full_prefix_rewrites: 'Reescritas de prefixo completo', output: 'Saída', unattributed: 'Não atribuído',
118
+ },
119
+ method: {
120
+ instruction_stack: 'o contexto da primeira resposta, incluindo o conteúdo inicial do usuário, define uma linha de base de prefixo fixo. O prefixo em cache posterior conta até essa linha de base, e as reescritas por mudança de prefixo a redefinem com o histórico que houver naquele momento.',
121
+ history_resent: 'cada resposta contribui com os tokens de leitura de cache acima da linha de base de prefixo fixo da sua sessão, nunca abaixo de zero.',
122
+ reread_files: 'o incremento medido de entrada e gravação em cache, depois de subtrair a saída anterior, é repartido na proporção dos bytes de cada resultado, e os caminhos que o Read lê de novo são atribuídos aqui.',
123
+ subagent_fanout: 'as transcrições dos subagentes contribuem com suas categorias de entrada medidas, depois da alocação das reescritas.',
124
+ tool_output: 'o mesmo incremento medido é repartido entre os demais resultados de ferramentas na proporção dos seus bytes.',
125
+ conversation: 'os bytes das mensagens do usuário recebem sua parte desse incremento medido, e os intervalos que misturam usuário e ferramentas são marcados como compartilhados.',
126
+ full_prefix_rewrites: 'os turnos que atendem ao critério contribuem com seus tokens medidos de gravação em cache e ficam fora da alocação de incrementos por evento.',
127
+ output: 'cada resposta contribui uma única vez com seus tokens de saída gerados e registrados.',
128
+ unattributed: 'o uso medido residual inclui a saída anterior descontada dos incrementos de conteúdo recebido, e também os intervalos sem evidência utilizável de eventos.',
129
+ },
130
+ headers: ['Categoria', 'Tokens', 'USD de tabela', '% da sessão', '% do último turno'],
131
+ unattributed: 'não atribuído',
132
+ unpriced: 'sem preço',
133
+ to: 'a',
134
+ forkUnavailable: 'Uso indisponível: o histórico herdado do Codex não tem um ponto de corte verificável. O uso copiado fica de fora, não é contado como zero.',
135
+ summary: (responses, tokens, usd) => `${plural(responses, 'resposta', 'respostas')} do assistente | ${tokens} tokens | ${usd === null ? 'sem equivalente' : `${usd} equivalente`} ao preço de tabela da API`,
136
+ usage: (input, cacheWrite, cacheRead, output) => `Uso: entrada ${input}, gravação em cache ${cacheWrite}, leitura de cache ${cacheRead}, saída ${output}.`,
137
+ shares: 'As porcentagens de tokens repartem o uso registrado; os tamanhos em bytes apenas dividem incrementos medidos de tokens e nunca são convertidos em tokens.',
138
+ increments: (shared, rebaselines, priorOutput) => `Incrementos compartilhados entre eventos: ${shared}. Novas linhas de base do prefixo: ${rebaselines}. Tokens de saída anterior retidos na entrada não atribuída: ${priorOutput}.`,
139
+ observed: calls => `Chamadas observadas: ${plural(calls.readCalls, 'leitura', 'leituras')} de ${plural(calls.uniqueReadFiles, 'caminho', 'caminhos')}, ${plural(calls.repeatedReadCalls, 'leitura repetida', 'leituras repetidas')}, ${plural(calls.spawnCalls, 'subagente iniciado', 'subagentes iniciados')}, ${plural(calls.toolResultRecords, 'resultado de ferramenta', 'resultados de ferramentas')}.`,
140
+ methodTitle: 'Método',
141
+ explicit: 'A atribuição explícita de tokens informada pelo host tem prioridade sobre o método de deltas nas respostas que a incluem.',
142
+ unpricedModels: models => `Modelos sem preço (apenas tokens): ${models}. Não há tarifa exata verificada para pelo menos uma categoria de tokens.`,
143
+ missingModel: 'sem id de modelo',
144
+ 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
+ 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
+ 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',
151
+ };
152
+ exports.WHY_TEXT = { en, es, pt };
@@ -39,10 +39,14 @@ export interface LiveInput {
39
39
  }
40
40
  export declare function pacePath(home: string, sessionId: string): string;
41
41
  export declare function readPricing(home: string, policy?: Policy): PricingTable;
42
+ /** `words` translates the two words a figure can carry (the why report's languages); the digits never change. */
42
43
  export declare function dollars(value: {
43
44
  min: number;
44
45
  max: number;
45
- } | null): string;
46
+ } | null, words?: {
47
+ unpriced: string;
48
+ to: string;
49
+ }): string;
46
50
  export declare function hostWindows(value: unknown, source: UsageWindow['source'], at: number): UsageWindow[];
47
51
  export declare function heavyTurnMessage(turn: InsightTurn, rates: PricingTable): string;
48
52
  /** Local advisory observer. No tool input or output content enters this API. */
@@ -21,8 +21,9 @@ function readPricing(home, policy) {
21
21
  const file = process.env.AGENTGUARD_BURN_PRICING_FILE || policy?.insights?.pricingFile || (0, node_path_1.join)(home, 'burn-pricing.json');
22
22
  return (0, node_fs_1.existsSync)(file) ? (0, pricing_1.loadPricingOverrides)(file) : {};
23
23
  }
24
- function dollars(value) {
25
- return value === null ? 'unpriced' : Math.abs(value.max - value.min) < 0.000001 ? `$${value.min.toFixed(2)}` : `$${value.min.toFixed(2)} to $${value.max.toFixed(2)}`;
24
+ /** `words` translates the two words a figure can carry (the why report's languages); the digits never change. */
25
+ function dollars(value, words = { unpriced: 'unpriced', to: 'to' }) {
26
+ return value === null ? words.unpriced : Math.abs(value.max - value.min) < 0.000001 ? `$${value.min.toFixed(2)}` : `$${value.min.toFixed(2)} ${words.to} $${value.max.toFixed(2)}`;
26
27
  }
27
28
  function hostWindows(value, source, at) {
28
29
  if (!value || typeof value !== 'object')
@@ -1,8 +1,27 @@
1
1
  import { type DollarRange, type PricingTable } from './pricing';
2
2
  import { type InsightHost, type InsightTranscript, type InsightTurn, type RewriteCause, type RewriteEvidence } from './types';
3
+ import { type WhyLang } from './i18n';
3
4
  export declare function sumPrices(values: Array<DollarRange | null>): DollarRange | null;
4
5
  export declare function totalTokens(turn: InsightTurn): number;
5
- export declare function renderWhy(transcript: InsightTranscript, rates?: PricingTable): string;
6
+ export declare const WHY_TIP_HIDE_LINE: string;
7
+ /**
8
+ * One next step from the session's own measured shares, first match wins; null
9
+ * when nothing stands out, never a generic line. Fan-out and history compare
10
+ * session tokens; rewrites compare list USD and are skipped when either figure
11
+ * is unpriced. A dollar range compares midpoints, as the `rewrites` share does.
12
+ */
13
+ export declare function whyTip(input: {
14
+ totalTokens: number;
15
+ fanoutTokens: number;
16
+ historyTokens: number;
17
+ rewriteUsd: DollarRange | null;
18
+ totalUsd: DollarRange | null;
19
+ }, lang?: WhyLang): string | null;
20
+ /** `lang` changes words only: every figure, id, command and URL prints as it does in English, and `why json` never passes through here. */
21
+ export declare function renderWhy(transcript: InsightTranscript, rates?: PricingTable, options?: {
22
+ tips?: boolean;
23
+ lang?: WhyLang;
24
+ }): string;
6
25
  export interface RewriteRow extends RewriteEvidence {
7
26
  sessionId: string;
8
27
  host: InsightHost;
@@ -1,7 +1,9 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.WHY_TIP_HIDE_LINE = void 0;
3
4
  exports.sumPrices = sumPrices;
4
5
  exports.totalTokens = totalTokens;
6
+ exports.whyTip = whyTip;
5
7
  exports.renderWhy = renderWhy;
6
8
  exports.rewriteReport = rewriteReport;
7
9
  exports.rewriteReportJson = rewriteReportJson;
@@ -12,10 +14,7 @@ const pricing_1 = require("./pricing");
12
14
  const live_1 = require("./live");
13
15
  const transcript_1 = require("./transcript");
14
16
  const types_1 = require("./types");
15
- const labels = {
16
- instruction_stack: 'Instruction stack + system', conversation: 'Conversation', history_resent: 'History re-sent', reread_files: 'Re-read files',
17
- subagent_fanout: 'Subagent fan-out', tool_output: 'Tool output', full_prefix_rewrites: 'Full-prefix rewrites', output: 'Output', unattributed: 'Unattributed',
18
- };
17
+ const i18n_1 = require("./i18n");
19
18
  function sumPrices(values) {
20
19
  return values.some(value => value === null) ? null : values.reduce((sum, value) => ({ min: sum.min + value.min, max: sum.max + value.max }), { min: 0, max: 0 });
21
20
  }
@@ -37,12 +36,36 @@ function table(headers, rows) {
37
36
  return [headers, ...rows].map(row => row.map((cell, i) => cell.padEnd(widths[i])).join(' ').trimEnd()).join('\n');
38
37
  }
39
38
  const count = (n) => n.toLocaleString('en-US');
40
- function renderWhy(transcript, rates = {}) {
39
+ /** The table's share column; the tip prints the same figure. */
40
+ const share = (tokens, total) => `${(total ? tokens / total * 100 : 0).toFixed(1)}%`;
41
+ const midpoint = (value) => (value.min + value.max) / 2;
42
+ exports.WHY_TIP_HIDE_LINE = i18n_1.WHY_TEXT.en.hide;
43
+ /**
44
+ * One next step from the session's own measured shares, first match wins; null
45
+ * when nothing stands out, never a generic line. Fan-out and history compare
46
+ * session tokens; rewrites compare list USD and are skipped when either figure
47
+ * is unpriced. A dollar range compares midpoints, as the `rewrites` share does.
48
+ */
49
+ function whyTip(input, lang = 'en') {
50
+ const { totalTokens, fanoutTokens, historyTokens, rewriteUsd, totalUsd } = input;
51
+ const text = i18n_1.WHY_TEXT[lang];
52
+ if (totalTokens > 0 && fanoutTokens / totalTokens >= 0.2)
53
+ return text.tipFanout(share(fanoutTokens, totalTokens));
54
+ if (rewriteUsd && totalUsd && midpoint(totalUsd) > 0 && midpoint(rewriteUsd) / midpoint(totalUsd) >= 0.15)
55
+ return text.tipRewrites((0, live_1.dollars)(rewriteUsd, text), (0, live_1.dollars)(totalUsd, text));
56
+ if (totalTokens > 0 && historyTokens / totalTokens >= 0.3)
57
+ return text.tipHistory(share(historyTokens, totalTokens));
58
+ return null;
59
+ }
60
+ /** `lang` changes words only: every figure, id, command and URL prints as it does in English, and `why json` never passes through here. */
61
+ function renderWhy(transcript, rates = {}, options = {}) {
62
+ const lang = options.lang ?? 'en', text = i18n_1.WHY_TEXT[lang];
63
+ const money = (value) => (0, live_1.dollars)(value, text);
41
64
  if (transcript.state.forkHistoryBoundaryUnknown)
42
65
  return [
43
66
  `AgentGuard why: ${transcript.sessionId}`,
44
- 'Usage unavailable: inherited Codex history has no verifiable boundary. Copied usage is excluded, not counted as zero.',
45
- table(['Bucket', 'Tokens', 'List USD', 'Session tokens', 'Last turn tokens'], types_1.INSIGHT_BUCKETS.map(bucket => [labels[bucket], 'unattributed', 'unattributed', 'unattributed', 'unattributed'])),
67
+ text.forkUnavailable,
68
+ table(text.headers, types_1.INSIGHT_BUCKETS.map(bucket => [text.labels[bucket], text.unattributed, text.unattributed, text.unattributed, text.unattributed])),
46
69
  ].join('\n');
47
70
  const turns = (0, transcript_1.deduplicateTurns)(transcript.turns).sort((a, b) => (a.at ?? 0) - (b.at ?? 0));
48
71
  const attribution = (0, attribution_1.attributeTurns)(turns), lastAttribution = attribution.turnAttributions.at(-1);
@@ -52,42 +75,36 @@ function renderWhy(transcript, rates = {}) {
52
75
  && byTurn.get(turn.id).buckets.some(bucket => bucket.categories.cacheCreation > 0 && bucket.categories.cacheCreation < turn.cacheWriteTokens));
53
76
  const totals = { input: 0, write: 0, read: 0, output: 0 };
54
77
  turns.forEach(turn => { totals.input += turn.inputTokens; totals.write += turn.cacheWriteTokens; totals.read += turn.cacheReadTokens; totals.output += turn.outputTokens; });
78
+ const bucketTokens = (bucket) => attribution.buckets.find(item => item.bucket === bucket).tokens;
79
+ const bucketUsd = (bucket) => sumPrices(turns.map(turn => bucketPrice(turn, byTurn.get(turn.id).buckets.find(item => item.bucket === bucket), rates)));
80
+ const totalUsd = sumPrices(prices.map(price => price.usd));
55
81
  const rows = types_1.INSIGHT_BUCKETS.map(bucket => {
56
- const row = attribution.buckets.find(item => item.bucket === bucket);
57
- const lastTokens = lastAttribution?.buckets.find(item => item.bucket === bucket).tokens ?? 0;
58
- return [labels[bucket], count(row.tokens), (0, live_1.dollars)(sumPrices(turns.map(turn => bucketPrice(turn, byTurn.get(turn.id).buckets.find(item => item.bucket === bucket), rates)))),
59
- `${(attribution.totalTokens ? row.tokens / attribution.totalTokens * 100 : 0).toFixed(1)}%`,
60
- `${(lastAttribution?.totalTokens ? lastTokens / lastAttribution.totalTokens * 100 : 0).toFixed(1)}%`];
82
+ const tokens = bucketTokens(bucket), lastTokens = lastAttribution?.buckets.find(item => item.bucket === bucket).tokens ?? 0;
83
+ return [text.labels[bucket], count(tokens), money(bucketUsd(bucket)), share(tokens, attribution.totalTokens), share(lastTokens, lastAttribution?.totalTokens ?? 0)];
61
84
  });
62
- const unknownModels = [...new Set(prices.filter(price => price.usd === null).map(price => price.model ?? 'missing model id'))];
85
+ const unknownModels = [...new Set(prices.filter(price => price.usd === null).map(price => price.model ?? text.missingModel))];
86
+ const tip = options.tips ? whyTip({ totalTokens: attribution.totalTokens, fanoutTokens: bucketTokens('subagent_fanout'),
87
+ historyTokens: bucketTokens('history_resent'), rewriteUsd: bucketUsd('full_prefix_rewrites'), totalUsd }, lang) : null;
63
88
  return [
64
89
  `AgentGuard why: ${transcript.sessionId}`,
65
- `${turns.length} assistant responses | ${count(attribution.totalTokens)} tokens | ${(0, live_1.dollars)(sumPrices(prices.map(price => price.usd)))} API list equivalent`,
66
- `Usage: input ${count(totals.input)}, cache creation ${count(totals.write)}, cache read ${count(totals.read)}, output ${count(totals.output)}.`,
67
- '', table(['Bucket', 'Tokens', 'List USD', 'Session tokens', 'Last turn tokens'], rows), '',
68
- 'Token shares partition recorded usage; byte sizes only split measured token increments and are never converted into tokens.',
69
- `Shared event increments: ${attribution.sharedTurns}. Prefix rebaselines: ${attribution.prefixRebaselines}. Prior output retained in unattributed input: ${count(attribution.previousOutputTokensReserved)} tokens.`,
70
- `Observed calls: ${transcript.observations.readCalls} reads of ${transcript.observations.uniqueReadFiles} paths, ${transcript.observations.repeatedReadCalls} repeated reads, ${transcript.observations.spawnCalls} spawns, ${transcript.observations.toolResultRecords} tool results.`,
71
- '', 'Method',
72
- 'Instruction stack + system: the first response context sets a fixed-prefix baseline including initial user content, later cached prefix is counted up to it, and prefix-change rewrites reset it with any history then present.',
73
- 'History re-sent: each response contributes cache-read tokens above its session fixed-prefix baseline, floored at zero.',
74
- 'Re-read files: the measured input and cache-creation increment after prior output subtraction is split by result bytes, with repeated Read paths assigned here.',
75
- 'Subagent fan-out: child transcripts contribute their measured input categories after rewrite allocation.',
76
- 'Tool output: the same measured increment is split by result bytes among other tool results.',
77
- 'Conversation: user-message bytes receive their share of that measured increment, with mixed user and tool intervals marked shared.',
78
- 'Full-prefix rewrites: qualifying turns contribute their measured cache-creation tokens and are excluded from event-increment allocation.',
79
- 'Output: every response contributes its recorded generated output tokens once.',
80
- 'Unattributed: residual measured usage includes prior output deducted from arriving-content increments and intervals without usable event evidence.',
81
- ...(turns.some(turn => turn.explicitAttribution.length > 0) ? ['Explicit host token attribution takes precedence over the delta method for responses that provide it.'] : []),
82
- ...(unknownModels.length ? [`Tokens only for unpriced models: ${unknownModels.join(', ')}. No verified exact model rate is available for at least one token category.`] : []),
83
- ...(prices.some(price => price.unknownCacheWriteTokens > 0) ? ['Cache TTL is missing for some writes; their dollars span the verified five-minute and one-hour rates.'] : []),
84
- ...(mixedWriteAllocation ? ['Some bucket cache-write costs are ranges because mixed cache lifetimes are not attributed to individual buckets. Range endpoints are not additive across buckets.'] : []),
85
- `Usage records de-duplicated: ${transcript.diagnostics.duplicateUsageRecords}. Malformed lines skipped: ${transcript.diagnostics.malformedLines}.`,
90
+ text.summary(turns.length, count(attribution.totalTokens), totalUsd === null ? null : money(totalUsd)),
91
+ text.usage(count(totals.input), count(totals.write), count(totals.read), count(totals.output)),
92
+ '', table(text.headers, rows), '',
93
+ text.shares,
94
+ text.increments(attribution.sharedTurns, attribution.prefixRebaselines, count(attribution.previousOutputTokensReserved)),
95
+ text.observed(transcript.observations),
96
+ '', text.methodTitle,
97
+ ...types_1.INSIGHT_BUCKETS.map(bucket => `${text.labels[bucket]}: ${text.method[bucket]}`),
98
+ ...(turns.some(turn => turn.explicitAttribution.length > 0) ? [text.explicit] : []),
99
+ ...(unknownModels.length ? [text.unpricedModels(unknownModels.join(', '))] : []),
100
+ ...(prices.some(price => price.unknownCacheWriteTokens > 0) ? [text.missingTtl] : []),
101
+ ...(mixedWriteAllocation ? [text.mixedRanges] : []),
102
+ text.diagnostics(transcript.diagnostics.duplicateUsageRecords, transcript.diagnostics.malformedLines),
103
+ ...(tip ? ['', tip, text.hide] : []),
86
104
  ].join('\n');
87
105
  }
88
106
  const stamp = (at) => at === undefined ? 'unknown time' : new Date(at).toISOString().replace(/\.\d{3}Z$/, 'Z');
89
107
  const idle = (idleMs) => idleMs === undefined ? '-' : (0, attribution_1.idleLabel)(idleMs);
90
- const midpoint = (value) => (value.min + value.max) / 2;
91
108
  function rewriteReport(transcripts, rates = {}) {
92
109
  const turns = (0, transcript_1.deduplicateTurns)(transcripts.flatMap(transcript => transcript.turns)).sort((a, b) => (a.at ?? 0) - (b.at ?? 0) || a.id.localeCompare(b.id));
93
110
  const grouped = new Map();
@@ -1,4 +1,12 @@
1
1
  export declare const TEAM_LINE = "Using this at work? Team puts one policy on every seat. agentguard.run/pricing";
2
+ /**
3
+ * The quiet flag the AgentGuard plugin writes and reads too
4
+ * (agentguard-codex-plugin/runtime/upgrade-moments.cjs), so one switch hides
5
+ * the `why` tip, this monthly summary and the plugin's upgrade lines.
6
+ */
7
+ export declare const quietFile: (home: string) => string;
8
+ /** `quiet on` creates the flag (idempotent); `quiet off` removes that one file and nothing else. */
9
+ export declare function setQuiet(home: string, on: boolean): void;
2
10
  export interface MonthlySummary {
3
11
  month: string;
4
12
  spawnsStopped: number;
@@ -1,6 +1,7 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.TEAM_LINE = void 0;
3
+ exports.quietFile = exports.TEAM_LINE = void 0;
4
+ exports.setQuiet = setQuiet;
4
5
  exports.pluginDirectories = pluginDirectories;
5
6
  exports.monthlySummary = monthlySummary;
6
7
  exports.renderMonthlySummary = renderMonthlySummary;
@@ -9,6 +10,35 @@ const node_fs_1 = require("node:fs");
9
10
  const node_path_1 = require("node:path");
10
11
  const ledger_panel_1 = require("./ledger-panel");
11
12
  exports.TEAM_LINE = 'Using this at work? Team puts one policy on every seat. agentguard.run/pricing';
13
+ /**
14
+ * The quiet flag the AgentGuard plugin writes and reads too
15
+ * (agentguard-codex-plugin/runtime/upgrade-moments.cjs), so one switch hides
16
+ * the `why` tip, this monthly summary and the plugin's upgrade lines.
17
+ */
18
+ const quietFile = (home) => (0, node_path_1.join)(home, 'upgrade-moments', 'quiet');
19
+ exports.quietFile = quietFile;
20
+ /** `quiet on` creates the flag (idempotent); `quiet off` removes that one file and nothing else. */
21
+ function setQuiet(home, on) {
22
+ const file = (0, exports.quietFile)(home);
23
+ if (on) {
24
+ (0, node_fs_1.mkdirSync)((0, node_path_1.dirname)(file), { recursive: true, mode: 0o700 });
25
+ try {
26
+ (0, node_fs_1.writeFileSync)(file, '1\n', { flag: 'wx', mode: 0o600 });
27
+ }
28
+ catch (error) {
29
+ if (error.code !== 'EEXIST')
30
+ throw error;
31
+ }
32
+ return;
33
+ }
34
+ try {
35
+ (0, node_fs_1.unlinkSync)(file);
36
+ }
37
+ catch (error) {
38
+ if (error.code !== 'ENOENT')
39
+ throw error;
40
+ }
41
+ }
12
42
  const object = (value) => value && typeof value === 'object' && !Array.isArray(value) ? value : {};
13
43
  function read(file, limit = 1024 * 1024 * 64) {
14
44
  const fd = (0, node_fs_1.openSync)(file, node_fs_1.constants.O_RDONLY | node_fs_1.constants.O_NOFOLLOW | node_fs_1.constants.O_NONBLOCK);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@agentguard-run/burn",
3
- "version": "0.3.15",
3
+ "version": "0.3.17",
4
4
  "description": "Local session usage and runaway-agent circuit breaker. Explain tokens, cache rewrites and API list cost, track pace, warn on heavy turns, and gate agent fan-out with signed receipts. Developer command ranking requires explicit --rank.",
5
5
  "license": "SEE LICENSE IN LICENSE",
6
6
  "type": "commonjs",