@agentguard-run/burn 0.3.28 → 0.5.0
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 +23 -0
- package/README.md +67 -1
- package/dist/src/adapters/codex.d.ts +4 -2
- package/dist/src/adapters/codex.js +55 -9
- package/dist/src/cli.js +101 -13
- package/dist/src/history/claude-transcript.d.ts +0 -13
- package/dist/src/history/claude-transcript.js +11 -10
- package/dist/src/hook/pre-tool-use.d.ts +0 -16
- package/dist/src/hook/pre-tool-use.js +15 -10
- package/dist/src/index.d.ts +6 -1
- package/dist/src/index.js +27 -1
- package/dist/src/insights/i18n.d.ts +1 -0
- package/dist/src/insights/i18n.js +9 -7
- package/dist/src/insights/launch-evidence.d.ts +25 -0
- package/dist/src/insights/launch-evidence.js +54 -0
- package/dist/src/insights/price-shadow.js +2 -1
- package/dist/src/insights/pricing.js +8 -2
- package/dist/src/insights/status-data.d.ts +6 -0
- package/dist/src/insights/status-data.js +65 -0
- package/dist/src/insights/status-fields.d.ts +74 -0
- package/dist/src/insights/status-fields.js +136 -0
- package/dist/src/insights/status-text.d.ts +107 -0
- package/dist/src/insights/status-text.js +36 -0
- package/dist/src/insights/tally.d.ts +47 -0
- package/dist/src/insights/tally.js +266 -0
- package/dist/src/insights/transcript.js +9 -1
- package/dist/src/insights/tree.d.ts +36 -0
- package/dist/src/insights/tree.js +285 -0
- package/dist/src/insights/types.d.ts +2 -0
- package/dist/src/receipt.d.ts +10 -0
- package/dist/src/receipt.js +53 -2
- package/dist/src/telemetry-cli.d.ts +5 -0
- package/dist/src/telemetry-cli.js +57 -0
- package/dist/src/tool-names.d.ts +6 -0
- package/dist/src/tool-names.js +10 -0
- package/dist/src/upgrade-moments.js +2 -1
- package/docs/OCT5_VERIFICATION.md +118 -0
- package/docs/TREE_AND_TALLY.md +70 -0
- package/docs/USAGE_AND_PRICING.md +4 -2
- package/docs/launch-tree-local-oct5.txt +7 -0
- package/docs/oct5-followup/REPORT.md +105 -0
- package/docs/oct5-followup/checks.json +20 -0
- package/docs/oct5-followup/free-plugin-fixture-output.txt +12 -0
- package/docs/oct5-followup/tally-after.json +5 -0
- package/docs/oct5-followup/tally-after.txt +1 -0
- package/docs/oct5-followup/tree-after.json +40 -0
- package/docs/oct5-followup/tree-after.txt +7 -0
- package/docs/oct5-followup/tree-before.txt +7 -0
- package/docs/oct5-followup/verify-free-receipts.cjs +81 -0
- package/docs/session-tally-local-oct5.txt +1 -0
- package/package.json +7 -3
package/dist/src/index.js
CHANGED
|
@@ -15,7 +15,8 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) {
|
|
|
15
15
|
};
|
|
16
16
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
17
17
|
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.checkPolicyFile = exports.sessionTip = exports.MIN_FINISHED_SUBAGENTS = exports.decisionCostLine = exports.subagentCostLine = exports.finishedSubagents = exports.cloneReaderCursor = exports.restoreReaderCursor = exports.saveReaderCursor = exports.readSessionIncremental = 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 = exports.BurnStopError = exports.createRawApiGuard = exports.sha256 = exports.canonical = exports.receiptDigest = exports.verifyReceipt = exports.ReceiptSigner = exports.mergeCapabilities = exports.Gateway = exports.AGENT_OVERRIDE_REASON = void 0;
|
|
18
|
+
exports.parseStatusFields = exports.formatStatusFields = exports.sessionLaunchReceipts = exports.pluginLedgerDirectories = exports.renderSessionTally = exports.readLedgerDailyTallies = exports.readLedgerTallies = exports.tallyEntries = exports.sessionTally = exports.renderLaunchTree = exports.buildLaunchTree = exports.readLaunchTreeWithReceipts = exports.readLaunchTree = 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.LAUNCH_TOOLS = exports.isLaunchTool = exports.CODEX_FORBIDDEN_FIELDS = exports.readCodexTranscriptUsage = exports.parseCodexTranscript = exports.codexHooksSnippet = exports.handleCodexHook = exports.cursorHooksSnippet = exports.handleCursorHook = exports.BurnStopError = exports.createRawApiGuard = exports.sha256 = exports.canonical = exports.readSpawnAdmission = exports.receiptDigest = exports.verifyReceipt = exports.ReceiptSigner = exports.mergeCapabilities = exports.Gateway = exports.AGENT_OVERRIDE_REASON = void 0;
|
|
19
|
+
exports.readStatusMetrics = exports.readStatusBurn = exports.statusColor = exports.statusPace = void 0;
|
|
19
20
|
__exportStar(require("./types"), exports);
|
|
20
21
|
var defaults_1 = require("./defaults");
|
|
21
22
|
Object.defineProperty(exports, "DEFAULT_POLICY", { enumerable: true, get: function () { return defaults_1.DEFAULT_POLICY; } });
|
|
@@ -94,6 +95,7 @@ var receipt_1 = require("./receipt");
|
|
|
94
95
|
Object.defineProperty(exports, "ReceiptSigner", { enumerable: true, get: function () { return receipt_1.ReceiptSigner; } });
|
|
95
96
|
Object.defineProperty(exports, "verifyReceipt", { enumerable: true, get: function () { return receipt_1.verifyReceipt; } });
|
|
96
97
|
Object.defineProperty(exports, "receiptDigest", { enumerable: true, get: function () { return receipt_1.receiptDigest; } });
|
|
98
|
+
Object.defineProperty(exports, "readSpawnAdmission", { enumerable: true, get: function () { return receipt_1.readSpawnAdmission; } });
|
|
97
99
|
Object.defineProperty(exports, "canonical", { enumerable: true, get: function () { return receipt_1.canonical; } });
|
|
98
100
|
Object.defineProperty(exports, "sha256", { enumerable: true, get: function () { return receipt_1.sha256; } });
|
|
99
101
|
var raw_api_1 = require("./adapters/raw-api");
|
|
@@ -108,6 +110,9 @@ Object.defineProperty(exports, "codexHooksSnippet", { enumerable: true, get: fun
|
|
|
108
110
|
Object.defineProperty(exports, "parseCodexTranscript", { enumerable: true, get: function () { return codex_1.parseCodexTranscript; } });
|
|
109
111
|
Object.defineProperty(exports, "readCodexTranscriptUsage", { enumerable: true, get: function () { return codex_1.readCodexTranscriptUsage; } });
|
|
110
112
|
Object.defineProperty(exports, "CODEX_FORBIDDEN_FIELDS", { enumerable: true, get: function () { return codex_1.CODEX_FORBIDDEN_FIELDS; } });
|
|
113
|
+
var tool_names_1 = require("./tool-names");
|
|
114
|
+
Object.defineProperty(exports, "isLaunchTool", { enumerable: true, get: function () { return tool_names_1.isLaunchTool; } });
|
|
115
|
+
Object.defineProperty(exports, "LAUNCH_TOOLS", { enumerable: true, get: function () { return tool_names_1.LAUNCH_TOOLS; } });
|
|
111
116
|
var server_1 = require("./proxy/server");
|
|
112
117
|
Object.defineProperty(exports, "startProxy", { enumerable: true, get: function () { return server_1.startProxy; } });
|
|
113
118
|
Object.defineProperty(exports, "profileFor", { enumerable: true, get: function () { return server_1.profileFor; } });
|
|
@@ -133,3 +138,24 @@ Object.defineProperty(exports, "renderHostHealth", { enumerable: true, get: func
|
|
|
133
138
|
var pre_tool_use_2 = require("./hook/pre-tool-use");
|
|
134
139
|
Object.defineProperty(exports, "findingSignature", { enumerable: true, get: function () { return pre_tool_use_2.findingSignature; } });
|
|
135
140
|
Object.defineProperty(exports, "inflateHookSession", { enumerable: true, get: function () { return pre_tool_use_2.inflateHookSession; } });
|
|
141
|
+
var tree_1 = require("./insights/tree");
|
|
142
|
+
Object.defineProperty(exports, "readLaunchTree", { enumerable: true, get: function () { return tree_1.readLaunchTree; } });
|
|
143
|
+
Object.defineProperty(exports, "readLaunchTreeWithReceipts", { enumerable: true, get: function () { return tree_1.readLaunchTreeWithReceipts; } });
|
|
144
|
+
Object.defineProperty(exports, "buildLaunchTree", { enumerable: true, get: function () { return tree_1.buildLaunchTree; } });
|
|
145
|
+
Object.defineProperty(exports, "renderLaunchTree", { enumerable: true, get: function () { return tree_1.renderLaunchTree; } });
|
|
146
|
+
var tally_1 = require("./insights/tally");
|
|
147
|
+
Object.defineProperty(exports, "sessionTally", { enumerable: true, get: function () { return tally_1.sessionTally; } });
|
|
148
|
+
Object.defineProperty(exports, "tallyEntries", { enumerable: true, get: function () { return tally_1.tallyEntries; } });
|
|
149
|
+
Object.defineProperty(exports, "readLedgerTallies", { enumerable: true, get: function () { return tally_1.readLedgerTallies; } });
|
|
150
|
+
Object.defineProperty(exports, "readLedgerDailyTallies", { enumerable: true, get: function () { return tally_1.readLedgerDailyTallies; } });
|
|
151
|
+
Object.defineProperty(exports, "renderSessionTally", { enumerable: true, get: function () { return tally_1.renderSessionTally; } });
|
|
152
|
+
Object.defineProperty(exports, "pluginLedgerDirectories", { enumerable: true, get: function () { return tally_1.pluginLedgerDirectories; } });
|
|
153
|
+
Object.defineProperty(exports, "sessionLaunchReceipts", { enumerable: true, get: function () { return tally_1.sessionLaunchReceipts; } });
|
|
154
|
+
var status_fields_1 = require("./insights/status-fields");
|
|
155
|
+
Object.defineProperty(exports, "formatStatusFields", { enumerable: true, get: function () { return status_fields_1.formatStatusFields; } });
|
|
156
|
+
Object.defineProperty(exports, "parseStatusFields", { enumerable: true, get: function () { return status_fields_1.parseStatusFields; } });
|
|
157
|
+
Object.defineProperty(exports, "statusPace", { enumerable: true, get: function () { return status_fields_1.statusPace; } });
|
|
158
|
+
Object.defineProperty(exports, "statusColor", { enumerable: true, get: function () { return status_fields_1.statusColor; } });
|
|
159
|
+
var status_data_1 = require("./insights/status-data");
|
|
160
|
+
Object.defineProperty(exports, "readStatusBurn", { enumerable: true, get: function () { return status_data_1.readStatusBurn; } });
|
|
161
|
+
Object.defineProperty(exports, "readStatusMetrics", { enumerable: true, get: function () { return status_data_1.readStatusMetrics; } });
|
|
@@ -11,6 +11,7 @@
|
|
|
11
11
|
*/
|
|
12
12
|
import { type CompareMetric, type InsightBucket, type InsightHost, type InsightObservations, type SessionCommits } from './types';
|
|
13
13
|
export type WhyLang = 'en' | 'es' | 'pt';
|
|
14
|
+
export { STATUS_TEXT } from './status-text';
|
|
14
15
|
/**
|
|
15
16
|
* The language of a flag value or locale: the part before '_', '-', '.' or '@',
|
|
16
17
|
* in any case, so es_MX.UTF-8, es-419 and ES are Spanish and pt_BR and pt-PT are
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.CALENDAR_TEXT = exports.COMPARE_TEXT = exports.DECISION_TEXT = exports.WHY_TEXT = void 0;
|
|
3
|
+
exports.CALENDAR_TEXT = exports.COMPARE_TEXT = exports.DECISION_TEXT = exports.WHY_TEXT = exports.STATUS_TEXT = void 0;
|
|
4
4
|
exports.whyLangOf = whyLangOf;
|
|
5
5
|
exports.detectWhyLang = detectWhyLang;
|
|
6
6
|
/**
|
|
@@ -15,6 +15,8 @@ exports.detectWhyLang = detectWhyLang;
|
|
|
15
15
|
* locale, and each renderer receives the chosen language as an argument.
|
|
16
16
|
*/
|
|
17
17
|
const types_1 = require("./types");
|
|
18
|
+
var status_text_1 = require("./status-text");
|
|
19
|
+
Object.defineProperty(exports, "STATUS_TEXT", { enumerable: true, get: function () { return status_text_1.STATUS_TEXT; } });
|
|
18
20
|
/**
|
|
19
21
|
* The language of a flag value or locale: the part before '_', '-', '.' or '@',
|
|
20
22
|
* in any case, so es_MX.UTF-8, es-419 and ES are Spanish and pt_BR and pt-PT are
|
|
@@ -89,7 +91,7 @@ const en = {
|
|
|
89
91
|
missingTtl: 'Cache TTL is missing for some writes; their dollars span the verified five-minute and one-hour rates.',
|
|
90
92
|
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.',
|
|
91
93
|
diagnostics: (duplicates, malformed) => `Usage records de-duplicated: ${duplicates}. Malformed lines skipped: ${malformed}.`,
|
|
92
|
-
tipFanout: share => `Next: sub-agents used ${share} of this session's tokens. AgentGuard's free plugin asks you before the next sub-agent past your limit starts: agentguard.run/
|
|
94
|
+
tipFanout: share => `Next: sub-agents used ${share} of this session's tokens. AgentGuard's free plugin asks you before the next sub-agent past your limit starts: https://agentguard.run/burn/next`,
|
|
93
95
|
tipFanoutPlugin: share => `Next: sub-agents used ${share} of this session's tokens. Give related work to one sub-agent instead of several.`,
|
|
94
96
|
tipRewrites: (rewrites, total) => `Next: full-prefix rewrites are ${rewrites} of ${total} API list equivalent here. See the cause of each one: npx agentguard-burn rewrites`,
|
|
95
97
|
tipSubagentModel: (count, model) => `Next: ${count} ${count === 1 ? 'sub-agent' : 'sub-agents'} ran on ${model}. For searching and reading logs, a smaller model does the job: set CLAUDE_CODE_SUBAGENT_MODEL=haiku, or put model: haiku in the sub-agent's definition.`,
|
|
@@ -159,7 +161,7 @@ const es = {
|
|
|
159
161
|
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.',
|
|
160
162
|
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.',
|
|
161
163
|
diagnostics: (duplicates, malformed) => `Registros de uso deduplicados: ${duplicates}. Líneas mal formadas omitidas: ${malformed}.`,
|
|
162
|
-
tipFanout: share => `Próximo paso: los subagentes usaron el ${share} de los tokens de esta sesión. El plugin gratuito de AgentGuard te pregunta antes de que empiece el siguiente subagente por encima de tu límite: agentguard.run/
|
|
164
|
+
tipFanout: share => `Próximo paso: los subagentes usaron el ${share} de los tokens de esta sesión. El plugin gratuito de AgentGuard te pregunta antes de que empiece el siguiente subagente por encima de tu límite: https://agentguard.run/burn/next`,
|
|
163
165
|
tipFanoutPlugin: share => `Próximo paso: los subagentes usaron el ${share} de los tokens de esta sesión. Da el trabajo relacionado a un solo subagente en lugar de a varios.`,
|
|
164
166
|
tipRewrites: (rewrites, total) => `Próximo paso: las reescrituras de prefijo completo suman ${rewrites} de ${total} (equivalente a precio de lista de la API) en esta sesión. Mira la causa de cada una: npx agentguard-burn rewrites`,
|
|
165
167
|
tipSubagentModel: (count, model) => `Próximo paso: ${plural(count, 'subagente usó', 'subagentes usaron')} ${model}. Para buscar y leer logs, un modelo más pequeño basta: define CLAUDE_CODE_SUBAGENT_MODEL=haiku, o pon model: haiku en la definición del subagente.`,
|
|
@@ -229,7 +231,7 @@ const pt = {
|
|
|
229
231
|
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.',
|
|
230
232
|
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.',
|
|
231
233
|
diagnostics: (duplicates, malformed) => `Registros de uso deduplicados: ${duplicates}. Linhas malformadas ignoradas: ${malformed}.`,
|
|
232
|
-
tipFanout: share => `Próximo passo: os subagentes usaram ${share} dos tokens desta sessão. O plugin gratuito do AgentGuard pergunta a você antes que o próximo subagente acima do seu limite comece: agentguard.run/
|
|
234
|
+
tipFanout: share => `Próximo passo: os subagentes usaram ${share} dos tokens desta sessão. O plugin gratuito do AgentGuard pergunta a você antes que o próximo subagente acima do seu limite comece: https://agentguard.run/burn/next`,
|
|
233
235
|
tipFanoutPlugin: share => `Próximo passo: os subagentes usaram ${share} dos tokens desta sessão. Dê o trabalho relacionado a um único subagente em vez de vários.`,
|
|
234
236
|
tipRewrites: (rewrites, total) => `Próximo passo: as reescritas de prefixo completo somam ${rewrites} de ${total} (equivalente ao preço de tabela da API) nesta sessão. Veja a causa de cada uma: npx agentguard-burn rewrites`,
|
|
235
237
|
tipSubagentModel: (count, model) => `Próximo passo: ${plural(count, 'subagente usou', 'subagentes usaram')} o ${model}. Para buscar e ler logs, um modelo menor dá conta: defina CLAUDE_CODE_SUBAGENT_MODEL=haiku, ou coloque model: haiku na definição do subagente.`,
|
|
@@ -371,7 +373,7 @@ const calendarEn = {
|
|
|
371
373
|
shortHistory: ['Claude Code deletes sessions older than 30 days by default.', 'Burn keeps each day\'s count whenever you run this, so the calendar grows.'],
|
|
372
374
|
saveFailed: 'Burn could not store the counts from this run.',
|
|
373
375
|
next: {
|
|
374
|
-
fanout: share => `Next: sub-agents used ${share} of these tokens. AgentGuard's free plugin asks you before the next sub-agent past your limit starts: agentguard.run/
|
|
376
|
+
fanout: share => `Next: sub-agents used ${share} of these tokens. AgentGuard's free plugin asks you before the next sub-agent past your limit starts: https://agentguard.run/burn/next`,
|
|
375
377
|
fanoutPlugin: share => `Next: sub-agents used ${share} of these tokens. Give related work to one sub-agent instead of several.`,
|
|
376
378
|
why: 'Next: see where one session\'s tokens went: npx agentguard-burn why',
|
|
377
379
|
},
|
|
@@ -402,7 +404,7 @@ const calendarEs = {
|
|
|
402
404
|
shortHistory: ['Claude Code borra las sesiones de más de 30 días de forma predeterminada.', 'Burn guarda el conteo diario cada vez que lo ejecutas, y el calendario crece.'],
|
|
403
405
|
saveFailed: 'Burn no pudo guardar los conteos de esta ejecución.',
|
|
404
406
|
next: {
|
|
405
|
-
fanout: share => `Próximo paso: los subagentes usaron el ${share} de estos tokens. El plugin gratuito de AgentGuard te pregunta antes de que empiece el siguiente subagente por encima de tu límite: agentguard.run/
|
|
407
|
+
fanout: share => `Próximo paso: los subagentes usaron el ${share} de estos tokens. El plugin gratuito de AgentGuard te pregunta antes de que empiece el siguiente subagente por encima de tu límite: https://agentguard.run/burn/next`,
|
|
406
408
|
fanoutPlugin: share => `Próximo paso: los subagentes usaron el ${share} de estos tokens. Dale el trabajo relacionado a un solo subagente en vez de varios.`,
|
|
407
409
|
why: 'Próximo paso: a dónde fue cada token de una sesión: npx agentguard-burn why',
|
|
408
410
|
},
|
|
@@ -433,7 +435,7 @@ const calendarPt = {
|
|
|
433
435
|
shortHistory: ['O Claude Code apaga as sessões com mais de 30 dias por padrão.', 'O Burn salva a contagem diária a cada execução, então o calendário cresce.'],
|
|
434
436
|
saveFailed: 'O Burn não conseguiu salvar as contagens desta execução.',
|
|
435
437
|
next: {
|
|
436
|
-
fanout: share => `Próximo passo: os subagentes usaram ${share} destes tokens. O plugin gratuito do AgentGuard pergunta a você antes que o próximo subagente acima do seu limite comece: agentguard.run/
|
|
438
|
+
fanout: share => `Próximo passo: os subagentes usaram ${share} destes tokens. O plugin gratuito do AgentGuard pergunta a você antes que o próximo subagente acima do seu limite comece: https://agentguard.run/burn/next`,
|
|
437
439
|
fanoutPlugin: share => `Próximo passo: os subagentes usaram ${share} destes tokens. Dê o trabalho relacionado a um só subagente em vez de vários.`,
|
|
438
440
|
why: 'Próximo passo: para onde foi cada token de uma sessão: npx agentguard-burn why',
|
|
439
441
|
},
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import type { InsightParserState } from './types';
|
|
2
|
+
type Row = Record<string, any>;
|
|
3
|
+
export interface LaunchEvidence {
|
|
4
|
+
nodes: Record<string, {
|
|
5
|
+
activityAt?: number[];
|
|
6
|
+
name?: string;
|
|
7
|
+
model?: string;
|
|
8
|
+
depth?: number;
|
|
9
|
+
}>;
|
|
10
|
+
calls: Record<string, {
|
|
11
|
+
parent: string;
|
|
12
|
+
name?: string;
|
|
13
|
+
model?: string;
|
|
14
|
+
}>;
|
|
15
|
+
edges: Array<{
|
|
16
|
+
child: string;
|
|
17
|
+
parent: string;
|
|
18
|
+
source: string;
|
|
19
|
+
}>;
|
|
20
|
+
owners: Record<string, string>;
|
|
21
|
+
current?: string;
|
|
22
|
+
}
|
|
23
|
+
/** Called only for reports that explicitly request lineage collection. */
|
|
24
|
+
export declare function observeLaunchRecord(raw: Row, state: InsightParserState, at?: number): void;
|
|
25
|
+
export {};
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.observeLaunchRecord = observeLaunchRecord;
|
|
4
|
+
const tool_names_1 = require("../tool-names");
|
|
5
|
+
const record = (v) => v && typeof v === 'object' && !Array.isArray(v) ? v : {};
|
|
6
|
+
const id = (v) => typeof v === 'string' && /^[A-Za-z0-9][A-Za-z0-9_.:/-]{0,127}$/.test(v) ? v : undefined;
|
|
7
|
+
// Only host metadata labels are retained. Never retain an Agent prompt or description.
|
|
8
|
+
const label = (v) => typeof v === 'string' && /^[A-Za-z0-9][A-Za-z0-9 _./:-]{0,63}$/.test(v) ? v : undefined;
|
|
9
|
+
/** Called only for reports that explicitly request lineage collection. */
|
|
10
|
+
function observeLaunchRecord(raw, state, at) {
|
|
11
|
+
const e = state.launchEvidence;
|
|
12
|
+
const payload = record(raw.payload), result = record(raw.toolUseResult);
|
|
13
|
+
const anonymousSidechain = raw.isSidechain === true && !id(raw.agentId) && !state.sessionId.startsWith('agent-');
|
|
14
|
+
const owner = id(raw.agentId) ?? (anonymousSidechain ? 'unidentified-sidechain:' + state.sessionId : state.lineage?.sessionId ?? state.sessionId.replace(/^agent-/, ''));
|
|
15
|
+
e.current = owner;
|
|
16
|
+
const node = e.nodes[owner] ??= {};
|
|
17
|
+
if (at !== undefined)
|
|
18
|
+
(node.activityAt ??= []).push(at);
|
|
19
|
+
node.name ??= anonymousSidechain ? 'sidechain identity not recorded' : label(raw.agentName ?? raw.agentType ?? payload.agent_nickname ?? payload.agent_role);
|
|
20
|
+
const parent = id(raw.parentAgentId) ?? state.lineage?.parentSessionId;
|
|
21
|
+
if (parent && parent !== owner)
|
|
22
|
+
e.edges.push({ child: owner, parent, source: 'parent metadata' });
|
|
23
|
+
const blocks = Array.isArray(raw.message?.content) ? [...raw.message.content] : [];
|
|
24
|
+
if (raw.type === 'response_item')
|
|
25
|
+
blocks.push(payload);
|
|
26
|
+
for (const value of blocks) {
|
|
27
|
+
const block = record(value);
|
|
28
|
+
const callId = id(block.id ?? block.call_id ?? block.tool_use_id);
|
|
29
|
+
if (['tool_use', 'function_call', 'custom_tool_call'].includes(block.type) && (0, tool_names_1.isLaunchTool)(block.name) && callId) {
|
|
30
|
+
let input = record(block.input);
|
|
31
|
+
if (typeof block.arguments === 'string') {
|
|
32
|
+
try {
|
|
33
|
+
input = record(JSON.parse(block.arguments));
|
|
34
|
+
}
|
|
35
|
+
catch { }
|
|
36
|
+
}
|
|
37
|
+
e.calls[callId] = { parent: owner, name: label(input.name ?? input.subagent_type ?? input.agent_type), model: label(input.model) };
|
|
38
|
+
}
|
|
39
|
+
if (['tool_result', 'function_call_output', 'custom_tool_call_output'].includes(block.type) && callId) {
|
|
40
|
+
let output = result;
|
|
41
|
+
if (typeof block.output === 'string') {
|
|
42
|
+
try {
|
|
43
|
+
output = record(JSON.parse(block.output));
|
|
44
|
+
}
|
|
45
|
+
catch { }
|
|
46
|
+
}
|
|
47
|
+
const child = id(output.agentId ?? output.agent_id), launch = e.calls[callId];
|
|
48
|
+
if (child && launch && block.is_error !== true && output.status !== 'failed') {
|
|
49
|
+
e.edges.push({ child, parent: launch.parent, source: 'launch tool result' });
|
|
50
|
+
e.nodes[child] = { ...e.nodes[child], ...(launch.name ? { name: launch.name } : {}), ...(launch.model ? { model: launch.model } : {}) };
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
}
|
|
@@ -3,6 +3,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
|
|
|
3
3
|
exports.PRICE_LABEL = void 0;
|
|
4
4
|
exports.priceShadowReport = priceShadowReport;
|
|
5
5
|
exports.renderPriceShadow = renderPriceShadow;
|
|
6
|
+
const tool_names_1 = require("../tool-names");
|
|
6
7
|
const node_fs_1 = require("node:fs");
|
|
7
8
|
const node_path_1 = require("node:path");
|
|
8
9
|
const receipt_1 = require("../receipt");
|
|
@@ -43,7 +44,7 @@ function collectSpawns(row, calls) {
|
|
|
43
44
|
const name = (0, history_1.identifier)(block.name), id = (0, history_1.identifier)(block.id ?? block.call_id ?? block.tool_use_id);
|
|
44
45
|
if (!id)
|
|
45
46
|
continue;
|
|
46
|
-
if (['tool_use', 'function_call', 'custom_tool_call'].includes(String(block.type)) && name &&
|
|
47
|
+
if (['tool_use', 'function_call', 'custom_tool_call'].includes(String(block.type)) && name && (0, tool_names_1.isLaunchTool)(name)) {
|
|
47
48
|
if (!calls.has(id))
|
|
48
49
|
calls.set(id, { at });
|
|
49
50
|
}
|
|
@@ -33,9 +33,15 @@ exports.MODEL_PRICING = Object.freeze({
|
|
|
33
33
|
'claude-opus-5-5': Object.freeze({ ...rates(4, 0.2, 5, 8, 20), verifiedAt: '2026-09-22' }),
|
|
34
34
|
'claude-opus-5': rates(5, 0.5, 6.25, 10, 25),
|
|
35
35
|
'claude-opus-4-8': rates(5, 0.5, 6.25, 10, 25),
|
|
36
|
-
// Verified 2026-
|
|
37
|
-
'
|
|
36
|
+
// Verified 2026-10-07: Anthropic halved Sonnet 5.5 cache hits to 0.05x base input ($0.10) on 2026-10-07.
|
|
37
|
+
// The pricing page's prompt caching section states it; its model table row still read $0.20 that day.
|
|
38
|
+
// Burn prices every session at the current list price, so earlier Sonnet 5.5 sessions use $0.10 too.
|
|
39
|
+
'claude-sonnet-5-5': Object.freeze({ ...rates(2, 0.1, 2.5, 4, 10), verifiedAt: '2026-10-07' }),
|
|
38
40
|
'claude-sonnet-5': rates(2, 0.2, 2.5, 4, 10),
|
|
41
|
+
// Verified 2026-10-07: Haiku 5.5 (released that day) is priced by prompt length: over 100,000 prompt
|
|
42
|
+
// tokens every category is 5x ($0.50 input, $0.05 cache hits, $0.625 and $1 cache writes, $2.50 output).
|
|
43
|
+
'claude-haiku-5-5': Object.freeze({ ...rates(0.1, 0.01, 0.125, 0.2, 0.5), verifiedAt: '2026-10-07',
|
|
44
|
+
longContext: Object.freeze({ aboveInputTokens: 100_000, inputMultiplier: 5, outputMultiplier: 5 }) }),
|
|
39
45
|
'claude-haiku-4-5-20251001': rates(1, 0.1, 1.25, 2, 5),
|
|
40
46
|
'gpt-6-astra': openaiRates(10, 1, 12.5, 50, 'https://developers.openai.com/api/docs/pricing'),
|
|
41
47
|
'gpt-6-sol': Object.freeze({ ...openaiRates(2, 0.2, 2.5, 10, 'https://developers.openai.com/api/docs/pricing'), verifiedAt: '2026-09-22' }),
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import { type StatusBurn, type StatusMetrics } from './status-fields';
|
|
2
|
+
export declare function readStatusBurn(home: string, sessionId: string): StatusBurn;
|
|
3
|
+
export declare function readStatusMetrics(home: string, session: string, fields: string, dataDir?: string, includeShare?: boolean): Promise<StatusMetrics & {
|
|
4
|
+
share?: number;
|
|
5
|
+
totalTokens?: number;
|
|
6
|
+
}>;
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.readStatusBurn = readStatusBurn;
|
|
4
|
+
exports.readStatusMetrics = readStatusMetrics;
|
|
5
|
+
const node_fs_1 = require("node:fs");
|
|
6
|
+
const node_path_1 = require("node:path");
|
|
7
|
+
const spend_1 = require("@agentguard-run/spend");
|
|
8
|
+
const defaults_1 = require("../defaults");
|
|
9
|
+
const pre_tool_use_1 = require("../hook/pre-tool-use");
|
|
10
|
+
const gateway_1 = require("../gateway");
|
|
11
|
+
const session_1 = require("../state/session");
|
|
12
|
+
const sessions_1 = require("./sessions");
|
|
13
|
+
const transcript_1 = require("./transcript");
|
|
14
|
+
const live_1 = require("./live");
|
|
15
|
+
const render_1 = require("./render");
|
|
16
|
+
const status_fields_1 = require("./status-fields");
|
|
17
|
+
const tally_1 = require("./tally");
|
|
18
|
+
function readStatusBurn(home, sessionId) {
|
|
19
|
+
const present = (0, node_fs_1.existsSync)((0, node_path_1.join)(home, 'burn-policy.json'));
|
|
20
|
+
const policy = present ? (0, pre_tool_use_1.loadPolicy)(home, { notice: false }) : defaults_1.DEFAULT_POLICY;
|
|
21
|
+
const thresholds = policy.thresholds ?? defaults_1.DEFAULT_THRESHOLDS;
|
|
22
|
+
const state = (0, node_fs_1.existsSync)((0, node_path_1.join)(home, 'sessions')) ? new gateway_1.Gateway(home, { sign: false }).peek(sessionId)?.state : null;
|
|
23
|
+
const count = (minutes) => state ? (0, session_1.windowSum)(state.spawnsByActiveMinute, state.activeMinutes, minutes) : 0;
|
|
24
|
+
return { mode: present ? policy.mode : 'enforce',
|
|
25
|
+
burst: { count: count(thresholds.spawnRate.windowActiveMinutes), limit: thresholds.spawnRate.stop - 1 },
|
|
26
|
+
sustained: { count: count(thresholds.fanout.windowActiveMinutes ?? defaults_1.DEFAULT_THRESHOLDS.fanout.windowActiveMinutes), limit: thresholds.fanout.stop },
|
|
27
|
+
tokens: { used: state?.totalTokens ?? 0, limit: thresholds.sustained.stopTokens } };
|
|
28
|
+
}
|
|
29
|
+
async function readStatusMetrics(home, session, fields, dataDir, includeShare = false) {
|
|
30
|
+
const enabled = (0, status_fields_1.parseStatusFields)(fields).fields;
|
|
31
|
+
const result = {};
|
|
32
|
+
if (includeShare || enabled.includes('cost') || enabled.includes('cache'))
|
|
33
|
+
try {
|
|
34
|
+
const location = (0, sessions_1.selectInsightTranscript)(session);
|
|
35
|
+
const transcript = (0, transcript_1.readInsightSession)(location.path, { host: location.host, sessionId: location.sessionId });
|
|
36
|
+
if (!transcript.state.forkHistoryBoundaryUnknown && transcript.turns.length) {
|
|
37
|
+
const rates = (0, live_1.readPricing)(home), figures = (0, render_1.sessionFigures)(transcript, rates);
|
|
38
|
+
result.totalTokens = figures.attribution.totalTokens;
|
|
39
|
+
const childTokens = figures.attribution.buckets.find(bucket => bucket.bucket === 'subagent_fanout')?.tokens ?? 0;
|
|
40
|
+
if (childTokens > 0 && figures.attribution.totalTokens > 0)
|
|
41
|
+
result.share = 100 * childTokens / figures.attribution.totalTokens;
|
|
42
|
+
result.cost = figures.totalUsd;
|
|
43
|
+
const rewrites = (0, render_1.rewriteReportJson)([transcript], rates);
|
|
44
|
+
result.cache = { tokens: rewrites.totals.cacheWriteTokens, usd: rewrites.totals.usd };
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
catch { /* Missing or unknown transcript data stays unavailable. */ }
|
|
48
|
+
if (enabled.includes('spend')) {
|
|
49
|
+
const modified = (dir) => { try {
|
|
50
|
+
return (0, node_fs_1.statSync)((0, node_path_1.join)(dir, 'ledger/decisions.ndjson')).mtimeMs;
|
|
51
|
+
}
|
|
52
|
+
catch {
|
|
53
|
+
return 0;
|
|
54
|
+
} };
|
|
55
|
+
const directories = dataDir ? [dataDir] : (0, tally_1.pluginLedgerDirectories)(home, { prune: false }).sort((a, b) => modified(b) - modified(a));
|
|
56
|
+
for (const directory of directories) {
|
|
57
|
+
result.spend = await (0, spend_1.readLocalDailySpend)({ policyFile: (0, node_path_1.join)(directory, 'policy.json'), ledgerFile: (0, node_path_1.join)(directory, 'ledger/decisions.ndjson'), publicKeyFile: (0, node_path_1.join)(directory, 'public-key.hex') });
|
|
58
|
+
if (result.spend)
|
|
59
|
+
break;
|
|
60
|
+
}
|
|
61
|
+
if (!result.spend)
|
|
62
|
+
result.spend = await (0, spend_1.readLocalDailySpend)({ policyFile: (0, node_path_1.join)(home, 'policy.json'), ledgerFile: (0, node_path_1.join)(home, 'decisions.ndjson'), publicKeyFile: (0, node_path_1.join)(home, 'signing-public.key') });
|
|
63
|
+
}
|
|
64
|
+
return result;
|
|
65
|
+
}
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
import { type UsageWindow } from './pace';
|
|
2
|
+
import { STATUS_TEXT } from './status-text';
|
|
3
|
+
export declare const STATUS_FIELDS: readonly ["pace", "cost", "cache", "spend"];
|
|
4
|
+
export type StatusField = typeof STATUS_FIELDS[number];
|
|
5
|
+
export type StatusColor = 'yellow' | 'red' | null;
|
|
6
|
+
export interface StatusPart {
|
|
7
|
+
text: string;
|
|
8
|
+
color?: StatusColor | string;
|
|
9
|
+
background?: string;
|
|
10
|
+
bold?: boolean;
|
|
11
|
+
dim?: boolean;
|
|
12
|
+
field?: StatusField;
|
|
13
|
+
}
|
|
14
|
+
export interface StatusBurn {
|
|
15
|
+
mode: string;
|
|
16
|
+
burst: {
|
|
17
|
+
count: number;
|
|
18
|
+
limit: number;
|
|
19
|
+
};
|
|
20
|
+
sustained: {
|
|
21
|
+
count: number;
|
|
22
|
+
limit: number;
|
|
23
|
+
};
|
|
24
|
+
tokens: {
|
|
25
|
+
used: number;
|
|
26
|
+
limit: number;
|
|
27
|
+
};
|
|
28
|
+
}
|
|
29
|
+
export interface StatusMetrics {
|
|
30
|
+
cost?: {
|
|
31
|
+
min: number;
|
|
32
|
+
max: number;
|
|
33
|
+
} | null;
|
|
34
|
+
cache?: {
|
|
35
|
+
tokens: number;
|
|
36
|
+
usd: {
|
|
37
|
+
min: number;
|
|
38
|
+
max: number;
|
|
39
|
+
} | null;
|
|
40
|
+
} | null;
|
|
41
|
+
spend?: {
|
|
42
|
+
usedCents: number;
|
|
43
|
+
capCents: number;
|
|
44
|
+
resetsAt: number;
|
|
45
|
+
} | null;
|
|
46
|
+
}
|
|
47
|
+
export interface StatusInput extends StatusMetrics {
|
|
48
|
+
burn?: StatusBurn | null;
|
|
49
|
+
share?: number | null;
|
|
50
|
+
windows?: UsageWindow[];
|
|
51
|
+
fields?: string;
|
|
52
|
+
width?: number;
|
|
53
|
+
lang?: keyof typeof STATUS_TEXT;
|
|
54
|
+
now?: number;
|
|
55
|
+
failed?: boolean;
|
|
56
|
+
}
|
|
57
|
+
export declare function parseStatusFields(value?: string): {
|
|
58
|
+
fields: StatusField[];
|
|
59
|
+
unknown: string[];
|
|
60
|
+
};
|
|
61
|
+
export declare function statusColor(used: number, limit?: number): StatusColor;
|
|
62
|
+
export declare function statusCount(n: number): string;
|
|
63
|
+
export declare function statusPlans(windows?: UsageWindow[]): UsageWindow[];
|
|
64
|
+
export declare function statusPlan(windows?: UsageWindow[]): UsageWindow | undefined;
|
|
65
|
+
export declare function statusPace(windows?: UsageWindow[], now?: number): number | null;
|
|
66
|
+
export declare function formatStatusFields(input: StatusInput): {
|
|
67
|
+
text: string;
|
|
68
|
+
parts: StatusPart[];
|
|
69
|
+
panel: string[];
|
|
70
|
+
enabled: ("pace" | "spend" | "cost" | "cache")[];
|
|
71
|
+
unknown: string[];
|
|
72
|
+
dropped: ("pace" | "spend" | "cost" | "cache")[];
|
|
73
|
+
clipped: boolean;
|
|
74
|
+
};
|
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.STATUS_FIELDS = void 0;
|
|
4
|
+
exports.parseStatusFields = parseStatusFields;
|
|
5
|
+
exports.statusColor = statusColor;
|
|
6
|
+
exports.statusCount = statusCount;
|
|
7
|
+
exports.statusPlans = statusPlans;
|
|
8
|
+
exports.statusPlan = statusPlan;
|
|
9
|
+
exports.statusPace = statusPace;
|
|
10
|
+
exports.formatStatusFields = formatStatusFields;
|
|
11
|
+
const pace_1 = require("./pace");
|
|
12
|
+
const status_text_1 = require("./status-text");
|
|
13
|
+
// Display order is most useful first. Remove from the opposite end on overflow.
|
|
14
|
+
exports.STATUS_FIELDS = ['pace', 'cost', 'cache', 'spend'];
|
|
15
|
+
function parseStatusFields(value = '') {
|
|
16
|
+
const names = [...new Set(String(value).slice(0, 1024).split(',').map(s => s.trim().toLowerCase()).filter(Boolean))];
|
|
17
|
+
return { fields: exports.STATUS_FIELDS.filter(field => names.includes(field)),
|
|
18
|
+
unknown: names.filter(name => !exports.STATUS_FIELDS.includes(name)).map(name => name.replace(/[^a-z0-9_]/g, '').slice(0, 32) || '?') };
|
|
19
|
+
}
|
|
20
|
+
function statusColor(used, limit = 100) {
|
|
21
|
+
return limit > 0 && used / limit >= .9 ? 'red' : limit > 0 && used / limit >= .7 ? 'yellow' : null;
|
|
22
|
+
}
|
|
23
|
+
function statusCount(n) {
|
|
24
|
+
if (!Number.isFinite(n))
|
|
25
|
+
return '0';
|
|
26
|
+
for (const [size, unit] of [[1e9, 'B'], [1e6, 'M'], [1e3, 'K']]) {
|
|
27
|
+
if (n >= size)
|
|
28
|
+
return (n / size).toFixed(n >= size * 10 ? 0 : 1).replace(/\.0$/, '') + unit;
|
|
29
|
+
}
|
|
30
|
+
return String(Math.round(n));
|
|
31
|
+
}
|
|
32
|
+
function money(value, range) {
|
|
33
|
+
return Math.abs(value.max - value.min) < .000001 ? `$${value.min.toFixed(2)}` : `$${value.min.toFixed(2)} ${range} $${value.max.toFixed(2)}`;
|
|
34
|
+
}
|
|
35
|
+
function duration(minutes) {
|
|
36
|
+
const n = Math.max(0, Math.round(minutes / 10) * 10);
|
|
37
|
+
return '~' + (n >= 60 ? `${Math.floor(n / 60)}h` : '') + (n % 60 || n < 60 ? `${n % 60}m` : '');
|
|
38
|
+
}
|
|
39
|
+
function statusPlans(windows = []) {
|
|
40
|
+
const latest = new Map();
|
|
41
|
+
for (const window of windows)
|
|
42
|
+
if (Number.isFinite(window.usedPercent) && window.usedPercent >= 0 && window.usedPercent <= 100 &&
|
|
43
|
+
(!latest.has(window.name) || latest.get(window.name).observedAt <= window.observedAt))
|
|
44
|
+
latest.set(window.name, window);
|
|
45
|
+
return [...latest.values()].sort((a, b) => b.usedPercent - a.usedPercent);
|
|
46
|
+
}
|
|
47
|
+
function statusPlan(windows = []) {
|
|
48
|
+
return statusPlans(windows)[0];
|
|
49
|
+
}
|
|
50
|
+
function statusPace(windows = [], now = Date.now()) {
|
|
51
|
+
const plan = statusPlan(windows);
|
|
52
|
+
if (!plan)
|
|
53
|
+
return null;
|
|
54
|
+
const same = windows.filter(w => w.name === plan.name && w.resetsAt === plan.resetsAt && w.pool === plan.pool && w.source === plan.source &&
|
|
55
|
+
w.windowMinutes === plan.windowMinutes && w.observedAt >= now - 600000 && w.observedAt <= now &&
|
|
56
|
+
w.resetsAt > now && Number.isFinite(w.usedPercent) && w.usedPercent >= 0 && w.usedPercent <= 100);
|
|
57
|
+
if (!same.some(w => w.observedAt < plan.observedAt && w.usedPercent < plan.usedPercent))
|
|
58
|
+
return null;
|
|
59
|
+
const minutes = (0, pace_1.forecastLimit)(same, now).minutes;
|
|
60
|
+
return minutes !== null && minutes < (plan.resetsAt - now) / 60000 ? minutes : null;
|
|
61
|
+
}
|
|
62
|
+
function formatStatusFields(input) {
|
|
63
|
+
const words = status_text_1.STATUS_TEXT[input.lang ?? 'en'], selected = parseStatusFields(input.fields);
|
|
64
|
+
const plans = statusPlans(input.windows), plan = plans[0], pace = statusPace(input.windows, input.now);
|
|
65
|
+
const planName = (window) => window.name === 'five_hour' ? words.fiveHour : window.name === 'seven_day' ? words.weekly : window.name.replace(/[^a-zA-Z0-9_]/g, '').replace(/_/g, ' ');
|
|
66
|
+
const age = (window) => {
|
|
67
|
+
const elapsed = (input.now ?? Date.now()) - window.observedAt;
|
|
68
|
+
return elapsed > 60000 ? words.ago.replace('{minutes}', String(Math.floor(elapsed / 60000))) : '';
|
|
69
|
+
};
|
|
70
|
+
const optional = new Map();
|
|
71
|
+
if (pace !== null)
|
|
72
|
+
optional.set('pace', { text: `${words.limit} ${duration(pace)}`, color: pace < 30 ? 'yellow' : null });
|
|
73
|
+
if (input.cost)
|
|
74
|
+
optional.set('cost', { text: `≈${money(input.cost, words.range)} ${words.list}` });
|
|
75
|
+
if (input.cache && input.cache.tokens > 0)
|
|
76
|
+
optional.set('cache', { text: `${words.cache} ${statusCount(input.cache.tokens)}${input.cache.usd ? ` (≈${money(input.cache.usd, words.range)} ${words.list})` : ''}` });
|
|
77
|
+
if (input.spend && input.spend.capCents >= 0)
|
|
78
|
+
optional.set('spend', { text: `${words.spend} $${(input.spend.usedCents / 100).toFixed(2)} ${words.of} $${(input.spend.capCents / 100).toFixed(2)} ${words.list} ${words.today}`,
|
|
79
|
+
color: input.spend.capCents === 0 ? 'red' : statusColor(input.spend.usedCents, input.spend.capCents) });
|
|
80
|
+
const enabled = selected.fields.filter(field => optional.has(field));
|
|
81
|
+
const dropped = [];
|
|
82
|
+
const width = Math.max(1, Number.isFinite(input.width) ? Math.floor(input.width) : 200);
|
|
83
|
+
function parts(short = 0) {
|
|
84
|
+
const out = [{ text: 'AgentGuard ', background: '#2abcb4', color: '#04201e', bold: true }];
|
|
85
|
+
const burn = input.burn;
|
|
86
|
+
if (!burn) {
|
|
87
|
+
out.push({ text: input.failed ? ` ${words.unavailable} · /agentguard` : ` ${words.starting}`, dim: true });
|
|
88
|
+
return out;
|
|
89
|
+
}
|
|
90
|
+
const ratio = (w) => w.limit ? w.count / w.limit : 0;
|
|
91
|
+
const win = ratio(burn.sustained) > ratio(burn.burst) ? burn.sustained : burn.burst;
|
|
92
|
+
const color = statusColor(win.count, win.limit);
|
|
93
|
+
out.push({ text: ` ${short > 1 ? 'a' : words.agents} ${win.count}${short ? '/' : ` ${words.of} `}${win.limit}`, color, dim: !color });
|
|
94
|
+
const add = (text, extra = {}) => out.push({ text: ` · ${text}`, dim: !extra.color, ...extra });
|
|
95
|
+
add(`${short > 1 ? 't' : words.tokens} ${statusCount(burn.tokens.used)}${short ? '/' : ` ${words.of} `}${statusCount(burn.tokens.limit)}`, { color: statusColor(burn.tokens.used, burn.tokens.limit) });
|
|
96
|
+
if (typeof input.share === 'number' && Number.isFinite(input.share))
|
|
97
|
+
add(`${Math.round(input.share)}% ${short ? words.sub : words.share}`);
|
|
98
|
+
if (plan)
|
|
99
|
+
add(`${short && plan.name === 'five_hour' ? '5h' : planName(plan)} ${Math.round(plan.usedPercent)}%${age(plan) ? ` (${age(plan)})` : ''}`, { color: statusColor(plan.usedPercent) });
|
|
100
|
+
for (const field of enabled)
|
|
101
|
+
if (!dropped.includes(field)) {
|
|
102
|
+
const { text, ...style } = optional.get(field);
|
|
103
|
+
add(text, { ...style, field });
|
|
104
|
+
}
|
|
105
|
+
if (burn.mode === 'shadow')
|
|
106
|
+
add(words.watching, { color: 'yellow' });
|
|
107
|
+
if (short < 2)
|
|
108
|
+
add('/agentguard');
|
|
109
|
+
return out;
|
|
110
|
+
}
|
|
111
|
+
let output = parts();
|
|
112
|
+
const length = () => output.reduce((sum, part) => sum + [...part.text].length, 0);
|
|
113
|
+
for (const field of [...enabled].reverse()) {
|
|
114
|
+
if (length() <= width)
|
|
115
|
+
break;
|
|
116
|
+
dropped.push(field);
|
|
117
|
+
output = parts();
|
|
118
|
+
}
|
|
119
|
+
for (let short = 1; length() > width && short <= 2; short++)
|
|
120
|
+
output = parts(short);
|
|
121
|
+
// Extremely narrow host slots cannot hold every value. Preserve the data in
|
|
122
|
+
// parts and ask the host to clip one row rather than wrap or invent numbers.
|
|
123
|
+
const fullText = output.map(part => part.text).join('');
|
|
124
|
+
const text = [...fullText].slice(0, width).join('');
|
|
125
|
+
const panel = [
|
|
126
|
+
...plans.map(window => `${words.plan} ${Math.round(window.usedPercent)}% (${planName(window)}). ${words.reset} ${Number.isFinite(window.resetsAt) ? new Date(window.resetsAt).toISOString() : words.none}.${age(window) ? ` ${words.lastRead} ${age(window)}.` : ''}`),
|
|
127
|
+
pace !== null ? `${words.limit} ${duration(pace)}.` : words.paceEmpty,
|
|
128
|
+
input.cost ? `${words.costLead} ≈ ${money(input.cost, words.range)} ${words.costFull}.` : words.costEmpty,
|
|
129
|
+
input.cache && input.cache.tokens > 0 ? `${words.cacheLead} ${input.cache.tokens.toLocaleString('en-US')} ${words.tokens}${input.cache.usd ? ` (≈ ${money(input.cache.usd, words.range)} ${words.costFull})` : ''}.` : words.cacheEmpty,
|
|
130
|
+
input.spend ? `${words.spendLead} $${(input.spend.usedCents / 100).toFixed(2)} ${words.of} $${(input.spend.capCents / 100).toFixed(2)} ${words.list} ${words.today}. ${words.reset} ${new Date(input.spend.resetsAt).toISOString()}.` : words.spendEmpty,
|
|
131
|
+
`${words.enabled} ${selected.fields.join(', ') || words.none}. ${words.change}`,
|
|
132
|
+
selected.unknown.length ? `${words.unknown} ${selected.unknown.join(', ')}.` : null,
|
|
133
|
+
dropped.length ? `${words.hidden} ${dropped.join(', ')}.` : null,
|
|
134
|
+
].filter((line) => line !== null);
|
|
135
|
+
return { text, parts: output, panel, enabled: selected.fields, unknown: selected.unknown, dropped, clipped: fullText !== text };
|
|
136
|
+
}
|