@agentguard-run/burn 0.5.0 → 0.6.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 +109 -9
- package/dist/src/cli.js +205 -21
- package/dist/src/display-mode.d.ts +12 -0
- package/dist/src/display-mode.js +67 -0
- package/dist/src/index.d.ts +2 -0
- package/dist/src/index.js +12 -1
- package/dist/src/insights/calendar-render.js +2 -1
- package/dist/src/insights/compact-replay.d.ts +97 -0
- package/dist/src/insights/compact-replay.js +414 -0
- package/dist/src/insights/compact-settings.d.ts +30 -0
- package/dist/src/insights/compact-settings.js +122 -0
- package/dist/src/insights/first-run.d.ts +12 -0
- package/dist/src/insights/first-run.js +17 -0
- package/dist/src/insights/i18n.d.ts +19 -0
- package/dist/src/insights/i18n.js +82 -1
- package/dist/src/insights/render.d.ts +13 -1
- package/dist/src/insights/render.js +35 -21
- package/dist/src/insights/sessions.d.ts +4 -0
- package/dist/src/insights/sessions.js +18 -2
- package/dist/src/insights/simple-data.d.ts +20 -0
- package/dist/src/insights/simple-data.js +229 -0
- package/dist/src/insights/simple-render.d.ts +26 -0
- package/dist/src/insights/simple-render.js +92 -0
- package/dist/src/insights/simple-text.d.ts +33 -0
- package/dist/src/insights/simple-text.js +44 -0
- package/dist/src/insights/status-fields.d.ts +2 -2
- package/dist/src/insights/week-render.d.ts +4 -0
- package/dist/src/insights/week-render.js +31 -0
- package/dist/src/insights/week.d.ts +75 -0
- package/dist/src/insights/week.js +253 -0
- package/dist/src/live-panel.d.ts +2 -1
- package/dist/src/live-panel.js +29 -2
- package/dist/src/version.d.ts +2 -0
- package/dist/src/version.js +5 -0
- package/docs/OCT5_VERIFICATION.md +1 -1
- package/docs/simple-views.md +17 -0
- package/fixtures/burn-week-v1.json +1 -0
- package/package.json +2 -2
|
@@ -0,0 +1,229 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.billingKind = billingKind;
|
|
4
|
+
exports.recordSimpleHost = recordSimpleHost;
|
|
5
|
+
exports.readSimpleUsage = readSimpleUsage;
|
|
6
|
+
/** Host-reported amounts only. API list-price calculations never enter this view. */
|
|
7
|
+
const node_crypto_1 = require("node:crypto");
|
|
8
|
+
const node_fs_1 = require("node:fs");
|
|
9
|
+
const node_path_1 = require("node:path");
|
|
10
|
+
const history_1 = require("./history");
|
|
11
|
+
const live_1 = require("./live");
|
|
12
|
+
const sessions_1 = require("./sessions");
|
|
13
|
+
const transcript_1 = require("./transcript");
|
|
14
|
+
const hash = (value) => (0, node_crypto_1.createHash)('sha256').update(value).digest('hex');
|
|
15
|
+
const amount = (value) => typeof value === 'number' && Number.isFinite(value) && value >= 0;
|
|
16
|
+
const observationPath = (home, file) => (0, node_path_1.join)(home, 'display-observations', hash(file) + '.json');
|
|
17
|
+
/** Recognize explicit host metadata, never credential contents or a model-name guess. */
|
|
18
|
+
function billingKind(value) {
|
|
19
|
+
const raw = (0, history_1.object)(value), billing = (0, history_1.object)(raw.billing), limits = (0, history_1.object)(raw.rate_limits);
|
|
20
|
+
const values = [billing.type, raw.billing_type, raw.billingType, raw.auth_type, raw.plan_type, limits.plan_type];
|
|
21
|
+
if (values.some(v => ['subscription', 'stripe_subscription', 'pro', 'max', 'team', 'enterprise', 'plus', 'business'].includes(String(v))))
|
|
22
|
+
return 'subscription';
|
|
23
|
+
if (values.some(v => ['api_key', 'api-key', 'usage_credits', 'usage-credit', 'pay_as_you_go', 'prepaid', 'metered'].includes(String(v))))
|
|
24
|
+
return 'metered';
|
|
25
|
+
// Claude's named plan windows are positive evidence. Absence proves nothing.
|
|
26
|
+
if ((0, live_1.hostWindows)(limits, 'claude-statusline', Date.now()).length)
|
|
27
|
+
return 'subscription';
|
|
28
|
+
return 'unknown';
|
|
29
|
+
}
|
|
30
|
+
function readObservation(home, file) {
|
|
31
|
+
try {
|
|
32
|
+
const raw = (0, history_1.object)(JSON.parse((0, node_fs_1.readFileSync)(observationPath(home, file), 'utf8')));
|
|
33
|
+
if (raw.schema === 1)
|
|
34
|
+
return { schema: 1, billing: raw.billing === 'subscription' || raw.billing === 'metered' ? raw.billing : 'unknown',
|
|
35
|
+
costs: (Array.isArray(raw.costs) ? raw.costs : []).flatMap(value => {
|
|
36
|
+
const row = (0, history_1.object)(value);
|
|
37
|
+
return amount(row.at) && amount(row.usd) ? [{ at: row.at, usd: row.usd }] : [];
|
|
38
|
+
}) };
|
|
39
|
+
}
|
|
40
|
+
catch { /* No observation yet. */ }
|
|
41
|
+
return { schema: 1, billing: 'unknown', costs: [] };
|
|
42
|
+
}
|
|
43
|
+
/** Only allowlisted numbers and the billing category are persisted, under a path digest. */
|
|
44
|
+
function recordSimpleHost(home, file, payload, now = Date.now()) {
|
|
45
|
+
const billing = billingKind(payload), cost = (0, history_1.object)((0, history_1.object)(payload).cost).total_cost_usd;
|
|
46
|
+
if (billing === 'unknown' && !amount(cost))
|
|
47
|
+
return;
|
|
48
|
+
try {
|
|
49
|
+
const previous = readObservation(home, file);
|
|
50
|
+
const costs = previous.costs.filter(row => row.at <= now && row.at >= now - 86_400_000);
|
|
51
|
+
if (amount(cost))
|
|
52
|
+
costs.push({ at: now, usd: cost });
|
|
53
|
+
const value = { schema: 1, billing: billing === 'unknown' ? previous.billing : billing, costs: costs.slice(-2048) };
|
|
54
|
+
const path = observationPath(home, file), temporary = path + '.' + (0, node_crypto_1.randomUUID)() + '.tmp';
|
|
55
|
+
(0, node_fs_1.mkdirSync)((0, node_path_1.join)(home, 'display-observations'), { recursive: true, mode: 0o700 });
|
|
56
|
+
(0, node_fs_1.writeFileSync)(temporary, JSON.stringify(value), { mode: 0o600 });
|
|
57
|
+
(0, node_fs_1.renameSync)(temporary, path);
|
|
58
|
+
}
|
|
59
|
+
catch { /* Read-only homes still get an honest unavailable display. */ }
|
|
60
|
+
}
|
|
61
|
+
// A live panel may refresh twice a second. Unchanged transcripts are scanned once.
|
|
62
|
+
// Only numerical metadata survives a scan, never messages or tool arguments.
|
|
63
|
+
const metadataCache = new Map();
|
|
64
|
+
function metadata(location) {
|
|
65
|
+
const info = (0, node_fs_1.statSync)(location.path), signature = `${info.ino}:${info.size}:${info.mtimeMs}`;
|
|
66
|
+
const cached = metadataCache.get(location.path);
|
|
67
|
+
if (cached?.signature === signature)
|
|
68
|
+
return cached.value;
|
|
69
|
+
const value = { billing: 'unknown', windows: [], charges: [], firstAt: null, incomplete: false };
|
|
70
|
+
const kinds = new Set(), charges = new Map(), scan = { malformed: 0 };
|
|
71
|
+
let state;
|
|
72
|
+
let chunk = '', line = 0;
|
|
73
|
+
let quotaRows = [];
|
|
74
|
+
const flushCodex = () => {
|
|
75
|
+
if (!chunk)
|
|
76
|
+
return;
|
|
77
|
+
const parsed = (0, transcript_1.parseInsightTranscript)(chunk, { host: 'codex', sessionId: location.sessionId, state });
|
|
78
|
+
state = parsed.state;
|
|
79
|
+
const accepted = new Set(parsed.acceptedQuotaLineNumbers);
|
|
80
|
+
for (const row of quotaRows)
|
|
81
|
+
if (accepted.has(row.line))
|
|
82
|
+
value.windows.push(...(0, live_1.hostWindows)(row.limits, 'codex-transcript', row.at));
|
|
83
|
+
for (const turn of parsed.updatedTurns)
|
|
84
|
+
charges.set(turn.id, { id: turn.id, at: turn.at ?? null, usd: null });
|
|
85
|
+
chunk = '';
|
|
86
|
+
line = 0;
|
|
87
|
+
quotaRows = [];
|
|
88
|
+
};
|
|
89
|
+
for (const raw of (0, history_1.jsonRows)(location.path, scan)) {
|
|
90
|
+
const payload = (0, history_1.object)(raw.payload), message = (0, history_1.object)(raw.message);
|
|
91
|
+
const at = (0, history_1.timestamp)(raw.timestamp ?? payload.timestamp);
|
|
92
|
+
if (at !== null)
|
|
93
|
+
value.firstAt = Math.min(value.firstAt ?? at, at);
|
|
94
|
+
const kind = billingKind(raw.type === 'session_meta' || location.host === 'codex' ? payload : raw);
|
|
95
|
+
if (kind !== 'unknown')
|
|
96
|
+
kinds.add(kind);
|
|
97
|
+
if (location.host === 'codex') {
|
|
98
|
+
if (at !== null && payload.rate_limits)
|
|
99
|
+
quotaRows.push({ line, at, limits: payload.rate_limits });
|
|
100
|
+
chunk += JSON.stringify(raw) + '\n';
|
|
101
|
+
line++;
|
|
102
|
+
if (chunk.length >= 1024 * 1024)
|
|
103
|
+
flushCodex();
|
|
104
|
+
continue;
|
|
105
|
+
}
|
|
106
|
+
if (at !== null && ['system', 'rate_limit_event', 'status'].includes(String(raw.type)))
|
|
107
|
+
value.windows.push(...(0, live_1.hostWindows)(raw.rate_limits, 'claude-statusline', at));
|
|
108
|
+
if (raw.type !== 'assistant' || raw.isApiErrorMessage === true)
|
|
109
|
+
continue;
|
|
110
|
+
const id = typeof message.id === 'string' ? (0, transcript_1.providerResponseIdentity)(location.host, message.id) : typeof raw.uuid === 'string' ? hash(location.path + raw.uuid) : null;
|
|
111
|
+
if (!id) {
|
|
112
|
+
value.incomplete = true;
|
|
113
|
+
continue;
|
|
114
|
+
}
|
|
115
|
+
const usd = amount(raw.costUSD) ? raw.costUSD : null, previous = charges.get(id);
|
|
116
|
+
charges.set(id, { id, at: previous?.at !== null && previous?.at !== undefined ? Math.min(previous.at, at ?? previous.at) : at,
|
|
117
|
+
usd: previous?.usd !== null && previous?.usd !== undefined ? Math.max(previous.usd, usd ?? previous.usd) : usd });
|
|
118
|
+
}
|
|
119
|
+
flushCodex();
|
|
120
|
+
value.billing = kinds.size === 1 ? [...kinds][0] : 'unknown';
|
|
121
|
+
value.charges = [...charges.values()];
|
|
122
|
+
value.incomplete ||= scan.malformed > 0 || Boolean(state?.forkHistoryBoundaryUnknown) || kinds.size > 1;
|
|
123
|
+
// Bound long-lived panels without writing a second transcript index.
|
|
124
|
+
if (metadataCache.size >= 128)
|
|
125
|
+
metadataCache.delete(metadataCache.keys().next().value);
|
|
126
|
+
metadataCache.set(location.path, { signature, value });
|
|
127
|
+
return value;
|
|
128
|
+
}
|
|
129
|
+
function readSimpleUsage(home, options = {}) {
|
|
130
|
+
const now = options.now ?? Date.now();
|
|
131
|
+
const result = { billing: billingKind(options.payload), now,
|
|
132
|
+
windows: (0, live_1.hostWindows)((0, history_1.object)(options.payload).rate_limits, 'claude-statusline', now), spentTodayUsd: null, paceUsdPerHour: null };
|
|
133
|
+
let location = options.location;
|
|
134
|
+
try {
|
|
135
|
+
location ??= (0, sessions_1.selectInsightTranscript)(undefined, options.locations);
|
|
136
|
+
}
|
|
137
|
+
catch {
|
|
138
|
+
return result;
|
|
139
|
+
}
|
|
140
|
+
let selected;
|
|
141
|
+
try {
|
|
142
|
+
selected = metadata(location);
|
|
143
|
+
}
|
|
144
|
+
catch {
|
|
145
|
+
return result;
|
|
146
|
+
}
|
|
147
|
+
const observation = readObservation(home, location.path), currentKind = billingKind(options.payload);
|
|
148
|
+
result.billing = currentKind !== 'unknown' ? currentKind : selected.billing !== 'unknown' ? selected.billing : observation.billing;
|
|
149
|
+
result.windows = [...selected.windows, ...(0, live_1.hostWindows)((0, history_1.object)(options.payload).rate_limits, 'claude-statusline', now)];
|
|
150
|
+
try {
|
|
151
|
+
const pace = JSON.parse((0, node_fs_1.readFileSync)((0, live_1.pacePath)(home, location.sessionId), 'utf8'));
|
|
152
|
+
if (pace?.schema === 1 && pace.cursor?.pathDigest === hash(location.path) && !pace.parser?.forkHistoryBoundaryUnknown && Array.isArray(pace.windows))
|
|
153
|
+
result.windows.push(...pace.windows);
|
|
154
|
+
}
|
|
155
|
+
catch { /* A why report can precede the first statusline observation. */ }
|
|
156
|
+
result.windows = result.windows.filter(w => amount(w.observedAt) && w.observedAt <= now && w.observedAt >= now - 600_000 && amount(w.resetsAt) && w.resetsAt > now && amount(w.usedPercent) && w.usedPercent <= 100);
|
|
157
|
+
if (result.billing === 'unknown' && result.windows.some(w => w.source === 'claude-statusline'))
|
|
158
|
+
result.billing = 'subscription';
|
|
159
|
+
if (result.billing !== 'metered')
|
|
160
|
+
return result;
|
|
161
|
+
const today = new Date(now);
|
|
162
|
+
today.setHours(0, 0, 0, 0);
|
|
163
|
+
const start = today.getTime(), charges = new Map();
|
|
164
|
+
let cumulative = 0, cumulativePace = 0, paceKnown = true, covered = false;
|
|
165
|
+
const locations = options.locations ?? (0, sessions_1.discoverInsightTranscripts)();
|
|
166
|
+
const groups = [];
|
|
167
|
+
const firstObserved = new Map(), owners = new Map();
|
|
168
|
+
for (const item of [...new Map([location, ...locations].filter(l => l.host === location.host && !(0, sessions_1.isSessionSidecar)(l)).map(l => [l.path, l])).values()]) {
|
|
169
|
+
let data;
|
|
170
|
+
try {
|
|
171
|
+
data = metadata(item);
|
|
172
|
+
}
|
|
173
|
+
catch {
|
|
174
|
+
return result;
|
|
175
|
+
}
|
|
176
|
+
groups.push({ item, data });
|
|
177
|
+
for (const row of data.charges) {
|
|
178
|
+
owners.set(row.id, (owners.get(row.id) ?? 0) + 1);
|
|
179
|
+
if (row.at !== null)
|
|
180
|
+
firstObserved.set(row.id, Math.min(firstObserved.get(row.id) ?? row.at, row.at));
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
for (const { item, data } of groups) {
|
|
184
|
+
const host = readObservation(home, item.path);
|
|
185
|
+
const billing = item.path === location.path ? result.billing : data.billing === 'unknown' ? host.billing : data.billing;
|
|
186
|
+
if (billing === 'subscription')
|
|
187
|
+
continue;
|
|
188
|
+
// A copied response cannot become today's spending by acquiring a new timestamp.
|
|
189
|
+
const rows = data.charges.map(row => ({ ...row, at: firstObserved.get(row.id) ?? row.at })).filter(row => row.at === null || row.at >= start && row.at <= now);
|
|
190
|
+
if (!rows.length && !data.incomplete)
|
|
191
|
+
continue;
|
|
192
|
+
if (billing !== 'metered' || data.incomplete || rows.some(row => row.at === null))
|
|
193
|
+
return result;
|
|
194
|
+
if (rows.some(row => row.usd === null)) {
|
|
195
|
+
// A host's session total may include its helpers. Unknown overlap stays unknown.
|
|
196
|
+
if (rows.some(row => owners.get(row.id) > 1) || groups.some(group => group.item.path !== item.path
|
|
197
|
+
&& (group.item.path.startsWith(item.path.replace(/\.jsonl$/, '') + '/') || item.path.startsWith(group.item.path.replace(/\.jsonl$/, '') + '/'))))
|
|
198
|
+
return result;
|
|
199
|
+
// A cumulative host total covers today only when the recorded session starts today.
|
|
200
|
+
// Never prorate a lifetime cost across midnight, nor confuse it with a daily bill.
|
|
201
|
+
const samples = host.costs.filter(row => row.at >= start && row.at <= now).sort((a, b) => a.at - b.at);
|
|
202
|
+
const last = samples.at(-1);
|
|
203
|
+
if (!last || last.at < now - 60_000 || data.firstAt === null || data.firstAt < start)
|
|
204
|
+
return result;
|
|
205
|
+
cumulative += last.usd;
|
|
206
|
+
covered = true;
|
|
207
|
+
const before = samples.filter(row => row.at <= now - 600_000 && row.at >= now - 660_000).at(-1);
|
|
208
|
+
if (before && last.usd >= before.usd && last.at > before.at)
|
|
209
|
+
cumulativePace += (last.usd - before.usd) / ((last.at - before.at) / 60_000);
|
|
210
|
+
else
|
|
211
|
+
paceKnown = false;
|
|
212
|
+
continue;
|
|
213
|
+
}
|
|
214
|
+
covered ||= rows.length > 0;
|
|
215
|
+
for (const row of rows) {
|
|
216
|
+
const previous = charges.get(row.id);
|
|
217
|
+
if (!previous || row.usd > previous.usd)
|
|
218
|
+
charges.set(row.id, row);
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
if (!covered)
|
|
222
|
+
return result;
|
|
223
|
+
const values = [...charges.values()];
|
|
224
|
+
result.spentTodayUsd = cumulative + values.reduce((sum, row) => sum + row.usd, 0);
|
|
225
|
+
const perMinute = cumulativePace + values.filter(row => row.at > now - 600_000).reduce((sum, row) => sum + row.usd, 0) / 10;
|
|
226
|
+
// The recent pace per hour, never extrapolated to a day total: a short burst is not a forecast.
|
|
227
|
+
result.paceUsdPerHour = paceKnown ? perMinute * 60 : null;
|
|
228
|
+
return result;
|
|
229
|
+
}
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import { Canvas } from '../canvas';
|
|
2
|
+
import type { FrameOptions } from '../frames';
|
|
3
|
+
import { type WhyLang } from './i18n';
|
|
4
|
+
import type { SimpleUsage } from './simple-data';
|
|
5
|
+
import type { CompactReplayReport } from './compact-replay';
|
|
6
|
+
import type { PricingTable } from './pricing';
|
|
7
|
+
import type { InsightTranscript } from './types';
|
|
8
|
+
/** One action, from the very same cause and thresholds as the detailed report. */
|
|
9
|
+
export declare function simpleNextStep(transcript: InsightTranscript, rates?: PricingTable, lang?: WhyLang): string | null;
|
|
10
|
+
/** A replay saving describes recorded usage, never a change in plan-limit percentage. */
|
|
11
|
+
export declare function simpleReplayStep(report: CompactReplayReport, lang?: WhyLang, minimumPercent?: number): string | null;
|
|
12
|
+
export declare function simpleLines(usage: SimpleUsage, options?: {
|
|
13
|
+
lang?: WhyLang;
|
|
14
|
+
next?: string | null;
|
|
15
|
+
}): string[];
|
|
16
|
+
export declare function renderSimple(usage: SimpleUsage, options?: {
|
|
17
|
+
lang?: WhyLang;
|
|
18
|
+
next?: string | null;
|
|
19
|
+
line?: boolean;
|
|
20
|
+
title?: string;
|
|
21
|
+
}): string;
|
|
22
|
+
export declare function renderSimpleReplay(usage: SimpleUsage, report: CompactReplayReport, lang?: WhyLang, tips?: boolean): string;
|
|
23
|
+
export declare function renderSimplePanel(usage: SimpleUsage, options?: FrameOptions & {
|
|
24
|
+
lang?: WhyLang;
|
|
25
|
+
next?: string | null;
|
|
26
|
+
}): Canvas;
|
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.simpleNextStep = simpleNextStep;
|
|
4
|
+
exports.simpleReplayStep = simpleReplayStep;
|
|
5
|
+
exports.simpleLines = simpleLines;
|
|
6
|
+
exports.renderSimple = renderSimple;
|
|
7
|
+
exports.renderSimpleReplay = renderSimpleReplay;
|
|
8
|
+
exports.renderSimplePanel = renderSimplePanel;
|
|
9
|
+
const canvas_1 = require("../canvas");
|
|
10
|
+
const i18n_1 = require("./i18n");
|
|
11
|
+
const pace_1 = require("./pace");
|
|
12
|
+
const render_1 = require("./render");
|
|
13
|
+
function duration(minutes) {
|
|
14
|
+
const n = Math.max(0, Math.ceil(minutes));
|
|
15
|
+
return (n >= 60 ? `${Math.floor(n / 60)}h ` : '') + `${n % 60}m`;
|
|
16
|
+
}
|
|
17
|
+
const planName = (window) => window.name === 'five_hour' || window.windowMinutes === 300 ? 'fiveHour'
|
|
18
|
+
: window.name === 'seven_day' || window.windowMinutes === 10080 ? 'weekly' : null;
|
|
19
|
+
/** One action, from the very same cause and thresholds as the detailed report. */
|
|
20
|
+
function simpleNextStep(transcript, rates = {}, lang = 'en') {
|
|
21
|
+
if (transcript.state.forkHistoryBoundaryUnknown)
|
|
22
|
+
return null;
|
|
23
|
+
const input = (0, render_1.whyTipInput)((0, render_1.sessionFigures)(transcript, rates), rates), cause = (0, render_1.whyTipCause)(input);
|
|
24
|
+
if (!cause)
|
|
25
|
+
return null;
|
|
26
|
+
const step = cause === 'reloads' && (input.reloads.cause === 'model_switch' || input.reloads.cause === 'idle_ttl_expired') ? input.reloads.cause : cause;
|
|
27
|
+
return i18n_1.SIMPLE_TEXT[lang].steps[step];
|
|
28
|
+
}
|
|
29
|
+
/** A replay saving describes recorded usage, never a change in plan-limit percentage. */
|
|
30
|
+
function simpleReplayStep(report, lang = 'en', minimumPercent = 0) {
|
|
31
|
+
if (!report.suggestion || report.backtest.unreliable || !report.backtest.complete)
|
|
32
|
+
return null;
|
|
33
|
+
const row = report.windows.find(row => row.window === report.suggestion.window);
|
|
34
|
+
const percent = -(row?.tokenChangePercent ?? 0);
|
|
35
|
+
if (percent <= 0 || percent < minimumPercent)
|
|
36
|
+
return null;
|
|
37
|
+
return i18n_1.SIMPLE_TEXT[lang].replay(report.suggestion.command, percent.toFixed(0), report.days);
|
|
38
|
+
}
|
|
39
|
+
function simpleLines(usage, options = {}) {
|
|
40
|
+
const words = i18n_1.SIMPLE_TEXT[options.lang ?? 'en'], lines = [];
|
|
41
|
+
if (usage.billing === 'metered') {
|
|
42
|
+
lines.push(`${words.today}: ${usage.spentTodayUsd === null ? words.dollarsUnavailable : '$' + usage.spentTodayUsd.toFixed(2)}`);
|
|
43
|
+
lines.push(`${words.pace}: ${usage.paceUsdPerHour === null ? words.dollarsUnavailable : '$' + usage.paceUsdPerHour.toFixed(2) + ' ' + words.perHour}`);
|
|
44
|
+
}
|
|
45
|
+
else {
|
|
46
|
+
for (const name of ['fiveHour', 'weekly']) {
|
|
47
|
+
const samples = usage.windows.filter(w => planName(w) === name && Number.isFinite(w.observedAt) && w.observedAt <= usage.now && w.observedAt >= usage.now - 600_000 && w.resetsAt > usage.now && w.usedPercent >= 0 && w.usedPercent <= 100);
|
|
48
|
+
const latest = samples.filter(w => w.observedAt >= usage.now - 60_000).sort((a, b) => b.observedAt - a.observedAt)[0];
|
|
49
|
+
if (!latest) {
|
|
50
|
+
lines.push(`${words[name]}: ${words.unavailable}`);
|
|
51
|
+
continue;
|
|
52
|
+
}
|
|
53
|
+
const forecast = (0, pace_1.forecastLimit)(samples.filter(w => w.source === latest.source && w.pool === latest.pool && w.resetsAt === latest.resetsAt), usage.now);
|
|
54
|
+
lines.push(`${words[name]}: ${latest.usedPercent.toFixed(0)}% ${words.used}; ${words.reset} ${duration((latest.resetsAt - usage.now) / 60_000)}; `
|
|
55
|
+
+ (forecast.minutes === null ? words.paceUnavailable : `${duration(forecast.minutes)} ${words.left}`));
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
if (options.next)
|
|
59
|
+
lines.push(`${words.next}: ${options.next}`);
|
|
60
|
+
return lines;
|
|
61
|
+
}
|
|
62
|
+
function renderSimple(usage, options = {}) {
|
|
63
|
+
const words = i18n_1.SIMPLE_TEXT[options.lang ?? 'en'];
|
|
64
|
+
const title = options.title ?? `AgentGuard | ${words[usage.billing === 'metered' ? 'metered' : usage.billing === 'subscription' ? 'subscription' : 'unknown']}`;
|
|
65
|
+
const lines = simpleLines(usage, options);
|
|
66
|
+
if (options.line)
|
|
67
|
+
return [title, ...lines].join(' | ');
|
|
68
|
+
return [title, ...lines, ...(usage.spentTodayUsd !== null && usage.billing === 'metered' ? [words.reported] : [])].join('\n');
|
|
69
|
+
}
|
|
70
|
+
function renderSimpleReplay(usage, report, lang = 'en', tips = true) {
|
|
71
|
+
const suggestion = simpleReplayStep(report, lang);
|
|
72
|
+
return renderSimple(usage, { lang, next: tips ? suggestion : null }) + '\n' + (suggestion ? i18n_1.SIMPLE_TEXT[lang].replayCaution : i18n_1.SIMPLE_TEXT[lang].replayUnavailable);
|
|
73
|
+
}
|
|
74
|
+
function renderSimplePanel(usage, options = {}) {
|
|
75
|
+
const words = i18n_1.SIMPLE_TEXT[options.lang ?? 'en'], canvas = new canvas_1.Canvas(options);
|
|
76
|
+
canvas.header('AGENTGUARD / BURN', options.recorded ? words.recorded : words.live);
|
|
77
|
+
const lines = renderSimple(usage, options).split('\n');
|
|
78
|
+
let y = 3;
|
|
79
|
+
for (const line of lines) {
|
|
80
|
+
let remaining = line;
|
|
81
|
+
while (remaining && y < canvas.height - 2) {
|
|
82
|
+
let end = canvas.width;
|
|
83
|
+
if (remaining.length > end && remaining.lastIndexOf(' ', end) > 0)
|
|
84
|
+
end = remaining.lastIndexOf(' ', end);
|
|
85
|
+
canvas.put(y++, 0, remaining.slice(0, end), 'white');
|
|
86
|
+
remaining = remaining.slice(end).trimStart();
|
|
87
|
+
}
|
|
88
|
+
y++;
|
|
89
|
+
}
|
|
90
|
+
canvas.footer('', words.controls);
|
|
91
|
+
return canvas;
|
|
92
|
+
}
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import type { WhyLang } from './i18n';
|
|
2
|
+
interface SimpleText {
|
|
3
|
+
notice: string;
|
|
4
|
+
simple: string;
|
|
5
|
+
detailed: string;
|
|
6
|
+
saved: (mode: string) => string;
|
|
7
|
+
subscription: string;
|
|
8
|
+
metered: string;
|
|
9
|
+
unknown: string;
|
|
10
|
+
fiveHour: string;
|
|
11
|
+
weekly: string;
|
|
12
|
+
unavailable: string;
|
|
13
|
+
used: string;
|
|
14
|
+
reset: string;
|
|
15
|
+
left: string;
|
|
16
|
+
paceUnavailable: string;
|
|
17
|
+
today: string;
|
|
18
|
+
pace: string;
|
|
19
|
+
perHour: string;
|
|
20
|
+
dollarsUnavailable: string;
|
|
21
|
+
reported: string;
|
|
22
|
+
next: string;
|
|
23
|
+
live: string;
|
|
24
|
+
recorded: string;
|
|
25
|
+
controls: string;
|
|
26
|
+
replayUnavailable: string;
|
|
27
|
+
replayCaution: string;
|
|
28
|
+
helpers: (count: number, names: string) => string;
|
|
29
|
+
replay: (command: string, percent: string, days: number) => string;
|
|
30
|
+
steps: Record<'subagents' | 'reloads' | 'conversation' | 'setup' | 'model_switch' | 'idle_ttl_expired' | 'stopped', string>;
|
|
31
|
+
}
|
|
32
|
+
export declare const SIMPLE_TEXT: Record<WhyLang, SimpleText>;
|
|
33
|
+
export {};
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.SIMPLE_TEXT = void 0;
|
|
4
|
+
exports.SIMPLE_TEXT = {
|
|
5
|
+
en: {
|
|
6
|
+
notice: 'Showing the simple view. For tokens and cache detail: agentguard-burn mode detailed',
|
|
7
|
+
simple: 'simple', detailed: 'detailed', saved: mode => `Saved ${mode} view.`,
|
|
8
|
+
subscription: 'Subscription', metered: 'API or usage credits', unknown: 'Billing not available',
|
|
9
|
+
fiveHour: '5-hour', weekly: 'Weekly', unavailable: 'limit not available', used: 'used', reset: 'resets in', left: 'left at this pace', paceUnavailable: 'time left not available',
|
|
10
|
+
today: 'Spent today', pace: 'At this pace', perHour: 'per hour', dollarsUnavailable: 'spending not available', reported: 'Host-reported USD from today’s recorded sessions', next: 'Next',
|
|
11
|
+
live: 'LIVE', recorded: 'RECORDED', controls: 'p pause | q quit',
|
|
12
|
+
helpers: (count, names) => `Helpers: ${count}${names ? ` (${names})` : ''}`,
|
|
13
|
+
replayUnavailable: 'There is not enough evidence to suggest a smaller window.',
|
|
14
|
+
replayCaution: 'This estimates recorded work, not plan-limit savings. Shorter memory can lose context and change answers.',
|
|
15
|
+
replay: (command, percent, days) => `${command} would have used about ${percent}% less over the last ${days} days (estimate).`,
|
|
16
|
+
steps: { subagents: 'Give related work to one helper instead of several.', reloads: 'Start a fresh session with a short handoff note.', conversation: 'Start a fresh session with a short handoff note.', setup: 'Keep CLAUDE.md short and disable unused tools.', model_switch: 'Keep one model for this task.', idle_ttl_expired: 'Group related requests into one work period.', stopped: 'Finish an active helper before starting another.' },
|
|
17
|
+
},
|
|
18
|
+
es: {
|
|
19
|
+
notice: 'Mostrando la vista simple. Para ver tokens y detalles de caché: agentguard-burn mode detailed',
|
|
20
|
+
simple: 'simple', detailed: 'detallada', saved: mode => `Vista ${mode} guardada.`,
|
|
21
|
+
subscription: 'Suscripción', metered: 'API o créditos de uso', unknown: 'Facturación no disponible',
|
|
22
|
+
fiveHour: '5 horas', weekly: 'Semanal', unavailable: 'límite no disponible', used: 'usado', reset: 'se reinicia en', left: 'restantes a este ritmo', paceUnavailable: 'tiempo restante no disponible',
|
|
23
|
+
today: 'Gastado hoy', pace: 'A este ritmo', perHour: 'por hora', dollarsUnavailable: 'gasto no disponible', reported: 'USD informados por el servicio en las sesiones registradas hoy', next: 'Próximo paso',
|
|
24
|
+
live: 'EN VIVO', recorded: 'GRABADO', controls: 'p pausa | q salir',
|
|
25
|
+
helpers: (count, names) => `Ayudantes: ${count}${names ? ` (${names})` : ''}`,
|
|
26
|
+
replayUnavailable: 'No hay datos suficientes para sugerir una ventana menor.',
|
|
27
|
+
replayCaution: 'Estima el trabajo registrado, no el ahorro del límite del plan. Menos memoria puede perder contexto y cambiar las respuestas.',
|
|
28
|
+
replay: (command, percent, days) => `${command} habría usado cerca de ${percent}% menos en los últimos ${days} días (estimación).`,
|
|
29
|
+
steps: { subagents: 'Asigna el trabajo relacionado a un solo ayudante.', reloads: 'Inicia una sesión nueva con una breve nota de continuidad.', conversation: 'Inicia una sesión nueva con una breve nota de continuidad.', setup: 'Mantén CLAUDE.md corto y desactiva las herramientas sin uso.', model_switch: 'Mantén un solo modelo para esta tarea.', idle_ttl_expired: 'Agrupa las solicitudes relacionadas en un período de trabajo.', stopped: 'Termina un ayudante activo antes de iniciar otro.' },
|
|
30
|
+
},
|
|
31
|
+
pt: {
|
|
32
|
+
notice: 'Mostrando a visão simples. Para ver tokens e detalhes de cache: agentguard-burn mode detailed',
|
|
33
|
+
simple: 'simples', detailed: 'detalhada', saved: mode => `Visão ${mode} salva.`,
|
|
34
|
+
subscription: 'Assinatura', metered: 'API ou créditos de uso', unknown: 'Cobrança indisponível',
|
|
35
|
+
fiveHour: '5 horas', weekly: 'Semanal', unavailable: 'limite não disponível', used: 'usado', reset: 'renova em', left: 'restantes neste ritmo', paceUnavailable: 'tempo restante indisponível',
|
|
36
|
+
today: 'Gasto hoje', pace: 'Neste ritmo', perHour: 'por hora', dollarsUnavailable: 'gasto indisponível', reported: 'USD informados pelo serviço nas sessões registradas hoje', next: 'Próximo passo',
|
|
37
|
+
live: 'AO VIVO', recorded: 'GRAVADO', controls: 'p pausar | q sair',
|
|
38
|
+
helpers: (count, names) => `Ajudantes: ${count}${names ? ` (${names})` : ''}`,
|
|
39
|
+
replayUnavailable: 'Não há dados suficientes para sugerir uma janela menor.',
|
|
40
|
+
replayCaution: 'Estima o trabalho registrado, não a economia do limite do plano. Menos memória pode perder contexto e mudar as respostas.',
|
|
41
|
+
replay: (command, percent, days) => `${command} teria usado cerca de ${percent}% menos nos últimos ${days} dias (estimativa).`,
|
|
42
|
+
steps: { subagents: 'Dê o trabalho relacionado a um só ajudante.', reloads: 'Inicie uma sessão nova com uma breve nota de continuidade.', conversation: 'Inicie uma sessão nova com uma breve nota de continuidade.', setup: 'Mantenha CLAUDE.md curto e desative as ferramentas sem uso.', model_switch: 'Mantenha um modelo para esta tarefa.', idle_ttl_expired: 'Agrupe pedidos relacionados em um período de trabalho.', stopped: 'Termine um ajudante ativo antes de iniciar outro.' },
|
|
43
|
+
},
|
|
44
|
+
};
|
|
@@ -67,8 +67,8 @@ export declare function formatStatusFields(input: StatusInput): {
|
|
|
67
67
|
text: string;
|
|
68
68
|
parts: StatusPart[];
|
|
69
69
|
panel: string[];
|
|
70
|
-
enabled: ("
|
|
70
|
+
enabled: ("spend" | "pace" | "cost" | "cache")[];
|
|
71
71
|
unknown: string[];
|
|
72
|
-
dropped: ("
|
|
72
|
+
dropped: ("spend" | "pace" | "cost" | "cache")[];
|
|
73
73
|
clipped: boolean;
|
|
74
74
|
};
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.renderWeek = renderWeek;
|
|
4
|
+
const version_1 = require("../version");
|
|
5
|
+
const i18n_1 = require("./i18n");
|
|
6
|
+
const render_1 = require("./render");
|
|
7
|
+
const week_1 = require("./week");
|
|
8
|
+
/** Only fixed text, dates and figures appear in the weekly view. */
|
|
9
|
+
function renderWeek(report, lang = 'en') {
|
|
10
|
+
const text = i18n_1.WEEK_TEXT[lang], f = report.figures;
|
|
11
|
+
const priced = f.usdMicros.total !== null;
|
|
12
|
+
const total = priced ? f.usdMicros.total : f.tokens.total;
|
|
13
|
+
const dollar = (micros) => `$${(micros / 1_000_000).toFixed(2)}`;
|
|
14
|
+
const end = new Date(Date.parse(report.weekEnd) - 86_400_000).toISOString().slice(0, 10);
|
|
15
|
+
const shares = priced ? f.usdMicros : f.tokens;
|
|
16
|
+
return [
|
|
17
|
+
`Burn ${version_1.BURN_VERSION} | ${text.title(report.weekStart, end)}`,
|
|
18
|
+
text.summary((0, render_1.count)(f.tokens.total), priced ? dollar(f.usdMicros.total) : null),
|
|
19
|
+
...(priced ? [text.spent(dollar(f.usdMicros.waste))] : [text.tokenBasis]),
|
|
20
|
+
text.shares((0, render_1.share)(shares.useful, total), (0, render_1.share)(shares.waste, total), (0, render_1.share)(shares.unattributed, total), priced),
|
|
21
|
+
...week_1.WEEK_CAUSES.map(cause => {
|
|
22
|
+
const row = f.causes[cause];
|
|
23
|
+
return text.row(text.labels[cause], (0, render_1.share)(priced ? row.usdMicros : row.tokens, total), priced ? dollar(row.usdMicros) : null, (0, render_1.count)(row.tokens));
|
|
24
|
+
}),
|
|
25
|
+
...(priced && f.wrongModel.tokens > 0 ? [text.wrongModel((0, render_1.count)(f.wrongModel.tokens), dollar(f.wrongModel.usdMicros - f.wrongModel.smallerUsdMicros))] : []),
|
|
26
|
+
f.topCause === null ? text.noCause : text.next(text.labels[f.topCause], text.fixes[f.topCause]),
|
|
27
|
+
...(!report.complete ? [text.incomplete] : []),
|
|
28
|
+
...(report.local.excludedForkSessions || report.local.undatedTokens ? [text.excluded((0, render_1.count)(report.local.excludedForkSessions), (0, render_1.count)(report.local.undatedTokens))] : []),
|
|
29
|
+
text.privacy,
|
|
30
|
+
].join('\n');
|
|
31
|
+
}
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
import { type PricingTable } from './pricing';
|
|
2
|
+
import { transcriptRoots } from './sessions';
|
|
3
|
+
export declare const WEEK_SCHEMA = "agentguard.burn-week.v1";
|
|
4
|
+
export declare const SMALLER_MODEL = "claude-haiku-5-5";
|
|
5
|
+
export declare const WEEK_CAUSES: readonly ["history_resent", "reread_files", "subagent_fanout", "reloads"];
|
|
6
|
+
export declare const RELOAD_GROUPS: readonly ["idle", "model_switch", "other"];
|
|
7
|
+
export type WeekCause = typeof WEEK_CAUSES[number];
|
|
8
|
+
export type WeekTopCause = WeekCause | 'wrong_model' | 'reloads_idle' | 'reloads_model_switch';
|
|
9
|
+
export interface WeekAmount {
|
|
10
|
+
tokens: number;
|
|
11
|
+
usdMicros: number | null;
|
|
12
|
+
}
|
|
13
|
+
export interface WeekFigures {
|
|
14
|
+
tokens: {
|
|
15
|
+
total: number;
|
|
16
|
+
useful: number;
|
|
17
|
+
waste: number;
|
|
18
|
+
unattributed: number;
|
|
19
|
+
};
|
|
20
|
+
usdMicros: {
|
|
21
|
+
total: number | null;
|
|
22
|
+
useful: number | null;
|
|
23
|
+
waste: number | null;
|
|
24
|
+
unattributed: number | null;
|
|
25
|
+
};
|
|
26
|
+
causes: Record<WeekCause, WeekAmount>;
|
|
27
|
+
reloadsByCause: Record<typeof RELOAD_GROUPS[number], WeekAmount>;
|
|
28
|
+
subagentTokens: number;
|
|
29
|
+
wrongModel: WeekAmount & {
|
|
30
|
+
smallerUsdMicros: number | null;
|
|
31
|
+
};
|
|
32
|
+
topCause: WeekTopCause | null;
|
|
33
|
+
basis: 'estimated_api_list_price';
|
|
34
|
+
}
|
|
35
|
+
export interface WeekReport {
|
|
36
|
+
weekStart: string;
|
|
37
|
+
/** Exclusive Monday boundary, in UTC. */
|
|
38
|
+
weekEnd: string;
|
|
39
|
+
complete: boolean;
|
|
40
|
+
figures: WeekFigures;
|
|
41
|
+
/** Diagnostics stay on this machine, outside the saved file and upload. */
|
|
42
|
+
local: {
|
|
43
|
+
sessions: number;
|
|
44
|
+
excludedForkSessions: number;
|
|
45
|
+
undatedTokens: number;
|
|
46
|
+
unpricedModels: Array<string | null>;
|
|
47
|
+
};
|
|
48
|
+
}
|
|
49
|
+
export interface BurnWeekFile {
|
|
50
|
+
schema: typeof WEEK_SCHEMA;
|
|
51
|
+
weekStart: string;
|
|
52
|
+
viewedAt: string;
|
|
53
|
+
figures: WeekFigures;
|
|
54
|
+
}
|
|
55
|
+
export interface CollectWeekOptions {
|
|
56
|
+
weekStart?: string;
|
|
57
|
+
now?: number;
|
|
58
|
+
home?: string;
|
|
59
|
+
roots?: ReturnType<typeof transcriptRoots>;
|
|
60
|
+
rates?: PricingTable;
|
|
61
|
+
}
|
|
62
|
+
export interface SaveWeekResult {
|
|
63
|
+
saved: boolean;
|
|
64
|
+
reason: 'incomplete' | 'too_old' | 'empty' | 'write_failed' | null;
|
|
65
|
+
}
|
|
66
|
+
export declare function weekStartOf(ms: number): string;
|
|
67
|
+
export declare const lastCompletedWeekStart: (now?: number) => string;
|
|
68
|
+
export declare function isMonday(date: unknown): date is string;
|
|
69
|
+
/** Contract constants and tie order are copied in the plugin's weekly validator. */
|
|
70
|
+
export declare function topWeekCause(figures: WeekFigures): WeekTopCause | null;
|
|
71
|
+
/** Strict content-free contract: unknown keys and inconsistent arithmetic are errors. */
|
|
72
|
+
export declare function weekFigures(value: unknown): WeekFigures;
|
|
73
|
+
export declare function collectWeek({ weekStart, now, home, roots, rates }?: CollectWeekOptions): WeekReport;
|
|
74
|
+
/** Call only after this exact report has been displayed successfully. */
|
|
75
|
+
export declare function saveWeek(home: string, report: WeekReport, now?: number): SaveWeekResult;
|