@agentguard-run/burn 0.3.16 → 0.3.18
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 +18 -0
- package/README.md +28 -3
- package/dist/src/adapters/codex.js +4 -3
- package/dist/src/adapters/cursor.js +4 -3
- package/dist/src/cli.js +33 -2
- package/dist/src/conformance.js +2 -2
- package/dist/src/detectors/evaluate.js +36 -36
- package/dist/src/frames.d.ts +3 -1
- package/dist/src/frames.js +5 -4
- package/dist/src/hook/pre-tool-use.d.ts +20 -2
- package/dist/src/hook/pre-tool-use.js +84 -13
- package/dist/src/index.d.ts +2 -1
- package/dist/src/index.js +13 -2
- package/dist/src/insights/i18n.d.ts +65 -0
- package/dist/src/insights/i18n.js +152 -0
- package/dist/src/insights/live.d.ts +5 -1
- package/dist/src/insights/live.js +3 -2
- package/dist/src/insights/render.d.ts +5 -2
- package/dist/src/insights/render.js +29 -36
- package/dist/src/live-panel.d.ts +1 -1
- package/dist/src/live-panel.js +8 -7
- package/dist/src/replay/render.d.ts +2 -0
- package/dist/src/replay/render.js +15 -12
- package/dist/src/stop-text.d.ts +37 -0
- package/dist/src/stop-text.js +59 -0
- package/dist/src/types.d.ts +9 -0
- package/fixtures/live-sep20-stop-104x35.txt +1 -1
- package/package.json +1 -1
package/dist/src/index.d.ts
CHANGED
|
@@ -7,8 +7,9 @@ export { applyEvent, applyCorrection, newSessionState, windowSum, medianComplete
|
|
|
7
7
|
export { ReservationStore, Transaction, RESERVATION_TTL_MS, type Reservation, type CallReservation, type ComputeSnapshot } from './state/reservations';
|
|
8
8
|
export { replayAll, replaySession, replayEvents, discoverTranscripts, type ReplaySummary, type SessionReplay } from './replay/simulate';
|
|
9
9
|
export { renderReplay, renderStop } from './replay/render';
|
|
10
|
+
export { askReason, continueLines, overriddenLine, primarySummary, sessionSoFar, stopSummary, OVERRIDE_COMMAND, type StopHost } from './stop-text';
|
|
10
11
|
export { calibrate, type CalibrationResult } from './calibrate';
|
|
11
|
-
export { handlePreToolUse, refreshSession, loadPolicy, settingsSnippet, type HookInput, type HookOutput } from './hook/pre-tool-use';
|
|
12
|
+
export { handlePreToolUse, refreshSession, loadPolicy, settingsSnippet, asksPerson, agentOverrideAttempt, AGENT_OVERRIDE_REASON, type HookInput, type HookOutput } from './hook/pre-tool-use';
|
|
12
13
|
export * from './events';
|
|
13
14
|
export { Gateway, mergeCapabilities, type Decision, type GatewaySessionView, type UsageCoverage, type GatewayOptions } from './gateway';
|
|
14
15
|
export { ReceiptSigner, verifyReceipt, receiptDigest, canonical, sha256, type ReceiptPayload, type SignedReceipt } from './receipt';
|
package/dist/src/index.js
CHANGED
|
@@ -14,8 +14,8 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) {
|
|
|
14
14
|
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
|
|
15
15
|
};
|
|
16
16
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
17
|
-
exports.
|
|
18
|
-
exports.inflateHookSession = exports.findingSignature = exports.renderHostHealth = exports.readHookSessions = exports.configPath = exports.health = exports.install = exports.OVERRIDE_WINDOW_MS = exports.clearOverride = exports.consumeOverride = exports.readOverride = exports.writeOverride = exports.runConformance = exports.renderMachineStatus = void 0;
|
|
17
|
+
exports.BurnStopError = exports.createRawApiGuard = exports.sha256 = exports.canonical = exports.receiptDigest = exports.verifyReceipt = exports.ReceiptSigner = exports.mergeCapabilities = exports.Gateway = exports.AGENT_OVERRIDE_REASON = exports.agentOverrideAttempt = exports.asksPerson = exports.settingsSnippet = exports.loadPolicy = exports.refreshSession = exports.handlePreToolUse = exports.calibrate = exports.OVERRIDE_COMMAND = exports.stopSummary = exports.sessionSoFar = exports.primarySummary = exports.overriddenLine = exports.continueLines = exports.askReason = exports.renderStop = exports.renderReplay = exports.discoverTranscripts = exports.replayEvents = exports.replaySession = exports.replayAll = exports.RESERVATION_TTL_MS = exports.Transaction = exports.ReservationStore = exports.cacheReadRatio = exports.medianCompletedMinute = exports.windowSum = exports.newSessionState = exports.applyCorrection = exports.applyEvent = exports.normaliseLine = exports.newCursor = exports.readAll = exports.readIncremental = exports.evaluateLocalCompute = exports.fmt = exports.evaluate = exports.CALL_RESERVATION_TTL_MS = exports.DEFAULT_LOCAL_COMPUTE = exports.DEFAULT_THRESHOLDS = exports.DEFAULT_POLICY = void 0;
|
|
18
|
+
exports.inflateHookSession = exports.findingSignature = exports.renderHostHealth = exports.readHookSessions = exports.configPath = exports.health = exports.install = exports.OVERRIDE_WINDOW_MS = exports.clearOverride = exports.consumeOverride = exports.readOverride = exports.writeOverride = exports.runConformance = exports.renderMachineStatus = exports.UsageObserver = exports.profileFor = exports.startProxy = exports.CODEX_FORBIDDEN_FIELDS = exports.readCodexTranscriptUsage = exports.parseCodexTranscript = exports.codexHooksSnippet = exports.handleCodexHook = exports.cursorHooksSnippet = exports.handleCursorHook = void 0;
|
|
19
19
|
__exportStar(require("./types"), exports);
|
|
20
20
|
var defaults_1 = require("./defaults");
|
|
21
21
|
Object.defineProperty(exports, "DEFAULT_POLICY", { enumerable: true, get: function () { return defaults_1.DEFAULT_POLICY; } });
|
|
@@ -51,6 +51,14 @@ Object.defineProperty(exports, "discoverTranscripts", { enumerable: true, get: f
|
|
|
51
51
|
var render_1 = require("./replay/render");
|
|
52
52
|
Object.defineProperty(exports, "renderReplay", { enumerable: true, get: function () { return render_1.renderReplay; } });
|
|
53
53
|
Object.defineProperty(exports, "renderStop", { enumerable: true, get: function () { return render_1.renderStop; } });
|
|
54
|
+
var stop_text_1 = require("./stop-text");
|
|
55
|
+
Object.defineProperty(exports, "askReason", { enumerable: true, get: function () { return stop_text_1.askReason; } });
|
|
56
|
+
Object.defineProperty(exports, "continueLines", { enumerable: true, get: function () { return stop_text_1.continueLines; } });
|
|
57
|
+
Object.defineProperty(exports, "overriddenLine", { enumerable: true, get: function () { return stop_text_1.overriddenLine; } });
|
|
58
|
+
Object.defineProperty(exports, "primarySummary", { enumerable: true, get: function () { return stop_text_1.primarySummary; } });
|
|
59
|
+
Object.defineProperty(exports, "sessionSoFar", { enumerable: true, get: function () { return stop_text_1.sessionSoFar; } });
|
|
60
|
+
Object.defineProperty(exports, "stopSummary", { enumerable: true, get: function () { return stop_text_1.stopSummary; } });
|
|
61
|
+
Object.defineProperty(exports, "OVERRIDE_COMMAND", { enumerable: true, get: function () { return stop_text_1.OVERRIDE_COMMAND; } });
|
|
54
62
|
var calibrate_1 = require("./calibrate");
|
|
55
63
|
Object.defineProperty(exports, "calibrate", { enumerable: true, get: function () { return calibrate_1.calibrate; } });
|
|
56
64
|
var pre_tool_use_1 = require("./hook/pre-tool-use");
|
|
@@ -58,6 +66,9 @@ Object.defineProperty(exports, "handlePreToolUse", { enumerable: true, get: func
|
|
|
58
66
|
Object.defineProperty(exports, "refreshSession", { enumerable: true, get: function () { return pre_tool_use_1.refreshSession; } });
|
|
59
67
|
Object.defineProperty(exports, "loadPolicy", { enumerable: true, get: function () { return pre_tool_use_1.loadPolicy; } });
|
|
60
68
|
Object.defineProperty(exports, "settingsSnippet", { enumerable: true, get: function () { return pre_tool_use_1.settingsSnippet; } });
|
|
69
|
+
Object.defineProperty(exports, "asksPerson", { enumerable: true, get: function () { return pre_tool_use_1.asksPerson; } });
|
|
70
|
+
Object.defineProperty(exports, "agentOverrideAttempt", { enumerable: true, get: function () { return pre_tool_use_1.agentOverrideAttempt; } });
|
|
71
|
+
Object.defineProperty(exports, "AGENT_OVERRIDE_REASON", { enumerable: true, get: function () { return pre_tool_use_1.AGENT_OVERRIDE_REASON; } });
|
|
61
72
|
// Cross-tool layer (0.2.0)
|
|
62
73
|
__exportStar(require("./events"), exports);
|
|
63
74
|
var gateway_1 = require("./gateway");
|
|
@@ -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
|
|
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
|
-
|
|
25
|
-
|
|
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,9 @@
|
|
|
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 const WHY_TIP_HIDE_LINE
|
|
6
|
+
export declare const WHY_TIP_HIDE_LINE: string;
|
|
6
7
|
/**
|
|
7
8
|
* One next step from the session's own measured shares, first match wins; null
|
|
8
9
|
* when nothing stands out, never a generic line. Fan-out and history compare
|
|
@@ -15,9 +16,11 @@ export declare function whyTip(input: {
|
|
|
15
16
|
historyTokens: number;
|
|
16
17
|
rewriteUsd: DollarRange | null;
|
|
17
18
|
totalUsd: DollarRange | null;
|
|
18
|
-
}): string | 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. */
|
|
19
21
|
export declare function renderWhy(transcript: InsightTranscript, rates?: PricingTable, options?: {
|
|
20
22
|
tips?: boolean;
|
|
23
|
+
lang?: WhyLang;
|
|
21
24
|
}): string;
|
|
22
25
|
export interface RewriteRow extends RewriteEvidence {
|
|
23
26
|
sessionId: string;
|
|
@@ -14,10 +14,7 @@ const pricing_1 = require("./pricing");
|
|
|
14
14
|
const live_1 = require("./live");
|
|
15
15
|
const transcript_1 = require("./transcript");
|
|
16
16
|
const types_1 = require("./types");
|
|
17
|
-
const
|
|
18
|
-
instruction_stack: 'Instruction stack + system', conversation: 'Conversation', history_resent: 'History re-sent', reread_files: 'Re-read files',
|
|
19
|
-
subagent_fanout: 'Subagent fan-out', tool_output: 'Tool output', full_prefix_rewrites: 'Full-prefix rewrites', output: 'Output', unattributed: 'Unattributed',
|
|
20
|
-
};
|
|
17
|
+
const i18n_1 = require("./i18n");
|
|
21
18
|
function sumPrices(values) {
|
|
22
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 });
|
|
23
20
|
}
|
|
@@ -42,29 +39,33 @@ const count = (n) => n.toLocaleString('en-US');
|
|
|
42
39
|
/** The table's share column; the tip prints the same figure. */
|
|
43
40
|
const share = (tokens, total) => `${(total ? tokens / total * 100 : 0).toFixed(1)}%`;
|
|
44
41
|
const midpoint = (value) => (value.min + value.max) / 2;
|
|
45
|
-
exports.WHY_TIP_HIDE_LINE =
|
|
42
|
+
exports.WHY_TIP_HIDE_LINE = i18n_1.WHY_TEXT.en.hide;
|
|
46
43
|
/**
|
|
47
44
|
* One next step from the session's own measured shares, first match wins; null
|
|
48
45
|
* when nothing stands out, never a generic line. Fan-out and history compare
|
|
49
46
|
* session tokens; rewrites compare list USD and are skipped when either figure
|
|
50
47
|
* is unpriced. A dollar range compares midpoints, as the `rewrites` share does.
|
|
51
48
|
*/
|
|
52
|
-
function whyTip(input) {
|
|
49
|
+
function whyTip(input, lang = 'en') {
|
|
53
50
|
const { totalTokens, fanoutTokens, historyTokens, rewriteUsd, totalUsd } = input;
|
|
51
|
+
const text = i18n_1.WHY_TEXT[lang];
|
|
54
52
|
if (totalTokens > 0 && fanoutTokens / totalTokens >= 0.2)
|
|
55
|
-
return
|
|
53
|
+
return text.tipFanout(share(fanoutTokens, totalTokens));
|
|
56
54
|
if (rewriteUsd && totalUsd && midpoint(totalUsd) > 0 && midpoint(rewriteUsd) / midpoint(totalUsd) >= 0.15)
|
|
57
|
-
return
|
|
55
|
+
return text.tipRewrites((0, live_1.dollars)(rewriteUsd, text), (0, live_1.dollars)(totalUsd, text));
|
|
58
56
|
if (totalTokens > 0 && historyTokens / totalTokens >= 0.3)
|
|
59
|
-
return
|
|
57
|
+
return text.tipHistory(share(historyTokens, totalTokens));
|
|
60
58
|
return null;
|
|
61
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. */
|
|
62
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);
|
|
63
64
|
if (transcript.state.forkHistoryBoundaryUnknown)
|
|
64
65
|
return [
|
|
65
66
|
`AgentGuard why: ${transcript.sessionId}`,
|
|
66
|
-
|
|
67
|
-
table(
|
|
67
|
+
text.forkUnavailable,
|
|
68
|
+
table(text.headers, types_1.INSIGHT_BUCKETS.map(bucket => [text.labels[bucket], text.unattributed, text.unattributed, text.unattributed, text.unattributed])),
|
|
68
69
|
].join('\n');
|
|
69
70
|
const turns = (0, transcript_1.deduplicateTurns)(transcript.turns).sort((a, b) => (a.at ?? 0) - (b.at ?? 0));
|
|
70
71
|
const attribution = (0, attribution_1.attributeTurns)(turns), lastAttribution = attribution.turnAttributions.at(-1);
|
|
@@ -79,35 +80,27 @@ function renderWhy(transcript, rates = {}, options = {}) {
|
|
|
79
80
|
const totalUsd = sumPrices(prices.map(price => price.usd));
|
|
80
81
|
const rows = types_1.INSIGHT_BUCKETS.map(bucket => {
|
|
81
82
|
const tokens = bucketTokens(bucket), lastTokens = lastAttribution?.buckets.find(item => item.bucket === bucket).tokens ?? 0;
|
|
82
|
-
return [labels[bucket], count(tokens), (
|
|
83
|
+
return [text.labels[bucket], count(tokens), money(bucketUsd(bucket)), share(tokens, attribution.totalTokens), share(lastTokens, lastAttribution?.totalTokens ?? 0)];
|
|
83
84
|
});
|
|
84
|
-
const unknownModels = [...new Set(prices.filter(price => price.usd === null).map(price => price.model ??
|
|
85
|
+
const unknownModels = [...new Set(prices.filter(price => price.usd === null).map(price => price.model ?? text.missingModel))];
|
|
85
86
|
const tip = options.tips ? whyTip({ totalTokens: attribution.totalTokens, fanoutTokens: bucketTokens('subagent_fanout'),
|
|
86
|
-
historyTokens: bucketTokens('history_resent'), rewriteUsd: bucketUsd('full_prefix_rewrites'), totalUsd }) : null;
|
|
87
|
+
historyTokens: bucketTokens('history_resent'), rewriteUsd: bucketUsd('full_prefix_rewrites'), totalUsd }, lang) : null;
|
|
87
88
|
return [
|
|
88
89
|
`AgentGuard why: ${transcript.sessionId}`,
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
'', table(
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
'',
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
'Output: every response contributes its recorded generated output tokens once.',
|
|
104
|
-
'Unattributed: residual measured usage includes prior output deducted from arriving-content increments and intervals without usable event evidence.',
|
|
105
|
-
...(turns.some(turn => turn.explicitAttribution.length > 0) ? ['Explicit host token attribution takes precedence over the delta method for responses that provide it.'] : []),
|
|
106
|
-
...(unknownModels.length ? [`Tokens only for unpriced models: ${unknownModels.join(', ')}. No verified exact model rate is available for at least one token category.`] : []),
|
|
107
|
-
...(prices.some(price => price.unknownCacheWriteTokens > 0) ? ['Cache TTL is missing for some writes; their dollars span the verified five-minute and one-hour rates.'] : []),
|
|
108
|
-
...(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.'] : []),
|
|
109
|
-
`Usage records de-duplicated: ${transcript.diagnostics.duplicateUsageRecords}. Malformed lines skipped: ${transcript.diagnostics.malformedLines}.`,
|
|
110
|
-
...(tip ? ['', tip, exports.WHY_TIP_HIDE_LINE] : []),
|
|
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] : []),
|
|
111
104
|
].join('\n');
|
|
112
105
|
}
|
|
113
106
|
const stamp = (at) => at === undefined ? 'unknown time' : new Date(at).toISOString().replace(/\.\d{3}Z$/, 'Z');
|
package/dist/src/live-panel.d.ts
CHANGED
|
@@ -46,7 +46,7 @@ export declare function renderShowcasePanel(snapshot: LivePanelSnapshot, options
|
|
|
46
46
|
export declare function renderPhonePanel(snapshot: LivePanelSnapshot, options?: FrameOptions): Canvas;
|
|
47
47
|
export declare function renderLivePanel(snapshot: LivePanelSnapshot, options?: FrameOptions): Canvas;
|
|
48
48
|
/** STOP report adaptation uses only already-computed metadata, never local I/O. */
|
|
49
|
-
export declare function panelFromReport(report: BurnReport, at: number, outcome?: 'blocked' | 'shadow' | 'overridden' | 'allowed', subject?: 'spawn' | 'call'): LivePanelSnapshot;
|
|
49
|
+
export declare function panelFromReport(report: BurnReport, at: number, outcome?: 'blocked' | 'asked' | 'shadow' | 'overridden' | 'allowed', subject?: 'spawn' | 'call'): LivePanelSnapshot;
|
|
50
50
|
/** Display-only hold. Intake continues and the latest observation follows the card. */
|
|
51
51
|
export declare class StopHold {
|
|
52
52
|
private held?;
|
package/dist/src/live-panel.js
CHANGED
|
@@ -90,7 +90,7 @@ function renderShowcasePanel(snapshot, options = {}) {
|
|
|
90
90
|
for (let i = 0; i < 5; i++)
|
|
91
91
|
c.put(top + i, right, ' '.repeat(room), 'none');
|
|
92
92
|
c.put(top - 1, right, '─'.repeat(room), 'red');
|
|
93
|
-
c.put(top, right, 'STOP · ' + (snapshot.stop.blocked === true ? '
|
|
93
|
+
c.put(top, right, 'STOP · ' + (snapshot.stop.blocked === true ? 'refused' : snapshot.stop.blocked === false ? 'shadow / allowed' : 'outcome unknown'), 'red');
|
|
94
94
|
c.put(top + 1, right, snapshot.stop.reason.slice(0, room), 'red');
|
|
95
95
|
c.put(top + 2, right, snapshot.stopHold === false ? 'Latest STOP reason.' : 'Reason held for 2 seconds.', 'slate');
|
|
96
96
|
c.put(top + 3, right, '─'.repeat(room), 'red');
|
|
@@ -141,7 +141,7 @@ function renderPhonePanel(snapshot, options = {}) {
|
|
|
141
141
|
c.put(29, 0, (options.label ? options.label.toUpperCase() : 'Each copy runs its own context window.').slice(0, w), options.label ? 'slate' : 'white');
|
|
142
142
|
if (snapshot.stop) {
|
|
143
143
|
c.put(30, 0, '─'.repeat(w), 'red');
|
|
144
|
-
c.put(31, 0, ('STOP · ' + (snapshot.stop.blocked === true ? '
|
|
144
|
+
c.put(31, 0, ('STOP · ' + (snapshot.stop.blocked === true ? 'refused' : snapshot.stop.blocked === false ? 'shadow / allowed' : 'outcome unknown') + ' · ' + snapshot.stop.reason).slice(0, w), 'red');
|
|
145
145
|
c.put(32, 0, '─'.repeat(w), 'red');
|
|
146
146
|
}
|
|
147
147
|
c.put(33, 0, 'At the ceiling, the attempt is refused.'.slice(0, w), 'white');
|
|
@@ -186,7 +186,7 @@ function renderLivePanel(snapshot, options = {}) {
|
|
|
186
186
|
const y = h >= 30 ? h - 11 : 16;
|
|
187
187
|
for (let i = 0; i < 5; i++)
|
|
188
188
|
c.put(y + i, right, ' '.repeat(room), 'none');
|
|
189
|
-
c.put(y, right, 'STOP · ' + (snapshot.stop.blocked === true ? '
|
|
189
|
+
c.put(y, right, 'STOP · ' + (snapshot.stop.blocked === true ? 'refused' : snapshot.stop.blocked === false ? 'shadow / allowed' : 'outcome unknown'), 'red');
|
|
190
190
|
c.put(y + 1, right, snapshot.stop.reason.slice(0, room), 'red');
|
|
191
191
|
c.put(y + 2, right, snapshot.stopHold === false ? 'Latest STOP reason.' : 'Reason held for 2 seconds.', 'slate');
|
|
192
192
|
}
|
|
@@ -197,10 +197,11 @@ function renderLivePanel(snapshot, options = {}) {
|
|
|
197
197
|
function panelFromReport(report, at, outcome, subject) {
|
|
198
198
|
const rate = report.findings.find(f => f.detector === 'spawn_rate');
|
|
199
199
|
const decision = { id: digest(`${report.sessionId}:${at}`), at, tool: subject === 'call' ? 'model_call' : 'spawn', verdict: report.verdict,
|
|
200
|
-
reason: report.findings.map(f => `${f.detector}:${f.verdict} ${f.observed}/${f.threshold}`).join(' + ') || 'Reason not recorded.', blocked: outcome === undefined ? null : outcome === 'blocked' };
|
|
201
|
-
const note = outcome === 'blocked' ? (subject === 'call' ? 'model call
|
|
202
|
-
: outcome === '
|
|
203
|
-
: outcome === '
|
|
200
|
+
reason: report.findings.map(f => `${f.detector}:${f.verdict} ${f.observed}/${f.threshold}`).join(' + ') || 'Reason not recorded.', blocked: outcome === undefined ? null : outcome === 'blocked' || outcome === 'asked' };
|
|
201
|
+
const note = outcome === 'blocked' ? (subject === 'call' ? 'model call refused' : 'sub-agent launch refused')
|
|
202
|
+
: outcome === 'asked' ? 'sub-agent launch held for your yes'
|
|
203
|
+
: outcome === 'shadow' ? 'shadow: would have refused, call allowed' : outcome === 'overridden' ? 'override: call allowed'
|
|
204
|
+
: outcome === 'allowed' ? 'call allowed' : 'STOP boundary · enforcement outcome not recorded';
|
|
204
205
|
return { session: (/^[A-Za-z0-9_-]+$/.test(report.sessionId) ? report.sessionId : digest(report.sessionId)).slice(0, 8), startedAt: at, observedAt: at, elapsedMs: null, controls: false, stopHold: false,
|
|
205
206
|
spawns: rate?.observed ?? null, tokens: null, replayShare: Number.isFinite(report.cacheReadRatio) ? report.cacheReadRatio : null,
|
|
206
207
|
windowActiveMinutes: null, spawnCeiling: rate?.verdict === 'STOP' ? rate.threshold : null,
|
|
@@ -4,6 +4,7 @@
|
|
|
4
4
|
* runaway in, one line worth quoting. Pure ASCII/ANSI, degrades cleanly.
|
|
5
5
|
*/
|
|
6
6
|
import type { BurnReport } from '../types';
|
|
7
|
+
import { type StopHost } from '../stop-text';
|
|
7
8
|
import type { ReplaySummary, SessionReplay } from './simulate';
|
|
8
9
|
export declare function sparkline(curve: number[], stopAt: number | null, on: boolean): string;
|
|
9
10
|
export declare function comparison(tokens: number): string;
|
|
@@ -14,5 +15,6 @@ export declare function renderReplay(summary: ReplaySummary, opts?: {
|
|
|
14
15
|
export declare function renderStop(report: BurnReport, opts?: {
|
|
15
16
|
colour?: boolean;
|
|
16
17
|
subject?: 'spawn' | 'call';
|
|
18
|
+
host?: StopHost;
|
|
17
19
|
}): string;
|
|
18
20
|
export declare function renderSessionRow(s: SessionReplay): string;
|
|
@@ -12,6 +12,7 @@ exports.renderStop = renderStop;
|
|
|
12
12
|
exports.renderSessionRow = renderSessionRow;
|
|
13
13
|
const frames_1 = require("../frames");
|
|
14
14
|
const evaluate_1 = require("../detectors/evaluate");
|
|
15
|
+
const stop_text_1 = require("../stop-text");
|
|
15
16
|
const C = {
|
|
16
17
|
reset: '\x1b[0m',
|
|
17
18
|
bold: '\x1b[1m',
|
|
@@ -179,27 +180,29 @@ function renderReplay(summary, opts = {}) {
|
|
|
179
180
|
function renderStop(report, opts = {}) {
|
|
180
181
|
const on = opts.colour ?? false;
|
|
181
182
|
if (on)
|
|
182
|
-
return (0, frames_1.renderFrame)({ kind: 'report', report, subject: opts.subject, outcome: 'blocked' }, { colour: true }).render();
|
|
183
|
-
const lead = report.findings.find((f) => f.verdict === 'STOP')?.summary ?? 'Fan-out ceiling reached.';
|
|
183
|
+
return (0, frames_1.renderFrame)({ kind: 'report', report, subject: opts.subject, outcome: 'blocked', host: opts.host }, { colour: true }).render();
|
|
184
184
|
const w = 64;
|
|
185
185
|
const bar = '─'.repeat(w);
|
|
186
|
-
const title = opts.subject === 'call' ? ' model call
|
|
186
|
+
const title = opts.subject === 'call' ? ' model call refused' : ' sub-agent launch refused';
|
|
187
|
+
// One cause, one context line, two actions, one way to continue.
|
|
188
|
+
const row = (text, style = '') => paint(on, C.red, '│ ') + paint(on, style, text.padEnd(w - 1).slice(0, w - 1)) + paint(on, C.red, '│');
|
|
187
189
|
const lines = [];
|
|
188
190
|
lines.push(paint(on, C.red, `┌${bar}┐`));
|
|
189
191
|
lines.push(paint(on, C.red, '│ ') + paint(on, C.bold + C.bgRed + C.white, ' AGENTGUARD STOP ') + paint(on, C.bold, title) + paint(on, C.red, ' '.repeat(w - 18 - title.length) + '│'));
|
|
190
192
|
lines.push(paint(on, C.red, `├${bar}┤`));
|
|
191
|
-
|
|
192
|
-
|
|
193
|
+
for (const line of wrap((0, stop_text_1.stopSummary)(report), w - 1, ''))
|
|
194
|
+
lines.push(row(line));
|
|
195
|
+
lines.push(row((0, stop_text_1.sessionSoFar)(report, opts.subject), C.dim));
|
|
193
196
|
lines.push(paint(on, C.red, `├${bar}┤`));
|
|
194
|
-
lines.push(
|
|
195
|
-
report.prescriptions.slice(0,
|
|
196
|
-
const
|
|
197
|
-
|
|
198
|
-
lines.push(paint(on, C.red, '│ ') + line.padEnd(w - 1) + paint(on, C.red, '│'));
|
|
199
|
-
}
|
|
197
|
+
lines.push(row('WHAT TO DO', C.bold));
|
|
198
|
+
report.prescriptions.slice(0, 2).forEach((p, i) => {
|
|
199
|
+
for (const line of wrap(`${i + 1}. ${p}`, w - 2, ' '))
|
|
200
|
+
lines.push(row(line));
|
|
200
201
|
});
|
|
201
202
|
lines.push(paint(on, C.red, `├${bar}┤`));
|
|
202
|
-
|
|
203
|
+
const [label, command] = (0, stop_text_1.continueLines)(opts.host, opts.subject);
|
|
204
|
+
lines.push(row(label, C.dim));
|
|
205
|
+
lines.push(row(command));
|
|
203
206
|
lines.push(paint(on, C.red, `└${bar}┘`));
|
|
204
207
|
return lines.join('\n');
|
|
205
208
|
}
|